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 |
---|---|---|---|---|---|
chrisdugne/ludum-dare-36 | src/components/Background.lua | 1 | 1247 |
--------------------------------------------------------------------------------
local Background = {}
--------------------------------------------------------------------------------
function Background:darken()
self:setDarkBGAplha(1)
end
function Background:lighten()
self:setDarkBGAplha(0)
end
function Background:setDarkBGAplha(alpha)
transition.to(self.darkBG, {
alpha = alpha,
time = 700
})
end
--------------------------------------------------------------------------------
function Background:init()
App.display:toBack()
self.bg = display.newImageRect(
App.display,
'assets/images/background-light.jpg',
display.contentWidth,
display.contentHeight
)
self.darkBG = display.newImageRect(
App.display,
'assets/images/background-dark.jpg',
display.contentWidth,
display.contentHeight
)
self.bg.x = display.contentWidth*0.5
self.bg.y = display.contentHeight*0.5
self.darkBG.x = display.contentWidth*0.5
self.darkBG.y = display.contentHeight*0.5
self.darkBG.alpha = 1
end
--------------------------------------------------------------------------------
return Background
| bsd-3-clause |
weiDDD/WSSParticleSystem | cocos2d/external/lua/luasocket/script/socket/http.lua | 1 | 12697 | -----------------------------------------------------------------------------
-- HTTP/1.1 client support for the Lua language.
-- LuaSocket toolkit.
-- Author: Diego Nehab
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-------------------------------------------------------------------------------
local socket = require("socket.socket")
local url = require("socket.url")
local ltn12 = require("socket.ltn12")
local mime = require("socket.mime")
local string = require("string")
local headers = require("socket.headers")
local base = _G
local table = require("table")
socket.http = {}
local _M = socket.http
-----------------------------------------------------------------------------
-- Program constants
-----------------------------------------------------------------------------
-- connection timeout in seconds
TIMEOUT = 60
-- default port for document retrieval
_M.PORT = 80
-- user agent field sent in request
_M.USERAGENT = socket._VERSION
-----------------------------------------------------------------------------
-- Reads MIME headers from a connection, unfolding where needed
-----------------------------------------------------------------------------
local function receiveheaders(sock, headers)
local line, name, value, err
headers = headers or {}
-- get first line
line, err = sock:receive()
if err then return nil, err end
-- headers go until a blank line is found
while line ~= "" do
-- get field-name and value
name, value = socket.skip(2, string.find(line, "^(.-):%s*(.*)"))
if not (name and value) then return nil, "malformed reponse headers" end
name = string.lower(name)
-- get next line (value might be folded)
line, err = sock:receive()
if err then return nil, err end
-- unfold any folded values
while string.find(line, "^%s") do
value = value .. line
line = sock:receive()
if err then return nil, err end
end
-- save pair in table
if headers[name] then headers[name] = headers[name] .. ", " .. value
else headers[name] = value end
end
return headers
end
-----------------------------------------------------------------------------
-- Extra sources and sinks
-----------------------------------------------------------------------------
socket.sourcet["http-chunked"] = function(sock, headers)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function()
-- get chunk size, skip extention
local line, err = sock:receive()
if err then return nil, err end
local size = base.tonumber(string.gsub(line, ";.*", ""), 16)
if not size then return nil, "invalid chunk size" end
-- was it the last chunk?
if size > 0 then
-- if not, get chunk and skip terminating CRLF
local chunk, err, part = sock:receive(size)
if chunk then sock:receive() end
return chunk, err
else
-- if it was, read trailers into headers table
headers, err = receiveheaders(sock, headers)
if not headers then return nil, err end
end
end
})
end
socket.sinkt["http-chunked"] = function(sock)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function(self, chunk, err)
if not chunk then return sock:send("0\r\n\r\n") end
local size = string.format("%X\r\n", string.len(chunk))
return sock:send(size .. chunk .. "\r\n")
end
})
end
-----------------------------------------------------------------------------
-- Low level HTTP API
-----------------------------------------------------------------------------
local metat = { __index = {} }
function _M.open(host, port, create)
-- create socket with user connect function, or with default
local c = socket.try((create or socket.tcp)())
local h = base.setmetatable({ c = c }, metat)
-- create finalized try
h.try = socket.newtry(function() h:close() end)
-- set timeout before connecting
h.try(c:settimeout(_M.TIMEOUT))
h.try(c:connect(host, port or _M.PORT))
-- here everything worked
return h
end
function metat.__index:sendrequestline(method, uri)
local reqline = string.format("%s %s HTTP/1.1\r\n", method or "GET", uri)
return self.try(self.c:send(reqline))
end
function metat.__index:sendheaders(tosend)
local canonic = headers.canonic
local h = "\r\n"
for f, v in base.pairs(tosend) do
h = (canonic[f] or f) .. ": " .. v .. "\r\n" .. h
end
self.try(self.c:send(h))
return 1
end
function metat.__index:sendbody(headers, source, step)
source = source or ltn12.source.empty()
step = step or ltn12.pump.step
-- if we don't know the size in advance, send chunked and hope for the best
local mode = "http-chunked"
if headers["content-length"] then mode = "keep-open" end
return self.try(ltn12.pump.all(source, socket.sink(mode, self.c), step))
end
function metat.__index:receivestatusline()
local status = self.try(self.c:receive(5))
-- identify HTTP/0.9 responses, which do not contain a status line
-- this is just a heuristic, but is what the RFC recommends
if status ~= "HTTP/" then return nil, status end
-- otherwise proceed reading a status line
status = self.try(self.c:receive("*l", status))
local code = socket.skip(2, string.find(status, "HTTP/%d*%.%d* (%d%d%d)"))
return self.try(base.tonumber(code), status)
end
function metat.__index:receiveheaders()
return self.try(receiveheaders(self.c))
end
function metat.__index:receivebody(headers, sink, step)
sink = sink or ltn12.sink.null()
step = step or ltn12.pump.step
local length = base.tonumber(headers["content-length"])
local t = headers["transfer-encoding"] -- shortcut
local mode = "default" -- connection close
if t and t ~= "identity" then mode = "http-chunked"
elseif base.tonumber(headers["content-length"]) then mode = "by-length" end
return self.try(ltn12.pump.all(socket.source(mode, self.c, length),
sink, step))
end
function metat.__index:receive09body(status, sink, step)
local source = ltn12.source.rewind(socket.source("until-closed", self.c))
source(status)
return self.try(ltn12.pump.all(source, sink, step))
end
function metat.__index:close()
return self.c:close()
end
-----------------------------------------------------------------------------
-- High level HTTP API
-----------------------------------------------------------------------------
local function adjusturi(reqt)
local u = reqt
-- if there is a proxy, we need the full url. otherwise, just a part.
if not reqt.proxy and not PROXY then
u = {
path = socket.try(reqt.path, "invalid path 'nil'"),
params = reqt.params,
query = reqt.query,
fragment = reqt.fragment
}
end
return url.build(u)
end
local function adjustproxy(reqt)
local proxy = reqt.proxy or PROXY
if proxy then
proxy = url.parse(proxy)
return proxy.host, proxy.port or 3128
else
return reqt.host, reqt.port
end
end
local function adjustheaders(reqt)
-- default headers
local lower = {
["user-agent"] = _M.USERAGENT,
["host"] = reqt.host,
["connection"] = "close, TE",
["te"] = "trailers"
}
-- if we have authentication information, pass it along
if reqt.user and reqt.password then
lower["authorization"] =
"Basic " .. (mime.b64(reqt.user .. ":" .. reqt.password))
end
-- override with user headers
for i,v in base.pairs(reqt.headers or lower) do
lower[string.lower(i)] = v
end
return lower
end
-- default url parts
local default = {
host = "",
port = _M.PORT,
path ="/",
scheme = "http"
}
local function adjustrequest(reqt)
-- parse url if provided
local nreqt = reqt.url and url.parse(reqt.url, default) or {}
-- explicit components override url
for i,v in base.pairs(reqt) do nreqt[i] = v end
if nreqt.port == "" then nreqt.port = 80 end
socket.try(nreqt.host and nreqt.host ~= "",
"invalid host '" .. base.tostring(nreqt.host) .. "'")
-- compute uri if user hasn't overriden
nreqt.uri = reqt.uri or adjusturi(nreqt)
-- ajust host and port if there is a proxy
nreqt.host, nreqt.port = adjustproxy(nreqt)
-- adjust headers in request
nreqt.headers = adjustheaders(nreqt)
return nreqt
end
local function shouldredirect(reqt, code, headers)
return headers.location and
string.gsub(headers.location, "%s", "") ~= "" and
(reqt.redirect ~= false) and
(code == 301 or code == 302 or code == 303 or code == 307) and
(not reqt.method or reqt.method == "GET" or reqt.method == "HEAD")
and (not reqt.nredirects or reqt.nredirects < 5)
end
local function shouldreceivebody(reqt, code)
if reqt.method == "HEAD" then return nil end
if code == 204 or code == 304 then return nil end
if code >= 100 and code < 200 then return nil end
return 1
end
-- forward declarations
local trequest, tredirect
--[[local]] function tredirect(reqt, location)
local result, code, headers, status = trequest {
-- the RFC says the redirect URL has to be absolute, but some
-- servers do not respect that
url = url.absolute(reqt.url, location),
source = reqt.source,
sink = reqt.sink,
headers = reqt.headers,
proxy = reqt.proxy,
nredirects = (reqt.nredirects or 0) + 1,
create = reqt.create
}
-- pass location header back as a hint we redirected
headers = headers or {}
headers.location = headers.location or location
return result, code, headers, status
end
--[[local]] function trequest(reqt)
-- we loop until we get what we want, or
-- until we are sure there is no way to get it
local nreqt = adjustrequest(reqt)
local h = _M.open(nreqt.host, nreqt.port, nreqt.create)
-- send request line and headers
h:sendrequestline(nreqt.method, nreqt.uri)
h:sendheaders(nreqt.headers)
-- if there is a body, send it
if nreqt.source then
h:sendbody(nreqt.headers, nreqt.source, nreqt.step)
end
local code, status = h:receivestatusline()
-- if it is an HTTP/0.9 server, simply get the body and we are done
if not code then
h:receive09body(status, nreqt.sink, nreqt.step)
return 1, 200
end
local headers
-- ignore any 100-continue messages
while code == 100 do
headers = h:receiveheaders()
code, status = h:receivestatusline()
end
headers = h:receiveheaders()
-- at this point we should have a honest reply from the server
-- we can't redirect if we already used the source, so we report the error
if shouldredirect(nreqt, code, headers) and not nreqt.source then
h:close()
return tredirect(reqt, headers.location)
end
-- here we are finally done
if shouldreceivebody(nreqt, code) then
h:receivebody(headers, nreqt.sink, nreqt.step)
end
h:close()
return 1, code, headers, status
end
local function srequest(u, b)
local t = {}
local reqt = {
url = u,
sink = ltn12.sink.table(t)
}
if b then
reqt.source = ltn12.source.string(b)
reqt.headers = {
["content-length"] = string.len(b),
["content-type"] = "application/x-www-form-urlencoded"
}
reqt.method = "POST"
end
local code, headers, status = socket.skip(1, trequest(reqt))
return table.concat(t), code, headers, status
end
_M.request = socket.protect(function(reqt, body)
if base.type(reqt) == "string" then return srequest(reqt, body)
else return trequest(reqt) end
end)
return _M
| apache-2.0 |
TheAnswer/FirstTest | bin/scripts/items/objects/weapons/1H/ryykBlade.lua | 1 | 2401 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
ryykBlade = Weapon:new{
objectName = "Ryyk Blade",
templateName = "object/weapon/melee/sword/shared_sword_blade_ryyk.iff",
objectCRC = 1543947481,
objectType = ONEHANDMELEEWEAPON,
certification = "cert_sword_blade_ryyk",
attackSpeed = 3.3,
minDamage = 25,
maxDamage = 140
}
| lgpl-3.0 |
sk89q/Photocopy | lua/includes/modules/photocopy.lua | 1 | 44265 | -- Photocopy
-- Copyright (c) 2010 sk89q <http://www.sk89q.com>
--
-- 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, see <http://www.gnu.org/licenses/>.
--
-- $Id$
local putil = require("photocopy.util")
local hook = hook
local CastVector = putil.CastVector
local CastAngle = putil.CastAngle
local CastTable = putil.CastTable
local IsValidModel = util.IsValidModel
local QuickTrace = util.QuickTrace
local CRC = util.CRC
local SERVER = SERVER
local CLIENT = CLIENT
module("photocopy",package.seeall )
EntityModifiers = {}
--BoneModifiers = {}
EntityTableModifiers = {}
IgnoreClassKeys = {
class = "Class",
model = "Model",
skin = "Skin",
pos = "Pos",
position = "Pos",
ang = "Angle",
angle = "Angle",
physicsobjects = "PhysicsObjects",
}
--- Function to get a registered Photocopy reader.
-- @param fmt Format
function GetReader(fmt)
local fmtTable = list.Get("PhotocopyFormats")[fmt]
if not fmtTable then return nil end
return fmtTable.ReaderClass
end
--- Function to get a registered Photocopy writer.
-- @param fmt Format
function GetWriter(fmt)
local fmtTable = list.Get("PhotocopyFormats")[fmt]
if not fmtTable then return nil end
return fmtTable.WriterClass
end
--- Register a format.
-- @param id ID of the format
-- @param readerClass Reader class, can be nil
-- @param writerClass Writer class, can be nil
function RegisterFormat(id, readerCls, writerClass)
list.Set("PhotocopyFormats", id, {
ReaderClass = readerCls,
WriterClass = writerClass,
})
end
-- Register an entity modifier. Entity modifiers registered with
-- Photocopy are lower priority than ones registered with
-- the duplicator. Entity modifiers registered directly with Photocopy
-- are for compatibility fixes.
function RegisterEntityModifier(id, func)
EntityModifiers[id] = func
end
-- Register a bone modifier. Bone modifiers registered with
-- Photocopy are lower priority than ones registered with
-- the duplicator. Bone modifiers registered directly with Photocopy
-- are for compatibility fixes.
--[[
function RegisterBoneModifier(id, func)
BoneModifiers[id] = func
end
]]--
-- Register a entity table modifier. These are called as the table for
-- each entity is built, allowing for compatibility fixes.
function RegisterEntityTableModifier(id, func)
EntityTableModifiers[id] = func
end
------------------------------------------------------------
-- Clipboard
------------------------------------------------------------
Clipboard = putil.CreateClass()
--- Construct the clipboard.
-- @param offset Offset position
function Clipboard:__construct(offset)
if not offset then
error("Offset for copy is required" , 2)
end
self.Offset = offset
self.EntityData = {}
self.ConstraintData = {}
self.ConstraintIndex = {}
self.Filter = nil
end
--- Creates an entity table to work on. This is very similar to
-- duplicator.CopyEntTable().
-- @param ent
-- @return Table
function Clipboard:CopyEntTable(ent)
if ent.PreEntityCopy then ent:PreEntityCopy() end
local entTable = table.Copy(ent:GetTable())
if ent.PostEntityCopy then ent:PostEntityCopy() end
-- Prepare the table like the duplicator library
entTable.Pos = ent:GetPos()
entTable.Angle = ent:GetAngles()
entTable.Class = ent.ClassOverride or ent:GetClass()
entTable.Model = ent:GetModel() or nil
entTable.Skin = ent:GetSkin() or nil
-- Prepare the physics objects
entTable.PhysicsObjects = entTable.PhysicsObjects or {}
for bone = 0, ent:GetPhysicsObjectCount() - 1 do
local physObj = ent:GetPhysicsObjectNum(bone)
if physObj:IsValid() then
entTable.PhysicsObjects[bone] = entTable.PhysicsObjects[bone] or {}
entTable.PhysicsObjects[bone].Pos = physObj:GetPos()
entTable.PhysicsObjects[bone].Angle = physObj:GetAngle()
entTable.PhysicsObjects[bone].Frozen = not physObj:IsMoveable()
end
end
-- Flexes
local num = ent:GetFlexNum()
if num > 0 then
entTable.Flex = entTable.Flex or {}
for i = 0, num do
entTable.Flex[i] = ent:GetFlexWeight(i)
end
end
entTable.FlexScale = ent:GetFlexScale()
-- Toybox
entTable.ToyboxID = ent:GetToyboxID()
-- For entities that are a part of the map
-- Ignoring this for now
--[[
if ent:CreatedByMap() then
entTable.MapCreationID = ent:MapCreationID()
end
]]--
if ent.OnEntityCopyTableFinish then
ent:OnEntityCopyTableFinish(entTable)
end
return entTable
end
--- Prepare the table for an entity that will be saved.
-- @param ent Ent
-- @return Table
function Clipboard:PrepareEntityData(ent)
local entTable = self:CopyEntTable(ent)
-- This is what we will be saving
local data = {
Class = entTable.Class,
Model = entTable.Model:gsub("\\+", "/"),
Skin = entTable.Skin,
PhysicsObjects = entTable.PhysicsObjects,
EntityMods = entTable.EntityMods,
BoneMods = entTable.BoneMods,
LocalPos = entTable.Pos - self.Offset,
LocalAngle = entTable.Angle,
Flex = entTable.Flex,
FlexScale = entTable.FlexScale,
}
-- Localize positions in the physics objects
for _, physObj in pairs(data.PhysicsObjects) do
physObj.LocalPos = physObj.Pos - self.Offset
physObj.LocalAngle = physObj.Angle
physObj.Pos = nil
physObj.Angle = nil
end
-- Store parent
if ValidEntity(ent:GetParent()) then
data.SavedParentIdx = ent:GetParent():EntIndex()
end
local cls = duplicator.FindEntityClass(ent:GetClass())
if cls then
for _, argName in pairs(cls.Args) do
-- Some keys are redundant; we are already automatically
-- handling these (model, pos, ang) ourselves
if not IgnoreClassKeys[argName:lower()] then
data[argName] = entTable[argName]
end
end
end
self:ApplyEntityTableModifiers(ent, entTable, data)
return data
end
--- Apply entity table modifiers.
-- @param ent
function Clipboard:ApplyEntityTableModifiers(ent, entTable, data)
for id, func in pairs(EntityTableModifiers) do
local ret, err = pcall(func, self.Player, ent, entTable, data)
if not ret then
self:Warn("entity_table_modifier_error", id, ent:EntIndex(), err)
end
end
end
--- Prepare a constraint data table for a constraint.
-- @param constr Constraint
-- @return Table
function Clipboard:PrepareConstraintData(constr)
local constrData = {
Type = constr.Type,
length = constr.length, -- Fix
CreateTime = constr.CreateTime, -- Order fix
Entity = {}, -- Adv. Dupe compatible
}
local cls = duplicator.ConstraintType[constr.Type]
if cls then
for _, argName in pairs(cls.Args) do
-- Entities and bones are handled later
if not argName:match("Ent[0-9]?") and
not argName:match("Bone[0-9]?") then
constrData[argName] = constr[argName]
end
end
end
if constr.Ent and (constr.Ent:IsWorld() or constr.Ent:IsValid()) then
constrData.Entity[1] = {
Index = constr.Ent:EntIndex(),
World = constr.Ent:IsWorld() or nil,
Bone = constr.Bone,
}
else
for i = 1, 6 do
local id = "Ent" .. i
local ent = constr[id]
if ent and (ent:IsWorld() or ent:IsValid()) then
local constrInfo = {
Index = ent:EntIndex(),
World = ent:IsWorld() or nil,
Bone = constr["Bone" .. i],
WPos = constr["WPos" .. i],
Length = constr["Length" .. i],
}
local lpos = constr["LPos" .. i]
if ent:IsWorld() then
if lpos then
constrInfo.LPos = lpos - offset
else
constrInfo.LPos = offset
end
else
constrInfo.LPos = lpos
end
constrData.Entity[i] = constrInfo
end
end
end
-- TODO: Arg clean up
return constrData
end
--- Adds an entity (and its constrained entities) to this clipboard.
-- @param ent Entity
function Clipboard:Copy(ent)
if not ValidEntity(ent) then
error("Invalid entity given to copy")
end
if self.EntityData[ent:EntIndex()] then return end
-- Check filter
if self.Filter and not self.Filter:CanCopyEntity(ent) then return end
-- Build entity data from the entity
local data = self:PrepareEntityData(ent)
if self.Filter and not self.Filter:CanCopyEntityData(data) then return end
self.EntityData[ent:EntIndex()] = data
if constraint.HasConstraints(ent) then
local constraints = constraint.GetTable(ent)
for k, constr in pairs(constraints) do
local constrObj = constr.Constraint
if not self.ConstraintIndex[constrObj] then
self.ConstraintIndex[constrObj] = true
table.insert(self.ConstraintData,
self:PrepareConstraintData(constr))
-- Copy constrained entities
for _, constrEnt in pairs(constr.Entity) do
if ValidEntity(constrEnt.Entity) then
self:Copy(constrEnt.Entity)
end
end
end
end
end
table.SortByMember(self.ConstraintData, "CreateTime", function(a, b)
return a > b
end)
end
AccessorFunc(Clipboard, "EntityData", "EntityData")
AccessorFunc(Clipboard, "ConstraintData", "ConstraintData")
AccessorFunc(Clipboard, "Offset", "Offset")
AccessorFunc(Clipboard, "Filter", "Filter")
local function MarkConstraint(ent)
ent.CreateTime = CurTime()
end
hook.Add("OnEntityCreated", "PhotocopyConstraintMarker", function(ent)
-- Is this a constraint?
if ValidEntity(ent) and ent:GetClass():lower():match("^phys_") then
timer.Simple(0, MarkConstraint, ent)
end
end)
--- Function to override duplication for prop_physics. This version has
-- no effect, which is the main advantage. This is largely copied from sandbox.
-- @param ply
-- @param pos
-- @param model
-- @param physObj
-- @param data Entity data
local function PropClassFunction(ply, pos, ang, model, physObjs, data)
data.Pos = pos
data.Angle = ang
data.Model = model
if not gamemode.Call("PlayerSpawnProp", ply, model) then return end
local ent = ents.Create("prop_physics")
duplicator.DoGeneric(ent, data)
ent:Spawn()
ent:Activate()
duplicator.DoGenericPhysics(ent, ply, data)
duplicator.DoFlex(ent, data.Flex, data.FlexScale)
gamemode.Call("PlayerSpawnedProp", ply, model, ent)
FixInvalidPhysicsObject(ent)
return ent
end
------------------------------------------------------------
-- Paster
------------------------------------------------------------
CreateConVar("photocopy_paste_spawn_rate", "5", { FCVAR_ARCHIVE })
CreateConVar("photocopy_paste_setup_rate", "20", { FCVAR_ARCHIVE })
CreateConVar("photocopy_paste_constrain_rate", "10", { FCVAR_ARCHIVE })
Paster = putil.CreateClass(putil.IterativeProcessor)
--- Construct the Paster. Currently the angle to paste at cannot have a
-- non-zero pitch or roll, as some entities will spawn with an incorrect
-- orientation (the cause is not yet pinpointed).
-- @param clipboard Clipboard
-- @param ply Player
-- @param originPos Position to paste at
-- @param originAng Angle to paste at
function Paster:__construct(clipboard, ply, originPos, originAng)
putil.IterativeProcessor.__construct(self)
self.EntityData = table.Copy(clipboard.EntityData)
self.ConstraintData = table.Copy(clipboard.ConstraintData)
self.Player = ply
self.Pos = originPos
self.Ang = originAng
self.SpawnFrozen = false
self.NoConstraints = false
self.Filter = nil
self.SpawnRate = GetConVar("photocopy_paste_spawn_rate"):GetInt()
self.PostSetupRate = GetConVar("photocopy_paste_setup_rate"):GetInt()
self.ConstrainRate = GetConVar("photocopy_paste_constrain_rate"):GetInt()
self.CreatedEntsMap = {}
self.CreatedEnts = {}
self.CurIndex = nil
self:SetNext(0, self._Spawn)
self:CreateHelperEnt()
end
--- Transform a position and angle according to the offsets. This function
-- converts all the local positions and angles to their actual new positions
-- and angles.
-- @param pos
-- @param ang
-- @return Transformed position
-- @return Transformed angle
function Paster:Transform(pos, ang)
return LocalToWorld(pos, ang, self.Pos, self.Ang)
end
--- Check to make sure that this entity can be created. This function can
-- be overrided to control what can be created before the entity is actually
-- created. The passed table can also be modified safely.
-- @param entData
-- @return Boolean indicating whether the entity can be created
function Paster:CanCreateEntity(entData)
if type(entData.Class) ~= 'string' then return false end
if entData.Class == "" then return false end
if not self.Filter then return true end
//PrintTable(self.Filter)
return self.Filter:CanCreateEntity(entData)
end
--- After the entity is created, this function can be used to undo the entity.
-- Return true if the entity should continue existing, otherwise return
-- false to have the entity removed.
-- @param ply
-- @param ent
-- @param entData entity table
-- @return Boolean indicating whether the entity can be created
function Paster:CanAllowEntity(ent, entData)
if not self.Filter then return true end
return self.Filter:CanAllowEntity(ent, entData)
end
--- Check to see whether this constraint can be created. Return false in
-- this function to disable. The constraint data table can also be modified.
function Paster:CanCreateConstraint(constrData)
if not self.Filter then return true end
return self.Filter:CanCreateConstraint(constrData)
end
--- Apply entity modifiers. The duplicator's ApplyEntityModifiers() will
-- fail on a bad entity modifier function, but this one will log
-- individual errors to the paster log.
-- @param ent
function Paster:ApplyEntityModifiers(ent)
-- Lower priority modifiers of Photocopy
for type, func in pairs(EntityModifiers) do
-- Skip ones that are registered with the duplicator
if not duplicator.EntityModifiers[type] and ent.EntityMods[type] then
local ret, err = pcall(func, self.Player, ent, ent.EntityMods[type])
if not ret then
self:Warn("entity_photocopy_modifier_error", type, ent:EntIndex(), err)
end
end
end
for type, func in pairs(duplicator.EntityModifiers) do
if ent.EntityMods[type] then
local ret, err = pcall(func, self.Player, ent, ent.EntityMods[type])
if not ret then
self:Warn("entity_modifier_error", type, ent:EntIndex(), err)
end
end
end
end
--- Apply bone modifiers. See ApplyEntityModifiers().
-- @param ent
function Paster:ApplyBoneModifiers(ent)
for type, func in pairs(duplicator.BoneModifiers) do
for bone, args in pairs(ent.PhysicsObjects) do
if ent.BoneMods[bone] and ent.BoneMods[bone][type] then
local physObj = ent:GetPhysicsObjectNum(bone)
if ent.PhysicsObjects[bone] then
local ret, err = pcall(func, self.Player, ent, bone,
physObj, ent.BoneMods[bone][type])
if not ret then
self:Warn("bone_modifier_error", type, ent:EntIndex(), err)
end
end
end
end
end
end
--- Restore the position and angle values of the entity data table. Because
-- this modifies the passed table, a copy of the table is advised (if
-- required). The Model and Skin keys are also casted to their respective types.
-- @param entData
function Paster:PrepareEntityData(entData)
local pos, ang = self:Transform(CastVector(entData.LocalPos),
CastAngle(entData.LocalAngle))
entData.Pos = pos
entData.Angle = ang
-- Remove keys
entData.LocalPos = nil
entData.LocalAngle = nil
-- Do the same for the physics objects
if entData.PhysicsObjects then
for index, physObj in pairs(entData.PhysicsObjects) do
local pos, ang = self:Transform(CastVector(physObj.LocalPos),
CastAngle(physObj.LocalAngle))
physObj.Pos = pos
physObj.Angle = ang
physObj.LocalPos = nil
physObj.LocalAngle = nil
end
end
entData.Model = tostring(entData.Model)
entData.Skin = tonumber(entData.Skin) or 0
end
--- Create an entity from entity data.
-- @param entData
-- @return Entity or nil
function Paster:CreateEntity(entData)
local cls = duplicator.FindEntityClass(entData.Class)
-- If the entity doesn't have a special saving routine, we can create
-- it generically
if not cls then
return self:CreateGenericEntity(entData)
end
local factory = cls.Func
local args = {}
-- Using our own prop_physics factory function that doesn't have the effect
if entData.Class == "prop_physics" then
if not IsValidModel(entData.Model) then
self:Warn("missing_model", entData.Model)
return nil
end
factory = PropClassFunction
end
-- Get class arguments
for _, argName in ipairs(cls.Args) do
local lowerArgName = argName:lower()
local newArgName = IgnoreClassKeys[lowerArgName] and IgnoreClassKeys[lowerArgName] or argName
local val = nil
if argName == "Data" then -- Duplicator has this special key
val = entData
elseif newArgName then
val = entData[newArgName]
else
val = entData[argName]
end
-- Legacy duplicator compatibility
if val == nil then
val = false
end
table.insert(args, val)
end
local ret, res = pcall(factory, self.Player,
unpack(args, 1, table.maxn(args)))
if ret then
return res
else
self:Warn("entity_factory_error", entData.Class, res)
return nil
end
end
--- Create a generic entity. This is called for entities that do not have
-- a registered class type. If the entity also doesn't exist on the server,
-- then CreateDummyEntity() will be called.
-- @param entData
function Paster:CreateGenericEntity(entData)
local ent = ents.Create(entData.Class)
if not ent:IsValid() then
-- Allow people to write their own dummy entities
return self:CreateDummyEntity(entData)
end
if not IsValidModel(entData.Model) then
self:Warn("missing_model", entData.Model)
return nil
end
-- Apply position and model
duplicator.DoGeneric(ent, entData)
ent:Spawn()
ent:Activate()
-- Apply physics object data
duplicator.DoGenericPhysics(ent, self.Player, entData)
return ent
end
--- Create a dummy entity (for entities that do not exist). This function
-- can be overrided if you want to handle this a bit differently.
-- @param entData Entity data
function Paster:CreateDummyEntity(entData)
if not IsValidModel(entData.Model) then
self:Warn("missing_model", entData.Model)
return nil
else
self:Warn("unknown_entity_type", entData.Class)
end
local ent = ents.Create("prop_physics")
ent:SetCollisionGroup(COLLISION_GROUP_WORLD)
-- Apply position and model
duplicator.DoGeneric(ent, entData)
ent:Spawn()
ent:Activate()
-- Apply physics object data
duplicator.DoGenericPhysics(ent, self.Player, entData)
return ent
end
--- Set up the entity. Called right after the entity has been spawned and
-- before all entities have been spawned.
-- @param ent Entity
-- @param entData
function Paster:SetupEntity(ent, entData)
-- We will need these later
entData.BoneMods = CastTable(entData.BoneMods)
entData.EntityMods = CastTable(entData.EntityMods)
entData.PhysicsObjects = CastTable(entData.PhysicsObjects)
ent.BoneMods = table.Copy(entData.BoneMods)
ent.EntityMods = table.Copy(entData.EntityMods)
ent.PhysicsObjects = table.Copy(entData.PhysicsObjects)
self:ApplyEntityModifiers(ent)
self:ApplyBoneModifiers(ent)
-- Set skin manually
if tonumber(entData.Skin) then
ent:SetSkin(tonumber(entData.Skin))
end
-- Seat fix
if ent:GetClass() == "prop_vehicle_prisoner_pod" and
ent:GetModel() ~= "models/vehicles/prisoner_pod_inner.mdl" and
not ent.HandleAnimation then
ent.HandleAnimation = function(self, ply)
return self:SelectWeightedSequence(ACT_GMOD_SIT_ROLLERCOASTER)
end
end
end
--- Called on each entity after all the entities have eben spawned.
-- @param ent Entity
-- @param entData
function Paster:PostSetupEntity(ent, entData)
-- Duplicator hook
if ent.PostEntityPaste then
putil.ProtectedCall(ent.PostEntityPaste, ent, self.Player, ent, self.CreatedEntsMap)
end
-- Clean up
if ent.EntityMods then
ent.EntityMods.RDDupeInfo = nil
ent.EntityMods.WireDupeInfo = nil
end
end
--- Create a constraint from a constraint data table.
-- @param constrData
function Paster:CreateConstraint(constrData)
if not constrData.Type then return end
if not self:CanCreateConstraint(constrData) then
self:Warn("constraint_create_disallowed", constrData.Type, constrData.Index or -1)
return
end
local cls = duplicator.ConstraintType[constrData.Type]
if not cls then return end
local factory = cls.Func
local args = {}
-- Get class arguments
for _, argName in ipairs(cls.Args) do
local val = constrData[argName]
if argName == "pl" then val = self.Player end
local c, i = argName:match("([A-Za-z]+)([1-6]?)")
local data = constrData.Entity[tonumber(i) or 1]
-- Have to pull the data out of that Entity sub-table
if c == "Ent" then
if data.World then
val = GetWorldEntity()
else
val = self.CreatedEntsMap[data.Index or -1]
if not ValidEntity(val) then
self:Warn("constraint_invalid_reference", constrData.Type, data.Index or -1)
return
end
end
elseif c == "Bone" then
val = data.Bone
elseif c == "LPos" then
if data.World and type(data.LPos) == 'Vector' then
val = data.LPos + self.Pos
else
val = data.LPos
end
elseif c == "WPos" then
val = data.WPos
elseif c == "Length" then
val = data.Length
end
-- Legacy duplicator compatibility
if val == nil then
val = false
end
table.insert(args, val)
end
local ret, res = pcall(factory, unpack(args, 1, table.maxn(args)))
if ret then
-- Elastic fix
if type(constrData.length) == 'number' then
res:Fire("SetSpringLength", constrData.length, 0)
res.length = constrData.length
end
return res
else
self:Warn("constraint_create_fail", constrData.Type, res)
return nil
end
end
--- Called at the very end, after all the entities and constraints have
-- been created.
function Paster:Finalize()
undo.Create("photocopy")
for entIndex, ent in pairs(self.CreatedEntsMap) do
if ValidEntity(ent) then
undo.AddEntity(ent)
local entData = self.EntityData[entIndex]
ent:SetNotSolid(false)
ent:SetParent()
-- Unfreeze physics objects
if not self.SpawnFrozen then
for bone = 0, ent:GetPhysicsObjectCount() - 1 do
local physObj = ent:GetPhysicsObjectNum(bone)
if physObj:IsValid() then
local b = entData.PhysicsObjects[bone] or {}
local shouldBeFrozen = b.Frozen and true or false
physObj:EnableMotion(not shouldBeFrozen)
end
end
end
-- RD2 compatibility
if ent.RDbeamlibDrawer then
ent.RDbeamlibDrawer:SetParent()
end
-- Parent
if not self.NoConstraints then
self:ApplyParenting(ent, entData)
end
end
end
undo.SetPlayer(self.Player)
undo.Finish()
local legacyPasteData = {
[1] = {
CreatedEntities = self.CreatedEntsMap,
},
}
hook.Call("AdvDupe_FinishPasting", GAMEMODE, legacyPasteData, 1)
hook.Call("DuplicationFinished", GAMEMODE, self.CreatedEntsMap)
end
--- Apply parenting.
-- @param ent
-- @param entData
function Paster:ApplyParenting(ent, entData)
local parentID = entData.SavedParentIdx
if not parentID then return end
local ent2 = self.CreatedEntsMap[parentID]
if ValidEntity(ent2) and ent != ent2 then
ent:SetParent()
-- Prevent circular parents
if ent == ent2:GetParent() then
ent2:SetParent()
end
ent:SetParent(ent2)
end
end
--- Creates a helper entity that is essential to spawning some parented
-- contraptions. Without a helper entity, these contraptions may freeze the
-- server once unfrozen. The helper entity also allows the player to undo
-- the contraption while spawning.
-- @param ent
-- @param entData
function Paster:CreateHelperEnt()
if ValidEntity(self.HelperEnt) then return end
self.HelperEnt = ents.Create("base_anim")
self.HelperEnt:SetNotSolid(true)
self.HelperEnt:SetPos(self.Pos)
putil.FreezeAllPhysObjs(self.HelperEnt)
self.HelperEnt:SetNoDraw(true)
self.HelperEnt:Spawn()
self.HelperEnt:Activate()
self.Player:AddCleanup("duplicates", self.HelperEnt)
undo.Create("photocopy_paste")
undo.AddEntity(self.HelperEnt)
undo.SetPlayer(self.Player)
undo.Finish()
end
--- Create the props.
function Paster:_Spawn()
self:SetNext(0.1)
for i = 1, self.SpawnRate do
local entIndex, entData = next(self.EntityData, self.CurIndex)
self.CurIndex = entIndex
if not entIndex then
self.CurIndex = nil
self:SetNext(0.05, self._PostSetup)
return
end
self:PrepareEntityData(entData)
if self:CanCreateEntity(entData) then
local ent = self:CreateEntity(entData)
if not self:CanAllowEntity(ent, entData) then
ent:Remove()
self:Warn("entity_create_disallowed", entData.Class, entIndex)
elseif ValidEntity(ent) then
if ValidEntity(self.HelperEnt) then
ent:SetParent(self.HelperEnt)
end
self.Player:AddCleanup("duplicates", ent)
self:SetupEntity(ent, entData)
self.CreatedEntsMap[entIndex] = ent
ent:SetNotSolid(true)
putil.FreezeAllPhysObjs(ent)
end
else
self:Warn("entity_create_disallowed", entData.Class, entIndex)
end
end
end
--- Do some post setup.
function Paster:_PostSetup()
self:SetNext(0.01)
for i = 1, self.PostSetupRate do
local entIndex, entData = next(self.EntityData, self.CurIndex)
self.CurIndex = entIndex
if not entIndex then
self.CurIndex = nil
if self.NoConstraints then
self:SetNext(0.05, self._Finalize)
else
self:SetNext(0.1, self._Constrain)
end
return
end
local ent = self.CreatedEntsMap[entIndex]
if ValidEntity(ent) then -- Maybe something happened
self:PostSetupEntity(ent, entData)
end
end
end
--- Do some post setup.
function Paster:_Constrain()
self:SetNext(0.1)
for i = 1, self.ConstrainRate do
local k, constrData = next(self.ConstraintData, self.CurIndex)
self.CurIndex = k
if not k then
self.CurIndex = nil
self:SetNext(0.1, self._Finalize)
return
end
self:CreateConstraint(constrData)
end
end
--- Finalization.
function Paster:_Finalize()
self:Finalize()
if ValidEntity(self.HelperEnt) then
self.HelperEnt:Remove()
end
self:SetNext(0, false)
end
AccessorFunc(Paster, "NoConstraints", "NoConstraints", FORCE_BOOL)
AccessorFunc(Paster, "SpawnFrozen", "SpawnFrozen", FORCE_BOOL)
AccessorFunc(Paster, "Filter", "Filter")
------------------------------------------------------------
-- Reader
------------------------------------------------------------
Reader = putil.CreateClass(putil.IterativeProcessor)
-- Constructor.
function Reader:__construct(data)
putil.IterativeProcessor.__construct(self)
if data == nil then
error("Photocopy Reader got empty data")
end
self.Data = data
self.Clipboard = nil
end
function Reader:GetName() return nil end
function Reader:GetDescription() return nil end
function Reader:GetCreatorName() return nil end
function Reader:GetSaveTime() return nil end
function Reader:GetOriginPos() return Vector(0, 0, 0) end
function Reader:GetOriginAngle() return Angle(0, 0, 0) end
AccessorFunc(Reader, "Clipboard", "Clipboard")
------------------------------------------------------------
-- Writer
------------------------------------------------------------
Writer = putil.CreateClass(putil.IterativeProcessor)
-- Constructor.
function Writer:__construct(clipboard)
putil.IterativeProcessor.__construct(self)
self.Clipboard = clipboard
self.Output = ""
end
function Writer:SetName(name) end
function Writer:SetDescription(desc) end
function Writer:SetCreatorName(name) end
function Writer:SetSaveTime(t) end
function Writer:SetOriginPos(pos) end
function Writer:SetOriginAngle(pos) end
AccessorFunc(Writer, "Output", "Output")
------------------------------------------------------------
-- Filter
------------------------------------------------------------
Filter = putil.CreateClass()
--- Construct the filter.
function Filter:__construct(offset)
end
--- Check to make sure that this entity can be copied.
-- @param ent
-- @return Boolean indicating whether the entity can be created
function Filter:CanCopyEntity(ent)
return true
end
--- Check to make sure that this entity can be copied. The passed table can
-- be modified safely.
-- @param entData
-- @return Boolean indicating whether the entity can be created
function Filter:CanCopyEntityData(entData)
return true
end
--- Check to make sure that this entity can be pasted before actual
-- entity creation. The passed table can be modified safely.
-- @param entData
-- @return Boolean indicating whether the entity can be created
function Filter:CanCreateEntity(entData)
return true
end
--- After the entity is created, this function can be used to undo the entity.
-- Return true if the entity should continue existing, otherwise return
-- false to have the entity removed.
-- @param ent
-- @param entData entity table
-- @return Boolean indicating whether the entity can be created
function Filter:CanAllowEntity(ent, entData)
return true
end
--- Check to see whether this constraint can be created. Return false in
-- this function to disable. The constraint data table can also be modified.
-- @param constrData
-- @return Boolean indicating whether the entity can be created
function Filter:CanCreateConstraint(constrData)
return true
end
------------------------------------------------------------
-- Networker
------------------------------------------------------------
if SERVER then
CreateConVar("photocopy_ghost_rate" , "50" , {FCVAR_ARCHIVE} ) // usermessages per second for ghost info
svGhoster = putil.CreateClass(putil.IterativeProcessor)
--the networker, will send things from the server to the client via usermessages
-- @param data
-- @param data override for files
function svGhoster:__construct( ply )
putil.IterativeProcessor.__construct(self)
self.ply = ply
end
-- the initialiser
-- @param clipboard, a clipboard object
function svGhoster:Initialize( clipboard , offset)
//GetTime()
self.EntityData = clipboard.EntityData
self.Pos = clipboard:GetOffset()
self.offset = offset or (clipboard:GetOffset() - QuickTrace( clipboard:GetOffset() , clipboard:GetOffset() - Vector(0,0,10000) , ents.GetAll() ).HitPos)
self.SendRate = GetConVar("photocopy_ghost_rate"):GetInt() / 10
self.CurIndex = nil
self.GhostParent = self:GetGhostController()
self:SetNext(0, self.SendInitializeInfo)
//GetTime()
end
-- Creates the ghost entity a single player's ghost parent too, bound to that player
function svGhoster:CreateGhostEnt()
local ent = ents.Create("base_anim")
ent:SetColor(0,0,0,0)
ent:SetCollisionGroup(COLLISION_GROUP_WORLD)
ent:SetNotSolid(true)
ent:Spawn()
ent:Activate()
self.ply.GhostController = ent
return ent
end
hook.Add("PlayerDisconnected" , "photocopy_remove_ghostent" , function( ply )
SafeRemoveEntity(ply.GhostController)
end)
hook.Add("PlayerDeath" , "photocopy_remove_ghostent" , function( ply )
//SafeRemoveEntity(ply.GhostController)
//ply.GhostController = nil
end)
hook.Add("PlayerSpawn" , "photocopy_create_ghostent" , function( ply )
if !ply.GhostController then
local ent = ents.Create("base_anim")
ent:SetColor(0,0,0,0)
ent:SetCollisionGroup(COLLISION_GROUP_WORLD)
ent:SetNotSolid(true)
ent:Spawn()
ent:Activate()
ply.GhostController = ent
end
end)
-- Returns the player's GhostParet
function svGhoster:GetGhostController()
local ent
if IsValid(self.ply.GhostController) then
ent = self.ply.GhostController
else
ent = self:CreateGhostEnt()
end
ent:SetPos(self.Pos)
return ent
end
-- Sends the initializer info to start a new ghost
function svGhoster:SendInitializeInfo()
//GetTime()
umsg.Start("photocopy_ghost_init" , self.ply )
umsg.Entity( self:GetGhostController() )
umsg.Float( self.offset.x )
umsg.Float( self.offset.y )
umsg.Float( self.offset.z )
umsg.End()
self:SetNext(0 , self.SendGhostInfo)
//GetTime()
end
--ghost info
function svGhoster:SendGhostInfo()
//GetTime()
local entIndex , entData
local pos , ang
for i = 1 , self.SendRate do
entIndex , entData = next(self.EntityData, self.CurIndex)
self.CurIndex = entIndex
if not entIndex then
self.CurIndex = nil
self:SetNext(0,false)
return
end
umsg.Start("photocopy_ghost_info" , self.ply )
umsg.String(entData.Model)
-- postion
pos = entData.LocalPos
umsg.Float(pos.x)
umsg.Float(pos.y)
umsg.Float(pos.z)
--angle
ang = entData.LocalAngle
umsg.Float(ang.p)
umsg.Float(ang.y)
umsg.Float(ang.r)
umsg.End()
end
self:SetNext(0)
//GetTime()
end
------------------------------------------------------------
-- svFileNetworker
------------------------------------------------------------
svFileNetworker = putil.CreateClass(putil.IterativeProcessor)
function svFileNetworker:__construct( ply )
putil.IterativeProcessor.__construct(self)
self.ply = ply
datastream.Hook("photocopy_serverfiletransfer"..tostring(ply) , function( pl , handler , id , encoded , decoded ) self:ReceiveFile( pl , decoded) end)
hook.Add("AcceptStream" , "photocopy_serverfiletransfer"..tostring(ply) , function(pl) return pl == ply end)
end
function svFileNetworker:SendToClient( data , filename , callback , ply )
if self.Sending then return end
self.ply = ply or self.ply
self.data = data
self.index = 0
self.chunk = 0
self.length = math.ceil( #data / 245 )
self.Sending = true
umsg.Start( "photocopy_clientfiletransfer_init" , self.ply )
umsg.String( CRC( self.data ) )
umsg.String( filename )
umsg.Long( self.length )
umsg.End()
self:Start( function() self.Sending = false if callback then callback() end end )
self:SetNext(0.025 , self.SendData )
end
function svFileNetworker:SendData()
for i = 1 , 5 do
self.chunk = self.chunk + 1
if self.chunk == self.length then self:SetNext( 0 , false ) end
local str = string.sub( self.data , self.index , self.index +245 )
umsg.Start( "photocopy_clientfiletransfer_data" , self.ply )
umsg.String( str )
umsg.End()
self.index = self.index + 246
end
self:SetNext( 0 )
end
function svFileNetworker:SetCallbacks( OnSuccess , OnFailed )
if OnSuccess then
self.OnSuccess = OnSuccess
else
self.OnSuccess = function() end
end
if OnFailed then
self.OnFailed = OnFailed
else
self.OnFailed = function() end
end
end
function svFileNetworker:ReceiveFile( ply , tab )
local filename = tab[1]
local crc = tab[2]
local data = tab[3]
if crc == CRC( tab[3] ) then
self.OnSuccess( filename , data )
else
self.OnFailed()
end
end
end
if CLIENT then
------------------------------------------------------------
-- clFileNetworker
------------------------------------------------------------
clFileNetworker = putil.CreateClass(putil.IterativeProcessor)
-- constructer, there should only ever be one clFileNetworker class client side ever
function clFileNetworker:__construct()
putil.IterativeProcessor.__construct(self)
self.Length = 0
self.Index = 0
usermessage.Hook( "photocopy_clientfiletransfer_init" , function( um ) self:InitializeTransfer( um:ReadString() , um:ReadString() , um:ReadLong() ) end)
usermessage.Hook( "photocopy_clientfiletransfer_data" , function( um ) self:ReceiveData( um:ReadString() ) end)
end
-- Called when the initializing usermessage is received.
-- @param crc a crc of the file
-- @param length of the file /250, amount of usermessages to be received.
function clFileNetworker:InitializeTransfer( crc , filename , length )
self.CRC = crc
self.Length = length
self.FileName = filename
self.ReceivingFile = true
self.Index = 0
self.Progress = 0
self.Strings = {}
end
-- Called when part of the data is received
-- @param strchunk a string 250 chars in length, received by the usermessage
function clFileNetworker:ReceiveData( strchunk )
self.Index = self.Index + 1
self.Strings[ #self.Strings + 1 ] = strchunk
if self.Index == self.Length then self:Finish() end
end
-- called when the entire file is received, turns the received chunks into a string again
function clFileNetworker:Finish()
self.Receiving = false
local concat = table.concat( self.Strings , "" )
local crc = CRC( concat )
if crc == self.CRC then
self.OnReceived( concat , self.FileName )
else
self.OnFailed( concat , crc )
end
end
-- Used to set the OnSucces and OnFailed callback
-- param OnSuccess called when succesful file transfer
-- param OnFailed called when unsuccessful file transfer
function clFileNetworker:SetCallbacks( OnReceived , OnFailed )
if OnReceived then
self.OnReceived = OnReceived
else
self.OnReceived = function() end
end
if OnFailed then
self.OnFailed = OnFailed
else
self.OnFailed = function() end
end
end
-- Sending files
-- @param data filename callbackcompleted
function clFileNetworker:SendToServer( data , filename , callbackcompleted )
if self.Receiving then notification.AddLegacy( "Cannot upload file while downloading a file", NOTIFY_ERROR , 7 ) return end
self.Sending = true
self.Length = #filename + #CRC(data) + #data
local function Completed( ... )
self.Sending = false
callbackcompleted(...)
end
self.SendID = datastream.StreamToServer("photocopy_serverfiletransfer"..tostring(LocalPlayer()) , { filename , CRC(data) , data}, Completed )
end
-- returns the progress on the file download
function clFileNetworker:GetProgress()
if self.ReceivingFile then
return (self.Index / self.Length) * 100
elseif self.Sending then
return ((datastream.GetProgress( self.SendID ) or 0) / self.Length) * 100
end
end
end // end "if CLIENT then" block
MsgN("Photocopy %Version$ loaded (http://www.sk89q.com/projects/photocopy/)")
include("photocopy/compat.lua")
local list = file.FindInLua("photocopy/formats/*.lua")
for _, f in pairs(list) do
MsgN("Photocopy: Auto-loading format file: " .. f)
include("photocopy/formats/" .. f)
end
| gpl-2.0 |
TheAnswer/FirstTest | bin/scripts/creatures/objects/naboo/citys/emperorRetreat.lua | 1 | 9818 | --Copyright (C) 2008 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
corvetteNpc5 = Creature:new {
objectName = "corvetteNpc5",
creatureType = "NPC",
speciesName = "ja_ce_yiaso",
combatFlags = 0,
creatureBitmask = 264,
stfName = "npc_spawner_n",
objectCRC = 3682206605,
positionX = -44.015461,
positionY = -31.585495,
positionZ = 0.200001,
directionX = -0.000003,
directionZ = -0.000007,
directionY = 0.198956,
directionW = 0.980008,
randomMovement = 0,
mood = "npc_imperial",
cellID = 1418884
}
corvetteNpc6 = Creature:new {
objectName = "corvetteNpc6",
creatureType = "NPC",
speciesName = "mouse_droid",
combatFlags = 0,
creatureBitmask = 264,
stfName = "mob/creature_names",
objectCRC = 1579087581,
positionX = -45.790001,
positionY = -12.500000,
positionZ = 0.200001,
directionX = 0.000000,
directionZ = 0.000000,
directionY = -0.693698,
directionW = 0.720290,
randomMovement = 0,
mood = "neutral",
cellID = 1418879
}
corvetteNpc7 = Creature:new {
objectName = "corvetteNpc7",
creatureType = "NPC",
speciesName = "lord_hethrir",
combatFlags = 0,
creatureBitmask = 264,
stfName = "mob/creature_names",
objectCRC = 3645848119,
positionX = 4.980000,
positionY = -41.820000,
positionZ = 0.200735,
directionX = -0.000004,
directionZ = 0.000001,
directionY = -0.398778,
directionW = 0.917047,
randomMovement = 0,
mood = "neutral",
cellID = 1418876
}
corvetteNpc8 = Creature:new {
objectName = "corvetteNpc8",
creatureType = "NPC",
speciesName = "ra7_bug_droid",
combatFlags = 0,
creatureBitmask = 264,
stfName = "mob/creature_names",
objectCRC = 781965517,
positionX = 4.000000,
positionY = -45.299999,
positionZ = 0.200735,
directionX = 0.000000,
directionZ = 0.000000,
directionY = -0.052336,
directionW = 0.998630,
randomMovement = 0,
mood = "neutral",
cellID = 1418876
}
corvetteNpc9 = Creature:new {
objectName = "corvetteNpc9",
creatureType = "NPC",
speciesName = "loam_redge",
combatFlags = 0,
creatureBitmask = 264,
stfName = "mob/creature_names",
objectCRC = 1449644294,
positionX = 19.290001,
positionY = -41.959999,
positionZ = 0.200000,
directionX = -0.000001,
directionZ = 0.000000,
directionY = 0.519065,
directionW = 0.854735,
randomMovement = 0,
mood = "neutral",
cellID = 1418875
}
corvetteNpc10 = Creature:new {
objectName = "corvetteNpc10",
creatureType = "NPC",
speciesName = "vyrke",
combatFlags = 0,
creatureBitmask = 264,
stfName = "npc_spawner_n",
objectCRC = 3852132037,
positionX = 23.127373,
positionY = -42.530930,
positionZ = 0.200000,
directionX = -0.000002,
directionZ = 0.000000,
directionY = 0.110912,
directionW = 0.993830,
randomMovement = 0,
mood = "npc_imperial",
cellID = 1418875
}
corvetteNpc11 = Creature:new {
objectName = "corvetteNpc11",
creatureType = "NPC",
speciesName = "mouse_droid",
combatFlags = 0,
creatureBitmask = 264,
stfName = "mob/creature_names",
objectCRC = 1579087581,
positionX = 23.830000,
positionY = -40.419998,
positionZ = 0.200000,
directionX = 0.000000,
directionZ = 0.000000,
directionY = 0.935313,
directionW = 0.353856,
randomMovement = 0,
mood = "neutral",
cellID = 1418875
}
corvetteNpc12 = Creature:new {
objectName = "corvetteNpc12",
creatureType = "NPC",
combatFlags = 0,
creatureBitmask = 264,
stfName = "Lt. Velso",
objectCRC = 3435443235,
positionX = 23.625877,
positionY = -19.098454,
positionZ = 0.200000,
directionX = 0.000001,
directionZ = 0.000007,
directionY = 0.915357,
directionW = -0.402642,
randomMovement = 0,
mood = "npc_imperial",
cellID = 1418874
}
corvetteNpc17 = Creature:new {
objectName = "corvetteNpc17",
creatureType = "NPC",
speciesName = "mouse_droid",
combatFlags = 0,
creatureBitmask = 264,
stfName = "mob/creature_names",
objectCRC = 1579087581,
positionX = 12.250561,
positionY = -24.380045,
positionZ = 0.199998,
directionX = 0.000000,
directionZ = 0.000000,
directionY = 0.591327,
directionW = 0.806455,
randomMovement = 0,
mood = "neutral",
cellID = 1418874
}
corvetteNpc18 = Creature:new {
objectName = "corvetteNpc18",
creatureType = "NPC",
combatFlags = 0,
creatureBitmask = 264,
stfName = "Wurson Harro",
objectCRC = 67035887,
positionX = 33.341969,
positionY = -35.839436,
positionZ = 0.200000,
directionX = -0.000003,
directionZ = 0.000000,
directionY = 0.075535,
directionW = 0.997143,
randomMovement = 0,
mood = "npc_imperial",
cellID = 1418873
}
corvetteNpc19 = Creature:new {
objectName = "corvetteNpc19",
creatureType = "NPC",
speciesName = "kaja_orzee",
combatFlags = 0,
creatureBitmask = 264,
stfName = "mob/creature_names",
objectCRC = 2220741380,
positionX = 2.060000,
positionY = -13.740000,
positionZ = 0.200000,
directionX = -0.000003,
directionZ = -0.000001,
directionY = 0.673244,
directionW = 0.739421,
randomMovement = 0,
mood = "neutral",
cellID = 1418872
}
corvetteNpc20 = Creature:new {
objectName = "corvetteNpc20",
creatureType = "NPC",
speciesName = "fa_zoll",
combatFlags = 0,
creatureBitmask = 264,
stfName = "npc_spawner_n",
objectCRC = 2167455850,
positionX = 2444.228271,
positionY = -3896.671143,
positionZ = 292.000000,
directionX = 0.000000,
directionZ = 0.000000,
directionY = 0.977988,
directionW = -0.208663,
randomMovement = 0,
mood = "npc_imperial",
cellID = 0
}
corvetteNpc21 = Creature:new {
objectName = "corvetteNpc21",
creatureType = "NPC",
combatFlags = 0,
creatureBitmask = 264,
stfName = "Captain Thrawn",
objectCRC = 721694525,
positionX = 2369.500000,
positionY = -3922.000000,
positionZ = 291.909363,
directionX = 0.000000,
directionZ = 0.000000,
directionY = 0.684220,
directionW = 0.729275,
randomMovement = 0,
mood = "",
cellID = 0
}
corvetteNpc22 = Creature:new {
objectName = "corvetteNpc22",
creatureType = "NPC",
combatFlags = 0,
creatureBitmask = 264,
stfName = "Colonel Veers",
objectCRC = 548983473,
positionX = 2369.000000,
positionY = -3921.000000,
positionZ = 291.909363,
directionX = -0.006290,
directionZ = -0.005092,
directionY = 0.777236,
directionW = 0.629157,
randomMovement = 0,
mood = "conversation",
cellID = 0
}
corvetteNpc23 = Creature:new {
objectName = "corvetteNpc23",
creatureType = "NPC",
combatFlags = 0,
creatureBitmask = 264,
stfName = "DS-602",
objectCRC = 1719126009,
positionX = 2447.500000,
positionY = -3898.000000,
positionZ = 292.000000,
directionX = 0.000000,
directionZ = 0.000000,
directionY = 0.968887,
directionW = -0.247504,
randomMovement = 0,
mood = "npc_sitting_chair",
cellID = 0
}
corvetteNpc24 = Creature:new {
objectName = "corvetteNpc24",
creatureType = "NPC",
combatFlags = 0,
creatureBitmask = 264,
stfName = "DS-753",
objectCRC = 1719126009,
positionX = 2431.979980,
positionY = -3887.320068,
positionZ = 292.000000,
directionX = 0.000000,
directionZ = 0.000000,
directionY = 0.989016,
directionW = -0.147809,
randomMovement = 0,
mood = "npc_use_terminal_high",
cellID = 0
}
corvetteNpc25 = Creature:new {
objectName = "corvetteNpc25",
creatureType = "NPC",
speciesName = "imperial_pilot",
combatFlags = 0,
creatureBitmask = 264,
stfName = "npc_spawner_n",
objectCRC = 3287330740,
positionX = 2413.233643,
positionY = -3939.152832,
positionZ = 292.000000,
directionX = 0.000000,
directionZ = 0.000000,
directionY = 0.982066,
directionW = 0.188536,
randomMovement = 0,
mood = "neutral",
cellID = 0
}
corvetteNpc27 = Creature:new {
objectName = "corvetteNpc27",
creatureType = "NPC",
combatFlags = 0,
creatureBitmask = 264,
stfName = "Lt. Allard Lissara",
objectCRC = 3498321727,
positionX = 2414.937500,
positionY = -3948.007324,
positionZ = 292.000000,
directionX = 0.000000,
directionZ = 0.000000,
directionY = 0.264089,
directionW = 0.964498,
randomMovement = 0,
mood = "npc_imperial",
cellID = 0
}
| lgpl-3.0 |
weiDDD/WSSParticleSystem | cocos2d/external/lua/luasocket/script/socket/tp.lua | 1 | 3753 | -----------------------------------------------------------------------------
-- Unified SMTP/FTP subsystem
-- LuaSocket toolkit.
-- Author: Diego Nehab
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-----------------------------------------------------------------------------
local base = _G
local string = require("string")
local socket = require("socket.socket")
local ltn12 = require("socket.ltn12")
socket.tp = {}
local _M = socket.tp
-----------------------------------------------------------------------------
-- Program constants
-----------------------------------------------------------------------------
_M.TIMEOUT = 60
-----------------------------------------------------------------------------
-- Implementation
-----------------------------------------------------------------------------
-- gets server reply (works for SMTP and FTP)
local function get_reply(c)
local code, current, sep
local line, err = c:receive()
local reply = line
if err then return nil, err end
code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)"))
if not code then return nil, "invalid server reply" end
if sep == "-" then -- reply is multiline
repeat
line, err = c:receive()
if err then return nil, err end
current, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)"))
reply = reply .. "\n" .. line
-- reply ends with same code
until code == current and sep == " "
end
return code, reply
end
-- metatable for sock object
local metat = { __index = {} }
function metat.__index:check(ok)
local code, reply = get_reply(self.c)
if not code then return nil, reply end
if base.type(ok) ~= "function" then
if base.type(ok) == "table" then
for i, v in base.ipairs(ok) do
if string.find(code, v) then
return base.tonumber(code), reply
end
end
return nil, reply
else
if string.find(code, ok) then return base.tonumber(code), reply
else return nil, reply end
end
else return ok(base.tonumber(code), reply) end
end
function metat.__index:command(cmd, arg)
cmd = string.upper(cmd)
if arg then
return self.c:send(cmd .. " " .. arg.. "\r\n")
else
return self.c:send(cmd .. "\r\n")
end
end
function metat.__index:sink(snk, pat)
local chunk, err = c:receive(pat)
return snk(chunk, err)
end
function metat.__index:send(data)
return self.c:send(data)
end
function metat.__index:receive(pat)
return self.c:receive(pat)
end
function metat.__index:getfd()
return self.c:getfd()
end
function metat.__index:dirty()
return self.c:dirty()
end
function metat.__index:getcontrol()
return self.c
end
function metat.__index:source(source, step)
local sink = socket.sink("keep-open", self.c)
local ret, err = ltn12.pump.all(source, sink, step or ltn12.pump.step)
return ret, err
end
-- closes the underlying c
function metat.__index:close()
self.c:close()
return 1
end
-- connect with server and return c object
function _M.connect(host, port, timeout, create)
local c, e = (create or socket.tcp)()
if not c then return nil, e end
c:settimeout(timeout or _M.TIMEOUT)
local r, e = c:connect(host, port)
if not r then
c:close()
return nil, e
end
return base.setmetatable({c = c}, metat)
end
return _M
| apache-2.0 |
Andrettin/Wyrmsun | scripts/species/mammal/perissodactyl/rhinocerotid.lua | 1 | 3972 | -- _________ __ __
-- / _____// |_____________ _/ |______ ____ __ __ ______
-- \_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/
-- / \| | | | \// __ \| | / __ \_/ /_/ > | /\___ \
-- /_______ /|__| |__| (____ /__| (____ /\___ /|____//____ >
-- \/ \/ \//_____/ \/
-- ______________________ ______________________
-- T H E W A R B E G I N S
-- Stratagus - A free fantasy real time strategy game engine
--
-- (c) Copyright 2016-2022 by Andrettin
--
-- 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
DefineSpeciesFamily("rhinocerotidae", { -- Source: Mauricio Antón and Jorge Morales, "Madrid antes del hombre", 2009, pp. 32-33.
Name = "Rhinocerotidae",
Order = "perissodactyla"
})
DefineSpeciesGenus("aceratherium", { -- Source: Mauricio Antón and Jorge Morales, "Madrid antes del hombre", 2009, pp. 54-55.
Name = "Aceratherium",
Family = "rhinocerotidae"
})
DefineSpeciesGenus("hispanotherium", { -- Source: Mauricio Antón and Jorge Morales, "Madrid antes del hombre", 2009, pp. 18, 54-55.
Name = "Hispanotherium",
Family = "rhinocerotidae"
})
DefineSpeciesGenus("rhinoceros", { -- Source: http://www.itis.gov/servlet/SingleRpt/SingleRpt?search_topic=TSN&search_value=624934
Name = "Rhinoceros",
Family = "rhinocerotidae"
})
DefineSpecies("aceratherium-incisivum", { -- Source: Mauricio Antón and Jorge Morales, "Madrid antes del hombre", 2009, pp. 54-55.
Name = "Aceratherium", -- Aceratherium incisivum
Genus = "aceratherium",
Species = "incisivum",
Homeworld = "earth",
Terrains = {"grass", "semi_dry_grass", "dry_grass", "dirt", "dry-mud", "mud"}, -- this species lived in Miocene Madrid, which was mostly arid with a swampy lake in the middle
EvolvesFrom = {"palaeotherium"},
Era = "miocene"
-- lived in Western Europe
-- 120cm shoulder height
-- adapted to eat soft vegetals like bush leaves and fruits, but could also eat a larger range of vegetals according to the situation
})
DefineSpecies("hispanotherium-matritense", { -- Source: Mauricio Antón and Jorge Morales, "Madrid antes del hombre", 2009, pp. 18, 54-55.
Name = "Hispanotherium", -- Madrilenian Hispanotherium
Genus = "hispanotherium",
Species = "matritense",
Homeworld = "earth",
Terrains = {"grass", "semi_dry_grass", "dry_grass", "dirt", "dry-mud", "mud"}, -- this species lived in Miocene Madrid, which was mostly arid with a swampy lake in the middle
EvolvesFrom = {"palaeotherium"},
Era = "miocene" -- Middle and Upper Miocene
-- dwelled in open environments which possessed few trees
-- lived in Western Europe, Turkey and China
-- 100cm shoulder height
-- its teeth were adapted to eat hard vegetable matter
-- adapted to running and to open and dry spaces
})
DefineSpecies("rhinoceros-unicornis", { -- Source: http://www.itis.gov/servlet/SingleRpt/SingleRpt?search_topic=TSN&search_value=625005
Name = "Rhinoceros", -- One-Horned Rhinoceros
Genus = "rhinoceros",
Species = "unicornis",
Homeworld = "earth",
EvolvesFrom = {"aceratherium-incisivum", "hispanotherium-matritense"}, -- earlier Rhinocerotids
Era = "holocene"
})
| gpl-2.0 |
TheAnswer/FirstTest | bin/scripts/object/tangible/lair/salt_mynock/objects.lua | 1 | 6064 | --Copyright (C) 2009 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
object_tangible_lair_salt_mynock_shared_lair_salt_mynock = SharedTangibleObjectTemplate:new {
appearanceFilename = "appearance/defaultappearance.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 25,
clientDataFile = "clientdata/client_shared_lair_small.cdf",
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@lair_d:salt_mynock",
gameObjectType = 4,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 64,
objectName = "@lair_n:salt_mynock",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
useStructureFootprintOutline = 0
}
ObjectTemplates:addTemplate(object_tangible_lair_salt_mynock_shared_lair_salt_mynock, 2598164093)
object_tangible_lair_salt_mynock_shared_lair_salt_mynock_mountain = SharedTangibleObjectTemplate:new {
appearanceFilename = "appearance/defaultappearance.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 25,
clientDataFile = "clientdata/client_shared_lair_small.cdf",
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@lair_d:salt_mynock_mountain",
gameObjectType = 4,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 64,
objectName = "@lair_n:salt_mynock_mountain",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
useStructureFootprintOutline = 0
}
ObjectTemplates:addTemplate(object_tangible_lair_salt_mynock_shared_lair_salt_mynock_mountain, 3617713744)
object_tangible_lair_salt_mynock_shared_lair_salt_mynock_wasteland = SharedTangibleObjectTemplate:new {
appearanceFilename = "appearance/defaultappearance.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 25,
clientDataFile = "clientdata/client_shared_lair_small.cdf",
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@lair_d:salt_mynock_wasteland",
gameObjectType = 4,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 64,
objectName = "@lair_n:salt_mynock_wasteland",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
useStructureFootprintOutline = 0
}
ObjectTemplates:addTemplate(object_tangible_lair_salt_mynock_shared_lair_salt_mynock_wasteland, 4030433492)
| lgpl-3.0 |
JarnoVgr/ZombieSurvival | gamemodes/zombiesurvival/entities/weapons/weapon_zs_boardpack/cl_init.lua | 1 | 2564 | include("shared.lua")
SWEP.PrintName = "Junk Pack"
SWEP.Description = "It's simply a pack of wooden junk kept together with some duct tape.\nVery useful for making barricades when no materials are around.\nNeeds something like a hammer and nails to keep the things in place."
SWEP.ViewModelFOV = 45
SWEP.ViewModelFlip = false
SWEP.Slot = 4
SWEP.SlotPos = 0
function SWEP:DrawHUD()
if GetConVarNumber("crosshair") ~= 1 then return end
self:DrawCrosshairDot()
surface.SetFont("ZSHUDFont")
local text = translate.Get("right_click_to_hammer_nail")
local nails = self:GetPrimaryAmmoCount()
local nTEXW, nTEXH = surface.GetTextSize(text)
draw.SimpleText("Junk", "ZSHUDFont", ScrW() - nTEXW * 0.4 - 24, ScrH() - nTEXH * 2, nails > 0 and COLOR_GREY or COLOR_GREY, TEXT_ALIGN_CENTER)
draw.SimpleText("Pack", "ZSHUDFont", ScrW() - nTEXW * 0.4 - 24, ScrH() - nTEXH * 1.2, nails > 0 and COLOR_GREY or COLOR_GREY, TEXT_ALIGN_CENTER)
local hudsplat3 = Material("hud/hud_bottom_right.png") --Items for the HUD.
local Hud_Image_3 = {
color = Color( 225, 225, 225, 400 ); -- Color overlay of image; white = original color of image
material = Material("hud/hud_bottom_right.png"); -- Material to be used
x = 1600; -- x coordinate for the material to be rendered ( mat is drawn from top left to bottom right )
y = 980; -- y coordinate for the material to be rendered ( mat is drawn from top left to bottom right )
w = 320; -- width of the material to span
h = 100; -- height of the material to span
};
surface.SetMaterial(hudsplat3)
surface.SetDrawColor(225, 225, 225, 200 )
surface.DrawTexturedRect(Hud_Image_3.x, Hud_Image_3.y, Hud_Image_3.w, Hud_Image_3.h)
end
function SWEP:Deploy()
self.IdleAnimation = CurTime() + self:SequenceDuration()
return true
end
function SWEP:DrawWorldModel()
local owner = self.Owner
if owner:IsValid() and self:GetReplicatedAmmo() > 0 then
local id = owner:LookupAttachment("anim_attachment_RH")
if id and id > 0 then
local attch = owner:GetAttachment(id)
if attch then
cam.Start3D(EyePos() + (owner:GetPos() - attch.Pos + Vector(0, 0, 24)), EyeAngles())
self:DrawModel()
cam.End3D()
end
end
end
end
SWEP.DrawWorldModelTranslucent = SWEP.DrawWorldModel
function SWEP:Initialize()
self:SetDeploySpeed(1.1)
end
function SWEP:GetViewModelPosition(pos, ang)
if self:GetPrimaryAmmoCount() <= 0 then
return pos + ang:Forward() * -256, ang
end
return pos, ang
end
function SWEP:DrawWeaponSelection(...)
return self:BaseDrawWeaponSelection(...)
end
| gpl-2.0 |
nullifye/tg-bot-pi | tg_bot/utils.lua | 1 | 4359 | function vardump(value, depth, key)
local linePrefix = ""
local spaces = ""
if key ~= nil then
linePrefix = "["..key.."] = "
end
if depth == nil then
depth = 0
else
depth = depth + 1
for i=1, depth do spaces = spaces .. " " end
end
if type(value) == 'table' then
mTable = getmetatable(value)
if mTable == nil then
print(spaces ..linePrefix.."(table) ")
else
print(spaces .."(metatable) ")
value = mTable
end
for tableKey, tableValue in pairs(value) do
vardump(tableValue, depth, tableKey)
end
elseif type(value) == 'function' or
type(value) == 'thread' or
type(value) == 'userdata' or
value == nil
then
print(spaces..tostring(value))
else
print(spaces..linePrefix.."("..type(value)..") "..tostring(value))
end
end
function exec(cmd)
local f = assert(io.popen( cmd , 'r' ))
output = f:read('*all')
f:close()
return output
end
-- http://stackoverflow.com/a/15706820
-- this uses an custom sorting function ordering by val descending
-- for k,v in sort_pairs(table, function(t,a,b) return t[b] < t[a] end) do
function sort_pairs(t, order)
-- collect the keys
local keys = {}
for k in pairs(t) do keys[#keys+1] = k end
-- if order function given, sort by it by passing the table and keys a, b,
-- otherwise just sort the keys
if order then
table.sort(keys, function(a,b) return order(t, a, b) end)
else
table.sort(keys)
end
-- return the iterator function
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], t[keys[i]]
end
end
end
-- http://unix.stackexchange.com/questions/176249/checking-urls-for-http-code-200
function http_code(url, codes)
statuscode = exec('curl -I -s --connect-timeout 10 "'..url..'" -o /dev/null -w "%{http_code}"')
return string.match(codes, statuscode) ~= nil
end
function filesize(myfile)
local f = assert(io.open( myfile , 'r' ))
output = f:seek('end')
f:close()
return output
end
-- http://stackoverflow.com/a/28665686
function getargs(text)
local t = {}
local e = 0
while true do
local b = e+1
b = text:find("%S",b)
if b == nil then break end
if text:sub(b,b) == "'" then
e = text:find("'",b+1)
b = b+1
elseif text:sub(b,b) == '"' then
e = text:find('"',b+1)
b = b+1
else
e = text:find("%s",b+1)
end
if e == nil then e = #text+1 end
t[#t+1] = text:sub(b,e-1)
if #t > 1 then
--sanitize: remove $ except for the first arg
t[#t] = string.gsub(t[#t], "%$", "")
end
end
return t
end
function command(msg, cmd)
return msg.text == cmd
end
-- Lua implementation of PHP scandir function / http://stackoverflow.com/a/9102300
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- deprecated
function reload_plugins()
package.loaded['./tg_bot/vars'] = nil
package.loaded['./tg_bot/utils'] = nil
--package.loaded['./tg_bot/bot'] = nil
require './tg_bot/vars'
require './tg_bot/utils'
--require './tg_bot/bot'
end
function isadmin(msg)
return string.match(ADMINLIST, msg.from.id) ~= nil
end
function onlytobot(msg)
return msg.to.id == our_id
end
function admintobot(msg)
return isadmin(msg) and onlytobot(msg)
end
function replyto(msg)
if msg.to.type == 'user' then
if msg.to.id == our_id then
return 'user#id'..msg.from.id
else
return 'user#id'..msg.to.id
end
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
end
-- http://lua-users.org/wiki/StringRecipes
function decodeURI(str)
str = string.gsub (str, "+", " ")
str = string.gsub (str, "%%(%x%x)",
function(h) return string.char(tonumber(h,16)) end)
str = string.gsub (str, "\r\n", "\n")
return str
end
function encodeURI(str)
if (str) then
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^%w %-%_%.%~])",
function (c) return string.format ("%%%02X", string.byte(c)) end)
str = string.gsub (str, " ", "+")
end
return str
end
| apache-2.0 |
perusio/lua-uri | lunit-console.lua | 20 | 3449 |
--[[--------------------------------------------------------------------------
This file is part of lunit 0.5.
For Details about lunit look at: http://www.mroth.net/lunit/
Author: Michael Roth <mroth@nessie.de>
Copyright (c) 2006-2008 Michael Roth <mroth@nessie.de>
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.
--]]--------------------------------------------------------------------------
--[[
begin()
run(testcasename, testname)
err(fullname, message, traceback)
fail(fullname, where, message, usermessage)
pass(testcasename, testname)
done()
Fullname:
testcase.testname
testcase.testname:setupname
testcase.testname:teardownname
--]]
require "lunit"
module( "lunit-console", package.seeall )
local function printformat(format, ...)
io.write( string.format(format, ...) )
end
local columns_printed = 0
local function writestatus(char)
if columns_printed == 0 then
io.write(" ")
end
if columns_printed == 60 then
io.write("\n ")
columns_printed = 0
end
io.write(char)
io.flush()
columns_printed = columns_printed + 1
end
local msgs = {}
function begin()
local total_tc = 0
local total_tests = 0
for tcname in lunit.testcases() do
total_tc = total_tc + 1
for testname, test in lunit.tests(tcname) do
total_tests = total_tests + 1
end
end
printformat("Loaded testsuite with %d tests in %d testcases.\n\n", total_tests, total_tc)
end
function run(testcasename, testname)
-- NOP
end
function err(fullname, message, traceback)
writestatus("E")
msgs[#msgs+1] = "Error! ("..fullname.."):\n"..message.."\n\t"..table.concat(traceback, "\n\t") .. "\n"
end
function fail(fullname, where, message, usermessage)
writestatus("F")
local text = "Failure ("..fullname.."):\n"..
where..": "..message.."\n"
if usermessage then
text = text .. where..": "..usermessage.."\n"
end
msgs[#msgs+1] = text
end
function pass(testcasename, testname)
writestatus(".")
end
function done()
printformat("\n\n%d Assertions checked.\n", lunit.stats.assertions )
print()
for i, msg in ipairs(msgs) do
printformat( "%3d) %s\n", i, msg )
end
printformat("Testsuite finished (%d passed, %d failed, %d errors).\n",
lunit.stats.passed, lunit.stats.failed, lunit.stats.errors )
end
| mit |
zhityer/zhityer | plugins/google.lua | 722 | 1037 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searches Google and send results",
usage = "!google [terms]: Searches Google and send results",
patterns = {
"^!google (.*)$",
"^%.[g|G]oogle (.*)$"
},
run = run
}
| gpl-2.0 |
GoogleFrog/Zero-K | LuaUI/utility_two.lua | 17 | 1410 | -- Utility function for ZK
-- Will try to read LUA content from target file and create BACKUP if have a successful read (in user's Spring folder) OR DELETE them if have a failure read
-- This prevent corrupted file from being used.
-- Note: currently only a "table" is considered a valid file
function CheckLUAFileAndBackup(filePath, headerString)
local chunk, err = loadfile(filePath)
local success = false
if (chunk) then --if original content is LUA OK:
local tmp = {}
setfenv(chunk, tmp)
local tab = chunk()
if tab and type(tab) == "table" then
table.save(chunk(),filePath..".bak",headerString) --write to backup
success = true
end
end
if (not success) then --if original content is not LUA OK:
Spring.Log("CheckLUAFileAndBackup","warning", tostring(err) .. " (Now will find backup file)")
chunk, err = loadfile(filePath..".bak")
if (chunk) then --if backup content is LUA OK:
local tmp = {}
setfenv(chunk, tmp)
local tab = chunk()
if tab and type(tab) == "table" then
table.save(chunk(),filePath,headerString) --overwrite original
success = true
end
end
if (not success) then --if backup content is also not LUA OK:
Spring.Log("CheckLUAFileAndBackup","warning", tostring(err) .. " (Backup file not available)")
Spring.Echo(os.remove (filePath)) --delete original
Spring.Echo(os.remove (filePath..".bak")) --delete backup
end
end
end | gpl-2.0 |
TheSuperAlaa/TheSuperBot | tg/test.lua | 210 | 2571 | started = 0
our_id = 0
function vardump(value, depth, key)
local linePrefix = ""
local spaces = ""
if key ~= nil then
linePrefix = "["..key.."] = "
end
if depth == nil then
depth = 0
else
depth = depth + 1
for i=1, depth do spaces = spaces .. " " end
end
if type(value) == 'table' then
mTable = getmetatable(value)
if mTable == nil then
print(spaces ..linePrefix.."(table) ")
else
print(spaces .."(metatable) ")
value = mTable
end
for tableKey, tableValue in pairs(value) do
vardump(tableValue, depth, tableKey)
end
elseif type(value) == 'function' or
type(value) == 'thread' or
type(value) == 'userdata' or
value == nil
then
print(spaces..tostring(value))
else
print(spaces..linePrefix.."("..type(value)..") "..tostring(value))
end
end
print ("HI, this is lua script")
function ok_cb(extra, success, result)
end
-- Notification code {{{
function get_title (P, Q)
if (Q.type == 'user') then
return P.first_name .. " " .. P.last_name
elseif (Q.type == 'chat') then
return Q.title
elseif (Q.type == 'encr_chat') then
return 'Secret chat with ' .. P.first_name .. ' ' .. P.last_name
else
return ''
end
end
local lgi = require ('lgi')
local notify = lgi.require('Notify')
notify.init ("Telegram updates")
local icon = os.getenv("HOME") .. "/.telegram-cli/telegram-pics/telegram_64.png"
function do_notify (user, msg)
local n = notify.Notification.new(user, msg, icon)
n:show ()
end
-- }}}
function on_msg_receive (msg)
if started == 0 then
return
end
if msg.out then
return
end
do_notify (get_title (msg.from, msg.to), msg.text)
if (msg.text == 'ping') then
if (msg.to.id == our_id) then
send_msg (msg.from.print_name, 'pong', ok_cb, false)
else
send_msg (msg.to.print_name, 'pong', ok_cb, false)
end
return
end
if (msg.text == 'PING') then
if (msg.to.id == our_id) then
fwd_msg (msg.from.print_name, msg.id, ok_cb, false)
else
fwd_msg (msg.to.print_name, msg.id, ok_cb, false)
end
return
end
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
--vardump (chat)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
function cron()
-- do something
postpone (cron, false, 1.0)
end
function on_binlog_replay_end ()
started = 1
postpone (cron, false, 1.0)
end
| gpl-2.0 |
Invertika/data | scripts/maps/ow-p0003-o0000-o0000.lua | 1 | 1395 | ----------------------------------------------------------------------------------
-- Map File --
-- --
-- In dieser Datei stehen die entsprechenden externen NPC's, Trigger und --
-- anderer Dinge. --
-- --
----------------------------------------------------------------------------------
-- Copyright 2008 The Invertika Development Team --
-- --
-- This file is part of Invertika. --
-- --
-- Invertika 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 any later version. --
----------------------------------------------------------------------------------
require "scripts/lua/npclib"
require "scripts/libs/warp"
atinit(function()
create_inter_map_warp_trigger(95, 105, 89, 83) --- Intermap warp
end)
| gpl-3.0 |
StaymanHou/Hacking-the-Pentest-Tutor-Game | lib/LoveFrames/objects/multichoice.lua | 7 | 10857 | --[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2012-2014 Kenny Shields --
--]]------------------------------------------------
-- multichoice object
local newobject = loveframes.NewObject("multichoice", "loveframes_object_multichoice", true)
--[[---------------------------------------------------------
- func: initialize()
- desc: initializes the object
--]]---------------------------------------------------------
function newobject:initialize()
self.type = "multichoice"
self.choice = ""
self.text = "Select an option"
self.width = 200
self.height = 25
self.listpadding = 0
self.listspacing = 0
self.buttonscrollamount = 200
self.mousewheelscrollamount = 1500
self.sortfunc = function(a, b) return a < b end
self.haslist = false
self.dtscrolling = true
self.enabled = true
self.internal = false
self.choices = {}
self.listheight = nil
end
--[[---------------------------------------------------------
- func: update(deltatime)
- desc: updates the object
--]]---------------------------------------------------------
function newobject:update(dt)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
local alwaysupdate = self.alwaysupdate
if not visible then
if not alwaysupdate then
return
end
end
local parent = self.parent
local base = loveframes.base
local update = self.Update
self:CheckHover()
-- move to parent if there is a parent
if parent ~= base then
self.x = self.parent.x + self.staticx
self.y = self.parent.y + self.staticy
end
if update then
update(self, dt)
end
end
--[[---------------------------------------------------------
- func: draw()
- desc: draws the object
--]]---------------------------------------------------------
function newobject:draw()
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
local skins = loveframes.skins.available
local skinindex = loveframes.config["ACTIVESKIN"]
local defaultskin = loveframes.config["DEFAULTSKIN"]
local selfskin = self.skin
local skin = skins[selfskin] or skins[skinindex]
local drawfunc = skin.DrawMultiChoice or skins[defaultskin].DrawMultiChoice
local draw = self.Draw
local drawcount = loveframes.drawcount
-- set the object's draw order
self:SetDrawOrder()
if draw then
draw(self)
else
drawfunc(self)
end
end
--[[---------------------------------------------------------
- func: mousepressed(x, y, button)
- desc: called when the player presses a mouse button
--]]---------------------------------------------------------
function newobject:mousepressed(x, y, button)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
local hover = self.hover
local haslist = self.haslist
local enabled = self.enabled
if hover and not haslist and enabled and button == "l" then
local baseparent = self:GetBaseParent()
if baseparent and baseparent.type == "frame" then
baseparent:MakeTop()
end
self.haslist = true
self.list = loveframes.objects["multichoicelist"]:new(self)
self.list:SetState(self.state)
loveframes.downobject = self
end
end
--[[---------------------------------------------------------
- func: mousereleased(x, y, button)
- desc: called when the player releases a mouse button
--]]---------------------------------------------------------
function newobject:mousereleased(x, y, button)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
end
--[[---------------------------------------------------------
- func: AddChoice(choice)
- desc: adds a choice to the current list of choices
--]]---------------------------------------------------------
function newobject:AddChoice(choice)
local choices = self.choices
table.insert(choices, choice)
return self
end
--[[---------------------------------------------------------
- func: RemoveChoice(choice)
- desc: removes the specified choice from the object's
list of choices
--]]---------------------------------------------------------
function newobject:RemoveChoice(choice)
local choices = self.choices
for k, v in ipairs(choices) do
if v == choice then
table.remove(choices, k)
break
end
end
return self
end
--[[---------------------------------------------------------
- func: SetChoice(choice)
- desc: sets the current choice
--]]---------------------------------------------------------
function newobject:SetChoice(choice)
self.choice = choice
return self
end
--[[---------------------------------------------------------
- func: SelectChoice(choice)
- desc: selects a choice
--]]---------------------------------------------------------
function newobject:SelectChoice(choice)
local onchoiceselected = self.OnChoiceSelected
self.choice = choice
if self.list then
self.list:Close()
end
if onchoiceselected then
onchoiceselected(self, choice)
end
return self
end
--[[---------------------------------------------------------
- func: SetListHeight(height)
- desc: sets the height of the list of choices
--]]---------------------------------------------------------
function newobject:SetListHeight(height)
self.listheight = height
return self
end
--[[---------------------------------------------------------
- func: SetPadding(padding)
- desc: sets the padding of the list of choices
--]]---------------------------------------------------------
function newobject:SetPadding(padding)
self.listpadding = padding
return self
end
--[[---------------------------------------------------------
- func: SetSpacing(spacing)
- desc: sets the spacing of the list of choices
--]]---------------------------------------------------------
function newobject:SetSpacing(spacing)
self.listspacing = spacing
return self
end
--[[---------------------------------------------------------
- func: GetValue()
- desc: gets the value (choice) of the object
--]]---------------------------------------------------------
function newobject:GetValue()
return self.choice
end
--[[---------------------------------------------------------
- func: GetChoice()
- desc: gets the current choice (same as get value)
--]]---------------------------------------------------------
function newobject:GetChoice()
return self.choice
end
--[[---------------------------------------------------------
- func: SetText(text)
- desc: sets the object's text
--]]---------------------------------------------------------
function newobject:SetText(text)
self.text = text
return self
end
--[[---------------------------------------------------------
- func: GetText()
- desc: gets the object's text
--]]---------------------------------------------------------
function newobject:GetText()
return self.text
end
--[[---------------------------------------------------------
- func: SetButtonScrollAmount(speed)
- desc: sets the scroll amount of the object's scrollbar
buttons
--]]---------------------------------------------------------
function newobject:SetButtonScrollAmount(amount)
self.buttonscrollamount = amount
return self
end
--[[---------------------------------------------------------
- func: GetButtonScrollAmount()
- desc: gets the scroll amount of the object's scrollbar
buttons
--]]---------------------------------------------------------
function newobject:GetButtonScrollAmount()
return self.buttonscrollamount
end
--[[---------------------------------------------------------
- func: SetMouseWheelScrollAmount(amount)
- desc: sets the scroll amount of the mouse wheel
--]]---------------------------------------------------------
function newobject:SetMouseWheelScrollAmount(amount)
self.mousewheelscrollamount = amount
return self
end
--[[---------------------------------------------------------
- func: GetMouseWheelScrollAmount()
- desc: gets the scroll amount of the mouse wheel
--]]---------------------------------------------------------
function newobject:GetButtonScrollAmount()
return self.mousewheelscrollamount
end
--[[---------------------------------------------------------
- func: SetDTScrolling(bool)
- desc: sets whether or not the object should use delta
time when scrolling
--]]---------------------------------------------------------
function newobject:SetDTScrolling(bool)
self.dtscrolling = bool
return self
end
--[[---------------------------------------------------------
- func: GetDTScrolling()
- desc: gets whether or not the object should use delta
time when scrolling
--]]---------------------------------------------------------
function newobject:GetDTScrolling()
return self.dtscrolling
end
--[[---------------------------------------------------------
- func: Sort(func)
- desc: sorts the object's choices
--]]---------------------------------------------------------
function newobject:Sort(func)
local default = self.sortfunc
if func then
table.sort(self.choices, func)
else
table.sort(self.choices, default)
end
return self
end
--[[---------------------------------------------------------
- func: SetSortFunction(func)
- desc: sets the object's default sort function
--]]---------------------------------------------------------
function newobject:SetSortFunction(func)
self.sortfunc = func
return self
end
--[[---------------------------------------------------------
- func: GetSortFunction(func)
- desc: gets the object's default sort function
--]]---------------------------------------------------------
function newobject:GetSortFunction()
return self.sortfunc
end
--[[---------------------------------------------------------
- func: Clear()
- desc: removes all choices from the object's list
of choices
--]]---------------------------------------------------------
function newobject:Clear()
self.choices = {}
self.choice = ""
self.text = "Select an option"
return self
end
--[[---------------------------------------------------------
- func: SetClickable(bool)
- desc: sets whether or not the object is enabled
--]]---------------------------------------------------------
function newobject:SetEnabled(bool)
self.enabled = bool
return self
end
--[[---------------------------------------------------------
- func: GetEnabled()
- desc: gets whether or not the object is enabled
--]]---------------------------------------------------------
function newobject:GetEnabled()
return self.enabled
end | apache-2.0 |
USABOT6/usabot | plugins/plugins.lua | 325 | 6164 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'. '..v..' '..status..'\n'
end
end
local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled'
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..v..' '..status..'\n'
end
end
local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return 'Plugin '..plugin_name..' is enabled'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return 'Plugin '..plugin_name..' does not exists'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return 'Plugin '..name..' does not exists'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return 'Plugin '..name..' not enabled'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "Plugin doesn't exists"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return 'Plugin '..plugin..' disabled on this chat'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'This plugin is not disabled'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return 'Plugin '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == 'enable' and matches[3] == 'chat' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == 'disable' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plugins disable [plugin] chat : disable plugin only this chat.",
"!plugins enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plugins : list all plugins.",
"!plugins enable [plugin] : enable plugin.",
"!plugins disable [plugin] : disable plugin.",
"!plugins reload : reloads all plugins." },
},
patterns = {
"^!plugins$",
"^!plugins? (enable) ([%w_%.%-]+)$",
"^!plugins? (disable) ([%w_%.%-]+)$",
"^!plugins? (enable) ([%w_%.%-]+) (chat)",
"^!plugins? (disable) ([%w_%.%-]+) (chat)",
"^!plugins? (reload)$" },
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end | gpl-2.0 |
Invertika/data | scripts/maps/ow-n0013-p0023-o0000.lua | 1 | 1400 | ----------------------------------------------------------------------------------
-- Map File --
-- --
-- In dieser Datei stehen die entsprechenden externen NPC's, Trigger und --
-- anderer Dinge. --
-- --
----------------------------------------------------------------------------------
-- Copyright 2010 The Invertika Development Team --
-- --
-- This file is part of Invertika. --
-- --
-- Invertika 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 any later version. --
----------------------------------------------------------------------------------
require "scripts/lua/npclib"
require "scripts/libs/warp"
atinit(function()
create_inter_map_warp_trigger(728, 676, 726, 778) --- Intermap warp
end)
| gpl-3.0 |
Invertika/data | scripts/maps/ow-n0015-p0007-o0000.lua | 1 | 1400 | ----------------------------------------------------------------------------------
-- Map File --
-- --
-- In dieser Datei stehen die entsprechenden externen NPC's, Trigger und --
-- anderer Dinge. --
-- --
----------------------------------------------------------------------------------
-- Copyright 2010 The Invertika Development Team --
-- --
-- This file is part of Invertika. --
-- --
-- Invertika 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 any later version. --
----------------------------------------------------------------------------------
require "scripts/lua/npclib"
require "scripts/libs/warp"
atinit(function()
create_inter_map_warp_trigger(814, 762, 812, 864) --- Intermap warp
end)
| gpl-3.0 |
tehran980/Telehsn | plugins/btc.lua | 289 | 1375 | -- See https://bitcoinaverage.com/api
local function getBTCX(amount,currency)
local base_url = 'https://api.bitcoinaverage.com/ticker/global/'
-- Do request on bitcoinaverage, the final / is critical!
local res,code = https.request(base_url..currency.."/")
if code ~= 200 then return nil end
local data = json:decode(res)
-- Easy, it's right there
text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid
-- If we have a number as second parameter, calculate the bitcoin amount
if amount~=nil then
btc = tonumber(amount) / tonumber(data.ask)
text = text.."\n "..currency .." "..amount.." = BTC "..btc
end
return text
end
local function run(msg, matches)
local cur = 'EUR'
local amt = nil
-- Get the global match out of the way
if matches[1] == "!btc" then
return getBTCX(amt,cur)
end
if matches[2] ~= nil then
-- There is a second match
amt = matches[2]
cur = string.upper(matches[1])
else
-- Just a EUR or USD param
cur = string.upper(matches[1])
end
return getBTCX(amt,cur)
end
return {
description = "Bitcoin global average market value (in EUR or USD)",
usage = "!btc [EUR|USD] [amount]",
patterns = {
"^!btc$",
"^!btc ([Ee][Uu][Rr])$",
"^!btc ([Uu][Ss][Dd])$",
"^!btc (EUR) (%d+[%d%.]*)$",
"^!btc (USD) (%d+[%d%.]*)$"
},
run = run
}
| gpl-2.0 |
GoogleFrog/Zero-K | units/corsumo.lua | 1 | 15954 | unitDef = {
unitname = [[corsumo]],
name = [[Sumo]],
description = [[Heavy Assault Jumper - On to Repulse, Off to Attract]],
acceleration = 0.1,
activateWhenBuilt = true,
brakeRate = 0.1,
buildCostEnergy = 1700,
buildCostMetal = 1700,
builder = false,
buildPic = [[CORSUMO.png]],
buildTime = 1700,
canAttack = true,
canGuard = true,
canMove = true,
canPatrol = true,
category = [[LAND]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[64 64 64]],
collisionVolumeTest = 1,
collisionVolumeType = [[ellipsoid]],
corpse = [[DEAD]],
customParams = {
canjump = 1,
jump_range = 360,
jump_height = 110,
jump_speed = 6,
jump_delay = 30,
jump_reload = 15,
jump_from_midair = 0,
jump_rotate_midair = 0,
--description_bp = [[Robô dispersador]],
description_fr = [[Robot Émeutier]],
description_de = [[Springender Sturm Roboter]],
description_pl = [[Ciezki robot szturmowy]],
helptext = [[The Sumo's impressive armor makes it a near-unstoppable sphere of death. It stomps on enemy units to break up their formation and can toss the survivors around with its Gravity Beams. Its stomp is the only way it can damage buildings.]],
--helptext_bp = [[O raio de calor do Sumo é muito poderoso a curto alcançe, mas se dissipa com a distância e é bem mais fraca de longe. A velocidade alta de disparo o torna ideal para lutar contra grandes grupos de unidades baratas. ]],
--helptext_fr = [[Le rayon r chaleur du Sumo est capable de délivrer une puissance de feu important sur un point précis. Plus la cible est proche, plus les dégâts seront importants. La précision du rayon est idéale pour lutter contre de larges vagues d'ennemis, mais l'imposant blindage du Sumo le restreint r une vitesse réduite.]],
--helptext_de = [[Der Sumo nutzt seinen mächtigen Heat Ray in nächster Nähe, auf größerer Entfernung aber verliert er entsprechend an Feuerkraft. Er eignet sich ideal, um größere Gruppen von billigen, feindlichen Einheiten zu vernichten. Bemerkenswert ist, dass der Sumo in die Luft springen kann und schließlich auf feindlichen Einheiten landet, was diesen enormen Schaden zufügt.]],
helptext_pl = [[Sumo posiada imponujaca wytrzymalosc i podwojne promienie grawitacyjne, ktore moga przyciagac lub odpychac inne jednostki. Moze rowniez skakac, co w polaczeniu z jego duza masa pozwala mu zgniatac wrogie jednostki, skaczac na nie.]],
aimposoffset = [[0 6 0]],
midposoffset = [[0 6 0]],
modelradius = [[32]],
},
explodeAs = [[BIG_UNIT]],
footprintX = 4,
footprintZ = 4,
iconType = [[t3jumpjetriot]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
losEmitHeight = 40,
mass = 621,
maxDamage = 13500,
maxSlope = 36,
maxVelocity = 1.15,
maxWaterDepth = 22,
minCloakDistance = 75,
movementClass = [[KBOT4]],
noAutoFire = false,
noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE SUB]],
objectName = [[m-9.s3o]],
onoffable = true,
script = [[corsumo.lua]],
seismicSignature = 4,
selfDestructAs = [[BIG_UNIT]],
sfxtypes = {
explosiongenerators = {
[[custom:sumosmoke]],
[[custom:BEAMWEAPON_MUZZLE_ORANGE]],
},
},
side = [[CORE]],
sightDistance = 480,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[crossFoot]],
trackWidth = 66,
turnRate = 500,
upright = false,
workerTime = 0,
weapons = {
{
def = [[FAKELASER]],
mainDir = [[0 0 1]],
maxAngleDif = 30,
},
{
def = [[GRAVITY_NEG]],
badTargetCategory = [[]],
onlyTargetCategory = [[FIXEDWING HOVER SWIM LAND SHIP GUNSHIP]],
mainDir = [[-1 0 0]],
maxAngleDif = 222,
},
{
def = [[GRAVITY_NEG]],
badTargetCategory = [[]],
onlyTargetCategory = [[FIXEDWING HOVER SWIM LAND SHIP GUNSHIP]],
mainDir = [[1 0 0]],
maxAngleDif = 222,
},
{
def = [[GRAVITY_POS]],
badTargetCategory = [[]],
onlyTargetCategory = [[FIXEDWING HOVER SWIM LAND SHIP GUNSHIP]],
mainDir = [[-1 0 0]],
maxAngleDif = 222,
},
{
def = [[GRAVITY_POS]],
badTargetCategory = [[]],
onlyTargetCategory = [[FIXEDWING HOVER SWIM LAND SHIP GUNSHIP]],
mainDir = [[1 0 0]],
maxAngleDif = 222,
},
{
def = [[LANDING]],
badTargetCategory = [[]],
mainDir = [[1 0 0]],
maxAngleDif = 0,
onlyTargetCategory = [[]],
},
},
weaponDefs = {
FAKELASER = {
name = [[Fake Laser]],
areaOfEffect = 12,
beamlaser = 1,
beamTime = 0.1,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
damage = {
default = 0,
subs = 0,
},
duration = 0.11,
edgeEffectiveness = 0.99,
explosionGenerator = [[custom:flash1green]],
fireStarter = 70,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
largeBeamLaser = true,
laserFlareSize = 5.53,
minIntensity = 1,
noSelfDamage = true,
proximityPriority = 10,
range = 440,
reloadtime = 0.11,
rgbColor = [[0 1 0]],
soundStart = [[weapon/laser/laser_burn5]],
soundTrigger = true,
targetMoveError = 0.05,
texture1 = [[largelaser]],
texture2 = [[flare]],
texture3 = [[flare]],
texture4 = [[smallflare]],
thickness = 5.53,
tolerance = 10000,
turret = false,
weaponType = [[BeamLaser]],
weaponVelocity = 900,
},
GRAVITY_NEG = {
name = [[Attractive Gravity]],
areaOfEffect = 8,
avoidFriendly = false,
burst = 6,
burstrate = 0.01,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
customParams = {
impulse = [[-125]],
},
damage = {
default = 0.001,
planes = 0.001,
subs = 5E-05,
},
duration = 0.0333,
endsmoke = [[0]],
explosionGenerator = [[custom:NONE]],
impactOnly = true,
intensity = 0.7,
interceptedByShieldType = 0,
noSelfDamage = true,
predictBoost = 1,
proximityPriority = -15,
range = 460,
reloadtime = 0.2,
renderType = 4,
rgbColor = [[0 0 1]],
rgbColor2 = [[1 0.5 1]],
size = 2,
soundStart = [[weapon/gravity_fire]],
soundTrigger = true,
startsmoke = [[0]],
thickness = 4,
tolerance = 5000,
turret = true,
weaponTimer = 0.1,
weaponType = [[LaserCannon]],
weaponVelocity = 2200,
},
GRAVITY_POS = {
name = [[Repulsive Gravity]],
areaOfEffect = 8,
avoidFriendly = false,
burst = 6,
burstrate = 0.01,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
customParams = {
impulse = [[125]],
},
damage = {
default = 0.001,
planes = 0.001,
subs = 5E-05,
},
duration = 0.0333,
endsmoke = [[0]],
explosionGenerator = [[custom:NONE]],
impactOnly = true,
intensity = 0.7,
interceptedByShieldType = 0,
noSelfDamage = true,
predictBoost = 1,
proximityPriority = 15,
range = 440,
reloadtime = 0.2,
renderType = 4,
rgbColor = [[1 0 0]],
rgbColor2 = [[1 0.5 1]],
size = 2,
soundStart = [[weapon/gravity_fire]],
soundTrigger = true,
startsmoke = [[0]],
thickness = 4,
tolerance = 5000,
turret = true,
weaponTimer = 0.1,
weaponType = [[LaserCannon]],
weaponVelocity = 2200,
},
HEATRAY = {
name = [[Heat Ray]],
accuracy = 512,
areaOfEffect = 20,
beamWeapon = true,
cegTag = [[HEATRAY_CEG]],
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
damage = {
default = 50,
subs = 2.5,
},
duration = 0.3,
dynDamageExp = 1,
dynDamageInverted = false,
explosionGenerator = [[custom:HEATRAY_HIT]],
fallOffRate = 1,
fireStarter = 90,
heightMod = 1,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
noSelfDamage = true,
proximityPriority = 10,
range = 390,
reloadtime = 0.1,
rgbColor = [[1 0.1 0]],
rgbColor2 = [[1 1 0.25]],
soundStart = [[weapon/heatray_fire]],
thickness = 3,
tolerance = 5000,
turret = true,
weaponType = [[LaserCannon]],
weaponVelocity = 500,
},
PARTICLEBEAM = {
name = [[Auto Particle Beam]],
beamDecay = 0.85,
beamTime = 0.01,
beamttl = 45,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
damage = {
default = 60,
subs = 3,
},
explosionGenerator = [[custom:flash1red]],
fireStarter = 100,
impactOnly = true,
impulseFactor = 0,
interceptedByShieldType = 1,
laserFlareSize = 7.5,
minIntensity = 1,
pitchtolerance = 8192,
range = 320,
reloadtime = 0.5,
rgbColor = [[1 0 0]],
soundStart = [[weapon/laser/mini_laser]],
soundStartVolume = 6,
thickness = 5,
tolerance = 8192,
turret = true,
weaponType = [[BeamLaser]],
},
DISRUPTOR = {
name = [[Disruptor Pulse Beam]],
areaOfEffect = 24,
beamdecay = 0.9,
beamTime = 0.03,
beamttl = 50,
coreThickness = 0.25,
craterBoost = 0,
craterMult = 0,
customparams = {
timeslow_damagefactor = 2,
},
damage = {
default = 250,
},
explosionGenerator = [[custom:flash2purple]],
fireStarter = 30,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
largeBeamLaser = true,
laserFlareSize = 4.33,
minIntensity = 1,
noSelfDamage = true,
range = 320,
reloadtime = 2,
rgbColor = [[0.3 0 0.4]],
soundStart = [[weapon/laser/heavy_laser5]],
soundStartVolume = 3,
soundTrigger = true,
sweepfire = false,
texture1 = [[largelaser]],
texture2 = [[flare]],
texture3 = [[flare]],
texture4 = [[smallflare]],
thickness = 12,
tolerance = 18000,
turret = true,
weaponType = [[BeamLaser]],
weaponVelocity = 500,
},
LANDING = {
name = [[Sumo Landing]],
areaOfEffect = 340,
canattackground = false,
craterBoost = 4,
craterMult = 6,
damage = {
default = 1001.1,
planes = 1001.1,
subs = 50,
},
edgeEffectiveness = 0,
explosionGenerator = [[custom:FLASH64]],
impulseBoost = 0.5,
impulseFactor = 1,
interceptedByShieldType = 1,
noSelfDamage = true,
range = 5,
reloadtime = 13,
soundHit = [[krog_stomp]],
soundStart = [[krog_stomp]],
soundStartVolume = 3,
startsmoke = [[1]],
turret = false,
weaponType = [[Cannon]],
weaponVelocity = 5,
customParams = {
hidden = true
}
},
},
featureDefs = {
DEAD = {
description = [[Wreckage - Sumo]],
blocking = true,
category = [[corpses]],
damage = 13500,
energy = 0,
featureDead = [[HEAP]],
featurereclamate = [[SMUDGE01]],
footprintX = 3,
footprintZ = 3,
height = [[20]],
hitdensity = [[100]],
metal = 680,
object = [[m-9_wreck.s3o]],
reclaimable = true,
reclaimTime = 680,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
HEAP = {
description = [[Debris - Sumo]],
blocking = false,
category = [[heaps]],
damage = 13500,
energy = 0,
featurereclamate = [[SMUDGE01]],
footprintX = 3,
footprintZ = 3,
height = [[4]],
hitdensity = [[100]],
metal = 340,
object = [[debris3x3a.s3o]],
reclaimable = true,
reclaimTime = 340,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
},
}
return lowerkeys({ corsumo = unitDef })
| gpl-2.0 |
remakeelectric/luci | protocols/luci-proto-relay/luasrc/model/cbi/admin_network/proto_relay.lua | 70 | 1945 | -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
local ipaddr, network
local forward_bcast, forward_dhcp, gateway, expiry, retry, table
ipaddr = section:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Address to access local relay bridge"))
ipaddr.datatype = "ip4addr"
network = s:taboption("general", DynamicList, "network", translate("Relay between networks"))
network.widget = "checkbox"
network.exclude = arg[1]
network.template = "cbi/network_netlist"
network.nocreate = true
network.nobridges = true
network.novirtual = true
network:depends("proto", "relay")
forward_bcast = section:taboption("advanced", Flag, "forward_bcast",
translate("Forward broadcast traffic"))
forward_bcast.default = forward_bcast.enabled
forward_dhcp = section:taboption("advanced", Flag, "forward_dhcp",
translate("Forward DHCP traffic"))
forward_dhcp.default = forward_dhcp.enabled
gateway = section:taboption("advanced", Value, "gateway",
translate("Use DHCP gateway"),
translate("Override the gateway in DHCP responses"))
gateway.datatype = "ip4addr"
gateway:depends("forward_dhcp", forward_dhcp.enabled)
expiry = section:taboption("advanced", Value, "expiry",
translate("Host expiry timeout"),
translate("Specifies the maximum amount of seconds after which hosts are presumed to be dead"))
expiry.placeholder = "30"
expiry.datatype = "min(1)"
retry = section:taboption("advanced", Value, "retry",
translate("ARP retry threshold"),
translate("Specifies the maximum amount of failed ARP requests until hosts are presumed to be dead"))
retry.placeholder = "5"
retry.datatype = "min(1)"
table = section:taboption("advanced", Value, "table",
translate("Use routing table"),
translate("Override the table used for internal routes"))
table.placeholder = "16800"
table.datatype = "range(0,65535)"
| apache-2.0 |
teleofis/OpenWRT | feeds/routing/cjdns/lua/cjdns/admin.lua | 9 | 2664 | -- Cjdns admin module for Lua
-- Written by Philip Horger
common = require 'cjdns/common'
AdminInterface = {}
AdminInterface.__index = AdminInterface
common.AdminInterface = AdminInterface
function AdminInterface.new(properties)
properties = properties or {}
properties.host = properties.host or "127.0.0.1"
properties.port = properties.port or 11234
properties.password = properties.password or nil
properties.config = properties.config or common.ConfigFile.new("/etc/cjdroute.conf", false)
properties.timeout = properties.timeout or 2
properties.udp = common.UDPInterface.new(properties)
return setmetatable(properties, AdminInterface)
end
function AdminInterface:send(object)
local bencoded, err = bencode.encode(object)
if err then
return nil, err
end
local sock_obj = assert(socket.udp())
sock_obj:settimeout(self.timeout)
local _, err = sock_obj:sendto(bencoded, self.host, self.port)
if err then
return nil, err
end
return sock_obj
end
function AdminInterface:recv(sock_obj)
local retrieved, err = sock_obj:receive()
if not retrieved then
return nil, "ai:recv > " .. err
end
local bencoded, err = bencode.decode(retrieved)
if bencoded then
return bencoded
else
return nil, "ai:recv > " .. err
end
end
function AdminInterface:call(request)
local sock_obj, err = self:send(request)
if err then
return nil, "ai:call > " .. err
end
return self:recv(sock_obj)
end
function AdminInterface:getCookie()
local cookie_response, err = self:call({ q = "cookie" })
if not cookie_response then
return nil, "ai:getCookie > " .. err
end
return cookie_response.cookie
end
function AdminInterface:auth(request)
local funcname = request.q
local args = {}
for k, v in pairs(request) do
args[k] = v
end
-- Step 1: Get cookie
local cookie, err = self:getCookie()
if err then
return nil, err
end
-- Step 2: Calculate hash1 (password + cookie)
local plaintext1 = self.password .. cookie
local hash1 = sha2.sha256hex(plaintext1)
-- Step 3: Calculate hash2 (intermediate stage request)
local request = {
q = "auth",
aq = funcname,
args = args,
hash = hash1,
cookie = cookie
}
local plaintext2, err = bencode.encode(request)
if err then
return nil, err
end
local hash2 = sha2.sha256hex(plaintext2)
-- Step 4: Update hash in request, then ship it out
request.hash = hash2
return self:call(request)
end
| gpl-2.0 |
fliping/flip | lib/lmmdb.lua | 2 | 12030 | -- -*- mode: lua; tab-width: 2; indent-tabs-mode: 1; st-rulers: [70] -*-
-- vim: ts=4 sw=4 ft=lua noet
---------------------------------------------------------------------
-- @author Daniel Barney <daniel@pagodabox.com>
-- @copyright 2014, Pagoda Box, Inc.
-- @doc
--
-- @end
-- Created : 6 Feb 2015 by Daniel Barney <daniel@pagodabox.com>
---------------------------------------------------------------------
local ffi = require("ffi")
local fs = require("fs")
local raw = require('luvi').bundle.readfile('extention/mdb/libraries/liblmdb/liblmdb.so')
fs.writeFileSync('/tmp/mdb.so',raw)
local lmdb = ffi.load('/tmp/mdb.so')
ffi.cdef[[
char* mdb_version (int* major, int* minor, int* patch);
char* mdb_strerror (int err);
]]
local MDB = {}
function MDB.version()
local major = ffi.new("int[1]", 0)
local minor = ffi.new("int[1]", 0)
local patch = ffi.new("int[1]", 0)
local version = lmdb.mdb_version(major,minor,patch)
return ffi.string(version),major[0],minor[0],patch[0]
end
function MDB.error(err)
if err == 0 then return end
local num = ffi.new("int", err)
local res = lmdb.mdb_strerror(num)
return ffi.string(res)
end
local Env =
{MDB_FIXEDMAP = 0x01
,MDB_NOSUBDIR = 0x4000
,MDB_NOSYNC = 0x10000
,MDB_RDONLY = 0x20000
,MDB_NOMETASYNC = 0x40000
,MDB_WRITEMAP = 0x80000
,MDB_MAPASYNC = 0x100000
,MDB_NOTLS = 0x200000
,MDB_NOLOCK = 0x400000
,MDB_NORDAHEAD = 0x800000
,MDB_NOMEMINIT = 0x1000000}
ffi.cdef[[
typedef void* MDB_env;
typedef int mdb_mode_t;
typedef int mdb_filehandle_t;
typedef unsigned int MDB_dbi;
typedef void* MDB_txn;
typedef void* MDB_cursor;
typedef struct {
unsigned int ms_psize;
unsigned int ms_depth;
size_t ms_branch_pages;
size_t ms_leaf_pages;
size_t ms_overflow_pages;
size_t ms_entries;
} MDB_stat;
typedef struct {
void * me_mapaddr;
size_t me_mapsize;
size_t me_last_pgno;
size_t me_last_txnid;
unsigned int me_maxreaders;
unsigned int me_numreaders;
} MDB_envinfo;
typedef struct {
size_t mv_size;
void * mv_data;
} MDB_val;
typedef int MDB_cursor_op;
]]
local EnvFunctions =
[[int mdb_env_create (MDB_env *env);
int mdb_env_open (MDB_env env, const char *path, unsigned int flags, mdb_mode_t mode);
int mdb_env_copy (MDB_env env, const char *path);
int mdb_env_stat (MDB_env env, MDB_stat *stat);
int mdb_env_info (MDB_env env, MDB_envinfo *stat);
int mdb_env_sync (MDB_env env, int force);
void mdb_env_close (MDB_env env);
int mdb_env_set_flags (MDB_env env, unsigned int flags, int onoff);
int mdb_env_get_flags (MDB_env env, unsigned int *flags);
int mdb_env_get_path (MDB_env env, const char **path);
int mdb_env_get_fd (MDB_env env, mdb_filehandle_t *fd);
int mdb_env_set_mapsize (MDB_env env, size_t size);
int mdb_env_set_maxreaders (MDB_env env, unsigned int readers);
int mdb_env_get_maxreaders (MDB_env env, unsigned int *readers);
int mdb_env_set_maxdbs (MDB_env env, MDB_dbi dbs);
int mdb_env_get_maxkeysize (MDB_env env);
int mdb_env_set_userctx (MDB_env env, void *ctx);
int mdb_txn_begin (MDB_env env, MDB_txn *parent, unsigned int flags, MDB_txn *txn);
int mdb_reader_check (MDB_env env, int *dead);]]
local TxnFunctions =
[[MDB_env* mdb_txn_env (MDB_txn txn);
int mdb_txn_commit (MDB_txn txn);
void mdb_txn_abort (MDB_txn txn);
void mdb_txn_reset (MDB_txn txn);
int mdb_txn_renew (MDB_txn txn);
int mdb_stat (MDB_txn txn, MDB_dbi dbi, MDB_stat *stat);
int mdb_dbi_flags (MDB_txn txn, MDB_dbi dbi, unsigned int *flags);
int mdb_drop (MDB_txn txn, MDB_dbi dbi, int del);
int mdb_set_relctx (MDB_txn txn, MDB_dbi dbi, void *ctx);
int mdb_put (MDB_txn txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned int flags);
int mdb_del (MDB_txn txn, MDB_dbi dbi, MDB_val *key, MDB_val *data);
int mdb_cursor_open (MDB_txn txn, MDB_dbi dbi, MDB_cursor *cursor);
int mdb_cursor_renew (MDB_txn txn, MDB_cursor cursor);]]
local CursorFunctions =
[[void mdb_cursor_close (MDB_cursor cursor);
MDB_txn* mdb_cursor_txn (MDB_cursor cursor);
MDB_dbi mdb_cursor_dbi (MDB_cursor cursor);
int mdb_cursor_put (MDB_cursor cursor, MDB_val *key, MDB_val *data, unsigned int flags);
int mdb_cursor_del (MDB_cursor cursor, unsigned int flags);
int mdb_cursor_count (MDB_cursor cursor, size_t *countp);]]
local odd_functions =
[[int mdb_cursor_get (MDB_cursor cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op);
int mdb_get (MDB_txn txn, MDB_dbi dbi, MDB_val *key, MDB_val *data);
void mdb_dbi_close (MDB_env env, MDB_dbi dbi);
int mdb_dbi_open (MDB_txn txn, const char *name, unsigned int flags, MDB_dbi *dbi);]]
local unimplemented =
[[int mdb_set_compare (MDB_txn txn, MDB_dbi dbi, MDB_cmp_func *cmp);
int mdb_set_dupsort (MDB_txn txn, MDB_dbi dbi, MDB_cmp_func *cmp);
int mdb_set_relfunc (MDB_txn txn, MDB_dbi dbi, MDB_rel_func *rel);
int mdb_reader_list (MDB_env env, MDB_msg_func *func, void *ctx);
int mdb_cmp (MDB_txn txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b);
int mdb_dcmp (MDB_txn txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b);]]
ffi.cdef(EnvFunctions)
ffi.cdef(TxnFunctions)
ffi.cdef(CursorFunctions)
ffi.cdef(odd_functions)
function Env.create()
local pointer = ffi.new("MDB_env[1]",ffi.new("MDB_env",nil))
local err = lmdb.mdb_env_create(pointer)
return pointer[0],MDB.error(err)
end
function Env.open(env,path,flags,mode)
local err = lmdb.mdb_env_open(env,path,flags,mode)
return MDB.error(err)
end
function Env.copy(env,path)
local err = lmdb.mdb_env_copy(env,path)
return MDB.error(err)
end
local MDB_stat
local _MDB_stat = {}
MDB_stat = ffi.metatype("MDB_stat", _MDB_stat)
function Env.stat(env)
local stat = ffi.new("MDB_stat[1]",MDB_stat())
local err = lmdb.mdb_env_stat(env,stat)
return stat[0],MDB.error(err)
end
local MDB_envinfo
local _MDB_envinfo = {}
MDB_envinfo = ffi.metatype("MDB_envinfo", _MDB_envinfo)
function Env.info(env)
local stat = ffi.new("MDB_envinfo[1]",MDB_envinfo())
local err = lmdb.mdb_env_info(env,stat)
return stat[0],MDB.error(err)
end
function Env.sync(env,force)
if force then
force = 1
else
force = 0
end
local err = lmdb.mdb_env_sync(env,force)
return MDB.error(err)
end
function Env.close(env)
lmdb.mdb_env_close(env)
end
function Env.set_flags(env,flags,onoff)
if onoff then
onoff = 1
else
onoff = 0
end
local err = lmdb.mdb_env_set_flags(env,flags,onoff)
return MDB.error(err)
end
function Env.get_flags(env)
local flags = ffi.new("unsigned int[1]",0)
local err = lmdb.mdb_env_get_flags(env,flags)
return flags[0],MDB.error(err)
end
function Env.get_path(env)
local path = ffi.new("char*[1]",ffi.new("char*"))
local err = lmdb.mdb_env_get_path(env,ffi.cast("const char**",path))
return ffi.string(path[0]),MDB.error(err)
end
function Env.get_fd(env)
local fd = ffi.new("mdb_filehandle_t[1]")
local err = lmdb.mdb_env_get_fd(env,fd)
return fd[0],MDB.error(err)
end
function Env.set_mapsize(env,size)
local err = lmdb.mdb_env_set_mapsize(env,size)
return MDB.error(err)
end
function Env.set_maxreaders(env,readers)
local err = lmdb.mdb_env_set_maxreaders(env,readers)
return MDB.error(err)
end
function Env.get_maxreaders(env)
local readers = ffi.new("unsigned int[1]")
local err = lmdb.mdb_env_get_maxreaders(env,readers)
return readers[0],MDB.error(err)
end
function Env.set_maxdbs(env,max_dbs)
local err = lmdb.mdb_env_set_maxdbs(env,max_dbs)
return MDB.error(err)
end
function Env.get_maxkeysize(env)
local err = lmdb.mdb_env_get_maxkeysize(env)
return MDB.error(err)
end
-- function Env.get_context(env)
-- return lmdb.mdb_env_get_userctx(env)
-- end
-- function Env.set_context(env,context)
-- local err = lmdb.mdb_env_set_userctx(env,context)
-- return MDB.error(err)
-- end
function Env.reader_check(env)
local dead = ffi.new("unsigned int[1]")
local err = lmdb.mdb_reader_check(env,dead)
return dead[0],MDB.error(err)
end
function Env.txn_begin(env,parent,flags)
local txn = ffi.new("MDB_txn[1]",ffi.new("MDB_txn"))
local err = lmdb.mdb_txn_begin(env,parent,flags,txn)
return txn[0],MDB.error(err)
end
local Txn =
{MDB_RDONLY = 0x20000
,MDB_NOOVERWRITE = 0x10
,MDB_NODUPDATA = 0x20
,MDB_CURRENT = 0x40
,MDB_RESERVE = 0x10000
,MDB_APPEND = 0x20000
,MDB_APPENDDUP = 0x40000
,MDB_MULTIPLE = 0x80000}
function Txn.env(txn)
return lmdb.mdb_txn_env(txn)
end
function Txn.commit(txn)
return MDB.error(lmdb.mdb_txn_commit(txn))
end
function Txn.abort(txn)
lmdb.mdb_txn_abort(txn)
end
function Txn.reset(txn)
lmdb.mdb_txn_reset(txn)
end
function Txn.renew(txn)
return MDB.error(lmdb.mdb_txn_renew(txn))
end
function Txn.put(txn,dbi,key,data,flags)
local index = build_MDB_val(key)
local value = build_MDB_val(data)
local err = lmdb.mdb_put(txn,dbi,index,value,flags)
return MDB.error(err)
end
function Txn.get(txn,dbi,key,cast)
local value = ffi.new("MDB_val[1]")
local lookup = build_MDB_val(key)
local err = lmdb.mdb_get(txn,dbi,lookup,value)
local string
if err == 0 then
string = build_return(value,cast)
end
return string,MDB.error(err)
end
function Txn.del(txn,dbi,key,data)
local index = build_MDB_val(key)
local value
if data then
value = build_MDB_val(data)
end
local err = lmdb.mdb_del(txn,dbi,index,value)
return MDB.error(err)
end
local DB =
{MDB_REVERSEKEY = 0x02
,MDB_DUPSORT = 0x04
,MDB_INTEGERKEY = 0x08
,MDB_DUPFIXED = 0x10
,MDB_INTEGERDUP = 0x20
,MDB_REVERSEDUP = 0x40
,MDB_CREATE = 0x40000}
function DB.open(txn,name,flags)
local index = ffi.new("MDB_dbi[1]")
local err = lmdb.mdb_dbi_open(txn,name,flags,index)
return index[0],MDB.error(err)
end
function DB.close(txn,dbi)
lmdb.mdb_dbi_close(txn,dbi)
end
function DB.flags(txn,dbi)
local flags = ffi.new("unsigned int[1]")
local err = lmdb.mdb_dbi_flags(txn,dbi,flags)
return flags[0],MDB.error(err)
end
function DB.stat(txn,dbi)
local stat = ffi.new("MDB_stat[1]")
local err = lmdb.mdb_stat(txn,dbi,stat)
return stat[0],MDB.error(err)
end
function DB.drop(txn,dbi,del)
local err = lmdb.mdb_drop(txn,dbi,del)
return MDB.error(err)
end
local Cursor =
{MDB_FIRST = 0
,MDB_FIRST_DUP = 1
,MDB_GET_BOTH = 2
,MDB_GET_BOTH_RANGE = 3
,MDB_GET_CURRENT = 4
,MDB_GET_MULTIPLE = 5
,MDB_LAST = 6
,MDB_LAST_DUP = 7
,MDB_NEXT = 8
,MDB_NEXT_DUP = 9
,MDB_NEXT_MULTIPLE = 10
,MDB_NEXT_NODUP = 11
,MDB_PREV = 12
,MDB_PREV_DUP = 13
,MDB_PREV_NODUP = 14
,MDB_SET = 15
,MDB_SET_KEY = 16
,MDB_SET_RANGE = 17}
function Cursor.open(txn,dbi)
local cursor = ffi.new("MDB_cursor[1]",ffi.new("MDB_cursor"))
local err = lmdb.mdb_cursor_open(txn,dbi,cursor)
return cursor[0],MDB.error(err)
end
function Cursor.close(cursor)
lmdb.mdb_cursor_close(cursor)
end
function Cursor.get(cursor,key,op,icast,cast)
local index = build_MDB_val(key)
local value = ffi.new("MDB_val[1]")
value[0].mv_data = ffi.cast("void*",nil)
value[0].mv_size = 0
local err = lmdb.mdb_cursor_get(cursor,index,value,op)
if not (err == 0) then
return nil,nil,MDB.error(err)
else
index = build_return(index,icast)
value = build_return(value,cast)
return index,value,MDB.error(err)
end
end
function build_return(value,cast)
if cast then
if not (ffi.sizeof(cast) == value[0].mv_size) then
p("cast looses precision",cast,ffi.sizeof(cast),value[0].mv_size)
end
return ffi.cast(cast,value[0].mv_data)
elseif value then
return ffi.string(value[0].mv_data,value[0].mv_size)
end
end
function build_MDB_val(elem)
local value = ffi.new("MDB_val[1]")
if type(elem) == "cdata" then
value[0].mv_data = ffi.cast("void*",elem)
value[0].mv_size = ffi.sizeof(elem)
elseif type(elem) == "number" then
value[0].mv_data = ffi.cast("void*",ffi.new("long[1]",elem))
value[0].mv_size = ffi.sizeof("long")
else
value[0].mv_data = ffi.cast("void*",elem)
if elem then
value[0].mv_size = #elem
else
value[0].mv_size = 0
end
end
return value
end
p("using Lightning Memory Mapped Database",MDB.version())
return {Env = Env,DB = DB, Txn = Txn,Cursor = Cursor} | mit |
Invertika/data | scripts/maps/ow-n0010-n0024-o0000.lua | 1 | 1400 | ----------------------------------------------------------------------------------
-- Map File --
-- --
-- In dieser Datei stehen die entsprechenden externen NPC's, Trigger und --
-- anderer Dinge. --
-- --
----------------------------------------------------------------------------------
-- Copyright 2010 The Invertika Development Team --
-- --
-- This file is part of Invertika. --
-- --
-- Invertika 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 any later version. --
----------------------------------------------------------------------------------
require "scripts/lua/npclib"
require "scripts/libs/warp"
atinit(function()
create_inter_map_warp_trigger(548, 498, 550, 600) --- Intermap warp
end)
| gpl-3.0 |
GoogleFrog/Zero-K | LuaRules/Gadgets/unit_fix_dropped_startpos.lua | 4 | 2103 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if not gadgetHandler:IsSyncedCode() then
return
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "DroppedStartPos",
desc = "fixes start postion for dropped players",
author = "SirMaverick",
date = "August 3, 2009",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true
}
end
local modOptions = Spring.GetModOptions()
local fudgeFactor = 128 -- added to max to solve edge-of-startpos problem
function gadget:GameFrame(n)
if (n == 1) and (Game.startPosType == 2) then
if modOptions and (modOptions.shuffle == "off" or modOptions.shuffle == 'box') then
-- ok
else
-- don't undo shuffle
gadgetHandler:RemoveGadget()
return
end
-- check if all units are within their start boxes
local units = Spring.GetAllUnits()
for i=1,#units do
repeat -- emulating "continue"
local unitid = units[i]
local allyid = Spring.GetUnitAllyTeam(unitid)
if not allyid then break end
local xmin, zmin, xmax, zmax = Spring.GetAllyTeamStartBox(allyid)
if not xmin then break end
xmin = xmin - fudgeFactor
zmin = zmin - fudgeFactor
xmax = xmax + fudgeFactor
zmax = zmax + fudgeFactor
local x, y, z = Spring.GetUnitPosition(unitid)
if not x then break end
if (GG.PlanetWars and (GG.PlanetWars.unitsByID[unitid] or GG.PlanetWars.hqs)) or (xmin <= x and x <= xmax and zmin <= z and z <= zmax) then
-- all ok
else
-- move into middle of team start box
Spring.SetUnitPosition(unitid, (xmin+xmax)/2, (zmin+zmax)/2)
Spring.GiveOrderToUnit(unitid, CMD.STOP, {}, {});
end
until true
end
gadgetHandler:RemoveGadget()
return
end
end
| gpl-2.0 |
bagobor/cpp2lua-buindings-battle | external/LuaJIT-2.0.4/src/jit/dis_x86.lua | 89 | 29330 | ----------------------------------------------------------------------------
-- LuaJIT x86/x64 disassembler module.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
-- This is a helper module used by the LuaJIT machine code dumper module.
--
-- Sending small code snippets to an external disassembler and mixing the
-- output with our own stuff was too fragile. So I had to bite the bullet
-- and write yet another x86 disassembler. Oh well ...
--
-- The output format is very similar to what ndisasm generates. But it has
-- been developed independently by looking at the opcode tables from the
-- Intel and AMD manuals. The supported instruction set is quite extensive
-- and reflects what a current generation Intel or AMD CPU implements in
-- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3,
-- SSE4.1, SSE4.2, SSE4a and even privileged and hypervisor (VMX/SVM)
-- instructions.
--
-- Notes:
-- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported.
-- * No attempt at optimization has been made -- it's fast enough for my needs.
-- * The public API may change when more architectures are added.
------------------------------------------------------------------------------
local type = type
local sub, byte, format = string.sub, string.byte, string.format
local match, gmatch, gsub = string.match, string.gmatch, string.gsub
local lower, rep = string.lower, string.rep
-- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on.
local map_opc1_32 = {
--0x
[0]="addBmr","addVmr","addBrm","addVrm","addBai","addVai","push es","pop es",
"orBmr","orVmr","orBrm","orVrm","orBai","orVai","push cs","opc2*",
--1x
"adcBmr","adcVmr","adcBrm","adcVrm","adcBai","adcVai","push ss","pop ss",
"sbbBmr","sbbVmr","sbbBrm","sbbVrm","sbbBai","sbbVai","push ds","pop ds",
--2x
"andBmr","andVmr","andBrm","andVrm","andBai","andVai","es:seg","daa",
"subBmr","subVmr","subBrm","subVrm","subBai","subVai","cs:seg","das",
--3x
"xorBmr","xorVmr","xorBrm","xorVrm","xorBai","xorVai","ss:seg","aaa",
"cmpBmr","cmpVmr","cmpBrm","cmpVrm","cmpBai","cmpVai","ds:seg","aas",
--4x
"incVR","incVR","incVR","incVR","incVR","incVR","incVR","incVR",
"decVR","decVR","decVR","decVR","decVR","decVR","decVR","decVR",
--5x
"pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR",
"popUR","popUR","popUR","popUR","popUR","popUR","popUR","popUR",
--6x
"sz*pushaw,pusha","sz*popaw,popa","boundVrm","arplWmr",
"fs:seg","gs:seg","o16:","a16",
"pushUi","imulVrmi","pushBs","imulVrms",
"insb","insVS","outsb","outsVS",
--7x
"joBj","jnoBj","jbBj","jnbBj","jzBj","jnzBj","jbeBj","jaBj",
"jsBj","jnsBj","jpeBj","jpoBj","jlBj","jgeBj","jleBj","jgBj",
--8x
"arith!Bmi","arith!Vmi","arith!Bmi","arith!Vms",
"testBmr","testVmr","xchgBrm","xchgVrm",
"movBmr","movVmr","movBrm","movVrm",
"movVmg","leaVrm","movWgm","popUm",
--9x
"nop*xchgVaR|pause|xchgWaR|repne nop","xchgVaR","xchgVaR","xchgVaR",
"xchgVaR","xchgVaR","xchgVaR","xchgVaR",
"sz*cbw,cwde,cdqe","sz*cwd,cdq,cqo","call farViw","wait",
"sz*pushfw,pushf","sz*popfw,popf","sahf","lahf",
--Ax
"movBao","movVao","movBoa","movVoa",
"movsb","movsVS","cmpsb","cmpsVS",
"testBai","testVai","stosb","stosVS",
"lodsb","lodsVS","scasb","scasVS",
--Bx
"movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi",
"movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI",
--Cx
"shift!Bmu","shift!Vmu","retBw","ret","$lesVrm","$ldsVrm","movBmi","movVmi",
"enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS",
--Dx
"shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb",
"fp*0","fp*1","fp*2","fp*3","fp*4","fp*5","fp*6","fp*7",
--Ex
"loopneBj","loopeBj","loopBj","sz*jcxzBj,jecxzBj,jrcxzBj",
"inBau","inVau","outBua","outVua",
"callVj","jmpVj","jmp farViw","jmpBj","inBad","inVad","outBda","outVda",
--Fx
"lock:","int1","repne:rep","rep:","hlt","cmc","testb!Bm","testv!Vm",
"clc","stc","cli","sti","cld","std","incb!Bm","incd!Vm",
}
assert(#map_opc1_32 == 255)
-- Map for 1st opcode byte in 64 bit mode (overrides only).
local map_opc1_64 = setmetatable({
[0x06]=false, [0x07]=false, [0x0e]=false,
[0x16]=false, [0x17]=false, [0x1e]=false, [0x1f]=false,
[0x27]=false, [0x2f]=false, [0x37]=false, [0x3f]=false,
[0x60]=false, [0x61]=false, [0x62]=false, [0x63]="movsxdVrDmt", [0x67]="a32:",
[0x40]="rex*", [0x41]="rex*b", [0x42]="rex*x", [0x43]="rex*xb",
[0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb",
[0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb",
[0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb",
[0x82]=false, [0x9a]=false, [0xc4]=false, [0xc5]=false, [0xce]=false,
[0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false,
}, { __index = map_opc1_32 })
-- Map for 2nd opcode byte (0F xx). True CISC hell. Hey, I told you.
-- Prefix dependent MMX/SSE opcodes: (none)|rep|o16|repne, -|F3|66|F2
local map_opc2 = {
--0x
[0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret",
"invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu",
--1x
"movupsXrm|movssXrm|movupdXrm|movsdXrm",
"movupsXmr|movssXmr|movupdXmr|movsdXmr",
"movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm",
"movlpsXmr||movlpdXmr",
"unpcklpsXrm||unpcklpdXrm",
"unpckhpsXrm||unpckhpdXrm",
"movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm",
"movhpsXmr||movhpdXmr",
"$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm",
"hintnopVm","hintnopVm","hintnopVm","hintnopVm",
--2x
"movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil,
"movapsXrm||movapdXrm",
"movapsXmr||movapdXmr",
"cvtpi2psXrMm|cvtsi2ssXrVmt|cvtpi2pdXrMm|cvtsi2sdXrVmt",
"movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr",
"cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm",
"cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm",
"ucomissXrm||ucomisdXrm",
"comissXrm||comisdXrm",
--3x
"wrmsr","rdtsc","rdmsr","rdpmc","sysenter","sysexit",nil,"getsec",
"opc3*38",nil,"opc3*3a",nil,nil,nil,nil,nil,
--4x
"cmovoVrm","cmovnoVrm","cmovbVrm","cmovnbVrm",
"cmovzVrm","cmovnzVrm","cmovbeVrm","cmovaVrm",
"cmovsVrm","cmovnsVrm","cmovpeVrm","cmovpoVrm",
"cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm",
--5x
"movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm",
"rsqrtpsXrm|rsqrtssXrm","rcppsXrm|rcpssXrm",
"andpsXrm||andpdXrm","andnpsXrm||andnpdXrm",
"orpsXrm||orpdXrm","xorpsXrm||xorpdXrm",
"addpsXrm|addssXrm|addpdXrm|addsdXrm","mulpsXrm|mulssXrm|mulpdXrm|mulsdXrm",
"cvtps2pdXrm|cvtss2sdXrm|cvtpd2psXrm|cvtsd2ssXrm",
"cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm",
"subpsXrm|subssXrm|subpdXrm|subsdXrm","minpsXrm|minssXrm|minpdXrm|minsdXrm",
"divpsXrm|divssXrm|divpdXrm|divsdXrm","maxpsXrm|maxssXrm|maxpdXrm|maxsdXrm",
--6x
"punpcklbwPrm","punpcklwdPrm","punpckldqPrm","packsswbPrm",
"pcmpgtbPrm","pcmpgtwPrm","pcmpgtdPrm","packuswbPrm",
"punpckhbwPrm","punpckhwdPrm","punpckhdqPrm","packssdwPrm",
"||punpcklqdqXrm","||punpckhqdqXrm",
"movPrVSm","movqMrm|movdquXrm|movdqaXrm",
--7x
"pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pmu",
"pshiftd!Pmu","pshiftq!Mmu||pshiftdq!Xmu",
"pcmpeqbPrm","pcmpeqwPrm","pcmpeqdPrm","emms|",
"vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$",
nil,nil,
"||haddpdXrm|haddpsXrm","||hsubpdXrm|hsubpsXrm",
"movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr",
--8x
"joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj",
"jsVj","jnsVj","jpeVj","jpoVj","jlVj","jgeVj","jleVj","jgVj",
--9x
"setoBm","setnoBm","setbBm","setnbBm","setzBm","setnzBm","setbeBm","setaBm",
"setsBm","setnsBm","setpeBm","setpoBm","setlBm","setgeBm","setleBm","setgBm",
--Ax
"push fs","pop fs","cpuid","btVmr","shldVmru","shldVmrc",nil,nil,
"push gs","pop gs","rsm","btsVmr","shrdVmru","shrdVmrc","fxsave!Dmp","imulVrm",
--Bx
"cmpxchgBmr","cmpxchgVmr","$lssVrm","btrVmr",
"$lfsVrm","$lgsVrm","movzxVrBmt","movzxVrWmt",
"|popcntVrm","ud2Dp","bt!Vmu","btcVmr",
"bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt",
--Cx
"xaddBmr","xaddVmr",
"cmppsXrmu|cmpssXrmu|cmppdXrmu|cmpsdXrmu","$movntiVmr|",
"pinsrwPrWmu","pextrwDrPmu",
"shufpsXrmu||shufpdXrmu","$cmpxchg!Qmp",
"bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR",
--Dx
"||addsubpdXrm|addsubpsXrm","psrlwPrm","psrldPrm","psrlqPrm",
"paddqPrm","pmullwPrm",
"|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm",
"psubusbPrm","psubuswPrm","pminubPrm","pandPrm",
"paddusbPrm","padduswPrm","pmaxubPrm","pandnPrm",
--Ex
"pavgbPrm","psrawPrm","psradPrm","pavgwPrm",
"pmulhuwPrm","pmulhwPrm",
"|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr",
"psubsbPrm","psubswPrm","pminswPrm","porPrm",
"paddsbPrm","paddswPrm","pmaxswPrm","pxorPrm",
--Fx
"|||lddquXrm","psllwPrm","pslldPrm","psllqPrm",
"pmuludqPrm","pmaddwdPrm","psadbwPrm","maskmovqMrm||maskmovdquXrm$",
"psubbPrm","psubwPrm","psubdPrm","psubqPrm",
"paddbPrm","paddwPrm","padddPrm","ud",
}
assert(map_opc2[255] == "ud")
-- Map for three-byte opcodes. Can't wait for their next invention.
local map_opc3 = {
["38"] = { -- [66] 0f 38 xx
--0x
[0]="pshufbPrm","phaddwPrm","phadddPrm","phaddswPrm",
"pmaddubswPrm","phsubwPrm","phsubdPrm","phsubswPrm",
"psignbPrm","psignwPrm","psigndPrm","pmulhrswPrm",
nil,nil,nil,nil,
--1x
"||pblendvbXrma",nil,nil,nil,
"||blendvpsXrma","||blendvpdXrma",nil,"||ptestXrm",
nil,nil,nil,nil,
"pabsbPrm","pabswPrm","pabsdPrm",nil,
--2x
"||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm",
"||pmovsxwqXrm","||pmovsxdqXrm",nil,nil,
"||pmuldqXrm","||pcmpeqqXrm","||$movntdqaXrm","||packusdwXrm",
nil,nil,nil,nil,
--3x
"||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm",
"||pmovzxwqXrm","||pmovzxdqXrm",nil,"||pcmpgtqXrm",
"||pminsbXrm","||pminsdXrm","||pminuwXrm","||pminudXrm",
"||pmaxsbXrm","||pmaxsdXrm","||pmaxuwXrm","||pmaxudXrm",
--4x
"||pmulddXrm","||phminposuwXrm",
--Fx
[0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt",
},
["3a"] = { -- [66] 0f 3a xx
--0x
[0x00]=nil,nil,nil,nil,nil,nil,nil,nil,
"||roundpsXrmu","||roundpdXrmu","||roundssXrmu","||roundsdXrmu",
"||blendpsXrmu","||blendpdXrmu","||pblendwXrmu","palignrPrmu",
--1x
nil,nil,nil,nil,
"||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru",
nil,nil,nil,nil,nil,nil,nil,nil,
--2x
"||pinsrbXrVmu","||insertpsXrmu","||pinsrXrVmuS",nil,
--4x
[0x40] = "||dppsXrmu",
[0x41] = "||dppdXrmu",
[0x42] = "||mpsadbwXrmu",
--6x
[0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu",
[0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu",
},
}
-- Map for VMX/SVM opcodes 0F 01 C0-FF (sgdt group with register operands).
local map_opcvm = {
[0xc1]="vmcall",[0xc2]="vmlaunch",[0xc3]="vmresume",[0xc4]="vmxoff",
[0xc8]="monitor",[0xc9]="mwait",
[0xd8]="vmrun",[0xd9]="vmmcall",[0xda]="vmload",[0xdb]="vmsave",
[0xdc]="stgi",[0xdd]="clgi",[0xde]="skinit",[0xdf]="invlpga",
[0xf8]="swapgs",[0xf9]="rdtscp",
}
-- Map for FP opcodes. And you thought stack machines are simple?
local map_opcfp = {
-- D8-DF 00-BF: opcodes with a memory operand.
-- D8
[0]="faddFm","fmulFm","fcomFm","fcompFm","fsubFm","fsubrFm","fdivFm","fdivrFm",
"fldFm",nil,"fstFm","fstpFm","fldenvVm","fldcwWm","fnstenvVm","fnstcwWm",
-- DA
"fiaddDm","fimulDm","ficomDm","ficompDm",
"fisubDm","fisubrDm","fidivDm","fidivrDm",
-- DB
"fildDm","fisttpDm","fistDm","fistpDm",nil,"fld twordFmp",nil,"fstp twordFmp",
-- DC
"faddGm","fmulGm","fcomGm","fcompGm","fsubGm","fsubrGm","fdivGm","fdivrGm",
-- DD
"fldGm","fisttpQm","fstGm","fstpGm","frstorDmp",nil,"fnsaveDmp","fnstswWm",
-- DE
"fiaddWm","fimulWm","ficomWm","ficompWm",
"fisubWm","fisubrWm","fidivWm","fidivrWm",
-- DF
"fildWm","fisttpWm","fistWm","fistpWm",
"fbld twordFmp","fildQm","fbstp twordFmp","fistpQm",
-- xx C0-FF: opcodes with a pseudo-register operand.
-- D8
"faddFf","fmulFf","fcomFf","fcompFf","fsubFf","fsubrFf","fdivFf","fdivrFf",
-- D9
"fldFf","fxchFf",{"fnop"},nil,
{"fchs","fabs",nil,nil,"ftst","fxam"},
{"fld1","fldl2t","fldl2e","fldpi","fldlg2","fldln2","fldz"},
{"f2xm1","fyl2x","fptan","fpatan","fxtract","fprem1","fdecstp","fincstp"},
{"fprem","fyl2xp1","fsqrt","fsincos","frndint","fscale","fsin","fcos"},
-- DA
"fcmovbFf","fcmoveFf","fcmovbeFf","fcmovuFf",nil,{nil,"fucompp"},nil,nil,
-- DB
"fcmovnbFf","fcmovneFf","fcmovnbeFf","fcmovnuFf",
{nil,nil,"fnclex","fninit"},"fucomiFf","fcomiFf",nil,
-- DC
"fadd toFf","fmul toFf",nil,nil,
"fsub toFf","fsubr toFf","fdivr toFf","fdiv toFf",
-- DD
"ffreeFf",nil,"fstFf","fstpFf","fucomFf","fucompFf",nil,nil,
-- DE
"faddpFf","fmulpFf",nil,{nil,"fcompp"},
"fsubrpFf","fsubpFf","fdivrpFf","fdivpFf",
-- DF
nil,nil,nil,nil,{"fnstsw ax"},"fucomipFf","fcomipFf",nil,
}
assert(map_opcfp[126] == "fcomipFf")
-- Map for opcode groups. The subkey is sp from the ModRM byte.
local map_opcgroup = {
arith = { "add", "or", "adc", "sbb", "and", "sub", "xor", "cmp" },
shift = { "rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar" },
testb = { "testBmi", "testBmi", "not", "neg", "mul", "imul", "div", "idiv" },
testv = { "testVmi", "testVmi", "not", "neg", "mul", "imul", "div", "idiv" },
incb = { "inc", "dec" },
incd = { "inc", "dec", "callUmp", "$call farDmp",
"jmpUmp", "$jmp farDmp", "pushUm" },
sldt = { "sldt", "str", "lldt", "ltr", "verr", "verw" },
sgdt = { "vm*$sgdt", "vm*$sidt", "$lgdt", "vm*$lidt",
"smsw", nil, "lmsw", "vm*$invlpg" },
bt = { nil, nil, nil, nil, "bt", "bts", "btr", "btc" },
cmpxchg = { nil, "sz*,cmpxchg8bQmp,cmpxchg16bXmp", nil, nil,
nil, nil, "vmptrld|vmxon|vmclear", "vmptrst" },
pshiftw = { nil, nil, "psrlw", nil, "psraw", nil, "psllw" },
pshiftd = { nil, nil, "psrld", nil, "psrad", nil, "pslld" },
pshiftq = { nil, nil, "psrlq", nil, nil, nil, "psllq" },
pshiftdq = { nil, nil, "psrlq", "psrldq", nil, nil, "psllq", "pslldq" },
fxsave = { "$fxsave", "$fxrstor", "$ldmxcsr", "$stmxcsr",
nil, "lfenceDp$", "mfenceDp$", "sfenceDp$clflush" },
prefetch = { "prefetch", "prefetchw" },
prefetcht = { "prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2" },
}
------------------------------------------------------------------------------
-- Maps for register names.
local map_regs = {
B = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh",
"r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" },
B64 = { "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil",
"r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" },
W = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di",
"r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w" },
D = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi",
"r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d" },
Q = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" },
M = { "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7",
"mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext!
X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
"xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" },
}
local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" }
-- Maps for size names.
local map_sz2n = {
B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16,
}
local map_sz2prefix = {
B = "byte", W = "word", D = "dword",
Q = "qword",
M = "qword", X = "xword",
F = "dword", G = "qword", -- No need for sizes/register names for these two.
}
------------------------------------------------------------------------------
-- Output a nicely formatted line with an opcode and operands.
local function putop(ctx, text, operands)
local code, pos, hex = ctx.code, ctx.pos, ""
local hmax = ctx.hexdump
if hmax > 0 then
for i=ctx.start,pos-1 do
hex = hex..format("%02X", byte(code, i, i))
end
if #hex > hmax then hex = sub(hex, 1, hmax)..". "
else hex = hex..rep(" ", hmax-#hex+2) end
end
if operands then text = text.." "..operands end
if ctx.o16 then text = "o16 "..text; ctx.o16 = false end
if ctx.a32 then text = "a32 "..text; ctx.a32 = false end
if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end
if ctx.rex then
local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "")..
(ctx.rexx and "x" or "")..(ctx.rexb and "b" or "")
if t ~= "" then text = "rex."..t.." "..text end
ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false
ctx.rex = false
end
if ctx.seg then
local text2, n = gsub(text, "%[", "["..ctx.seg..":")
if n == 0 then text = ctx.seg.." "..text else text = text2 end
ctx.seg = false
end
if ctx.lock then text = "lock "..text; ctx.lock = false end
local imm = ctx.imm
if imm then
local sym = ctx.symtab[imm]
if sym then text = text.."\t->"..sym end
end
ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text))
ctx.mrm = false
ctx.start = pos
ctx.imm = nil
end
-- Clear all prefix flags.
local function clearprefixes(ctx)
ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false
ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false
ctx.rex = false; ctx.a32 = false
end
-- Fallback for incomplete opcodes at the end.
local function incomplete(ctx)
ctx.pos = ctx.stop+1
clearprefixes(ctx)
return putop(ctx, "(incomplete)")
end
-- Fallback for unknown opcodes.
local function unknown(ctx)
clearprefixes(ctx)
return putop(ctx, "(unknown)")
end
-- Return an immediate of the specified size.
local function getimm(ctx, pos, n)
if pos+n-1 > ctx.stop then return incomplete(ctx) end
local code = ctx.code
if n == 1 then
local b1 = byte(code, pos, pos)
return b1
elseif n == 2 then
local b1, b2 = byte(code, pos, pos+1)
return b1+b2*256
else
local b1, b2, b3, b4 = byte(code, pos, pos+3)
local imm = b1+b2*256+b3*65536+b4*16777216
ctx.imm = imm
return imm
end
end
-- Process pattern string and generate the operands.
local function putpat(ctx, name, pat)
local operands, regs, sz, mode, sp, rm, sc, rx, sdisp
local code, pos, stop = ctx.code, ctx.pos, ctx.stop
-- Chars used: 1DFGIMPQRSTUVWXacdfgijmoprstuwxyz
for p in gmatch(pat, ".") do
local x = nil
if p == "V" or p == "U" then
if ctx.rexw then sz = "Q"; ctx.rexw = false
elseif ctx.o16 then sz = "W"; ctx.o16 = false
elseif p == "U" and ctx.x64 then sz = "Q"
else sz = "D" end
regs = map_regs[sz]
elseif p == "T" then
if ctx.rexw then sz = "Q"; ctx.rexw = false else sz = "D" end
regs = map_regs[sz]
elseif p == "B" then
sz = "B"
regs = ctx.rex and map_regs.B64 or map_regs.B
elseif match(p, "[WDQMXFG]") then
sz = p
regs = map_regs[sz]
elseif p == "P" then
sz = ctx.o16 and "X" or "M"; ctx.o16 = false
regs = map_regs[sz]
elseif p == "S" then
name = name..lower(sz)
elseif p == "s" then
local imm = getimm(ctx, pos, 1); if not imm then return end
x = imm <= 127 and format("+0x%02x", imm)
or format("-0x%02x", 256-imm)
pos = pos+1
elseif p == "u" then
local imm = getimm(ctx, pos, 1); if not imm then return end
x = format("0x%02x", imm)
pos = pos+1
elseif p == "w" then
local imm = getimm(ctx, pos, 2); if not imm then return end
x = format("0x%x", imm)
pos = pos+2
elseif p == "o" then -- [offset]
if ctx.x64 then
local imm1 = getimm(ctx, pos, 4); if not imm1 then return end
local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end
x = format("[0x%08x%08x]", imm2, imm1)
pos = pos+8
else
local imm = getimm(ctx, pos, 4); if not imm then return end
x = format("[0x%08x]", imm)
pos = pos+4
end
elseif p == "i" or p == "I" then
local n = map_sz2n[sz]
if n == 8 and ctx.x64 and p == "I" then
local imm1 = getimm(ctx, pos, 4); if not imm1 then return end
local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end
x = format("0x%08x%08x", imm2, imm1)
else
if n == 8 then n = 4 end
local imm = getimm(ctx, pos, n); if not imm then return end
if sz == "Q" and (imm < 0 or imm > 0x7fffffff) then
imm = (0xffffffff+1)-imm
x = format(imm > 65535 and "-0x%08x" or "-0x%x", imm)
else
x = format(imm > 65535 and "0x%08x" or "0x%x", imm)
end
end
pos = pos+n
elseif p == "j" then
local n = map_sz2n[sz]
if n == 8 then n = 4 end
local imm = getimm(ctx, pos, n); if not imm then return end
if sz == "B" and imm > 127 then imm = imm-256
elseif imm > 2147483647 then imm = imm-4294967296 end
pos = pos+n
imm = imm + pos + ctx.addr
if imm > 4294967295 and not ctx.x64 then imm = imm-4294967296 end
ctx.imm = imm
if sz == "W" then
x = format("word 0x%04x", imm%65536)
elseif ctx.x64 then
local lo = imm % 0x1000000
x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo)
else
x = format("0x%08x", imm)
end
elseif p == "R" then
local r = byte(code, pos-1, pos-1)%8
if ctx.rexb then r = r + 8; ctx.rexb = false end
x = regs[r+1]
elseif p == "a" then x = regs[1]
elseif p == "c" then x = "cl"
elseif p == "d" then x = "dx"
elseif p == "1" then x = "1"
else
if not mode then
mode = ctx.mrm
if not mode then
if pos > stop then return incomplete(ctx) end
mode = byte(code, pos, pos)
pos = pos+1
end
rm = mode%8; mode = (mode-rm)/8
sp = mode%8; mode = (mode-sp)/8
sdisp = ""
if mode < 3 then
if rm == 4 then
if pos > stop then return incomplete(ctx) end
sc = byte(code, pos, pos)
pos = pos+1
rm = sc%8; sc = (sc-rm)/8
rx = sc%8; sc = (sc-rx)/8
if ctx.rexx then rx = rx + 8; ctx.rexx = false end
if rx == 4 then rx = nil end
end
if mode > 0 or rm == 5 then
local dsz = mode
if dsz ~= 1 then dsz = 4 end
local disp = getimm(ctx, pos, dsz); if not disp then return end
if mode == 0 then rm = nil end
if rm or rx or (not sc and ctx.x64 and not ctx.a32) then
if dsz == 1 and disp > 127 then
sdisp = format("-0x%x", 256-disp)
elseif disp >= 0 and disp <= 0x7fffffff then
sdisp = format("+0x%x", disp)
else
sdisp = format("-0x%x", (0xffffffff+1)-disp)
end
else
sdisp = format(ctx.x64 and not ctx.a32 and
not (disp >= 0 and disp <= 0x7fffffff)
and "0xffffffff%08x" or "0x%08x", disp)
end
pos = pos+dsz
end
end
if rm and ctx.rexb then rm = rm + 8; ctx.rexb = false end
if ctx.rexr then sp = sp + 8; ctx.rexr = false end
end
if p == "m" then
if mode == 3 then x = regs[rm+1]
else
local aregs = ctx.a32 and map_regs.D or ctx.aregs
local srm, srx = "", ""
if rm then srm = aregs[rm+1]
elseif not sc and ctx.x64 and not ctx.a32 then srm = "rip" end
ctx.a32 = false
if rx then
if rm then srm = srm.."+" end
srx = aregs[rx+1]
if sc > 0 then srx = srx.."*"..(2^sc) end
end
x = format("[%s%s%s]", srm, srx, sdisp)
end
if mode < 3 and
(not match(pat, "[aRrgp]") or match(pat, "t")) then -- Yuck.
x = map_sz2prefix[sz].." "..x
end
elseif p == "r" then x = regs[sp+1]
elseif p == "g" then x = map_segregs[sp+1]
elseif p == "p" then -- Suppress prefix.
elseif p == "f" then x = "st"..rm
elseif p == "x" then
if sp == 0 and ctx.lock and not ctx.x64 then
x = "CR8"; ctx.lock = false
else
x = "CR"..sp
end
elseif p == "y" then x = "DR"..sp
elseif p == "z" then x = "TR"..sp
elseif p == "t" then
else
error("bad pattern `"..pat.."'")
end
end
if x then operands = operands and operands..", "..x or x end
end
ctx.pos = pos
return putop(ctx, name, operands)
end
-- Forward declaration.
local map_act
-- Fetch and cache MRM byte.
local function getmrm(ctx)
local mrm = ctx.mrm
if not mrm then
local pos = ctx.pos
if pos > ctx.stop then return nil end
mrm = byte(ctx.code, pos, pos)
ctx.pos = pos+1
ctx.mrm = mrm
end
return mrm
end
-- Dispatch to handler depending on pattern.
local function dispatch(ctx, opat, patgrp)
if not opat then return unknown(ctx) end
if match(opat, "%|") then -- MMX/SSE variants depending on prefix.
local p
if ctx.rep then
p = ctx.rep=="rep" and "%|([^%|]*)" or "%|[^%|]*%|[^%|]*%|([^%|]*)"
ctx.rep = false
elseif ctx.o16 then p = "%|[^%|]*%|([^%|]*)"; ctx.o16 = false
else p = "^[^%|]*" end
opat = match(opat, p)
if not opat then return unknown(ctx) end
-- ctx.rep = false; ctx.o16 = false
--XXX fails for 66 f2 0f 38 f1 06 crc32 eax,WORD PTR [esi]
--XXX remove in branches?
end
if match(opat, "%$") then -- reg$mem variants.
local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end
opat = match(opat, mrm >= 192 and "^[^%$]*" or "%$(.*)")
if opat == "" then return unknown(ctx) end
end
if opat == "" then return unknown(ctx) end
local name, pat = match(opat, "^([a-z0-9 ]*)(.*)")
if pat == "" and patgrp then pat = patgrp end
return map_act[sub(pat, 1, 1)](ctx, name, pat)
end
-- Get a pattern from an opcode map and dispatch to handler.
local function dispatchmap(ctx, opcmap)
local pos = ctx.pos
local opat = opcmap[byte(ctx.code, pos, pos)]
pos = pos + 1
ctx.pos = pos
return dispatch(ctx, opat)
end
-- Map for action codes. The key is the first char after the name.
map_act = {
-- Simple opcodes without operands.
[""] = function(ctx, name, pat)
return putop(ctx, name)
end,
-- Operand size chars fall right through.
B = putpat, W = putpat, D = putpat, Q = putpat,
V = putpat, U = putpat, T = putpat,
M = putpat, X = putpat, P = putpat,
F = putpat, G = putpat,
-- Collect prefixes.
[":"] = function(ctx, name, pat)
ctx[pat == ":" and name or sub(pat, 2)] = name
if ctx.pos - ctx.start > 5 then return unknown(ctx) end -- Limit #prefixes.
end,
-- Chain to special handler specified by name.
["*"] = function(ctx, name, pat)
return map_act[name](ctx, name, sub(pat, 2))
end,
-- Use named subtable for opcode group.
["!"] = function(ctx, name, pat)
local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end
return dispatch(ctx, map_opcgroup[name][((mrm-(mrm%8))/8)%8+1], sub(pat, 2))
end,
-- o16,o32[,o64] variants.
sz = function(ctx, name, pat)
if ctx.o16 then ctx.o16 = false
else
pat = match(pat, ",(.*)")
if ctx.rexw then
local p = match(pat, ",(.*)")
if p then pat = p; ctx.rexw = false end
end
end
pat = match(pat, "^[^,]*")
return dispatch(ctx, pat)
end,
-- Two-byte opcode dispatch.
opc2 = function(ctx, name, pat)
return dispatchmap(ctx, map_opc2)
end,
-- Three-byte opcode dispatch.
opc3 = function(ctx, name, pat)
return dispatchmap(ctx, map_opc3[pat])
end,
-- VMX/SVM dispatch.
vm = function(ctx, name, pat)
return dispatch(ctx, map_opcvm[ctx.mrm])
end,
-- Floating point opcode dispatch.
fp = function(ctx, name, pat)
local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end
local rm = mrm%8
local idx = pat*8 + ((mrm-rm)/8)%8
if mrm >= 192 then idx = idx + 64 end
local opat = map_opcfp[idx]
if type(opat) == "table" then opat = opat[rm+1] end
return dispatch(ctx, opat)
end,
-- REX prefix.
rex = function(ctx, name, pat)
if ctx.rex then return unknown(ctx) end -- Only 1 REX prefix allowed.
for p in gmatch(pat, ".") do ctx["rex"..p] = true end
ctx.rex = true
end,
-- Special case for nop with REX prefix.
nop = function(ctx, name, pat)
return dispatch(ctx, ctx.rex and pat or "nop")
end,
}
------------------------------------------------------------------------------
-- Disassemble a block of code.
local function disass_block(ctx, ofs, len)
if not ofs then ofs = 0 end
local stop = len and ofs+len or #ctx.code
ofs = ofs + 1
ctx.start = ofs
ctx.pos = ofs
ctx.stop = stop
ctx.imm = nil
ctx.mrm = false
clearprefixes(ctx)
while ctx.pos <= stop do dispatchmap(ctx, ctx.map1) end
if ctx.pos ~= ctx.start then incomplete(ctx) end
end
-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len).
local function create_(code, addr, out)
local ctx = {}
ctx.code = code
ctx.addr = (addr or 0) - 1
ctx.out = out or io.write
ctx.symtab = {}
ctx.disass = disass_block
ctx.hexdump = 16
ctx.x64 = false
ctx.map1 = map_opc1_32
ctx.aregs = map_regs.D
return ctx
end
local function create64_(code, addr, out)
local ctx = create_(code, addr, out)
ctx.x64 = true
ctx.map1 = map_opc1_64
ctx.aregs = map_regs.Q
return ctx
end
-- Simple API: disassemble code (a string) at address and output via out.
local function disass_(code, addr, out)
create_(code, addr, out):disass()
end
local function disass64_(code, addr, out)
create64_(code, addr, out):disass()
end
-- Return register name for RID.
local function regname_(r)
if r < 8 then return map_regs.D[r+1] end
return map_regs.X[r-7]
end
local function regname64_(r)
if r < 16 then return map_regs.Q[r+1] end
return map_regs.X[r-15]
end
-- Public module functions.
module(...)
create = create_
create64 = create64_
disass = disass_
disass64 = disass64_
regname = regname_
regname64 = regname64_
| mit |
Ninjistix/darkstar | scripts/zones/Promyvion-Vahzl/npcs/_0md.lua | 7 | 1058 | -----------------------------------
-- Area: Promyvion vahzl
-- NPC: Memory flux (2)
-----------------------------------
package.loaded["scripts/zones/Promyvion-Vahzl/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Promyvion-Vahzl/TextIDs");
require("scripts/zones/Promyvion-Vahzl/MobIDs");
require("scripts/globals/missions");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus")==3 and not GetMobByID(SOLICITOR):isSpawned()) then
SpawnMob(SOLICITOR):updateClaim(player);
elseif (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus")==4) then
player:startEvent(52);
else
player:messageSpecial(OVERFLOWING_MEMORIES);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 52) then
player:setVar("PromathiaStatus",5);
end
end;
| gpl-3.0 |
Ninjistix/darkstar | scripts/zones/Port_Windurst/npcs/Kohlo-Lakolo.lua | 5 | 10978 | -----------------------------------
-- Area: Port Windurst
-- NPC: Kohlo-Lakolo
-- Invloved In Quests: Truth, Justice, and the Onion Way!,
-- Know One's Onions,
-- Inspector's Gadget,
-- Onion Rings,
-- Crying Over Onions,
-- Wild Card,
-- The Promise
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
function onTrade(player,npc,trade)
TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY);
KnowOnesOnions = player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS);
if (KnowOnesOnions == QUEST_ACCEPTED) then
count = trade:getItemCount();
WildOnion = trade:hasItemQty(4387,4);
if (WildOnion == true and count == 4) then
player:startEvent(398,0,4387);
end
elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then
count = trade:getItemCount();
RarabTail = trade:hasItemQty(4444,1);
if (RarabTail == true and count == 1) then
player:startEvent(378,0,4444);
end
end
end;
function onTrigger(player,npc)
TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY);
KnowOnesOnions = player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS);
InspectorsGadget = player:getQuestStatus(WINDURST,INSPECTOR_S_GADGET);
OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS);
CryingOverOnions = player:getQuestStatus(WINDURST,CRYING_OVER_ONIONS);
WildCard = player:getQuestStatus(WINDURST,WILD_CARD);
ThePromise = player:getQuestStatus(WINDURST,THE_PROMISE);
NeedToZone = player:needToZone();
Level = player:getMainLvl();
Fame = player:getFameLevel(WINDURST);
if (ThePromise == QUEST_COMPLETED) then
player:startEvent(544);
elseif (ThePromise == QUEST_ACCEPTED) then
InvisibleManSticker = player:hasKeyItem(INVISIBLE_MAN_STICKER);
if (InvisibleManSticker == true) then
ThePromiseCS_Seen = player:getVar("ThePromiseCS_Seen");
if (ThePromiseCS_Seen == 1) then
FreeSlots = player:getFreeSlotsCount();
if (FreeSlots >= 1) then
player:completeQuest(WINDURST,THE_PROMISE);
player:addFame(WINDURST,150);
player:delKeyItem(INVISIBLE_MAN_STICKER);
player:addItem(13135);
player:messageSpecial(ITEM_OBTAINED,13135);
player:setVar("ThePromise",0);
player:setVar("ThePromiseCS_Seen",0);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13135);
end
else
player:startEvent(522,0,INVISIBLE_MAN_STICKER);
end
else
player:startEvent(514);
end
elseif (WildCard == QUEST_COMPLETED) then
player:startEvent(513,0,INVISIBLE_MAN_STICKER);
elseif (WildCard == QUEST_ACCEPTED) then
WildCardVar = player:getVar("WildCard");
if (WildCardVar == 0) then
player:setVar("WildCard",1);
end
player:showText(npc,KOHLO_LAKOLO_DIALOG_A);
elseif (CryingOverOnions == QUEST_COMPLETED) then
player:startEvent(505);
elseif (CryingOverOnions == QUEST_ACCEPTED) then
CryingOverOnionsVar = player:getVar("CryingOverOnions");
if (CryingOverOnionsVar == 3) then
player:startEvent(512);
elseif (CryingOverOnionsVar == 2) then
player:startEvent(497);
else
player:startEvent(498);
end
elseif (OnionRings == QUEST_COMPLETED) then
if (NeedToZone == false and Fame >= 5) then
player:startEvent(496);
else
player:startEvent(440);
end
elseif (OnionRings == QUEST_ACCEPTED) then
OldRing = player:hasKeyItem(OLD_RING);
if (OldRing == true) then
OnionRingsTime = player:getVar("OnionRingsTime");
CurrentTime = os.time();
if (CurrentTime >= OnionRingsTime) then
player:startEvent(433);
else
player:startEvent(431);
end
end
elseif (InspectorsGadget == QUEST_COMPLETED) then
if (NeedToZone == false and Fame >= 3) then
OldRing = player:hasKeyItem(OLD_RING);
if (OldRing == true) then
OnionRingsVar = player:getVar("OnionRings");
if (OnionRingsVar == 1) then
player:startEvent(430,0,OLD_RING);
else
player:startEvent(432,0,OLD_RING);
end
else
player:startEvent(429);
end
else
player:startEvent(422);
end
elseif (InspectorsGadget == QUEST_ACCEPTED) then
FakeMoustache = player:hasKeyItem(FAKE_MOUSTACHE);
if (FakeMoustache == true) then
player:startEvent(421);
else
player:startEvent(414);
end
elseif (KnowOnesOnions == QUEST_COMPLETED) then
if (NeedToZone == false and Fame >= 2) then
player:startEvent(413);
else
player:startEvent(401);
end
elseif (KnowOnesOnions == QUEST_ACCEPTED) then
KnowOnesOnionsVar = player:getVar("KnowOnesOnions");
KnowOnesOnionsTime = player:getVar("KnowOnesOnionsTime");
CurrentTime = os.time();
if (KnowOnesOnionsVar == 2) then
player:startEvent(400);
elseif (KnowOnesOnionsVar == 1 and CurrentTime >= KnowOnesOnionsTime) then
player:startEvent(386);
elseif (KnowOnesOnionsVar == 1) then
player:startEvent(399,0,4387);
else
player:startEvent(392,0,4387);
end
elseif (TruthJusticeOnionWay == QUEST_COMPLETED) then
if (NeedToZone == false and Level >= 5) then
player:startEvent(391,0,4387);
else
player:startEvent(379);
end
elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then
player:startEvent(371);
elseif (TruthJusticeOnionWay == QUEST_AVAILABLE) then
player:startEvent(368);
else
player:startEvent(361);
end
end;
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 368 and option == 0) then
player:addQuest(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY);
elseif (csid == 378) then
FreeSlots = player:getFreeSlotsCount();
if (FreeSlots >= 1) then
player:completeQuest(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY);
player:addFame(WINDURST,75);
player:addTitle(STAR_ONION_BRIGADE_MEMBER);
player:tradeComplete();
player:addItem(13093);
player:messageSpecial(ITEM_OBTAINED,13093);
player:needToZone(true);
else
player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,13093);
end
elseif (csid == 391) then
player:addQuest(WINDURST,KNOW_ONE_S_ONIONS);
elseif (csid == 398) then
FreeSlots = player:getFreeSlotsCount();
if (FreeSlots >= 1) then
TradeTime = os.time();
player:tradeComplete();
player:addItem(4857);
player:messageSpecial(ITEM_OBTAINED,4857);
player:setVar("KnowOnesOnions",1);
player:setVar("KnowOnesOnionsTime", TradeTime + 86400);
else
player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,4857);
end
elseif (csid == 386 or csid == 400) then
player:completeQuest(WINDURST,KNOW_ONE_S_ONIONS);
player:addFame(WINDURST,80);
player:addTitle(SOB_SUPER_HERO);
player:setVar("KnowOnesOnions",0);
player:setVar("KnowOnesOnionsTime",0);
player:needToZone(true);
elseif (csid == 413 and option == 0) then
player:addQuest(WINDURST,INSPECTOR_S_GADGET);
elseif (csid == 421) then
FreeSlots = player:getFreeSlotsCount();
if (FreeSlots >= 1) then
player:completeQuest(WINDURST,INSPECTOR_S_GADGET);
player:addFame(WINDURST,90);
player:addTitle(FAKEMOUSTACHED_INVESTIGATOR);
player:addItem(13204);
player:messageSpecial(ITEM_OBTAINED,13204);
player:needToZone(true);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13204);
end
elseif (csid == 429) then
player:setVar("OnionRings",1);
elseif (csid == 430) then
OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS);
if (OnionRings == QUEST_AVAILABLE) then
CurrentTime = os.time();
player:addQuest(WINDURST,ONION_RINGS);
player:setVar("OnionRingsTime", CurrentTime + 86400);
end
elseif (csid == 432 or csid == 433) then
player:completeQuest(WINDURST,ONION_RINGS);
player:addFame(WINDURST,100);
player:addTitle(STAR_ONION_BRIGADIER);
player:delKeyItem(OLD_RING);
player:setVar("OnionRingsTime",0);
player:needToZone(true);
elseif (csid == 440) then
OnionRingsVar = player:getVar("OnionRings");
NeedToZone = player:getVar("NeedToZone");
if (OnionRingsVar == 2 and NeedToZone == 0) then
FreeSlots = player:getFreeSlotsCount();
if (FreeSlots >= 1) then
player:setVar("OnionRings",0);
player:addItem(17029);
player:messageSpecial(ITEM_OBTAINED,17029);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17029);
end
end
elseif (csid == 496) then
player:addQuest(WINDURST,CRYING_OVER_ONIONS);
elseif (csid == 497) then
player:setVar("CryingOverOnions",3);
elseif (csid == 513) then
player:addQuest(WINDURST,THE_PROMISE);
elseif (csid == 522) then
FreeSlots = player:getFreeSlotsCount();
if (FreeSlots >= 1) then
player:completeQuest(WINDURST,THE_PROMISE);
player:addFame(WINDURST,150);
player:delKeyItem(INVISIBLE_MAN_STICKER);
player:addItem(13135);
player:messageSpecial(ITEM_OBTAINED,13135);
player:setVar("ThePromise",0);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13135);
player:setVar("ThePromiseCS_Seen",1);
end
end
end; | gpl-3.0 |
Ninjistix/darkstar | scripts/globals/mobskills/tourbillion.lua | 31 | 1404 | ---------------------------------------------
-- Tourbillion
--
-- Description: Delivers an area attack. Additional effect duration varies with TP. Additional effect: Weakens defense.
-- Type: Physical
-- Shadow per hit
-- Range: Unknown range
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if(mob:getFamily() == 316) then
local mobSkin = mob:getModelId();
if (mobSkin == 1805) then
return 0;
else
return 1;
end
end
--[[TODO: Khimaira should only use this when its wings are up, which is animationsub() == 0.
There's no system to put them "down" yet, so it's not really fair to leave it active.
Tyger's fair game, though. :)]]
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 3;
local accmod = 1;
local dmgmod = 1.5;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded);
local duration = 20 * (skill:getTP() / 1000);
MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_DEFENSE_DOWN, 20, 0, duration);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
Ninjistix/darkstar | scripts/commands/delitem.lua | 8 | 1602 | ---------------------------------------------------------------------------------------------------
-- func: delitem
-- desc: Deletes a single item held by a player, if they have it.
---------------------------------------------------------------------------------------------------
require("scripts/globals/status");
cmdprops =
{
permission = 1,
parameters = "is"
};
function error(player, msg)
player:PrintToPlayer(msg);
player:PrintToPlayer("!delitem <itemID> {player}");
end;
function onTrigger(player, itemId, target)
-- validate itemId
if (itemId == nil or itemId < 1) then
error(player,"Invalid itemID.");
return;
end
-- validate target
local targ;
if (target == nil) then
targ = player;
else
targ = GetPlayerByName(target);
if (targ == nil) then
error(player,string.format("Player named '%s' not found!", target));
return;
end
end
-- search target inventory for item, and delete if found
for i = LOC_INVENTORY, LOC_WARDROBE4 do -- inventory locations enums
if (targ:hasItem(itemId, i)) then
targ:delItem(itemId, 1, i);
player:PrintToPlayer(string.format("Item %i was deleted from %s.", itemId, targ:getName()));
break;
end
if (i == LOC_WARDROBE4) then -- Wardrobe 4 is the last inventory location, if it reaches this point then the player does not have the item anywhere.
player:PrintToPlayer(string.format("%s does not have item %i.", targ:getName(), itemId));
end
end
end; | gpl-3.0 |
Ninjistix/darkstar | scripts/globals/abilities/ice_shot.lua | 2 | 3225 | -----------------------------------
-- Ability: Ice Shot
-- Consumes a Ice Card to enhance ice-based debuffs. Deals ice-based magic damage
-- Frost Effect: Enhanced DoT and AGI-
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/weaponskills");
require("scripts/globals/ability");
-----------------------------------
function onAbilityCheck(player,target,ability)
--ranged weapon/ammo: You do not have an appropriate ranged weapon equipped.
--no card: <name> cannot perform that action.
if (player:getWeaponSkillType(SLOT_RANGED) ~= SKILL_MRK or player:getWeaponSkillType(SLOT_AMMO) ~= SKILL_MRK) then
return 216,0;
end
if (player:hasItem(2177, 0) or player:hasItem(2974, 0)) then
return 0,0;
else
return 71, 0;
end
end;
function onUseAbility(player,target,ability,action)
local params = {};
params.includemab = true;
local dmg = (2 * player:getRangedDmg() + player:getAmmoDmg() + player:getMod(MOD_QUICK_DRAW_DMG)) * 1 + player:getMod(MOD_QUICK_DRAW_DMG_PERCENT)/100;
dmg = addBonusesAbility(player, ELE_ICE, target, dmg, params);
dmg = dmg * applyResistanceAbility(player,target,ELE_ICE,SKILL_MRK, (player:getStat(MOD_AGI)/2) + player:getMerit(MERIT_QUICK_DRAW_ACCURACY));
dmg = adjustForTarget(target,dmg,ELE_ICE);
local shadowsAbsorbed = 0
if shadowAbsorb(target) then
shadowsAbsorbed = 1
end
dmg = takeAbilityDamage(target, player, {}, true, dmg, SLOT_RANGED, 1, shadowsAbsorbed, 0, 0, action, nil);
if shadowsAbsorbed == 0 then
local effects = {};
local counter = 1;
local frost = target:getStatusEffect(EFFECT_FROST);
if (frost ~= nil) then
effects[counter] = frost;
counter = counter + 1;
end
local threnody = target:getStatusEffect(EFFECT_THRENODY);
if (threnody ~= nil and threnody:getSubPower() == MOD_WINDRES) then
effects[counter] = threnody;
counter = counter + 1;
end
local paralyze = target:getStatusEffect(EFFECT_PARALYSIS);
if (paralyze ~= nil) then
effects[counter] = paralyze;
counter = counter + 1;
end
if counter > 1 then
local effect = effects[math.random(1, counter-1)];
local duration = effect:getDuration();
local startTime = effect:getStartTime();
local tick = effect:getTick();
local power = effect:getPower();
local subpower = effect:getSubPower();
local tier = effect:getTier();
local effectId = effect:getType();
local subId = effect:getSubType();
power = power * 1.2;
target:delStatusEffectSilent(effectId);
target:addStatusEffect(effectId, power, tick, duration, subId, subpower, tier);
local newEffect = target:getStatusEffect(effectId);
newEffect:setStartTime(startTime);
end
end
local del = player:delItem(2177, 1) or player:delItem(2974, 1)
target:updateClaim(player);
return dmg;
end;
| gpl-3.0 |
Ninjistix/darkstar | scripts/zones/Dragons_Aery/npcs/relic.lua | 5 | 1535 | -----------------------------------
-- Area: Dragon's Aery
-- NPC: <this space intentionally left blank>
-- !pos -20 -2 61 154
-----------------------------------
package.loaded["scripts/zones/Dragons_Aery/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Dragons_Aery/TextIDs");
-----------------------------------
function onTrade(player,npc,trade)
-- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece
if (player:getVar("RELIC_IN_PROGRESS") == 18275 and trade:getItemCount() == 4 and trade:hasItemQty(18275,1) and
trade:hasItemQty(1573,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1454,1)) then
player:startEvent(3,18276);
end
end;
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 3) then
if (player:getFreeSlotsCount() < 2) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18276);
player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1453);
else
player:tradeComplete();
player:addItem(18276);
player:addItem(1453,30);
player:messageSpecial(ITEM_OBTAINED,18276);
player:messageSpecial(ITEMS_OBTAINED,1453,30);
player:setVar("RELIC_IN_PROGRESS",0);
end
end
end; | gpl-3.0 |
Ninjistix/darkstar | scripts/zones/Temenos/npcs/Armoury_Crate.lua | 21 | 8373 | -----------------------------------
-- Area: Temenos
-- NPC: Armoury Crate
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Temenos/TextIDs");
require("scripts/globals/limbus");
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local CofferID = npc:getID();
local CofferType=0;
local lootID=0;
local InstanceRegion=0;
local addtime=0;
local DespawnOtherCoffer=false;
local MimicID=0;
local X = npc:getXPos();
local Y = npc:getYPos();
local Z = npc:getZPos();
for coffer = 1,#ARMOURY_CRATES_LIST_TEMENOS,2 do
if (ARMOURY_CRATES_LIST_TEMENOS[coffer] == CofferID-16928768) then
CofferType=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][1];
InstanceRegion=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][2];
addtime=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][3];
DespawnOtherCoffer=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][4];
MimicID=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][5];
lootID=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][6];
end
end
printf("CofferID : %u",CofferID-16928768);
printf("Coffertype %u",CofferType);
printf("InstanceRegion: %u",InstanceRegion);
printf("addtime: %u",addtime);
printf("MimicID: %u",MimicID);
printf("lootID: %u",lootID);
local coffer = CofferID-16928768;
if (CofferType == cTIME) then
player:addTimeToSpecialBattlefield(InstanceRegion,addtime);
elseif (CofferType == cITEM) then
if (InstanceRegion == Central_Temenos_4th_Floor and coffer~=79) then
local randmimic = math.random(1,24)
print("randmimic" ..randmimic);
if ( randmimic < 19) then
local MimicList={16928986,16928987,16928988,16928989,16928990,16928991,16928992,16928993,16928994,16928995,16928996,16928997,16928998,16928999,16929000,16929001,16929002,16929003};
GetMobByID(MimicList[randmimic]):setSpawn(X,Y,Z);
SpawnMob(MimicList[randmimic]):setPos(X,Y,Z);
GetMobByID(MimicList[randmimic]):updateClaim(player);
else
player:BCNMSetLoot(lootID,InstanceRegion,CofferID);
player:getBCNMloot();
end
-- despawn les coffer du meme groupe
for coffer = 1, #ARMOURY_CRATES_LIST_TEMENOS, 2 do
if (ARMOURY_CRATES_LIST_TEMENOS[coffer+1][5] == MimicID) then
GetNPCByID(16928768+ARMOURY_CRATES_LIST_TEMENOS[coffer]):setStatus(STATUS_DISAPPEAR);
end
end
else
player:BCNMSetLoot(lootID, InstanceRegion, CofferID);
player:getBCNMloot();
end
elseif (CofferType == cRESTORE) then
player:RestoreAndHealOnBattlefield(InstanceRegion);
elseif (CofferType == cMIMIC) then
if (coffer == 284) then
GetMobByID(16928844):setSpawn(X,Y,Z);
SpawnMob(16928844):setPos(X,Y,Z)
GetMobByID(16928844):updateClaim(player);
elseif (coffer == 321) then
GetMobByID(16928853):setSpawn(X,Y,Z);
SpawnMob(16928853):setPos(X,Y,Z);
GetMobByID(16928853):updateClaim(player);
elseif (coffer == 348) then
GetMobByID(16928862):setSpawn(X,Y,Z);
SpawnMob(16928862):setPos(X,Y,Z);
GetMobByID(16928862):updateClaim(player);
elseif (coffer == 360) then
GetMobByID(16928871):setSpawn(X,Y,Z);
SpawnMob(16928871):setPos(X,Y,Z);
GetMobByID(16928871):updateClaim(player);
elseif (coffer == 393) then
GetMobByID(16928880):setSpawn(X,Y,Z);
SpawnMob(16928880):setPos(X,Y,Z);
GetMobByID(16928880):updateClaim(player);
elseif (coffer == 127) then
GetMobByID(16928889):setSpawn(X,Y,Z);
SpawnMob(16928889):setPos(X,Y,Z);
GetMobByID(16928889):updateClaim(player);
elseif (coffer == 123) then
GetMobByID(16928894):setSpawn(X,Y,Z);
SpawnMob(16928894):setPos(X,Y,Z);
GetMobByID(16928894):updateClaim(player);
end
end
if (DespawnOtherCoffer == true) then
HideArmouryCrates(InstanceRegion,TEMENOS);
if (InstanceRegion==Temenos_Eastern_Tower) then --despawn mob of the current floor
if (coffer == 173 or coffer == 215 or coffer == 284 or coffer == 40) then
--floor 1
if (GetMobAction(16928840) > 0) then DespawnMob(16928840); end
if (GetMobAction(16928841) > 0) then DespawnMob(16928841); end
if (GetMobAction(16928842) > 0) then DespawnMob(16928842); end
if (GetMobAction(16928843) > 0) then DespawnMob(16928843); end
GetNPCByID(16929228):setStatus(STATUS_NORMAL);
elseif (coffer == 174 or coffer == 216 or coffer == 321 or coffer == 45) then
--floor 2
if (GetMobAction(16928849) > 0) then DespawnMob(16928849); end
if (GetMobAction(16928850) > 0) then DespawnMob(16928850); end
if (GetMobAction(16928851) > 0) then DespawnMob(16928851); end
if (GetMobAction(16928852) > 0) then DespawnMob(16928852); end
GetNPCByID(16929229):setStatus(STATUS_NORMAL);
elseif (coffer == 181 or coffer == 217 or coffer == 348 or coffer == 46) then
--floor 3
if (GetMobAction(16928858) > 0) then DespawnMob(16928858); end
if (GetMobAction(16928859) > 0) then DespawnMob(16928859); end
if (GetMobAction(16928860) > 0) then DespawnMob(16928860); end
if (GetMobAction(16928861) > 0) then DespawnMob(16928861); end
GetNPCByID(16929230):setStatus(STATUS_NORMAL);
elseif (coffer == 182 or coffer == 236 or coffer == 360 or coffer == 47) then
--floor 4
if (GetMobAction(16928867) > 0) then DespawnMob(16928867); end
if (GetMobAction(16928868) > 0) then DespawnMob(16928868); end
if (GetMobAction(16928869) > 0) then DespawnMob(16928869); end
if (GetMobAction(16928870) > 0) then DespawnMob(16928870); end
GetNPCByID(16929231):setStatus(STATUS_NORMAL);
elseif (coffer == 183 or coffer == 261 or coffer == 393 or coffer == 68) then
--floor 5
if (GetMobAction(16928876) > 0) then DespawnMob(16928876); end
if (GetMobAction(16928877) > 0) then DespawnMob(16928877); end
if (GetMobAction(16928878) > 0) then DespawnMob(16928878); end
if (GetMobAction(16928879) > 0) then DespawnMob(16928879); end
GetNPCByID(16929232):setStatus(STATUS_NORMAL);
elseif (coffer == 277 or coffer == 190 or coffer == 127 or coffer == 69) then
--floor 6
if (GetMobAction(16928885) > 0) then DespawnMob(16928885); end
if (GetMobAction(16928886) > 0) then DespawnMob(16928886); end
if (GetMobAction(16928887) > 0) then DespawnMob(16928887); end
if (GetMobAction(16928888) > 0) then DespawnMob(16928888); end
GetNPCByID(16929233):setStatus(STATUS_NORMAL);
elseif (coffer == 70 or coffer == 123) then
--floor 7
if (GetMobAction(16928892) > 0) then DespawnMob(16928892); end
if (GetMobAction(16928893) > 0) then DespawnMob(16928893); end
GetNPCByID(16929234):setStatus(STATUS_NORMAL);
end
end
end
npc:setStatus(STATUS_DISAPPEAR);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
Ninjistix/darkstar | scripts/zones/Bastok_Markets/npcs/Aquillina.lua | 5 | 1544 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Aquillina
-- Starts & Finishes Repeatable Quest: A Flash In The Pan
-- Note: Reapeatable every 15 minutes.
-- !pos -97 -5 -81 235
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bastok_Markets/TextIDs");
require("scripts/globals/npc_util");
require("scripts/globals/quests");
function onTrade(player,npc,trade)
if (player:getQuestStatus(BASTOK,A_FLASH_IN_THE_PAN) >= QUEST_ACCEPTED) then
if (os.time() >= player:getVar("FlashInThePan")) then
if (npcUtil.tradeHas( trade, {{768,4}} )) then
player:startEvent(219);
end
else
player:startEvent(218);
end
end
end;
function onTrigger(player,npc)
if (player:getQuestStatus(BASTOK,A_FLASH_IN_THE_PAN) == QUEST_AVAILABLE) then
player:startEvent(217);
else
player:startEvent(116);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 217) then
player:addQuest(BASTOK, A_FLASH_IN_THE_PAN);
elseif (csid == 219) then
local fame = player:hasCompleteQuest(BASTOK, A_FLASH_IN_THE_PAN) and 8 or 75;
if (npcUtil.completeQuest(player, BASTOK, A_FLASH_IN_THE_PAN, {gil=100, fame=fame})) then
player:confirmTrade();
player:setVar("FlashInThePan",os.time() + 900);
end
end
end;
| gpl-3.0 |
wangyi0226/skynet | test/cluster/cluster_sender_base.lua | 1 | 6015 | ---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by jjq.
--- DateTime: 2022/8/30 15:52
--- 用户自定义cluster_sender基类
--- 只是一个简单的替代原生sender的例子,不做为标准
local skynet = require "skynet"
local sc = require "skynet.socketchannel"
local socket = require "skynet.socket"
local cluster = require "skynet.cluster.core"
local queue = require "skynet.queue"
local channel --socket channel obj
local session
local lock
local remote_node, self_hostname_pid
local root_host, root_port --可以是对方节点,也可以是负载均衡服的地址
local sc_init_obj
local req_load_balance --请求负载均衡
local CMD
local function resp_reader(sock)
local sz = socket.header(sock:read(2))
local msg = sock:read(sz)
return cluster.unpackresponse(msg) -- session, ok, data, padding
end
local function channel_creator()
if channel then
return true
end
if req_load_balance then
local host,port,backup_list = req_load_balance(root_host, root_port)
--有可能失败
if not host then
skynet.error(port)
return false
end
sc_init_obj.host = host
sc_init_obj.port = port
sc_init_obj.__backup = backup_list
end
session = 1
channel = sc.channel(sc_init_obj)
return channel:connect(true)
end
local function check_connection()
if not channel then
return lock(channel_creator)
end
return true
end
local command = {}
local function req(addr, msg, sz)
-- msg is a local pointer, cluster.packrequest will free it
local current_session = session
local request, new_session, padding = cluster.packrequest(addr, current_session, msg, sz)
session = new_session
return pcall(channel.request,channel,request,current_session,padding)
end
function command.req(addr, msg, sz)
local ok = check_connection()
if not ok then
skynet.response()(false)
return
end
local ok, msg = req(addr, msg, sz)
if ok then
if type(msg) == "table" then
skynet.ret(cluster.concat(msg))
else
skynet.ret(msg)
end
else
if req_load_balance then
channel = nil
end
skynet.error(msg)
skynet.response()(false)
end
end
function command.push(addr, msg, sz)
local ok = check_connection()
if not ok then
return ok
end
local request, new_session, padding = cluster.packpush(addr, session, msg, sz)
if padding then -- is multi push
session = new_session
end
local ok,msg = pcall(channel.request,channel,request, nil, padding)
if not ok and req_load_balance then
channel = nil
end
return ok,msg
end
function command.connect()
local ok = check_connection()
skynet.ret(skynet.pack(ok))
return ok
end
function command.changenode(host, port)
--host==false等于关闭连接
if not host then
if not channel then
skynet.ret(skynet.pack(nil))
return
end
skynet.error(string.format("Close cluster sender %s:%d", channel.__host, channel.__port))
channel:close()
if req_load_balance then
channel = nil
end
else
port = tonumber(port)
if root_host == host and root_port == port then
skynet.ret(skynet.pack(nil))
return
end
root_host, root_port = host, port
if not channel then
skynet.ret(skynet.pack(nil))
return
end
if req_load_balance then
channel:close()
channel = nil
else
sc_init_obj.host,sc_init_obj.port = root_host, root_port
channel:changehost(root_host, root_port)
--下次调用再连接
--channel:connect(true)
end
end
skynet.ret(skynet.pack(nil))
end
--临时性关闭socket,可以重连
function command.close()
if not channel then
skynet.ret(skynet.pack(nil))
return
end
skynet.error("close sender socket")
channel:close()
if req_load_balance then
channel = nil
end
skynet.ret(skynet.pack(nil))
end
local M = {}
function M.start(init_obj,...)
remote_node, self_hostname_pid, root_host, root_port = ...
root_port = tonumber(root_port)
req_load_balance = init_obj.req_load_balance
CMD = init_obj.CMD or {}
sc_init_obj = {
host = root_host,
port = root_port,
response = resp_reader,
nodelay = true,
auth = init_obj.auth,
overload = init_obj.overload,
}
skynet.start(function()
lock = queue()
local constructor = init_obj.constructor
if constructor then
constructor()
end
skynet.dispatch("lua", function(session , source, cmd, ...)
local f = command[cmd]
if f then
f(...)
return
end
f = assert(CMD[cmd])
skynet.ret(skynet.pack(f(...)))
end)
end)
end
function M.push(actor,...)
check_connection()
return command.push(actor, skynet.pack(...))
end
--第一个返回值是boolean,这样省的在调用层多写一个pcall
function M.req(actor,...)
check_connection()
local ok, msg = req(actor, skynet.pack(...))
if ok then
if type(msg) == "table" then
return true,skynet.unpack(cluster.concat(msg))
else
return true,skynet.unpack(msg)
end
else
if req_load_balance then
channel = nil
end
skynet.error(msg)
return ok,msg
end
end
function M.connect()
return check_connection()
end
return M | mit |
Ninjistix/darkstar | scripts/zones/Cloister_of_Gales/Zone.lua | 5 | 1074 | -----------------------------------
--
-- Zone: Cloister_of_Gales (201)
--
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Gales/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Cloister_of_Gales/TextIDs");
-----------------------------------
function onInitialize(zone)
end;
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-399.541,-1.697,-420,252);
end
return cs;
end;
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
function onRegionEnter(player,region)
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
johnsoch/cuberite | Server/Plugins/APIDump/Hooks/OnHopperPullingItem.lua | 44 | 1336 | return
{
HOOK_HOPPER_PULLING_ITEM =
{
CalledWhen = "A hopper is pulling an item from another block entity.",
DefaultFnName = "OnHopperPullingItem", -- also used as pagename
Desc = [[
This callback is called whenever a {{cHopperEntity|hopper}} transfers an {{cItem|item}} from another
block entity into its own internal storage. A plugin may decide to disallow the move by returning
true. Note that in such a case, the hook may be called again for the same hopper, with different
slot numbers.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "World where the hopper resides" },
{ Name = "Hopper", Type = "{{cHopperEntity}}", Notes = "The hopper that is pulling the item" },
{ Name = "DstSlot", Type = "number", Notes = "The destination slot in the hopper's {{cItemGrid|internal storage}}" },
{ Name = "SrcBlockEntity", Type = "{{cBlockEntityWithItems}}", Notes = "The block entity that is losing the item" },
{ Name = "SrcSlot", Type = "number", Notes = "Slot in SrcBlockEntity from which the item will be pulled" },
},
Returns = [[
If the function returns false or no value, the next plugin's callback is called. If the function
returns true, no other callback is called for this event and the hopper will not pull the item.
]],
}, -- HOOK_HOPPER_PULLING_ITEM
}
| apache-2.0 |
Ninjistix/darkstar | scripts/zones/Monarch_Linn/Zone.lua | 5 | 1057 | -----------------------------------
--
-- Zone: Monarch_Linn
--
-----------------------------------
package.loaded["scripts/zones/Monarch_Linn/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Monarch_Linn/TextIDs");
require("scripts/globals/settings");
-----------------------------------
function onInitialize(zone)
end;
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
function onZoneIn(player,prevZone)
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(12.527,0.345,-539.602,127);
end
local cs = -1;
return cs;
end;
function onRegionEnter(player,region)
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Ninjistix/darkstar | scripts/zones/Port_Jeuno/Zone.lua | 5 | 3115 | -----------------------------------
--
-- Zone: Port_Jeuno (246)
--
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_Jeuno/TextIDs");
require("scripts/globals/settings");
-----------------------------------
function onInitialize(zone)
end;
function onZoneIn(player,prevZone)
local cs = -1;
local month = tonumber(os.date("%m"));
local day = tonumber(os.date("%d"));
-- Retail start/end dates vary, I am going with Dec 5th through Jan 5th.
if ((month == 12 and day >= 5) or (month == 1 and day <= 5)) then
player:ChangeMusic(0,239);
player:ChangeMusic(1,239);
-- No need for an 'else' to change it back outside these dates as a re-zone will handle that.
end
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
if (prevZone == 223) then
cs = 0x2722;
player:setPos(-87.000, 12.000, 116.000, 128);
elseif (prevZone == 224) then
cs = 0x2724;
player:setPos(-50.000, 12.000, -116.000, 0);
elseif (prevZone == 225) then
cs = 0x2723;
player:setPos(16.000, 12.000, -117.000, 0);
elseif (prevZone == 226) then
cs = 0x2725;
player:setPos(-24.000, 12.000, 116.000, 128);
else
local position = math.random(1,3) - 2;
player:setPos(-192.5 ,-5,position,0);
if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then
cs = 30004;
end
player:setVar("PlayerMainJob",0);
end
elseif (ENABLE_ABYSSEA == 1 and player:getMainLvl() >= 30
and player:getQuestStatus(ABYSSEA, A_JOURNEY_BEGINS) == QUEST_AVAILABLE) then
cs = 324;
end
return cs
end;
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
function onTransportEvent(player,transport)
if (transport == 223) then
player:startEvent(10010);
elseif (transport == 224) then
player:startEvent(10012);
elseif (transport == 225) then
player:startEvent(10011);
elseif (transport == 226) then
player:startEvent(10013);
end
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 10010) then
player:setPos(0,0,0,0,223);
elseif (csid == 10011) then
player:setPos(0,0,0,0,225);
elseif (csid == 10012) then
player:setPos(0,0,0,0,224);
elseif (csid == 10013) then
player:setPos(0,0,0,0,226);
elseif (csid == 30004 and option == 0) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
elseif (csid == 324) then
player:addQuest(ABYSSEA, A_JOURNEY_BEGINS);
end
end; | gpl-3.0 |
ld-test/dromozoa-http | test/test_twitter.lua | 3 | 2283 | -- Copyright (C) 2015 Tomoyuki Fujimori <moyu@dromozoa.com>
--
-- This file is part of dromozoa-http.
--
-- dromozoa-http 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.
--
-- dromozoa-http 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 dromozoa-http. If not, see <http://www.gnu.org/licenses/>.
local base64 = require "dromozoa.commons.base64"
local json = require "dromozoa.commons.json"
local http = require "dromozoa.http"
local consumer_key = os.getenv("TWITTER_CONSUMER_KEY")
local consumer_secret = os.getenv("TWITTER_CONSUMER_SECRET")
local access_token = os.getenv("TWITTER_ACCESS_TOKEN")
local access_token_secret = os.getenv("TWITTER_ACCESS_TOKEN_SECRET")
if consumer_key == nil then
io.stderr:write("no consumer key\n")
os.exit()
end
if access_token == nil then
io.stderr:write("no access token\n")
os.exit()
end
local scheme = "https"
local host = "api.twitter.com"
local status_id = "663588769828724736"
local ua = http.user_agent():fail():verbose(false)
local uri = http.uri(scheme, host, "/1.1/statuses/show.json")
:param("id", status_id)
:param("trim_user", "true")
local request = http.request("GET", uri)
http.oauth(consumer_key, access_token):sign_header(request, consumer_secret, access_token_secret)
local response = assert(ua:request(request))
local result = json.decode(response.content)
assert(result.id_str == status_id)
assert(result.text:find("^不惑や知命"))
assert(result.source:find("Twitter for iPhone"))
-- local uri = http.uri(scheme, host, "/1.1/statuses/update.json")
-- local request = http.request("POST", uri)
-- :param("status", "@vaporoid ファイトだよ!")
-- http.oauth(consumer_key, access_token):sign_header(request, consumer_secret, access_token_secret)
-- print(request.oauth.signature_base_string)
-- local response = assert(ua:request(request))
| gpl-3.0 |
Ninjistix/darkstar | scripts/zones/Upper_Delkfutts_Tower/mobs/Autarch.lua | 3 | 1375 | -----------------------------------
-- Area: Upper Delkfutt's Tower
-- NM: Autarch
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(MOBMOD_AUTO_SPIKES,mob:getShortID());
mob:addStatusEffect(EFFECT_SHOCK_SPIKES,40,0,0);
mob:getStatusEffect(EFFECT_SHOCK_SPIKES):setFlag(32);
end;
function onSpikesDamage(mob,target,damage)
local INT_diff = mob:getStat(MOD_INT) - target:getStat(MOD_INT);
if (INT_diff > 20) then
INT_diff = 20 + ((INT_diff - 20)*0.5); -- INT above 20 is half as effective.
end
local dmg = ((damage+INT_diff)*0.5); -- INT adjustment and base damage averaged together.
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(mob, ELE_THUNDER, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(mob,target,ELE_THUNDER,0);
dmg = adjustForTarget(target,dmg,ELE_THUNDER);
dmg = finalMagicNonSpellAdjustments(mob,target,ELE_THUNDER,dmg);
if (dmg < 0) then
dmg = 0;
end
return SUBEFFECT_SHOCK_SPIKES,44,dmg;
end;
function onMobDeath(mob, player, isKiller)
end;
function onMobDespawn(mob)
-- UpdateNMSpawnPoint(mob:getID());
mob:setRespawnTime(math.random(7200,10800)); -- 2 to 3 hrs
end;
| gpl-3.0 |
mandersan/premake-core | modules/android/vsandroid_vcxproj.lua | 4 | 17615 | --
-- android/vsandroid_vcxproj.lua
-- vs-android integration for vstudio.
-- Copyright (c) 2012-2015 Manu Evans and the Premake project
--
local p = premake
p.modules.vsandroid = { }
local android = p.modules.android
local vsandroid = p.modules.vsandroid
local vc2010 = p.vstudio.vc2010
local vstudio = p.vstudio
local project = p.project
local config = p.config
--
-- Utility functions
--
local function setBoolOption(optionName, flag, value)
if flag ~= nil then
vc2010.element(optionName, nil, value)
end
end
--
-- Add android tools to vstudio actions.
--
if vstudio.vs2010_architectures ~= nil then
if _ACTION >= "vs2015" then
vstudio.vs2010_architectures.arm = "ARM"
else
vstudio.vs2010_architectures.android = "Android"
end
end
--
-- Extend global properties
--
premake.override(vc2010.elements, "globals", function (oldfn, prj)
local elements = oldfn(prj)
if prj.system == premake.ANDROID and prj.kind ~= premake.PACKAGING then
-- Remove "IgnoreWarnCompileDuplicatedFilename".
local pos = table.indexof(elements, vc2010.ignoreWarnDuplicateFilename)
table.remove(elements, pos)
elements = table.join(elements, {
android.androidApplicationType
})
end
return elements
end)
premake.override(vc2010.elements, "globalsCondition", function (oldfn, prj, cfg)
local elements = oldfn(prj, cfg)
if cfg.system == premake.ANDROID and cfg.system ~= prj.system and cfg.kind ~= premake.PACKAGING then
elements = table.join(elements, {
android.androidApplicationType
})
end
return elements
end)
function android.androidApplicationType(cfg)
vc2010.element("Keyword", nil, "Android")
vc2010.element("RootNamespace", nil, "%s", cfg.project.name)
if _ACTION >= "vs2019" then
vc2010.element("MinimumVisualStudioVersion", nil, "16.0")
elseif _ACTION >= "vs2017" then
vc2010.element("MinimumVisualStudioVersion", nil, "15.0")
elseif _ACTION >= "vs2015" then
vc2010.element("MinimumVisualStudioVersion", nil, "14.0")
end
vc2010.element("ApplicationType", nil, "Android")
if _ACTION >= "vs2017" then
vc2010.element("ApplicationTypeRevision", nil, "3.0")
elseif _ACTION >= "vs2015" then
vc2010.element("ApplicationTypeRevision", nil, "2.0")
else
vc2010.element("ApplicationTypeRevision", nil, "1.0")
end
end
--
-- Extend configurationProperties.
--
premake.override(vc2010.elements, "configurationProperties", function(oldfn, cfg)
local elements = oldfn(cfg)
if cfg.kind ~= p.UTILITY and cfg.kind ~= p.PACKAGING and cfg.system == premake.ANDROID then
table.remove(elements, table.indexof(elements, vc2010.characterSet))
table.remove(elements, table.indexof(elements, vc2010.wholeProgramOptimization))
table.remove(elements, table.indexof(elements, vc2010.windowsSDKDesktopARMSupport))
elements = table.join(elements, {
android.androidAPILevel,
android.androidStlType,
})
if _ACTION >= "vs2015" then
elements = table.join(elements, {
android.thumbMode,
})
end
end
return elements
end)
function android.androidAPILevel(cfg)
if cfg.androidapilevel ~= nil then
vc2010.element("AndroidAPILevel", nil, "android-" .. cfg.androidapilevel)
end
end
function android.androidStlType(cfg)
if cfg.stl ~= nil then
local stlType = {
["none"] = "system",
["gabi++"] = "gabi++",
["stlport"] = "stlport",
["gnu"] = "gnustl",
["libc++"] = "c++",
}
local postfix = iif(cfg.staticruntime == "On", "_static", "_shared")
local runtimeLib = iif(cfg.stl == "none", "system", stlType[cfg.stl] .. postfix)
if _ACTION >= "vs2015" then
vc2010.element("UseOfStl", nil, runtimeLib)
else
vc2010.element("AndroidStlType", nil, runtimeLib)
end
end
end
function android.thumbMode(cfg)
if cfg.thumbmode ~= nil then
local thumbMode =
{
thumb = "Thumb",
arm = "ARM",
disabled = "Disabled",
}
vc2010.element("ThumbMode", nil, thumbMode[cfg.thumbmode])
end
end
-- Note: this function is already patched in by vs2012...
premake.override(vc2010, "platformToolset", function(oldfn, cfg)
if cfg.system ~= premake.ANDROID then
return oldfn(cfg)
end
if _ACTION >= "vs2015" then
local gcc_map = {
["4.6"] = "GCC_4_6",
["4.8"] = "GCC_4_8",
["4.9"] = "GCC_4_9",
}
local clang_map = {
["3.4"] = "Clang_3_4",
["3.5"] = "Clang_3_5",
["3.6"] = "Clang_3_6",
["3.8"] = "Clang_3_8",
["5.0"] = "Clang_5_0",
}
if cfg.toolchainversion ~= nil then
local map = iif(cfg.toolset == "gcc", gcc_map, clang_map)
local ts = map[cfg.toolchainversion]
if ts == nil then
p.error('Invalid toolchainversion for the selected toolset (%s).', cfg.toolset or "clang")
end
vc2010.element("PlatformToolset", nil, ts)
end
else
local archMap = {
arm = "armv5te", -- should arm5 be default? vs-android thinks so...
arm5 = "armv5te",
arm7 = "armv7-a",
mips = "mips",
x86 = "x86",
}
local arch = cfg.architecture or "arm"
if (cfg.architecture ~= nil or cfg.toolchainversion ~= nil) and archMap[arch] ~= nil then
local defaultToolsetMap = {
arm = "arm-linux-androideabi-",
armv5 = "arm-linux-androideabi-",
armv7 = "arm-linux-androideabi-",
aarch64 = "aarch64-linux-android-",
mips = "mipsel-linux-android-",
mips64 = "mips64el-linux-android-",
x86 = "x86-",
x86_64 = "x86_64-",
}
local toolset = defaultToolsetMap[arch]
if cfg.toolset == "clang" then
error("The clang toolset is not yet supported by vs-android", 2)
toolset = toolset .. "clang"
elseif cfg.toolset and cfg.toolset ~= "gcc" then
error("Toolset not supported by the android NDK: " .. cfg.toolset, 2)
end
local version = cfg.toolchainversion or iif(cfg.toolset == "clang", "3.5", "4.9")
vc2010.element("PlatformToolset", nil, toolset .. version)
vc2010.element("AndroidArch", nil, archMap[arch])
end
end
end)
--
-- Extend clCompile.
--
premake.override(vc2010.elements, "clCompile", function(oldfn, cfg)
local elements = oldfn(cfg)
if cfg.system == premake.ANDROID then
elements = table.join(elements, {
android.debugInformation,
android.strictAliasing,
android.fpu,
android.pic,
android.shortEnums,
android.cStandard,
android.cppStandard,
})
if _ACTION >= "vs2015" then
table.remove(elements, table.indexof(elements, vc2010.debugInformationFormat))
-- Android has C[pp]LanguageStandard instead.
table.remove(elements, table.indexof(elements, vc2010.languageStandard))
-- Ignore multiProcessorCompilation for android projects, they use UseMultiToolTask instead.
table.remove(elements, table.indexof(elements, vc2010.multiProcessorCompilation))
-- minimalRebuild also ends up in android projects somehow.
table.remove(elements, table.indexof(elements, vc2010.minimalRebuild))
-- VS has NEON support through EnableNeonCodegen.
table.replace(elements, vc2010.enableEnhancedInstructionSet, android.enableEnhancedInstructionSet)
-- precompiledHeaderFile support.
table.replace(elements, vc2010.precompiledHeaderFile, android.precompiledHeaderFile)
end
end
return elements
end)
function android.precompiledHeaderFile(fileName, cfg)
-- Doesn't work for project-relative paths.
vc2010.element("PrecompiledHeaderFile", nil, "%s", path.getabsolute(path.rebase(fileName, cfg.basedir, cfg.location)))
end
function android.debugInformation(cfg)
if cfg.flags.Symbols then
_p(3,'<GenerateDebugInformation>true</GenerateDebugInformation>')
end
end
function android.strictAliasing(cfg)
if cfg.strictaliasing ~= nil then
vc2010.element("StrictAliasing", nil, iif(cfg.strictaliasing == "Off", "false", "true"))
end
end
function android.fpu(cfg)
if cfg.fpu ~= nil then
_p(3,'<SoftFloat>true</SoftFloat>', iif(cfg.fpu == "Software", "true", "false"))
end
end
function android.pic(cfg)
if cfg.pic ~= nil then
vc2010.element("PositionIndependentCode", nil, iif(cfg.pic == "On", "true", "false"))
end
end
function android.verboseCompiler(cfg)
setBoolOption("Verbose", cfg.flags.VerboseCompiler, "true")
end
function android.undefineAllPreprocessorDefinitions(cfg)
setBoolOption("UndefineAllPreprocessorDefinitions", cfg.flags.UndefineAllPreprocessorDefinitions, "true")
end
function android.showIncludes(cfg)
setBoolOption("ShowIncludes", cfg.flags.ShowIncludes, "true")
end
function android.dataLevelLinking(cfg)
setBoolOption("DataLevelLinking", cfg.flags.DataLevelLinking, "true")
end
function android.shortEnums(cfg)
setBoolOption("UseShortEnums", cfg.flags.UseShortEnums, "true")
end
function android.cStandard(cfg)
local c_langmap = {
["C98"] = "c98",
["C99"] = "c99",
["C11"] = "c11",
["gnu99"] = "gnu99",
["gnu11"] = "gnu11",
}
if c_langmap[cfg.cdialect] ~= nil then
vc2010.element("CLanguageStandard", nil, c_langmap[cfg.cdialect])
end
end
function android.cppStandard(cfg)
local cpp_langmap = {
["C++98"] = "c++98",
["C++11"] = "c++11",
["C++14"] = "c++1y",
["C++17"] = "c++1z",
["C++latest"] = "c++1z",
["gnu++98"] = "gnu++98",
["gnu++11"] = "gnu++11",
["gnu++14"] = "gnu++1y",
["gnu++17"] = "gnu++1z",
}
if cpp_langmap[cfg.cppdialect] ~= nil then
vc2010.element("CppLanguageStandard", nil, cpp_langmap[cfg.cppdialect])
end
end
p.override(vc2010, "additionalCompileOptions", function(oldfn, cfg, condition)
if cfg.system == p.ANDROID then
local opts = cfg.buildoptions
if cfg.disablewarnings and #cfg.disablewarnings > 0 then
for _, warning in ipairs(cfg.disablewarnings) do
table.insert(opts, '-Wno-' .. warning)
end
end
-- -fvisibility=<>
if cfg.visibility ~= nil then
table.insert(opts, p.tools.gcc.cxxflags.visibility[cfg.visibility])
end
if #opts > 0 then
opts = table.concat(opts, " ")
vc2010.element("AdditionalOptions", condition, '%s %%(AdditionalOptions)', opts)
end
else
oldfn(cfg, condition)
end
end)
p.override(vc2010, "warningLevel", function(oldfn, cfg)
if _ACTION >= "vs2015" and cfg.system == p.ANDROID and cfg.warnings and cfg.warnings ~= "Off" then
vc2010.element("WarningLevel", nil, "EnableAllWarnings")
elseif (_ACTION >= "vs2015" and cfg.system == p.ANDROID and cfg.warnings) or not (_ACTION >= "vs2015" and cfg.system == p.ANDROID) then
oldfn(cfg)
end
end)
premake.override(vc2010, "clCompilePreprocessorDefinitions", function(oldfn, cfg, condition)
if cfg.system == p.ANDROID then
vc2010.preprocessorDefinitions(cfg, cfg.defines, false, condition)
else
oldfn(cfg, condition)
end
end)
premake.override(vc2010, "exceptionHandling", function(oldfn, cfg, condition)
if cfg.system == p.ANDROID then
-- Note: Android defaults to 'off'
local exceptions = {
On = "Enabled",
Off = "Disabled",
UnwindTables = "UnwindTables",
}
if _ACTION >= "vs2015" then
if exceptions[cfg.exceptionhandling] ~= nil then
vc2010.element("ExceptionHandling", condition, exceptions[cfg.exceptionhandling])
end
else
if cfg.exceptionhandling == premake.ON then
vc2010.element("GccExceptionHandling", condition, "true")
end
end
else
oldfn(cfg, condition)
end
end)
function android.enableEnhancedInstructionSet(cfg)
if cfg.vectorextensions == "NEON" then
vc2010.element("EnableNeonCodegen", nil, "true")
end
end
premake.override(vc2010, "runtimeTypeInfo", function(oldfn, cfg, condition)
if cfg.system == premake.ANDROID then
-- Note: Android defaults to 'off'
if cfg.rtti == premake.ON then
vc2010.element("RuntimeTypeInfo", condition, "true")
end
else
oldfn(cfg, condition)
end
end)
--
-- Extend Link.
--
premake.override(vc2010, "generateDebugInformation", function(oldfn, cfg)
-- Note: Android specifies the debug info in the clCompile section
if cfg.system ~= premake.ANDROID then
oldfn(cfg)
end
end)
--
-- Add android tools to vstudio actions.
--
premake.override(vc2010.elements, "itemDefinitionGroup", function(oldfn, cfg)
local elements = oldfn(cfg)
if cfg.system == premake.ANDROID and _ACTION < "vs2015" then
elements = table.join(elements, {
android.antBuild,
})
end
return elements
end)
function android.antPackage(cfg)
p.push('<AntPackage>')
if cfg.androidapplibname ~= nil then
vc2010.element("AndroidAppLibName", nil, cfg.androidapplibname)
else
vc2010.element("AndroidAppLibName", nil, "$(RootNamespace)")
end
p.pop('</AntPackage>')
end
function android.antBuild(cfg)
if cfg.kind == premake.STATICLIB or cfg.kind == premake.SHAREDLIB then
return
end
_p(2,'<AntBuild>')
_p(3,'<AntBuildType>%s</AntBuildType>', iif(premake.config.isDebugBuild(cfg), "Debug", "Release"))
_p(2,'</AntBuild>')
end
premake.override(vc2010, "additionalCompileOptions", function(oldfn, cfg, condition)
if cfg.system == premake.ANDROID then
vsandroid.additionalOptions(cfg, condition)
end
return oldfn(cfg, condition)
end)
premake.override(vc2010.elements, "user", function(oldfn, cfg)
if cfg.system == p.ANDROID then
return {}
else
return oldfn(cfg)
end
end)
--
-- Add options unsupported by vs-android UI to <AdvancedOptions>.
--
function vsandroid.additionalOptions(cfg)
if _ACTION >= "vs2015" then
else
local function alreadyHas(t, key)
for _, k in ipairs(t) do
if string.find(k, key) then
return true
end
end
return false
end
if not cfg.architecture or string.startswith(cfg.architecture, "arm") then
-- we might want to define the arch to generate better code
-- if not alreadyHas(cfg.buildoptions, "-march=") then
-- if cfg.architecture == "armv6" then
-- table.insert(cfg.buildoptions, "-march=armv6")
-- elseif cfg.architecture == "armv7" then
-- table.insert(cfg.buildoptions, "-march=armv7")
-- end
-- end
-- ARM has a comprehensive set of floating point options
if cfg.fpu ~= "Software" and cfg.floatabi ~= "soft" then
if cfg.architecture == "armv7" then
-- armv7 always has VFP, may not have NEON
if not alreadyHas(cfg.buildoptions, "-mfpu=") then
if cfg.vectorextensions == "NEON" then
table.insert(cfg.buildoptions, "-mfpu=neon")
elseif cfg.fpu == "Hardware" or cfg.floatabi == "softfp" or cfg.floatabi == "hard" then
table.insert(cfg.buildoptions, "-mfpu=vfpv3-d16") -- d16 is the lowest common denominator
end
end
if not alreadyHas(cfg.buildoptions, "-mfloat-abi=") then
if cfg.floatabi == "hard" then
table.insert(cfg.buildoptions, "-mfloat-abi=hard")
else
-- Android should probably use softfp by default for compatibility
table.insert(cfg.buildoptions, "-mfloat-abi=softfp")
end
end
else
-- armv5/6 may not have VFP
if not alreadyHas(cfg.buildoptions, "-mfpu=") then
if cfg.fpu == "Hardware" or cfg.floatabi == "softfp" or cfg.floatabi == "hard" then
table.insert(cfg.buildoptions, "-mfpu=vfp")
end
end
if not alreadyHas(cfg.buildoptions, "-mfloat-abi=") then
if cfg.floatabi == "softfp" then
table.insert(cfg.buildoptions, "-mfloat-abi=softfp")
elseif cfg.floatabi == "hard" then
table.insert(cfg.buildoptions, "-mfloat-abi=hard")
end
end
end
elseif cfg.floatabi == "soft" then
table.insert(cfg.buildoptions, "-mfloat-abi=soft")
end
if cfg.endian == "Little" then
table.insert(cfg.buildoptions, "-mlittle-endian")
elseif cfg.endian == "Big" then
table.insert(cfg.buildoptions, "-mbig-endian")
end
elseif cfg.architecture == "mips" then
-- TODO...
if cfg.vectorextensions == "MXU" then
table.insert(cfg.buildoptions, "-mmxu")
end
elseif cfg.architecture == "x86" then
-- TODO...
end
end
end
--
-- Disable subsystem.
--
p.override(vc2010, "subSystem", function(oldfn, cfg)
if cfg.system ~= p.ANDROID then
return oldfn(cfg)
end
end)
--
-- Remove .lib and list in LibraryDependencies instead of AdditionalDependencies.
--
p.override(vc2010, "additionalDependencies", function(oldfn, cfg, explicit)
if cfg.system == p.ANDROID then
local links = {}
-- If we need sibling projects to be listed explicitly, grab them first
if explicit then
links = config.getlinks(cfg, "siblings", "fullpath")
end
-- Then the system libraries, which come undecorated
local system = config.getlinks(cfg, "system", "name")
for i = 1, #system do
local link = system[i]
table.insert(links, link)
end
-- TODO: When to use LibraryDependencies vs AdditionalDependencies
if #links > 0 then
links = path.translate(table.concat(links, ";"))
vc2010.element("LibraryDependencies", nil, "%%(LibraryDependencies);%s", links)
end
else
return oldfn(cfg, explicit)
end
end)
function android.useMultiToolTask(cfg)
-- Android equivalent of 'MultiProcessorCompilation'
if cfg.flags.MultiProcessorCompile then
vc2010.element("UseMultiToolTask", nil, "true")
end
end
premake.override(vc2010.elements, "outputProperties", function(oldfn, cfg)
if cfg.system == p.ANDROID then
return table.join(oldfn(cfg), {
android.useMultiToolTask,
})
else
return oldfn(cfg)
end
end)
--
-- Disable override of OutDir. This is breaking deployment.
--
p.override(vc2010, "outDir", function(oldfn, cfg)
if cfg.system ~= p.ANDROID then
return oldfn(cfg)
end
end)
| bsd-3-clause |
Ninjistix/darkstar | scripts/globals/items/kenkonken.lua | 3 | 4657 | -----------------------------------------
-- ID: 19008
-- Item: Kenkonken
-----------------------------------------
require("scripts/globals/msg");
require("scripts/globals/status");
require("scripts/globals/weaponskills");
require("scripts/globals/weaponskillids");
-----------------------------------
local NAME_WEAPONSKILL = "AFTERMATH_KENKONKEN";
local NAME_EFFECT_LOSE = "AFTERMATH_LOST_KENKONKEN";
-- https://www.bg-wiki.com/bg/Mythic_Aftermath
local aftermathTable = {};
-- Kenkonken (75)
aftermathTable[19008] =
{
{ -- Tier 1
duration = 60,
mods =
{
{ id = MOD_ACC, power = function(tp) return math.floor(tp / 100); end }
}
},
{ -- Tier 2
duration = 90,
mods =
{
{ id = MOD_ATT, power = function(tp) return math.floor(2 * tp / 50 - 60); end }
}
},
{ -- Tier 3
duration = 120,
mods =
{
{ id = MOD_MYTHIC_OCC_ATT_TWICE, power = function(tp) return 40; end }
}
}
};
-- Kenkonken (80)
aftermathTable[19077] =
{
{ -- Tier 1
duration = 90,
mods =
{
{ id = MOD_ACC, power = function(tp) return math.floor(3 * tp / 200); end }
}
},
{ -- Tier 2
duration = 120,
mods =
{
{ id = MOD_ATT, power = function(tp) return math.floor(3 * tp / 50 - 90); end }
}
},
{ -- Tier 3
duration = 180,
mods =
{
{ id = MOD_MYTHIC_OCC_ATT_TWICE, power = function(tp) return 60; end }
}
}
};
aftermathTable[19097] = aftermathTable[19077]; -- Kenkonken (85)
aftermathTable[19836] = aftermathTable[19077]; -- Kenkonken (90)
-- Kenkonken (95)
aftermathTable[19727] =
{
{ -- Tier 1
duration = 90,
mods =
{
{ id = MOD_ACC, power = function(tp) return math.floor(tp / 50 + 10); end }
}
},
{ -- Tier 2
duration = 120,
mods =
{
{ id = MOD_ATT, power = function(tp) return math.floor(tp * 0.06 - 80); end }
}
},
{ -- Tier 3
duration = 180,
mods =
{
{ id = MOD_MYTHIC_OCC_ATT_TWICE, power = function(tp) return 40; end },
{ id = MOD_MYTHIC_OCC_ATT_THRICE, power = function(tp) return 20; end }
}
}
};
aftermathTable[19836] = aftermathTable[19727]; -- Kenkonken (99)
aftermathTable[19965] = aftermathTable[19727]; -- Kenkonken (99/II)
aftermathTable[20484] = aftermathTable[19727]; -- Kenkonken (119)
aftermathTable[20485] = aftermathTable[19727]; -- Kenkonken (119/II)
aftermathTable[20511] = aftermathTable[19727]; -- Kenkonken (119/III)
function onWeaponskill(user, target, wsid, tp, action)
if (wsid == WEAPONSKILL_STRINGING_PUMMEL) then -- Stringing Pummel onry
if (shouldApplyAftermath(user, tp)) then
local itemId = user:getEquipID(SLOT_MAIN);
if (aftermathTable[itemId]) then
-- Apply the effect and add mods
addMythicAftermathEffect(user, tp, aftermathTable[itemId]);
-- Add a listener for when aftermath wears (to remove mods)
user:addListener("EFFECT_LOSE", NAME_EFFECT_LOSE, aftermathLost);
-- Aftermath applies to pets
local pet = user:getPet();
if (pet) then
addMythicAftermathEffect(pet, tp, aftermathTable[itemId]);
end
end
end
end
end
function aftermathLost(target, effect)
if (effect:getType() == EFFECT_AFTERMATH) then
local itemId = target:getEquipID(SLOT_MAIN);
if (aftermathTable[itemId]) then
-- Remove mods
removeMythicAftermathEffect(target, effect, aftermathTable[itemId]);
-- Remove the effect listener
target:removeListener(NAME_EFFECT_LOSE);
-- Remove from pet
local pet = target:getPet();
if (pet) then
removeMythicAftermathEffect(pet, effect, aftermathTable[itemId]);
end
end
end
end
function onItemCheck(player, param, caster)
if (param == ITEMCHECK_EQUIP) then
player:addListener("WEAPONSKILL_USE", NAME_WEAPONSKILL, onWeaponskill);
elseif (param == ITEMCHECK_UNEQUIP) then
-- Make sure we clean up the effect and mods
if (player:hasStatusEffect(EFFECT_AFTERMATH)) then
aftermathLost(player, player:getStatusEffect(EFFECT_AFTERMATH));
end
player:removeListener(NAME_WEAPONSKILL);
end
return 0;
end | gpl-3.0 |
SharpWoW/Chocobo | Broker_Chocobo.lua | 1 | 1931 | --[[
Copyright (c) 2010-2020 by Adam Hellberg
This file is part of Chocobo.
Chocobo 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.
Chocobo 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 Chocobo. If not, see <http://www.gnu.org/licenses/>.
--]]
--#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#--
--# Broker_Chocobo #--
--# Thanks to Lothaer on Curse for the idea and initial version of this. #--
--#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#--
local L = _G["ChocoboLocale"]
local data = LibStub:GetLibrary("LibDataBroker-1.1"):NewDataObject("Broker_Chocobo", {
type = "launcher",
label = Chocobo.Name .. " |cff00FF00(" .. Chocobo.Version .. ")|r",
icon = "Interface\\AddOns\\Chocobo\\icon.tga",
text = L["Broker_Text"]
})
function data.OnTooltipShow(tip)
tip:AddLine((L["Broker_Version"]):format(Chocobo.Version))
tip:AddLine(L["Broker_LeftClick"])
tip:AddLine(L["Broker_MiddleClick"])
tip:AddLine(L["Broker_RightClick"])
end
function data.OnClick(self, button)
if button == "LeftButton" then
-- Open sound control first to expand group
Chocobo.SoundControl.Options:Open()
Chocobo.Options:Open()
elseif button == "MiddleButton" then
Chocobo.SoundControl:Toggle()
elseif button == "RightButton" then
Chocobo.SoundControl.Options:Open()
end
end
| gpl-3.0 |
Ninjistix/darkstar | scripts/globals/abilities/spectral_jig.lua | 2 | 1183 | -----------------------------------
-- Ability: Spectral jig
-- Allows you to evade enemies by making you undetectable by sight and sound.
-- Obtained: Dancer Level 25
-- TP Required: 0
-- Recast Time: 30 seconds
-- Duration: 3 minutes
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/utils");
require("scripts/globals/msg");
-----------------------------------
function onAbilityCheck(player,target,ability)
return 0,0;
end;
function onUseAbility(player,target,ability)
local baseDuration = 180;
local durationMultiplier = 1.0 + utils.clamp(player:getMod(MOD_JIG_DURATION), 0, 50) / 100;
local finalDuration = math.floor(baseDuration * durationMultiplier * SNEAK_INVIS_DURATION_MULTIPLIER);
if (player:hasStatusEffect(EFFECT_SNEAK) == false) then
player:addStatusEffect(EFFECT_SNEAK,0,10,finalDuration);
player:addStatusEffect(EFFECT_INVISIBLE,0,10,finalDuration);
ability:setMsg(msgBasic.SPECTRAL_JIG); -- Gains the effect of sneak and invisible
else
ability:setMsg(msgBasic.NO_EFFECT); -- no effect on player.
end
return 1;
end;
| gpl-3.0 |
SPARKTEA/sparkteam1 | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-3.0 |
saecoiq/Spam-Bot | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
Ninjistix/darkstar | scripts/globals/abilities/maintenance.lua | 2 | 2478 | -----------------------------------
-- Ability: Maintenance
-- Cures your automaton of status ailments. Special items required
-- Obtained: Puppetmaster Level 30
-- Recast Time: 1:30
-- Duration: Instant
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/pets")
require("scripts/globals/msg");
local idStrengths = {
[18731] = 1, -- Automaton Oil
[18732] = 2, -- Automaton Oil + 1
[18733] = 3, -- Automaton Oil + 2
[19185] = 4 -- Automaton Oil + 3
}
function onAbilityCheck(player,target,ability)
if not player:getPet() then
return msgBasic.REQUIRES_A_PET, 0
elseif not player:getPetID() or not (player:getPetID() >= 69 and player:getPetID() <= 72) then
return msgBasic.NO_EFFECT_ON_PET, 0
else
local id = player:getEquipID(SLOT_AMMO)
if idStrengths[id] then
return 0, 0
else
return msgBasic.UNABLE_TO_USE_JA, 0
end
end
end
function onUseAbility(player,target,ability)
local id = player:getEquipID(SLOT_AMMO)
local pet = player:getPet()
local function removeStatus()
--if pet:delStatusEffect(EFFECT_DOOM) then return true end
if pet:delStatusEffect(EFFECT_PETRIFICATION) then return true end
--if pet:delStatusEffect(EFFECT_LULLABY) then return true end
--if pet:delStatusEffect(EFFECT_SLEEP_II) then return true end
--if pet:delStatusEffect(EFFECT_SLEEP) then return true end
if pet:delStatusEffect(EFFECT_SILENCE) then return true end
if pet:delStatusEffect(EFFECT_BANE) then return true end
if pet:delStatusEffect(EFFECT_CURSE_II) then return true end
if pet:delStatusEffect(EFFECT_CURSE) then return true end
if pet:delStatusEffect(EFFECT_PARALYSIS) then return true end
if pet:delStatusEffect(EFFECT_PLAGUE) then return true end
if pet:delStatusEffect(EFFECT_POISON) then return true end
if pet:delStatusEffect(EFFECT_DISEASE) then return true end
if pet:delStatusEffect(EFFECT_BLINDNESS) then return true end
if pet:eraseStatusEffect() ~= 255 then return true end
return false
end
local toremove = idStrengths[id] or 1
local removed = 0
repeat
if not removeStatus() then break end
toremove = toremove - 1
removed = removed + 1
until (toremove <= 0)
player:removeAmmo()
return removed
end
| gpl-3.0 |
Ninjistix/darkstar | scripts/globals/items/green_quiche.lua | 3 | 1098 | -----------------------------------------
-- ID: 5170
-- Item: green_quiche
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Magic 10
-- Agility 1
-- Vitality -1
-- Ranged ACC % 7
-- Ranged ACC Cap 15
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5170);
end;
function onEffectGain(target, effect)
target:addMod(MOD_MP, 10);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_FOOD_RACCP, 7);
target:addMod(MOD_FOOD_RACC_CAP, 15);
end;
function onEffectLose(target, effect)
target:delMod(MOD_MP, 10);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_FOOD_RACCP, 7);
target:delMod(MOD_FOOD_RACC_CAP, 15);
end;
| gpl-3.0 |
yuna98/dbteam | libs/redis.lua | 566 | 1214 | local Redis = require 'redis'
local FakeRedis = require 'fakeredis'
local params = {
host = os.getenv('REDIS_HOST') or '127.0.0.1',
port = tonumber(os.getenv('REDIS_PORT') or 6379)
}
local database = os.getenv('REDIS_DB')
local password = os.getenv('REDIS_PASSWORD')
-- Overwrite HGETALL
Redis.commands.hgetall = Redis.command('hgetall', {
response = function(reply, command, ...)
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
})
local redis = nil
-- Won't launch an error if fails
local ok = pcall(function()
redis = Redis.connect(params)
end)
if not ok then
local fake_func = function()
print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m')
end
fake_func()
fake = FakeRedis.new()
print('\27[31mRedis addr: '..params.host..'\27[39m')
print('\27[31mRedis port: '..params.port..'\27[39m')
redis = setmetatable({fakeredis=true}, {
__index = function(a, b)
if b ~= 'data' and fake[b] then
fake_func(b)
end
return fake[b] or fake_func
end })
else
if password then
redis:auth(password)
end
if database then
redis:select(database)
end
end
return redis
| gpl-2.0 |
Xagul/forgottenserver | data/talkactions/scripts/buyhouse.lua | 16 | 1163 | function onSay(player, words, param)
local housePrice = configManager.getNumber(configKeys.HOUSE_PRICE)
if housePrice == -1 then
return true
end
if not player:isPremium() then
player:sendCancelMessage("You need a premium account.")
return false
end
local position = player:getPosition()
position:getNextPosition(player:getDirection())
local tile = Tile(position)
local house = tile and tile:getHouse()
if house == nil then
player:sendCancelMessage("You have to be looking at the door of the house you would like to buy.")
return false
end
if house:getOwnerGuid() > 0 then
player:sendCancelMessage("This house already has an owner.")
return false
end
if player:getHouse() then
player:sendCancelMessage("You are already the owner of a house.")
return false
end
local price = house:getTileCount() * housePrice
if not player:removeMoney(price) then
player:sendCancelMessage("You do not have enough money.")
return false
end
house:setOwnerGuid(player:getGuid())
player:sendTextMessage(MESSAGE_INFO_DESCR, "You have successfully bought this house, be sure to have the money for the rent in the bank.")
return false
end
| gpl-2.0 |
gmorishere/s | plugins/google.lua | 336 | 1323 | do
local function googlethat(query)
local url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&safe=active&&rsz=5&'
local parameters = 'q='..(URL.escape(query) or '')
-- Do the request
local res, code = https.request(url..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=''
i = 0
for key,val in ipairs(results) do
i = i+1
stringresults=stringresults..i..'. '..val[1]..'\n'..val[2]..'\n'
end
return stringresults
end
local function run(msg, matches)
-- comment this line if you want this plugin works in private message.
if not is_chat_msg(msg) then return nil end
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = 'Returns five results from Google. Safe search is enabled by default.',
usage = ' !google [terms]: Searches Google and send results',
patterns = {
'^!google (.*)$',
'^%.[g|G]oogle (.*)$'
},
run = run
}
end
| gpl-2.0 |
davidbuzz/ardupilot | libraries/AP_Scripting/tests/math.lua | 26 | 25303 | -- $Id: math.lua,v 1.77 2016/06/23 15:17:20 roberto Exp roberto $
--[[
*****************************************************************************
* Copyright (C) 1994-2016 Lua.org, PUC-Rio.
*
* 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 code is copied from https://github.com/lua/tests and slightly modified to work within ArduPilot
gcs:send_text(6, "testing numbers and math lib")
local minint = math.mininteger
local maxint = math.maxinteger
local intbits = math.floor(math.log(maxint, 2) + 0.5) + 1
assert((1 << intbits) == 0)
assert(minint == 1 << (intbits - 1))
assert(maxint == minint - 1)
-- number of bits in the mantissa of a floating-point number
local floatbits = 24
do
local p = 2.0^floatbits
while p < p + 1.0 do
p = p * 2.0
floatbits = floatbits + 1
end
end
local function isNaN (x)
return (x ~= x)
end
assert(isNaN(0/0))
assert(not isNaN(1/0))
do
local x = 2.0^floatbits
assert(x > x - 1.0 and x == x + 1.0)
gcs:send_text(6, string.format("%d-bit integers, %d-bit (mantissa) floats",
intbits, floatbits))
end
assert(math.type(0) == "integer" and math.type(0.0) == "float"
and math.type("10") == nil)
local function checkerror (msg, f, ...)
local s, err = pcall(f, ...)
assert(not s and string.find(err, msg))
end
local msgf2i = "number.* has no integer representation"
-- float equality
function eq (a,b,limit)
if not limit then
if floatbits >= 50 then limit = 1E-11
else limit = 1E-5
end
end
-- a == b needed for +inf/-inf
return a == b or math.abs(a-b) <= limit
end
-- equality with types
function eqT (a,b)
return a == b and math.type(a) == math.type(b)
end
-- basic float notation
assert(0e12 == 0 and .0 == 0 and 0. == 0 and .2e2 == 20 and 2.E-1 == 0.2)
do
local a,b,c = "2", " 3e0 ", " 10 "
assert(a+b == 5 and -b == -3 and b+"2" == 5 and "10"-c == 0)
assert(type(a) == 'string' and type(b) == 'string' and type(c) == 'string')
assert(a == "2" and b == " 3e0 " and c == " 10 " and -c == -" 10 ")
assert(c%a == 0 and a^b == 08)
a = 0
assert(a == -a and 0 == -0)
end
do
local x = -1
local mz = 0/x -- minus zero
t = {[0] = 10, 20, 30, 40, 50}
assert(t[mz] == t[0] and t[-0] == t[0])
end
do -- tests for 'modf'
local a,b = math.modf(3.5)
assert(a == 3.0 and b == 0.5)
a,b = math.modf(-2.5)
assert(a == -2.0 and b == -0.5)
a,b = math.modf(-3e23)
assert(a == -3e23 and b == 0.0)
a,b = math.modf(3e35)
assert(a == 3e35 and b == 0.0)
a,b = math.modf(-1/0) -- -inf
assert(a == -1/0 and b == 0.0)
a,b = math.modf(1/0) -- inf
assert(a == 1/0 and b == 0.0)
a,b = math.modf(0/0) -- NaN
assert(isNaN(a) and isNaN(b))
a,b = math.modf(3) -- integer argument
assert(eqT(a, 3) and eqT(b, 0.0))
a,b = math.modf(minint)
assert(eqT(a, minint) and eqT(b, 0.0))
end
assert(math.huge > 10e30)
assert(-math.huge < -10e30)
-- integer arithmetic
assert(minint < minint + 1)
assert(maxint - 1 < maxint)
assert(0 - minint == minint)
assert(minint * minint == 0)
assert(maxint * maxint * maxint == maxint)
-- testing floor division and conversions
for _, i in pairs{-16, -15, -3, -2, -1, 0, 1, 2, 3, 15} do
for _, j in pairs{-16, -15, -3, -2, -1, 1, 2, 3, 15} do
for _, ti in pairs{0, 0.0} do -- try 'i' as integer and as float
for _, tj in pairs{0, 0.0} do -- try 'j' as integer and as float
local x = i + ti
local y = j + tj
assert(i//j == math.floor(i/j))
end
end
end
end
assert(1//0.0 == 1/0)
assert(-1 // 0.0 == -1/0)
assert(eqT(3.5 // 1.5, 2.0))
assert(eqT(3.5 // -1.5, -3.0))
assert(maxint // maxint == 1)
assert(maxint // 1 == maxint)
assert((maxint - 1) // maxint == 0)
assert(maxint // (maxint - 1) == 1)
assert(minint // minint == 1)
assert(minint // minint == 1)
assert((minint + 1) // minint == 0)
assert(minint // (minint + 1) == 1)
assert(minint // 1 == minint)
assert(minint // -1 == -minint)
assert(minint // -2 == 2^(intbits - 2))
assert(maxint // -1 == -maxint)
-- negative exponents
do
assert(2^-3 == 1 / 2^3)
assert(eq((-3)^-3, 1 / (-3)^3))
for i = -3, 3 do -- variables avoid constant folding
for j = -3, 3 do
-- domain errors (0^(-n)) are not portable
if not _port or i ~= 0 or j > 0 then
assert(eq(i^j, 1 / i^(-j)))
end
end
end
end
-- comparison between floats and integers (border cases)
if floatbits < intbits then
assert(2.0^floatbits == (1 << floatbits))
assert(2.0^floatbits - 1.0 == (1 << floatbits) - 1.0)
assert(2.0^floatbits - 1.0 ~= (1 << floatbits))
-- float is rounded, int is not
assert(2.0^floatbits + 1.0 ~= (1 << floatbits) + 1)
else -- floats can express all integers with full accuracy
assert(maxint == maxint + 0.0)
assert(maxint - 1 == maxint - 1.0)
assert(minint + 1 == minint + 1.0)
assert(maxint ~= maxint - 1.0)
end
assert(maxint + 0.0 == 2.0^(intbits - 1) - 1.0)
assert(minint + 0.0 == minint)
assert(minint + 0.0 == -2.0^(intbits - 1))
-- order between floats and integers
assert(1 < 1.1); assert(not (1 < 0.9))
assert(1 <= 1.1); assert(not (1 <= 0.9))
assert(-1 < -0.9); assert(not (-1 < -1.1))
assert(1 <= 1.1); assert(not (-1 <= -1.1))
assert(-1 < -0.9); assert(not (-1 < -1.1))
assert(-1 <= -0.9); assert(not (-1 <= -1.1))
assert(minint <= minint + 0.0)
assert(minint + 0.0 <= minint)
assert(not (minint < minint + 0.0))
assert(not (minint + 0.0 < minint))
assert(maxint < minint * -1.0)
assert(maxint <= minint * -1.0)
do
local fmaxi1 = 2^(intbits - 1)
assert(maxint < fmaxi1)
assert(maxint <= fmaxi1)
assert(not (fmaxi1 <= maxint))
assert(minint <= -2^(intbits - 1))
assert(-2^(intbits - 1) <= minint)
end
if floatbits < intbits then
gcs:send_text(6, "testing order (floats can't represent all int)")
local fmax = 2^floatbits
local ifmax = fmax | 0
assert(fmax < ifmax + 1)
assert(fmax - 1 < ifmax)
assert(-(fmax - 1) > -ifmax)
assert(not (fmax <= ifmax - 1))
assert(-fmax > -(ifmax + 1))
assert(not (-fmax >= -(ifmax - 1)))
assert(fmax/2 - 0.5 < ifmax//2)
assert(-(fmax/2 - 0.5) > -ifmax//2)
assert(maxint < 2^intbits)
assert(minint > -2^intbits)
assert(maxint <= 2^intbits)
assert(minint >= -2^intbits)
else
gcs:send_text(6, "testing order (floats can represent all ints)")
assert(maxint < maxint + 1.0)
assert(maxint < maxint + 0.5)
assert(maxint - 1.0 < maxint)
assert(maxint - 0.5 < maxint)
assert(not (maxint + 0.0 < maxint))
assert(maxint + 0.0 <= maxint)
assert(not (maxint < maxint + 0.0))
assert(maxint + 0.0 <= maxint)
assert(maxint <= maxint + 0.0)
assert(not (maxint + 1.0 <= maxint))
assert(not (maxint + 0.5 <= maxint))
assert(not (maxint <= maxint - 1.0))
assert(not (maxint <= maxint - 0.5))
assert(minint < minint + 1.0)
assert(minint < minint + 0.5)
assert(minint <= minint + 0.5)
assert(minint - 1.0 < minint)
assert(minint - 1.0 <= minint)
assert(not (minint + 0.0 < minint))
assert(not (minint + 0.5 < minint))
assert(not (minint < minint + 0.0))
assert(minint + 0.0 <= minint)
assert(minint <= minint + 0.0)
assert(not (minint + 1.0 <= minint))
assert(not (minint + 0.5 <= minint))
assert(not (minint <= minint - 1.0))
end
do
local NaN = 0/0
assert(not (NaN < 0))
assert(not (NaN > minint))
assert(not (NaN <= -9))
assert(not (NaN <= maxint))
assert(not (NaN < maxint))
assert(not (minint <= NaN))
assert(not (minint < NaN))
end
-- avoiding errors at compile time
--local function checkcompt (msg, code)
-- checkerror(msg, assert(load(code)))
--end
--checkcompt("divide by zero", "return 2 // 0")
--checkcompt(msgf2i, "return 2.3 >> 0")
--checkcompt(msgf2i, ("return 2.0^%d & 1"):format(intbits - 1))
--checkcompt("field 'huge'", "return math.huge << 1")
--checkcompt(msgf2i, ("return 1 | 2.0^%d"):format(intbits - 1))
--checkcompt(msgf2i, "return 2.3 ~ '0.0'")
-- testing overflow errors when converting from float to integer (runtime)
local function f2i (x) return x | x end
checkerror(msgf2i, f2i, math.huge) -- +inf
checkerror(msgf2i, f2i, -math.huge) -- -inf
checkerror(msgf2i, f2i, 0/0) -- NaN
if floatbits < intbits then
-- conversion tests when float cannot represent all integers
assert(maxint + 1.0 == maxint + 0.0)
assert(minint - 1.0 == minint + 0.0)
checkerror(msgf2i, f2i, maxint + 0.0)
assert(f2i(2.0^(intbits - 2)) == 1 << (intbits - 2))
assert(f2i(-2.0^(intbits - 2)) == -(1 << (intbits - 2)))
assert((2.0^(floatbits - 1) + 1.0) // 1 == (1 << (floatbits - 1)) + 1)
-- maximum integer representable as a float
local mf = maxint - (1 << (floatbits - intbits)) + 1
assert(f2i(mf + 0.0) == mf) -- OK up to here
mf = mf + 1
assert(f2i(mf + 0.0) ~= mf) -- no more representable
else
-- conversion tests when float can represent all integers
assert(maxint + 1.0 > maxint)
assert(minint - 1.0 < minint)
assert(f2i(maxint + 0.0) == maxint)
checkerror("no integer rep", f2i, maxint + 1.0)
checkerror("no integer rep", f2i, minint - 1.0)
end
-- 'minint' should be representable as a float no matter the precision
assert(f2i(minint + 0.0) == minint)
-- testing numeric strings
assert("2" + 1 == 3)
assert("2 " + 1 == 3)
assert(" -2 " + 1 == -1)
assert(" -0xa " + 1 == -9)
-- Literal integer Overflows (new behavior in 5.3.3)
do
-- no overflows
assert(eqT(tonumber(tostring(maxint)), maxint))
assert(eqT(tonumber(tostring(minint)), minint))
-- add 1 to last digit as a string (it cannot be 9...)
local function incd (n)
local s = string.format("%d", n)
s = string.gsub(s, "%d$", function (d)
assert(d ~= '9')
return string.char(string.byte(d) + 1)
end)
return s
end
-- 'tonumber' with overflow by 1
assert(eqT(tonumber(incd(maxint)), maxint + 1.0))
assert(eqT(tonumber(incd(minint)), minint - 1.0))
-- large numbers
assert(eqT(tonumber("1"..string.rep("0", 30)), 1e30))
assert(eqT(tonumber("-1"..string.rep("0", 30)), -1e30))
-- hexa format still wraps around
assert(eqT(tonumber("0x1"..string.rep("0", 30)), 0))
-- lexer in the limits
--assert(minint == load("return " .. minint)())
--assert(eqT(maxint, load("return " .. maxint)()))
assert(eqT(10000000000000000000000.0, 10000000000000000000000))
assert(eqT(-10000000000000000000000.0, -10000000000000000000000))
end
-- testing 'tonumber'
-- 'tonumber' with numbers
assert(tonumber(3.4) == 3.4)
assert(eqT(tonumber(3), 3))
assert(eqT(tonumber(maxint), maxint) and eqT(tonumber(minint), minint))
assert(tonumber(1/0) == 1/0)
-- 'tonumber' with strings
assert(tonumber("0") == 0)
assert(tonumber("") == nil)
assert(tonumber(" ") == nil)
assert(tonumber("-") == nil)
assert(tonumber(" -0x ") == nil)
assert(tonumber{} == nil)
assert(tonumber'+0.01' == 1/100 and tonumber'+.01' == 0.01 and
tonumber'.01' == 0.01 and tonumber'-1.' == -1 and
tonumber'+1.' == 1)
assert(tonumber'+ 0.01' == nil and tonumber'+.e1' == nil and
tonumber'1e' == nil and tonumber'1.0e+' == nil and
tonumber'.' == nil)
assert(tonumber('-012') == -010-2)
assert(tonumber('-1.2e2') == - - -120)
assert(tonumber("0xffffffffffff") == (1 << (4*12)) - 1)
assert(tonumber("0x"..string.rep("f", (intbits//4))) == -1)
assert(tonumber("-0x"..string.rep("f", (intbits//4))) == 1)
-- testing 'tonumber' with base
assert(tonumber(' 001010 ', 2) == 10)
assert(tonumber(' 001010 ', 10) == 001010)
assert(tonumber(' -1010 ', 2) == -10)
assert(tonumber('10', 36) == 36)
assert(tonumber(' -10 ', 36) == -36)
assert(tonumber(' +1Z ', 36) == 36 + 35)
assert(tonumber(' -1z ', 36) == -36 + -35)
assert(tonumber('-fFfa', 16) == -(10+(16*(15+(16*(15+(16*15)))))))
assert(tonumber(string.rep('1', (intbits - 2)), 2) + 1 == 2^(intbits - 2))
assert(tonumber('ffffFFFF', 16)+1 == (1 << 32))
assert(tonumber('0ffffFFFF', 16)+1 == (1 << 32))
assert(tonumber('-0ffffffFFFF', 16) - 1 == -(1 << 40))
for i = 2,36 do
local i2 = i * i
local i10 = i2 * i2 * i2 * i2 * i2 -- i^10
assert(tonumber('\t10000000000\t', i) == i10)
end
if not _soft then
-- tests with very long numerals
assert(tonumber("0x"..string.rep("f", 13)..".0") == 2.0^(4*13) - 1)
assert(tonumber("0x"..string.rep("f", 150)..".0") == 2.0^(4*150) - 1)
assert(tonumber("0x"..string.rep("f", 300)..".0") == 2.0^(4*300) - 1)
assert(tonumber("0x"..string.rep("f", 500)..".0") == 2.0^(4*500) - 1)
assert(tonumber('0x3.' .. string.rep('0', 1000)) == 3)
assert(tonumber('0x' .. string.rep('0', 1000) .. 'a') == 10)
assert(tonumber('0x0.' .. string.rep('0', 13).."1") == 2.0^(-4*14))
assert(tonumber('0x0.' .. string.rep('0', 150).."1") == 2.0^(-4*151))
assert(tonumber('0x0.' .. string.rep('0', 300).."1") == 2.0^(-4*301))
assert(tonumber('0x0.' .. string.rep('0', 500).."1") == 2.0^(-4*501))
assert(tonumber('0xe03' .. string.rep('0', 1000) .. 'p-4000') == 3587.0)
assert(tonumber('0x.' .. string.rep('0', 1000) .. '74p4004') == 0x7.4)
end
-- testing 'tonumber' for invalid formats
--[[
local function f (...)
if select('#', ...) == 1 then
return (...)
else
return "***"
end
end
assert(f(tonumber('fFfa', 15)) == nil)
assert(f(tonumber('099', 8)) == nil)
assert(f(tonumber('1\0', 2)) == nil)
assert(f(tonumber('', 8)) == nil)
assert(f(tonumber(' ', 9)) == nil)
assert(f(tonumber(' ', 9)) == nil)
assert(f(tonumber('0xf', 10)) == nil)
assert(f(tonumber('inf')) == nil)
assert(f(tonumber(' INF ')) == nil)
assert(f(tonumber('Nan')) == nil)
assert(f(tonumber('nan')) == nil)
assert(f(tonumber(' ')) == nil)
assert(f(tonumber('')) == nil)
assert(f(tonumber('1 a')) == nil)
assert(f(tonumber('1 a', 2)) == nil)
assert(f(tonumber('1\0')) == nil)
assert(f(tonumber('1 \0')) == nil)
assert(f(tonumber('1\0 ')) == nil)
assert(f(tonumber('e1')) == nil)
assert(f(tonumber('e 1')) == nil)
assert(f(tonumber(' 3.4.5 ')) == nil)
]]
-- testing 'tonumber' for invalid hexadecimal formats
assert(tonumber('0x') == nil)
assert(tonumber('x') == nil)
assert(tonumber('x3') == nil)
assert(tonumber('0x3.3.3') == nil) -- two decimal points
assert(tonumber('00x2') == nil)
assert(tonumber('0x 2') == nil)
assert(tonumber('0 x2') == nil)
assert(tonumber('23x') == nil)
assert(tonumber('- 0xaa') == nil)
assert(tonumber('-0xaaP ') == nil) -- no exponent
assert(tonumber('0x0.51p') == nil)
assert(tonumber('0x5p+-2') == nil)
-- testing hexadecimal numerals
assert(0x10 == 16 and 0xfff == 2^12 - 1 and 0XFB == 251)
assert(0x0p12 == 0 and 0x.0p-3 == 0)
assert(0xFFFFFFFF == (1 << 32) - 1)
assert(tonumber('+0x2') == 2)
assert(tonumber('-0xaA') == -170)
assert(tonumber('-0xffFFFfff') == -(1 << 32) + 1)
-- possible confusion with decimal exponent
assert(0E+1 == 0 and 0xE+1 == 15 and 0xe-1 == 13)
-- floating hexas
assert(tonumber(' 0x2.5 ') == 0x25/16)
assert(tonumber(' -0x2.5 ') == -0x25/16)
assert(tonumber(' +0x0.51p+8 ') == 0x51)
assert(0x.FfffFFFF == 1 - '0x.00000001')
assert('0xA.a' + 0 == 10 + 10/16)
assert(0xa.aP4 == 0XAA)
assert(0x4P-2 == 1)
assert(0x1.1 == '0x1.' + '+0x.1')
assert(0Xabcdef.0 == 0x.ABCDEFp+24)
assert(1.1 == 1.+.1)
assert(100.0 == 1E2 and .01 == 1e-2)
assert(1111111111 - 1111111110 == 1000.00e-03)
assert(1.1 == '1.'+'.1')
assert(tonumber'1111111111' - tonumber'1111111110' ==
tonumber" +0.001e+3 \n\t")
assert(0.1e-30 > 0.9E-31 and 0.9E30 < 0.1e31)
assert(0.123456 > 0.123455)
assert(tonumber('+1.23E18') == 1.23*10.0^18)
-- testing order operators
assert(not(1<1) and (1<2) and not(2<1))
assert(not('a'<'a') and ('a'<'b') and not('b'<'a'))
assert((1<=1) and (1<=2) and not(2<=1))
assert(('a'<='a') and ('a'<='b') and not('b'<='a'))
assert(not(1>1) and not(1>2) and (2>1))
assert(not('a'>'a') and not('a'>'b') and ('b'>'a'))
assert((1>=1) and not(1>=2) and (2>=1))
assert(('a'>='a') and not('a'>='b') and ('b'>='a'))
assert(1.3 < 1.4 and 1.3 <= 1.4 and not (1.3 < 1.3) and 1.3 <= 1.3)
-- testing mod operator
assert(eqT(-4 % 3, 2))
assert(eqT(4 % -3, -2))
assert(eqT(-4.0 % 3, 2.0))
assert(eqT(4 % -3.0, -2.0))
assert(math.pi - math.pi % 1 == 3)
assert(math.pi - math.pi % 0.001 == 3.141)
assert(eqT(minint % minint, 0))
assert(eqT(maxint % maxint, 0))
assert((minint + 1) % minint == minint + 1)
assert((maxint - 1) % maxint == maxint - 1)
assert(minint % maxint == maxint - 1)
assert(minint % -1 == 0)
assert(minint % -2 == 0)
assert(maxint % -2 == -1)
-- testing unsigned comparisons
assert(math.ult(3, 4))
assert(not math.ult(4, 4))
assert(math.ult(-2, -1))
assert(math.ult(2, -1))
assert(not math.ult(-2, -2))
assert(math.ult(maxint, minint))
assert(not math.ult(minint, maxint))
assert(eq(math.sin(-9.8)^2 + math.cos(-9.8)^2, 1))
assert(eq(math.tan(math.pi/4), 1))
assert(eq(math.sin(math.pi/2), 1) and eq(math.cos(math.pi/2), 0))
assert(eq(math.atan(1), math.pi/4) and eq(math.acos(0), math.pi/2) and
eq(math.asin(1), math.pi/2))
assert(eq(math.deg(math.pi/2), 90) and eq(math.rad(90), math.pi/2))
assert(math.abs(-10.43) == 10.43)
assert(eqT(math.abs(minint), minint))
assert(eqT(math.abs(maxint), maxint))
assert(eqT(math.abs(-maxint), maxint))
assert(eq(math.atan(1,0), math.pi/2))
assert(math.fmod(10,3) == 1)
assert(eq(math.sqrt(10)^2, 10))
assert(eq(math.log(2, 10), math.log(2)/math.log(10)))
assert(eq(math.log(2, 2), 1))
assert(eq(math.log(9, 3), 2))
assert(eq(math.exp(0), 1))
assert(eq(math.sin(10), math.sin(10%(2*math.pi))))
assert(tonumber(' 1.3e-2 ') == 1.3e-2)
assert(tonumber(' -1.00000000000001 ') == -1.00000000000001)
-- testing constant limits
-- 2^23 = 8388608
assert(8388609 + -8388609 == 0)
assert(8388608 + -8388608 == 0)
assert(8388607 + -8388607 == 0)
do -- testing floor & ceil
assert(eqT(math.floor(3.4), 3))
assert(eqT(math.ceil(3.4), 4))
assert(eqT(math.floor(-3.4), -4))
assert(eqT(math.ceil(-3.4), -3))
assert(eqT(math.floor(maxint), maxint))
assert(eqT(math.ceil(maxint), maxint))
assert(eqT(math.floor(minint), minint))
assert(eqT(math.floor(minint + 0.0), minint))
assert(eqT(math.ceil(minint), minint))
assert(eqT(math.ceil(minint + 0.0), minint))
assert(math.floor(1e50) == 1e50)
assert(math.ceil(1e50) == 1e50)
assert(math.floor(-1e50) == -1e50)
assert(math.ceil(-1e50) == -1e50)
for _, p in pairs{31,32,63,64} do
assert(math.floor(2^p) == 2^p)
assert(math.floor(2^p + 0.5) == 2^p)
assert(math.ceil(2^p) == 2^p)
assert(math.ceil(2^p - 0.5) == 2^p)
end
checkerror("number expected", math.floor, {})
checkerror("number expected", math.ceil, print)
assert(eqT(math.tointeger(minint), minint))
assert(eqT(math.tointeger(minint .. ""), minint))
assert(eqT(math.tointeger(maxint), maxint))
assert(eqT(math.tointeger(maxint .. ""), maxint))
assert(eqT(math.tointeger(minint + 0.0), minint))
assert(math.tointeger(0.0 - minint) == nil)
assert(math.tointeger(math.pi) == nil)
assert(math.tointeger(-math.pi) == nil)
assert(math.floor(math.huge) == math.huge)
assert(math.ceil(math.huge) == math.huge)
assert(math.tointeger(math.huge) == nil)
assert(math.floor(-math.huge) == -math.huge)
assert(math.ceil(-math.huge) == -math.huge)
assert(math.tointeger(-math.huge) == nil)
assert(math.tointeger("34.0") == 34)
assert(math.tointeger("34.3") == nil)
assert(math.tointeger({}) == nil)
assert(math.tointeger(0/0) == nil) -- NaN
end
-- testing fmod for integers
for i = -6, 6 do
for j = -6, 6 do
if j ~= 0 then
local mi = math.fmod(i, j)
local mf = math.fmod(i + 0.0, j)
assert(mi == mf)
assert(math.type(mi) == 'integer' and math.type(mf) == 'float')
if (i >= 0 and j >= 0) or (i <= 0 and j <= 0) or mi == 0 then
assert(eqT(mi, i % j))
end
end
end
end
assert(eqT(math.fmod(minint, minint), 0))
assert(eqT(math.fmod(maxint, maxint), 0))
assert(eqT(math.fmod(minint + 1, minint), minint + 1))
assert(eqT(math.fmod(maxint - 1, maxint), maxint - 1))
checkerror("zero", math.fmod, 3, 0)
do -- testing max/min
checkerror("value expected", math.max)
checkerror("value expected", math.min)
assert(eqT(math.max(3), 3))
assert(eqT(math.max(3, 5, 9, 1), 9))
assert(math.max(maxint, 10e60) == 10e60)
assert(eqT(math.max(minint, minint + 1), minint + 1))
assert(eqT(math.min(3), 3))
assert(eqT(math.min(3, 5, 9, 1), 1))
assert(math.min(3.2, 5.9, -9.2, 1.1) == -9.2)
assert(math.min(1.9, 1.7, 1.72) == 1.7)
assert(math.min(-10e60, minint) == -10e60)
assert(eqT(math.min(maxint, maxint - 1), maxint - 1))
assert(eqT(math.min(maxint - 2, maxint, maxint - 1), maxint - 2))
end
-- testing implicit convertions
local a,b = '10', '20'
assert(a*b == 200 and a+b == 30 and a-b == -10 and a/b == 0.5 and -b == -20)
assert(a == '10' and b == '20')
do
gcs:send_text(6, "testing -0 and NaN")
local mz, z = -0.0, 0.0
assert(mz == z)
assert(1/mz < 0 and 0 < 1/z)
local a = {[mz] = 1}
assert(a[z] == 1 and a[mz] == 1)
a[z] = 2
assert(a[z] == 2 and a[mz] == 2)
local inf = math.huge * 2 + 1
mz, z = -1/inf, 1/inf
assert(mz == z)
assert(1/mz < 0 and 0 < 1/z)
local NaN = inf - inf
assert(NaN ~= NaN)
assert(not (NaN < NaN))
assert(not (NaN <= NaN))
assert(not (NaN > NaN))
assert(not (NaN >= NaN))
assert(not (0 < NaN) and not (NaN < 0))
local NaN1 = 0/0
assert(NaN ~= NaN1 and not (NaN <= NaN1) and not (NaN1 <= NaN))
local a = {}
assert(not pcall(rawset, a, NaN, 1))
assert(a[NaN] == nil)
a[1] = 1
assert(not pcall(rawset, a, NaN, 1))
assert(a[NaN] == nil)
-- strings with same binary representation as 0.0 (might create problems
-- for constant manipulation in the pre-compiler)
local a1, a2, a3, a4, a5 = 0, 0, "\0\0\0\0\0\0\0\0", 0, "\0\0\0\0\0\0\0\0"
assert(a1 == a2 and a2 == a4 and a1 ~= a3)
assert(a3 == a5)
end
gcs:send_text(6, "testing 'math.random'")
math.randomseed(0)
do -- test random for floats
local max = -math.huge
local min = math.huge
for i = 0, 20000 do
local t = math.random()
assert(0 <= t and t < 1)
max = math.max(max, t)
min = math.min(min, t)
if eq(max, 1, 0.001) and eq(min, 0, 0.001) then
goto ok
end
end
-- loop ended without satisfing condition
assert(false)
::ok::
end
do
local function aux (p, lim) -- test random for small intervals
local x1, x2
if #p == 1 then x1 = 1; x2 = p[1]
else x1 = p[1]; x2 = p[2]
end
local mark = {}; local count = 0 -- to check that all values appeared
for i = 0, lim or 2000 do
local t = math.random(table.unpack(p))
assert(x1 <= t and t <= x2)
if not mark[t] then -- new value
mark[t] = true
count = count + 1
end
if count == x2 - x1 + 1 then -- all values appeared; OK
goto ok
end
end
-- loop ended without satisfing condition
assert(false)
::ok::
end
aux({-10,0})
aux({6})
aux({-10, 10})
aux({minint, minint})
aux({maxint, maxint})
aux({minint, minint + 9})
aux({maxint - 3, maxint})
end
do
local function aux(p1, p2) -- test random for large intervals
local max = minint
local min = maxint
local n = 200
local mark = {}; local count = 0 -- to count how many different values
for _ = 1, n do
local t = math.random(p1, p2)
max = math.max(max, t)
min = math.min(min, t)
if not mark[t] then -- new value
mark[t] = true
count = count + 1
end
end
-- at least 80% of values are different
assert(count >= n * 0.8)
-- min and max not too far from formal min and max
local diff = (p2 - p1) // 8
assert(min < p1 + diff and max > p2 - diff)
end
aux(0, maxint)
aux(1, maxint)
aux(minint, -1)
aux(minint // 2, maxint // 2)
end
for i=1,100 do
assert(math.random(maxint) > 0)
assert(math.random(minint, -1) < 0)
end
assert(not pcall(math.random, 1, 2, 3)) -- too many arguments
-- empty interval
assert(not pcall(math.random, minint + 1, minint))
assert(not pcall(math.random, maxint, maxint - 1))
assert(not pcall(math.random, maxint, minint))
-- interval too large
assert(not pcall(math.random, minint, 0))
assert(not pcall(math.random, -1, maxint))
assert(not pcall(math.random, minint // 2, maxint // 2 + 1))
function update()
gcs:send_text(6, 'Math tests passed')
return update, 1000
end
return update()
| gpl-3.0 |
mandersan/premake-core | binmodules/luasocket/src/mbox.lua | 51 | 2654 | local _M = {}
if module then
mbox = _M
end
function _M.split_message(message_s)
local message = {}
message_s = string.gsub(message_s, "\r\n", "\n")
string.gsub(message_s, "^(.-\n)\n", function (h) message.headers = h end)
string.gsub(message_s, "^.-\n\n(.*)", function (b) message.body = b end)
if not message.body then
string.gsub(message_s, "^\n(.*)", function (b) message.body = b end)
end
if not message.headers and not message.body then
message.headers = message_s
end
return message.headers or "", message.body or ""
end
function _M.split_headers(headers_s)
local headers = {}
headers_s = string.gsub(headers_s, "\r\n", "\n")
headers_s = string.gsub(headers_s, "\n[ ]+", " ")
string.gsub("\n" .. headers_s, "\n([^\n]+)", function (h) table.insert(headers, h) end)
return headers
end
function _M.parse_header(header_s)
header_s = string.gsub(header_s, "\n[ ]+", " ")
header_s = string.gsub(header_s, "\n+", "")
local _, __, name, value = string.find(header_s, "([^%s:]-):%s*(.*)")
return name, value
end
function _M.parse_headers(headers_s)
local headers_t = _M.split_headers(headers_s)
local headers = {}
for i = 1, #headers_t do
local name, value = _M.parse_header(headers_t[i])
if name then
name = string.lower(name)
if headers[name] then
headers[name] = headers[name] .. ", " .. value
else headers[name] = value end
end
end
return headers
end
function _M.parse_from(from)
local _, __, name, address = string.find(from, "^%s*(.-)%s*%<(.-)%>")
if not address then
_, __, address = string.find(from, "%s*(.+)%s*")
end
name = name or ""
address = address or ""
if name == "" then name = address end
name = string.gsub(name, '"', "")
return name, address
end
function _M.split_mbox(mbox_s)
local mbox = {}
mbox_s = string.gsub(mbox_s, "\r\n", "\n") .."\n\nFrom \n"
local nj, i, j = 1, 1, 1
while 1 do
i, nj = string.find(mbox_s, "\n\nFrom .-\n", j)
if not i then break end
local message = string.sub(mbox_s, j, i-1)
table.insert(mbox, message)
j = nj+1
end
return mbox
end
function _M.parse(mbox_s)
local mbox = _M.split_mbox(mbox_s)
for i = 1, #mbox do
mbox[i] = _M.parse_message(mbox[i])
end
return mbox
end
function _M.parse_message(message_s)
local message = {}
message.headers, message.body = _M.split_message(message_s)
message.headers = _M.parse_headers(message.headers)
return message
end
return _M
| bsd-3-clause |
backburn/Probably | interface/buttons.lua | 1 | 7563 | -- ProbablyEngine Rotations - https://probablyengine.com/
-- Released under modified BSD, see attached LICENSE.
ProbablyEngine.buttons = {
frame = CreateFrame("Frame", "PE_Buttons", UIParent),
buttonFrame = CreateFrame("Frame", "PE_Buttons_Container", UIParent),
buttons = { },
size = 36,
scale = 1,
padding = 6,
count = 0,
}
-- Masque ?!
local MSQ = LibStub("Masque", true)
local probablySkinGroup
if MSQ then
probablySkinGroup = MSQ:Group("ProbablyEngine", "Buttons")
end
-- ElvUI ?!
local E, L, V, P, G
if IsAddOnLoaded("ElvUI") then
E, L, V, P, G = unpack(ElvUI)
ElvSkin = E:GetModule('ActionBars')
ProbablyEngine.buttons.padding = 3
ProbablyEngine.buttons.size = 31
end
ProbablyEngine.buttons.frame:SetPoint("CENTER", UIParent)
ProbablyEngine.buttons.frame:SetWidth(170)
ProbablyEngine.buttons.frame:SetHeight(ProbablyEngine.buttons.size+5)
ProbablyEngine.buttons.frame:SetMovable(true)
ProbablyEngine.buttons.frame:SetFrameStrata('HIGH')
ProbablyEngine.buttons.frame:Hide()
ProbablyEngine.buttons.buttonFrame:Hide()
ProbablyEngine.buttons.statusText = ProbablyEngine.buttons.frame:CreateFontString('PE_StatusText')
ProbablyEngine.buttons.statusText:SetFont("Fonts\\ARIALN.TTF", 16)
ProbablyEngine.buttons.statusText:SetShadowColor(0,0,0, 0.8)
ProbablyEngine.buttons.statusText:SetShadowOffset(-1,-1)
ProbablyEngine.buttons.statusText:SetPoint("CENTER", ProbablyEngine.buttons.frame)
ProbablyEngine.buttons.statusText:SetText("|cffffffff"..pelg('drag_to_position').."|r")
ProbablyEngine.buttons.frame.texture = ProbablyEngine.buttons.frame:CreateTexture()
ProbablyEngine.buttons.frame.texture:SetAllPoints(ProbablyEngine.buttons.frame)
ProbablyEngine.buttons.frame.texture:SetTexture(0,0,0,0.6)
ProbablyEngine.buttons.frame:SetScript("OnMouseDown", function(self, button)
if not self.isMoving then
self:StartMoving()
self.isMoving = true
end
end)
ProbablyEngine.buttons.frame:SetScript("OnMouseUp", function(self, button)
if self.isMoving then
self:StopMovingOrSizing()
self.isMoving = false
end
end)
ProbablyEngine.buttons.frame:SetScript("OnHide", function(self)
if self.isMoving then
self:StopMovingOrSizing()
self.isMoving = false
end
end)
ProbablyEngine.buttons.create = function(name, icon, callback, tooltipl1, tooltipl2)
if _G['PE_Buttons_' .. name] then
ProbablyEngine.buttons.buttons[name] = _G['PE_Buttons_' .. name]
_G['PE_Buttons_' .. name]:Show()
else
ProbablyEngine.buttons.buttons[name] = CreateFrame("CheckButton", "PE_Buttons_"..name, ProbablyEngine.buttons.buttonFrame, "ActionButtonTemplate")
end
ProbablyEngine.buttons.buttons[name]:RegisterForClicks("LeftButtonUp", "RightButtonUp")
local button = ProbablyEngine.buttons.buttons[name]
button:SetPoint("TOPLEFT", ProbablyEngine.buttons.frame, "TOPLEFT",
(
(ProbablyEngine.buttons.size*ProbablyEngine.buttons.count)
+
(ProbablyEngine.buttons.count*ProbablyEngine.buttons.padding)
+ 4
)
, -3)
button:SetWidth(ProbablyEngine.buttons.size)
button:SetHeight(ProbablyEngine.buttons.size)
-- theme it, Masque ?
if probablySkinGroup then
probablySkinGroup:AddButton(button)
end
-- theme it, ElvUI ?
if ElvSkin then
ElvSkin.db = E.db.actionbar
button:CreateBackdrop("ClassColor")
ElvSkin:StyleButton(button, nil, true)
button:SetCheckedTexture(nil)
button:SetPushedTexture(nil)
button.customTheme = function ()
button:SetCheckedTexture(nil)
local state = button.checked
if state then
button.backdrop:Show()
else
button.backdrop:Hide()
end
end
local originalCallback = callback or false
callback = function (self, mouseButton)
if originalCallback then
originalCallback(self, mouseButton)
end
button.customTheme()
end
end
if icon == nil then
button.icon:SetTexture('Interface\\ICONS\\INV_Misc_QuestionMark')
else
button.icon:SetTexture(icon)
end
button:SetScript("OnClick", callback)
if tooltipl1 ~= nil then
button:SetScript("OnEnter", function(self)
GameTooltip:SetOwner(self, "ANCHOR_TOP")
GameTooltip:AddLine("|cffffffff" .. tooltipl1 .. "|r")
if tooltipl2 then
GameTooltip:AddLine(tooltipl2)
end
GameTooltip:Show()
end)
button:SetScript("OnLeave", function(self)
GameTooltip:Hide()
end)
end
button.checked = false
button:SetPushedTexture(nil)
_G['PE_Buttons_'..name.."HotKey"]:SetText('Off')
_G['PE_Buttons_'..name.."HotKey"]:Hide()
if ProbablyEngine.config.read('buttonVisualText', false) then
_G['PE_Buttons_'..name.."HotKey"]:Show()
end
ProbablyEngine.buttons.count = ProbablyEngine.buttons.count + 1
end
ProbablyEngine.buttons.text = function(name, text)
local hotkey = _G['PE_Buttons_'.. name .."HotKey"]
hotkey:SetText(text);
hotkey:Show();
end
ProbablyEngine.buttons.setActive = function(name)
if _G['PE_Buttons_'.. name] then
_G['PE_Buttons_'.. name].checked = true
_G['PE_Buttons_'.. name]:SetChecked(1)
_G['PE_Buttons_'..name.."HotKey"]:SetText('On')
if _G['PE_Buttons_'.. name].customTheme then
_G['PE_Buttons_'.. name].customTheme()
end
ProbablyEngine.config.write('button_states', name, true)
end
end
ProbablyEngine.buttons.setInactive = function(name)
if _G['PE_Buttons_'.. name] then
_G['PE_Buttons_'.. name].checked = false
_G['PE_Buttons_'.. name]:SetChecked(0)
_G['PE_Buttons_'..name.."HotKey"]:SetText('Off')
if _G['PE_Buttons_'.. name].customTheme then
_G['PE_Buttons_'.. name].customTheme()
end
ProbablyEngine.config.write('button_states', name, false)
end
end
ProbablyEngine.buttons.toggle = function(name)
if _G['PE_Buttons_'.. name] then
local state = _G['PE_Buttons_'.. name].checked
if state then
ProbablyEngine.buttons.setInactive(name)
else
ProbablyEngine.buttons.setActive(name)
end
end
end
ProbablyEngine.buttons.icon = function(name, icon)
_G['PE_Buttons_'.. name ..'Icon']:SetTexture(icon)
end
ProbablyEngine.buttons.loadStates = function()
if ProbablyEngine.config.read('uishown') then
if ProbablyEngine.config.read('uishown') then
ProbablyEngine.buttons.buttonFrame:Show()
else
ProbablyEngine.buttons.buttonFrame:Hide()
end
else
ProbablyEngine.buttons.buttonFrame:Show()
ProbablyEngine.config.write('uishown', true)
end
for name in pairs(ProbablyEngine.buttons.buttons) do
local state = ProbablyEngine.config.read('button_states', name, false)
if state == true then
ProbablyEngine.buttons.setActive(name)
else
ProbablyEngine.buttons.setInactive(name)
end
end
end
ProbablyEngine.buttons.resetButtons = function ()
if ProbablyEngine.buttons.buttons then
local defaultButtons = { 'MasterToggle', 'cooldowns', 'multitarget', 'interrupt' }
for name, button in pairs(ProbablyEngine.buttons.buttons) do
-- button text toggles
if ProbablyEngine.config.read('buttonVisualText', false) then
_G['PE_Buttons_'..name.."HotKey"]:Show()
else
_G['PE_Buttons_'..name.."HotKey"]:Hide()
end
local original = false
for _, buttonName in pairs(defaultButtons) do
if name == buttonName then
original = true
break
end
end
if not original then
ProbablyEngine.buttons.buttons[name] = nil
button:Hide()
end
end
ProbablyEngine.buttons.count = table.length(ProbablyEngine.buttons.buttons)
end
end
| bsd-3-clause |
Ninjistix/darkstar | scripts/zones/Cloister_of_Flames/bcnms/trial-size_trial_by_fire.lua | 7 | 2141 | -----------------------------------
-- Area: Cloister of Flames
-- BCNM: Trial-size Trial by Fire
-- !pos -721 0 -598 207
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Flames/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Cloister_of_Flames/TextIDs");
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
player:startEvent(32001,1,1,1,instance:getTimeInside(),1,0,0);
elseif (leavecode == 4) then
player:setVar("TrialSizeFire_date",tonumber(os.date("%j"))); -- If you loose, you need to wait 1 real day
player:startEvent(32002);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 32001) then
if (player:hasSpell(298) == false) then
player:addSpell(298); -- Ifrit
player:messageSpecial(IFRIT_UNLOCKED,0,0,0);
end
if (player:hasItem(4181) == false) then
player:addItem(4181);
player:messageSpecial(ITEM_OBTAINED,4181); -- Scroll of instant warp
end
player:setVar("TrialSizeFire_date", 0);
player:addFame(KAZHAM,30);
player:completeQuest(OUTLANDS,TRIAL_SIZE_TRIAL_BY_FIRE);
end
end; | gpl-3.0 |
Ninjistix/darkstar | scripts/globals/abilities/aspir_samba.lua | 2 | 1316 | -----------------------------------
-- Ability: Aspir Samba
-- Inflicts the next target you strike with Aspir daze, allowing all those engaged in battle with it to drain its MP.
-- Obtained: Dancer Level 25
-- TP Required: 10%
-- Recast Time: 1:00
-- Duration: 2:00
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/msg");
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:hasStatusEffect(EFFECT_FAN_DANCE)) then
return msgBasic.UNABLE_TO_USE_JA2, 0;
elseif (player:hasStatusEffect(EFFECT_TRANCE)) then
return 0,0;
elseif (player:getTP() < 100) then
return msgBasic.NOT_ENOUGH_TP,0;
else
return 0,0;
end;
end;
function onUseAbility(player,target,ability)
-- Only remove TP if the player doesn't have Trance.
if not player:hasStatusEffect(EFFECT_TRANCE) then
player:delTP(100);
end;
local duration = 120 + player:getMod(MOD_SAMBA_DURATION);
duration = duration * (100 + player:getMod(MOD_SAMBA_PDURATION))/100;
player:delStatusEffect(EFFECT_HASTE_SAMBA);
player:delStatusEffect(EFFECT_DRAIN_SAMBA);
player:addStatusEffect(EFFECT_ASPIR_SAMBA,1,0,duration);
end;
| gpl-3.0 |
Ninjistix/darkstar | scripts/zones/Port_Bastok/npcs/Tilian.lua | 5 | 1080 | -----------------------------------
-- Area: Port Bastok
-- NPC: Tilian
-- Type: Quest NPC
-- !pos -118.460 4.999 -68.090 236
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_Bastok/TextIDs");
require("scripts/globals/quests");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local WildcatBastok = player:getVar("WildcatBastok");
if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,4) == false) then
player:startEvent(353);
else
player:startEvent(100);
end
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 353) then
player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",4,true);
end
end;
| gpl-3.0 |
Ninjistix/darkstar | scripts/globals/abilities/building_flourish.lua | 2 | 2641 | -----------------------------------
-- Ability: Building Flourish
-- Enhances potency of your next weapon skill. Requires at least one Finishing Move.
-- Obtained: Dancer Level 50
-- Finishing Moves Used: 1-3
-- Recast Time: 00:10
-- Duration: 01:00
--
-- Using one Finishing Move boosts the Accuracy of your next weapon skill.
-- Using two Finishing Moves boosts both the Accuracy and Attack of your next weapon skill.
-- Using three Finishing Moves boosts the Accuracy, Attack and Critical Hit Rate of your next weapon skill.
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/msg");
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then
return 0,0;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then
return 0,0;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then
return 0,0;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then
return 0,0;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then
return 0,0;
else
return msgBasic.NO_FINISHINGMOVES,0;
end;
end;
function onUseAbility(player,target,ability)
if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then
player:delStatusEffect(EFFECT_FINISHING_MOVE_1);
player:addStatusEffect(EFFECT_BUILDING_FLOURISH,1,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT));
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then
player:delStatusEffect(EFFECT_FINISHING_MOVE_2);
player:addStatusEffect(EFFECT_BUILDING_FLOURISH,2,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT));
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then
player:delStatusEffect(EFFECT_FINISHING_MOVE_3);
player:addStatusEffect(EFFECT_BUILDING_FLOURISH,3,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT));
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then
player:delStatusEffect(EFFECT_FINISHING_MOVE_4);
player:addStatusEffect(EFFECT_FINISHING_MOVE_1,1,0,7200);
player:addStatusEffect(EFFECT_BUILDING_FLOURISH,3,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT));
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then
player:delStatusEffect(EFFECT_FINISHING_MOVE_5);
player:addStatusEffect(EFFECT_FINISHING_MOVE_2,1,0,7200);
player:addStatusEffect(EFFECT_BUILDING_FLOURISH,3,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT));
end;
end; | gpl-3.0 |
dinodeck/ninety_nine_days_of_dev | 001_cancel_textboxes/code/ShopState.lua | 3 | 12714 |
ShopState = {}
ShopState.__index = ShopState
function ShopState:Create(stack, world, def)
def = def or {}
local this
this =
{
mStack = stack,
mWorld = world,
mDef = def,
mPanels = {},
mName = def.name or "Shop",
mActors = {},
mActorCharMap = {},
mState = "choose", -- "choose", "buy", "sell"
mTabs =
{
["buy"] = 1,
["sell"] = 2,
["exit"] = 3,
},
mChooseSelection = Selection:Create
{
data =
{
"Buy",
"Sell",
"Exit",
},
rows = 1,
columns = 3,
OnSelection = function(...) this:ChooseClick(...) end,
},
mStock = Selection:Create
{
data = def.stock,
displayRows = 5,
RenderItem = function(...) this:RenderStock(...) end,
OnSelection = function(...) this:OnBuy(...) end,
},
mInventory = nil,
mScrollbar = Scrollbar:Create(Texture.Find("scrollbar.png"), 145),
mFilterList =
{
['all'] = function(def) return true end,
['arms'] = function(def)
return def.type == 'armor' or def.type == 'weapon'
end,
['support'] = function(def)
return def.type == 'useable'
end
},
mCanUseSprite = Sprite.Create(),
-- Used every frame
mItemInvCount = 0,
mItemEquipCount,
mItemDescription = 0,
}
for _, v in pairs(this.mWorld.mParty.mMembers) do
table.insert(this.mActors, v)
local def = gCharacters[v.mId]
local char = Character:Create(def, {})
this.mActorCharMap[v] = char
end
local layout = Layout:Create()
layout:Contract('screen', 118, 40)
layout:SplitHorz('screen', 'top', 'bottom', 0.12, 1)
layout:SplitVert('top', 'title', 'choose', 0.75, 1)
layout:SplitHorz('bottom', 'top', 'char', 0.55, 1)
layout:SplitHorz('char', 'desc', 'char', 0.25, 1)
layout:SplitVert('top', 'inv', 'status', 0.35, 1)
this.mPanels =
{
layout:CreatePanel("title"),
layout:CreatePanel("choose"),
layout:CreatePanel("desc"),
layout:CreatePanel("char"),
layout:CreatePanel("inv"),
layout:CreatePanel("status")
}
this.mLayout = layout
this.mCanUseSprite:SetTexture(Texture.Find("up_caret.png"))
-- default to all
local filterId = def.sell_filter or 'all'
this.InvFilter = this.mFilterList[filterId]
local cX = layout:Left("choose") + 24
local cY = layout:MidY("choose")
this.mChooseSelection:SetPosition(cX, cY)
local sX = layout:Left("inv") - 16
local sY = layout:Top("inv") - 18
this.mPriceX = layout:Right("inv") - 56
this.mStock:SetPosition(sX, sY)
local scrollX = layout:Right("inv") - 14
local scrollY = layout:MidY("inv")
this.mScrollbar:SetPosition(scrollX, scrollY)
setmetatable(this, self)
this.mInventory = this:CreateInvSelection()
this.mStock:HideCursor()
this.mInventory:HideCursor()
return this
end
function ShopState:Enter() end
function ShopState:Exit() end
function ShopState:Update(dt) end
function ShopState:CreateInvSelection()
local stock = self.mWorld:FilterItems(self.InvFilter)
local inv = Selection:Create
{
data = stock or {},
displayRows = self.mStock.mDisplayRows,
RenderItem = function(...) self:RenderInventory(...) end,
OnSelection = function(...) self:OnSell(...) end,
spacingX = 225,
}
local x = self.mStock.mX
local y = self.mStock.mY
inv:SetPosition(x, y)
inv:HideCursor() -- hidden by default
return inv
end
function ShopState:OnBuy(index, item)
local gold = self.mWorld.mGold
if gold < item.price then
return -- can't afford
end
gold = gold - item.price
self.mWorld.mGold = gold
self.mWorld:AddItem(item.id)
local name = ItemDB[item.id].name
local message = string.format("Bought %s", name)
self.mStack:PushFit(gRenderer, 0, 0, message)
end
function ShopState:OnSell(index, item)
local gold = self.mWorld.mGold
local def = ItemDB[item.id]
self.mWorld:RemoveItem(item.id)
gold = gold + def.price
self.mWorld.mGold = gold
-- Refresh inventory disaply
self.mInventory = self:CreateInvSelection()
self.mInventory:ShowCursor()
-- Attempt to restore the index
for i = 1, index - 1 do
self.mInventory:MoveDown()
end
local message = string.format("Sold %s", def.name)
self.mStack:PushFit(gRenderer, 0, 0, message)
end
function ShopState:RenderStock(menu, renderer, x, y, item)
if item == nil then
return
end
local color = nil
if self.mWorld.mGold < item.price then
color = Vector.Create(0.6, 0.6, 0.6, 1)
end
self.mWorld:DrawItem(menu, renderer, x, y, item, color)
renderer:AlignTextX("right")
local priceStr = string.format(": %d", item.price)
renderer:DrawText2d(self.mPriceX, y, priceStr, color)
end
function ShopState:RenderInventory(menu, renderer, x, y, item)
if not item then
return
end
self.mWorld:DrawItem(menu, renderer, x, y, item)
local def = ItemDB[item.id]
renderer:AlignTextX("right")
local priceStr = string.format(": %d", def.price)
renderer:DrawText2d(self.mPriceX, y, priceStr)
end
function ShopState:BackToChooseState()
self.mState = "choose"
self.mChooseSelection:ShowCursor()
self.mInventory:HideCursor()
self.mStock:HideCursor()
end
function ShopState:ChooseClick(index, item)
if index == self.mTabs.buy then
self.mChooseSelection:HideCursor()
self.mStock:ShowCursor()
self.mState = "buy"
elseif index == self.mTabs.sell then
self.mChooseSelection:HideCursor()
self.mInventory:ShowCursor()
self.mState = "sell"
else
self.mStack:Pop() -- Remove self off the stack
end
end
function ShopState:RenderChooseFocus(renderer)
renderer:AlignText("left", "center")
self.mChooseSelection:Render(renderer)
local focus = self.mChooseSelection:GetIndex()
if focus == self.mTabs.buy then
self.mStock:Render(renderer)
self:UpdateScrollbar(renderer, self.mStock)
elseif focus == self.mTabs.sell then
self.mInventory:Render(renderer)
self:UpdateScrollbar(renderer, self.mInventory)
else
end
end
function ShopState:IsEquipmentBetter(actor, itemDef)
-- Only compare weapons or armor
if itemDef.type == "weapon" then
-- compare attack power
local diff = actor:PredictStats("weapon", itemDef)
return diff.attack > 0
elseif itemDef.type == "armor" then
-- compare defense power
local diff = actor:PredictStats("armor", itemDef)
return diff.defense > 0
end
return false
end
function ShopState:SetItemData(item)
if item then
local party = self.mWorld.mParty
self.mItemInvCount = self.mWorld:ItemCount(item.id)
self.mItemEquipCount = party:EquipCount(item.id)
local def = ItemDB[item.id]
self.mItemDef = def
self.mItemDescription = def.description
else
self.mItemInvCount = 0
self.mItemEquipCount = 0
self.mItemDescription = ""
self.mItemDef = nil
end
end
function ShopState:UpdateScrollbar(renderer, selection)
if selection:PercentageShown() <= 1 then
local scrolled = selection:PercentageScrolled()
local caretScale = selection:PercentageShown()
self.mScrollbar:SetScrollCaretScale(caretScale)
self.mScrollbar:SetNormalValue(scrolled)
self.mScrollbar:Render(renderer)
end
end
function ShopState:HandleInput()
if self.mState == "choose" then
self.mChooseSelection:HandleInput()
elseif self.mState == "buy" then
self.mStock:HandleInput()
if Keyboard.JustPressed(KEY_BACKSPACE) then
self:BackToChooseState()
end
elseif self.mState == "sell" then
self.mInventory:HandleInput()
if Keyboard.JustPressed(KEY_BACKSPACE) then
self:BackToChooseState()
end
end
end
function ShopState:DrawCharacters(renderer, itemDef)
local x = self.mLayout:Left("char") + 64
local y = self.mLayout:MidY("char")
local selectColor = Vector.Create(1, 1, 1, 1)
local powerColor = Vector.Create(0, 1, 1, 1)
local shadowColor = Vector.Create(0, 0, 0, 1)
for _, actor in ipairs(self.mActors) do
local char = self.mActorCharMap[actor]
local entity = char.mEntity
entity.mSprite:SetPosition(x, y)
entity:Render(renderer)
local canUse = false
local greaterPower = false
local equipped = false
if itemDef then
canUse = actor:CanUse(itemDef)
equipped = actor:EquipCount(itemDef.id) > 0
greaterPower = self:IsEquipmentBetter(actor, itemDef)
end
if canUse then
local selectY = y - (entity.mHeight / 2)
selectY = selectY - 6 -- add space
self.mCanUseSprite:SetPosition(x, selectY)
self.mCanUseSprite:SetColor(selectColor)
renderer:DrawSprite(self.mCanUseSprite)
end
if greaterPower then
local selectY = y + (entity.mHeight / 2)
local selectX = x - (entity.mWidth / 2)
selectX = selectX - 6 -- spacing
self.mCanUseSprite:SetPosition(selectX, selectY)
self.mCanUseSprite:SetColor(powerColor)
renderer:DrawSprite(self.mCanUseSprite)
end
if equipped then
local equipX = x - (entity.mWidth / 2)
local equipY = y - (entity.mWidth / 2)
equipX = equipX - 3
renderer:AlignText("right", "center")
renderer:DrawText2d(equipX + 2, equipY - 2, "E", shadowColor)
renderer:DrawText2d(equipX, equipY, "E")
end
x = x + 64
end
end
function ShopState:Render(renderer)
for k, v in ipairs(self.mPanels)do
v:Render(renderer)
end
-- Let's write the title
renderer:AlignText("center", "center")
renderer:ScaleText(1.25, 1.25)
local tX = self.mLayout:MidX("title")
local tY = self.mLayout:MidY("title")
renderer:DrawText2d(tX, tY, self.mName)
local x = self.mLayout:MidX("choose")
local y = self.mLayout:MidY("choose")
if self.mState == "choose" then
self:RenderChooseFocus(renderer)
self:SetItemData(nil)
elseif self.mState == "buy" then
local buyMessage = "What would you like?"
renderer:AlignText("center", "center")
renderer:DrawText2d(x, y, buyMessage)
renderer:AlignText("left", "center")
self.mStock:Render(renderer)
local item = self.mStock:SelectedItem()
self:SetItemData(item)
self:UpdateScrollbar(renderer, self.mStock)
elseif self.mState == "sell" then
local sellMessage = "Show me what you have."
renderer:AlignText("center", "center")
renderer:DrawText2d(x, y, sellMessage)
renderer:AlignText("left", "center")
self.mInventory:Render(renderer)
local item = self.mInventory:SelectedItem()
self:SetItemData(item)
self:UpdateScrollbar(renderer, self.mInventory)
end
-- Let's write the status bar
renderer:AlignText("right", "center")
renderer:ScaleText(1.1, 1.1)
local statusX = self.mLayout:MidX("status") - 4
local statusY = self.mLayout:Top("status") - 18
local valueX = statusX + 8
local gpText = "GP:"
local invText = "Inventory:"
local equipText = "Equipped:"
local gpValue = string.format("%d", self.mWorld.mGold)
local invValue = string.format("%d", self.mItemInvCount)
local equipValue = string.format("%d", self.mItemEquipCount)
renderer:DrawText2d(statusX, statusY, gpText)
renderer:DrawText2d(statusX, statusY - 32, invText)
renderer:DrawText2d(statusX, statusY - 50, equipText)
renderer:AlignText("left", "center")
renderer:DrawText2d(valueX, statusY, gpValue)
renderer:DrawText2d(valueX, statusY - 32, invValue)
renderer:DrawText2d(valueX, statusY - 50, equipValue)
renderer:AlignText("left", "center")
renderer:ScaleText(1,1)
local descX = self.mLayout:Left("desc") + 8
local descY = self.mLayout:MidY("desc")
renderer:DrawText2d(descX, descY, self.mItemDescription)
self:DrawCharacters(renderer, self.mItemDef)
end
| mit |
mandersan/premake-core | src/base/semver.lua | 22 | 6948 | local semver = {
_VERSION = '1.2.1',
_DESCRIPTION = 'semver for Lua',
_URL = 'https://github.com/kikito/semver.lua',
_LICENSE = [[
MIT LICENSE
Copyright (c) 2015 Enrique García Cota
Permission is hereby granted, free of charge, to any person obtaining a
copy of tother 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 tother permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
}
local function checkPositiveInteger(number, name)
assert(number >= 0, name .. ' must be a valid positive number')
assert(math.floor(number) == number, name .. ' must be an integer')
end
local function present(value)
return value and value ~= ''
end
-- splitByDot("a.bbc.d") == {"a", "bbc", "d"}
local function splitByDot(str)
str = str or ""
local t, count = {}, 0
str:gsub("([^%.]+)", function(c)
count = count + 1
t[count] = c
end)
return t
end
local function parsePrereleaseAndBuildWithSign(str)
local prereleaseWithSign, buildWithSign = str:match("^(-[^+]+)(+.+)$")
if not (prereleaseWithSign and buildWithSign) then
prereleaseWithSign = str:match("^(-.+)$")
buildWithSign = str:match("^(+.+)$")
end
assert(prereleaseWithSign or buildWithSign, ("The parameter %q must begin with + or - to denote a prerelease or a build"):format(str))
return prereleaseWithSign, buildWithSign
end
local function parsePrerelease(prereleaseWithSign)
if prereleaseWithSign then
local prerelease = prereleaseWithSign:match("^-(%w[%.%w-]*)$")
assert(prerelease, ("The prerelease %q is not a slash followed by alphanumerics, dots and slashes"):format(prereleaseWithSign))
return prerelease
end
end
local function parseBuild(buildWithSign)
if buildWithSign then
local build = buildWithSign:match("^%+(%w[%.%w-]*)$")
assert(build, ("The build %q is not a + sign followed by alphanumerics, dots and slashes"):format(buildWithSign))
return build
end
end
local function parsePrereleaseAndBuild(str)
if not present(str) then return nil, nil end
local prereleaseWithSign, buildWithSign = parsePrereleaseAndBuildWithSign(str)
local prerelease = parsePrerelease(prereleaseWithSign)
local build = parseBuild(buildWithSign)
return prerelease, build
end
local function parseVersion(str)
local sMajor, sMinor, sPatch, sPrereleaseAndBuild = str:match("^(%d+)%.?(%d*)%.?(%d*)(.-)$")
assert(type(sMajor) == 'string', ("Could not extract version number(s) from %q"):format(str))
local major, minor, patch = tonumber(sMajor), tonumber(sMinor), tonumber(sPatch)
local prerelease, build = parsePrereleaseAndBuild(sPrereleaseAndBuild)
return major, minor, patch, prerelease, build
end
-- return 0 if a == b, -1 if a < b, and 1 if a > b
local function compare(a,b)
return a == b and 0 or a < b and -1 or 1
end
local function compareIds(myId, otherId)
if myId == otherId then return 0
elseif not myId then return -1
elseif not otherId then return 1
end
local selfNumber, otherNumber = tonumber(myId), tonumber(otherId)
if selfNumber and otherNumber then -- numerical comparison
return compare(selfNumber, otherNumber)
-- numericals are always smaller than alphanums
elseif selfNumber then
return -1
elseif otherNumber then
return 1
else
return compare(myId, otherId) -- alphanumerical comparison
end
end
local function smallerIdList(myIds, otherIds)
local myLength = #myIds
local comparison
for i=1, myLength do
comparison = compareIds(myIds[i], otherIds[i])
if comparison ~= 0 then
return comparison == -1
end
-- if comparison == 0, continue loop
end
return myLength < #otherIds
end
local function smallerPrerelease(mine, other)
if mine == other or not mine then return false
elseif not other then return true
end
return smallerIdList(splitByDot(mine), splitByDot(other))
end
local methods = {}
function methods:nextMajor()
return semver(self.major + 1, 0, 0)
end
function methods:nextMinor()
return semver(self.major, self.minor + 1, 0)
end
function methods:nextPatch()
return semver(self.major, self.minor, self.patch + 1)
end
local mt = { __index = methods }
function mt:__eq(other)
return self.major == other.major and
self.minor == other.minor and
self.patch == other.patch and
self.prerelease == other.prerelease
-- notice that build is ignored for precedence in semver 2.0.0
end
function mt:__lt(other)
if self.major ~= other.major then return self.major < other.major end
if self.minor ~= other.minor then return self.minor < other.minor end
if self.patch ~= other.patch then return self.patch < other.patch end
return smallerPrerelease(self.prerelease, other.prerelease)
-- notice that build is ignored for precedence in semver 2.0.0
end
-- This works like the "pessimisstic operator" in Rubygems.
-- if a and b are versions, a ^ b means "b is backwards-compatible with a"
-- in other words, "it's safe to upgrade from a to b"
function mt:__pow(other)
if self.major == 0 then
return self == other
end
return self.major == other.major and
self.minor <= other.minor
end
function mt:__tostring()
local buffer = { ("%d.%d.%d"):format(self.major, self.minor, self.patch) }
if self.prerelease then table.insert(buffer, "-" .. self.prerelease) end
if self.build then table.insert(buffer, "+" .. self.build) end
return table.concat(buffer)
end
local function new(major, minor, patch, prerelease, build)
assert(major, "At least one parameter is needed")
if type(major) == 'string' then
major,minor,patch,prerelease,build = parseVersion(major)
end
patch = patch or 0
minor = minor or 0
checkPositiveInteger(major, "major")
checkPositiveInteger(minor, "minor")
checkPositiveInteger(patch, "patch")
local result = {major=major, minor=minor, patch=patch, prerelease=prerelease, build=build}
return setmetatable(result, mt)
end
setmetatable(semver, { __call = function(_, ...) return new(...) end })
semver._VERSION= semver(semver._VERSION)
return semver
| bsd-3-clause |
codedash64/Urho3D | bin/Data/LuaScripts/46_RaycastVehicleDemo.lua | 12 | 17493 | -- Vehicle example.
-- This sample demonstrates:
-- - Creating a heightmap terrain with collision
-- - Constructing a physical vehicle with rigid bodies for the hull and the wheels, joined with constraints
-- - Saving and loading the variables of a script object, including node & component references
require "LuaScripts/Utilities/Sample"
local CTRL_FORWARD = 1
local CTRL_BACK = 2
local CTRL_LEFT = 4
local CTRL_RIGHT = 8
local CTRL_BRAKE = 16
local CAMERA_DISTANCE = 10.0
local YAW_SENSITIVITY = 0.1
local ENGINE_FORCE = 2500.0
local DOWN_FORCE = 100.0
local MAX_WHEEL_ANGLE = 22.5
local CHASSIS_WIDTH = 2.6
local vehicleNode = nil
function Start()
-- Execute the common startup for samples
SampleStart()
-- Create static scene content
CreateScene()
-- Create the controllable vehicle
CreateVehicle()
-- Create the UI content
CreateInstructions()
-- Set the mouse mode to use in the sample
SampleInitMouseMode(MM_RELATIVE)
-- Subscribe to necessary events
SubscribeToEvents()
end
function CreateScene()
scene_ = Scene()
-- Create scene subsystem components
scene_:CreateComponent("Octree")
scene_:CreateComponent("PhysicsWorld")
-- Create camera and define viewport. Camera does not necessarily have to belong to the scene
cameraNode = Node()
local camera = cameraNode:CreateComponent("Camera")
camera.farClip = 500.0
renderer:SetViewport(0, Viewport:new(scene_, camera))
-- Create static scene content. First create a zone for ambient lighting and fog control
local zoneNode = scene_:CreateChild("Zone")
local zone = zoneNode:CreateComponent("Zone")
zone.ambientColor = Color(0.15, 0.15, 0.15)
zone.fogColor = Color(0.5, 0.5, 0.7)
zone.fogStart = 300.0
zone.fogEnd = 500.0
zone.boundingBox = BoundingBox(-2000.0, 2000.0)
-- Create a directional light to the world. Enable cascaded shadows on it
local lightNode = scene_:CreateChild("DirectionalLight")
lightNode.direction = Vector3(0.3, -0.5, 0.425)
local light = lightNode:CreateComponent("Light")
light.lightType = LIGHT_DIRECTIONAL
light.castShadows = true
light.shadowBias = BiasParameters(0.00025, 0.5)
light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
light.specularIntensity = 0.5
-- Create heightmap terrain with collision
local terrainNode = scene_:CreateChild("Terrain")
terrainNode.position = Vector3(0.0, 0.0, 0.0)
local terrain = terrainNode:CreateComponent("Terrain")
terrain.patchSize = 64
terrain.spacing = Vector3(2.0, 0.1, 2.0) -- Spacing between vertices and vertical resolution of the height map
terrain.smoothing = true
terrain.heightMap = cache:GetResource("Image", "Textures/HeightMap.png")
terrain.material = cache:GetResource("Material", "Materials/Terrain.xml")
-- The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
-- terrain patches and other objects behind it
terrain.occluder = true
local body = terrainNode:CreateComponent("RigidBody")
body.collisionLayer = 2 -- Use layer bitmask 2 for static geometry
local shape = terrainNode:CreateComponent("CollisionShape")
shape:SetTerrain()
-- Create 1000 mushrooms in the terrain. Always face outward along the terrain normal
local NUM_MUSHROOMS = 1000
for i = 1, NUM_MUSHROOMS do
local objectNode = scene_:CreateChild("Mushroom")
local position = Vector3(Random(2000.0) - 1000.0, 0.0, Random(2000.0) - 1000.0)
position.y = terrain:GetHeight(position) - 0.1
objectNode.position = position
-- Create a rotation quaternion from up vector to terrain normal
objectNode.rotation = Quaternion(Vector3(0.0, 1.0, 0.0), terrain:GetNormal(position))
objectNode:SetScale(3.0)
local object = objectNode:CreateComponent("StaticModel")
object.model = cache:GetResource("Model", "Models/Mushroom.mdl")
object.material = cache:GetResource("Material", "Materials/Mushroom.xml")
object.castShadows = true
local body = objectNode:CreateComponent("RigidBody")
body.collisionLayer = 2
local shape = objectNode:CreateComponent("CollisionShape")
shape:SetTriangleMesh(object.model, 0)
end
end
function CreateVehicle()
vehicleNode = scene_:CreateChild("Vehicle")
vehicleNode.position = Vector3(0.0, 5.0, 0.0)
-- Create the vehicle logic script object
local vehicle = vehicleNode:CreateScriptObject("Vehicle")
-- Create the rendering and physics components
vehicle:Init()
local hullBody = vehicleNode:GetComponent("RigidBody")
hullBody.mass = 800.0
hullBody.linearDamping = 0.2
hullBody.angularDamping = 0.5
hullBody.collisionLayer = 1
end
function CreateInstructions()
-- Construct new Text object, set string to display and font to use
local instructionText = ui.root:CreateChild("Text")
instructionText.text = "Use WASD keys to drive, mouse/touch to rotate camera\n"..
"F5 to save scene, F7 to load"
instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
-- The text has multiple rows. Center them in relation to each other
instructionText.textAlignment = HA_CENTER
-- Position the text relative to the screen center
instructionText.horizontalAlignment = HA_CENTER
instructionText.verticalAlignment = VA_CENTER
instructionText:SetPosition(0, ui.root.height / 4)
end
function SubscribeToEvents()
-- Subscribe to Update event for setting the vehicle controls before physics simulation
SubscribeToEvent("Update", "HandleUpdate")
-- Subscribe to PostUpdate event for updating the camera position after physics simulation
SubscribeToEvent("PostUpdate", "HandlePostUpdate")
-- Unsubscribe the SceneUpdate event from base class as the camera node is being controlled in HandlePostUpdate() in this sample
UnsubscribeFromEvent("SceneUpdate")
end
function HandleUpdate(eventType, eventData)
if vehicleNode == nil then
return
end
local vehicle = vehicleNode:GetScriptObject()
if vehicle == nil then
return
end
-- Get movement controls and assign them to the vehicle component. If UI has a focused element, clear controls
if ui.focusElement == nil then
vehicle.controls:Set(CTRL_FORWARD, input:GetKeyDown(KEY_W))
vehicle.controls:Set(CTRL_BACK, input:GetKeyDown(KEY_S))
vehicle.controls:Set(CTRL_LEFT, input:GetKeyDown(KEY_A))
vehicle.controls:Set(CTRL_RIGHT, input:GetKeyDown(KEY_D))
vehicle.controls:Set(CTRL_BRAKE, input:GetKeyDown(KEY_F))
-- Add yaw & pitch from the mouse motion or touch input. Used only for the camera, does not affect motion
if touchEnabled then
for i=0, input.numTouches - 1 do
local state = input:GetTouch(i)
if not state.touchedElement then -- Touch on empty space
local camera = cameraNode:GetComponent("Camera")
if not camera then return end
vehicle.controls.yaw = vehicle.controls.yaw + TOUCH_SENSITIVITY * camera.fov / graphics.height * state.delta.x
vehicle.controls.pitch = vehicle.controls.pitch + TOUCH_SENSITIVITY * camera.fov / graphics.height * state.delta.y
end
end
else
vehicle.controls.yaw = vehicle.controls.yaw + input.mouseMoveX * YAW_SENSITIVITY
vehicle.controls.pitch = vehicle.controls.pitch + input.mouseMoveY * YAW_SENSITIVITY
end
-- Limit pitch
vehicle.controls.pitch = Clamp(vehicle.controls.pitch, 0.0, 80.0)
-- Check for loading / saving the scene
if input:GetKeyPress(KEY_F5) then
scene_:SaveXML(fileSystem:GetProgramDir() .. "Data/Scenes/VehicleDemo.xml")
end
if input:GetKeyPress(KEY_F7) then
scene_:LoadXML(fileSystem:GetProgramDir() .. "Data/Scenes/VehicleDemo.xml")
vehicleNode = scene_:GetChild("Vehicle", true)
vehicleNode:GetScriptObject():PostInit()
end
else
vehicle.controls:Set(CTRL_FORWARD + CTRL_BACK + CTRL_LEFT + CTRL_RIGHT, false)
end
end
function HandlePostUpdate(eventType, eventData)
if vehicleNode == nil then
return
end
local vehicle = vehicleNode:GetScriptObject()
if vehicle == nil then
return
end
-- Physics update has completed. Position camera behind vehicle
local dir = Quaternion(vehicleNode.rotation:YawAngle(), Vector3(0.0, 1.0, 0.0))
dir = dir * Quaternion(vehicle.controls.yaw, Vector3(0.0, 1.0, 0.0))
dir = dir * Quaternion(vehicle.controls.pitch, Vector3(1.0, 0.0, 0.0))
local cameraTargetPos = vehicleNode.position - dir * Vector3(0.0, 0.0, CAMERA_DISTANCE)
local cameraStartPos = vehicleNode.position
-- Raycast camera against static objects (physics collision mask 2)
-- and move it closer to the vehicle if something in between
local cameraRay = Ray(cameraStartPos, (cameraTargetPos - cameraStartPos):Normalized())
local cameraRayLength = (cameraTargetPos - cameraStartPos):Length();
local physicsWorld = scene_:GetComponent("PhysicsWorld")
local result = physicsWorld:RaycastSingle(cameraRay, cameraRayLength, 2)
if result.body ~= nil then
cameraTargetPos = cameraStartPos + cameraRay.direction * (result.distance - 0.5)
end
cameraNode.position = cameraTargetPos
cameraNode.rotation = dir
end
-- Vehicle script object class
--
-- When saving, the node and component handles are automatically converted into nodeID or componentID attributes
-- and are acquired from the scene when loading. The steering member variable will likewise be saved automatically.
-- The Controls object can not be automatically saved, so handle it manually in the Load() and Save() methods
Vehicle = ScriptObject()
function Vehicle:Start()
-- Current left/right steering amount (-1 to 1.)
self.steering = 0.0
-- Vehicle controls.
self.controls = Controls()
self.suspensionRestLength = 0.6
self.suspensionStiffness = 14.0
self.suspensionDamping = 2.0
self.suspensionCompression = 4.0
self.wheelFriction = 1000.0
self.rollInfluence = 0.12
self.maxEngineForce = ENGINE_FORCE
self.wheelWidth = 0.4
self.wheelRadius = 0.5
self.brakingForce = 50.0
self.connectionPoints = {}
self.particleEmitterNodeList = {}
self.prevVelocity = Vector3()
end
function Vehicle:Load(deserializer)
self.controls.yaw = deserializer:ReadFloat()
self.controls.pitch = deserializer:ReadFloat()
end
function Vehicle:Save(serializer)
serializer:WriteFloat(self.controls.yaw)
serializer:WriteFloat(self.controls.pitch)
end
function Vehicle:Init()
-- This function is called only from the main program when initially creating the vehicle, not on scene load
local node = self.node
local hullObject = node:CreateComponent("StaticModel")
self.hullBody = node:CreateComponent("RigidBody")
local hullShape = node:CreateComponent("CollisionShape")
node.scale = Vector3(2.3, 1.0, 4.0)
hullObject.model = cache:GetResource("Model", "Models/Box.mdl")
hullObject.material = cache:GetResource("Material", "Materials/Stone.xml")
hullObject.castShadows = true
hullShape:SetBox(Vector3(1.0, 1.0, 1.0))
self.hullBody.mass = 800.0
self.hullBody.linearDamping = 0.2 -- Some air resistance
self.hullBody.angularDamping = 0.5
self.hullBody.collisionLayer = 1
local raycastVehicle = node:CreateComponent("RaycastVehicle")
raycastVehicle:Init()
local connectionHeight = -0.4
local isFrontWheel = true
local wheelDirection = Vector3(0, -1, 0)
local wheelAxle = Vector3(-1, 0, 0)
local wheelX = CHASSIS_WIDTH / 2.0 - self.wheelWidth
-- Front left
table.insert(self.connectionPoints, Vector3(-wheelX, connectionHeight, 2.5 - self.wheelRadius * 2.0))
-- Front right
table.insert(self.connectionPoints, Vector3(wheelX, connectionHeight, 2.5 - self.wheelRadius * 2.0))
-- Back left
table.insert(self.connectionPoints, Vector3(-wheelX, connectionHeight, -2.5 + self.wheelRadius * 2.0))
-- Back right
table.insert(self.connectionPoints, Vector3(wheelX, connectionHeight, -2.5 + self.wheelRadius * 2.0))
local LtBrown = Color(0.972, 0.780, 0.412)
for i = 1, #self.connectionPoints do
local wheelNode = scene_:CreateChild()
local connectionPoint = self.connectionPoints[i]
-- Front wheels are at front (z > 0)
-- Back wheels are at z < 0
-- Setting rotation according to wheel position
local isFrontWheel = connectionPoint.z > 0.0
if connectionPoint.x >= 0.0 then
wheelNode.rotation = Quaternion(0.0, 0.0, -90.0)
else
wheelNode.rotation = Quaternion(0.0, 0.0, 90.0)
end
wheelNode.worldPosition = node.worldPosition + node.worldRotation * connectionPoint
wheelNode.scale = Vector3(1.0, 0.65, 1.0)
raycastVehicle:AddWheel(wheelNode, wheelDirection, wheelAxle, self.suspensionRestLength, self.wheelRadius, isFrontWheel)
raycastVehicle:SetWheelSuspensionStiffness(i - 1, self.suspensionStiffness)
raycastVehicle:SetWheelDampingRelaxation(i - 1, self.suspensionDamping)
raycastVehicle:SetWheelDampingCompression(i - 1, self.suspensionCompression)
raycastVehicle:SetWheelRollInfluence(i - 1, self.rollInfluence)
local pWheel = wheelNode:CreateComponent("StaticModel")
pWheel.model = cache:GetResource("Model", "Models/Cylinder.mdl")
pWheel.material = cache:GetResource("Material", "Materials/Stone.xml")
pWheel.castShadows = true
end
self:PostInit()
end
function Vehicle:CreateEmitter(place)
local emitter = scene_:CreateChild()
local node = self.node
emitter.worldPosition = node.worldPosition + node.worldRotation * place + Vector3(0, -self.wheelRadius, 0)
local particleEmitter = emitter:CreateComponent("ParticleEmitter")
particleEmitter.effect = cache:GetResource("ParticleEffect", "Particle/Dust.xml")
particleEmitter.emitting = false
emitter.temporary = true
table.insert(self.particleEmitterNodeList, emitter)
end
function Vehicle:CreateEmitters()
self.particleEmitterNodeList = {}
local node = self.node
local raycastVehicle = node:GetComponent("RaycastVehicle")
for id = 0, raycastVehicle:GetNumWheels() do
local connectionPoint = raycastVehicle:GetWheelConnectionPoint(id)
self:CreateEmitter(connectionPoint)
end
end
function Vehicle:PostInit()
local node = self.node
local raycastVehicle = node:GetComponent("RaycastVehicle")
self.hullBody = node:GetComponent("RigidBody")
self:CreateEmitters();
raycastVehicle:ResetWheels();
end
function Vehicle:FixedUpdate(timeStep)
local node = self.node
local newSteering = 0.0
local accelerator = 0.0
local brake = false
if self.controls:IsDown(CTRL_LEFT) then
newSteering = -1.0
end
if self.controls:IsDown(CTRL_RIGHT) then
newSteering = 1.0
end
if self.controls:IsDown(CTRL_FORWARD) then
accelerator = 1.0
end
if self.controls:IsDown(CTRL_BACK) then
accelerator = -0.5
end
if self.controls:IsDown(CTRL_BRAKE) then
brake = true
end
-- When steering, wake up the wheel rigidbodies so that their orientation is updated
if newSteering ~= 0.0 then
self.steering = self.steering * 0.95 + newSteering * 0.05
else
self.steering = self.steering * 0.8 + newSteering * 0.2
end
local steeringRot = Quaternion(0.0, self.steering * MAX_WHEEL_ANGLE, 0.0)
local raycastVehicle = node:GetComponent("RaycastVehicle")
raycastVehicle:SetSteeringValue(0, self.steering)
raycastVehicle:SetSteeringValue(1, self.steering)
raycastVehicle:SetEngineForce(2, self.maxEngineForce * accelerator)
raycastVehicle:SetEngineForce(3, self.maxEngineForce * accelerator)
for i = 0, raycastVehicle:GetNumWheels() - 1 do
if brake then
raycastVehicle:SetBrake(i, self.brakingForce)
else
raycastVehicle:SetBrake(i, 0.0)
end
end
-- Apply downforce proportional to velocity
local localVelocity = self.hullBody.rotation:Inverse() * self.hullBody.linearVelocity
self.hullBody:ApplyForce(self.hullBody.rotation * Vector3(0.0, -1.0, 0.0) * Abs(localVelocity.z) * DOWN_FORCE)
end
function Vehicle:PostUpdate(timeStep)
local node = self.node
local raycastVehicle = node:GetComponent("RaycastVehicle")
if #self.particleEmitterNodeList == 0 then
return
end
local velocity = self.hullBody.linearVelocity
local accel = (velocity - self.prevVelocity) / timeStep
local planeAccel = Vector3(accel.x, 0.0, accel.z):Length()
for i = 0, raycastVehicle:GetNumWheels() - 1 do
local emitter = self.particleEmitterNodeList[i + 1]
local particleEmitter = emitter:GetComponent("ParticleEmitter")
if raycastVehicle:WheelIsGrounded(i) and (raycastVehicle:GetWheelSkidInfoCumulative(i) < 0.9 or raycastVehicle:GetBrake(i) > 2.0 or planeAccel > 15.0) then
emitter.worldPosition = raycastVehicle:GetContactPosition(i)
if not particleEmitter.emitting then
particleEmitter.emitting = true
end
else if particleEmitter.emitting then
particleEmitter.emitting = false
end
end
end
self.prevVelocity = velocity
end
| mit |
Ninjistix/darkstar | scripts/zones/Davoi/npcs/_45d.lua | 5 | 1258 | -----------------------------------
-- Area: Davoi
-- NPC: Wall of Banishing
-- Used In Quest: Whence Blows the Wind
-- !pos 181 0.1 -218 149
-----------------------------------
package.loaded["scripts/zones/Davoi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Davoi/TextIDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (npc:getAnimation() == 9) then
if (player:hasKeyItem(CRIMSON_ORB)) then
player:startEvent(42);
else
player:messageSpecial(CAVE_HAS_BEEN_SEALED_OFF);
player:messageSpecial(MAY_BE_SOME_WAY_TO_BREAK);
player:setVar("miniQuestForORB_CS",99);
end
end
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option,npc)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 42 and option == 0) then
player:messageSpecial(POWER_OF_THE_ORB_ALLOW_PASS);
npc:openDoor(12); -- needs retail timing
end
end; | gpl-3.0 |
Ninjistix/darkstar | scripts/globals/spells/absorb-tp.lua | 6 | 1469 | --------------------------------------
-- Spell: Absorb-TP
-- Steals an enemy's TP.
--------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/msg");
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local cap = 1200
local dmg = math.random(100, 1200);
--get resist multiplier (1x if no resist)
local params = {};
params.attribute = MOD_INT;
params.skillType = DARK_MAGIC_SKILL;
local resist = applyResistance(caster, target, spell, params);
--get the resisted damage
dmg = dmg * resist;
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = addBonuses(caster, spell, target, dmg);
--add in target adjustment
dmg = adjustForTarget(target, dmg, spell:getElement());
--add in final adjustments
if (resist <= 0.125) then
spell:setMsg(msgBasic.MAGIC_RESIST);
dmg = 0
else
spell:setMsg(msgBasic.MSGIC_ABSORB_TP);
dmg = dmg * ((100 + caster:getMod(MOD_AUGMENTS_ABSORB)) / 100)
if ((target:getTP()) < dmg) then
dmg = target:getTP();
end
if (dmg > cap) then
dmg = cap;
end
-- drain
caster:addTP(dmg);
target:addTP(-dmg);
end
return dmg;
end;
| gpl-3.0 |
Ninjistix/darkstar | scripts/globals/mobskills/absolute_terror.lua | 5 | 1357 | ---------------------------------------------
-- Absolute Terror
-- Causes Terror, which causes the victim to be stunned for the duration of the effect, this can not be removed.
---------------------------------------------
require("scripts/globals/monstertpmoves");
require("scripts/globals/settings");
require("scripts/globals/status");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:hasStatusEffect(EFFECT_MIGHTY_STRIKES)) then
return 1;
elseif (mob:hasStatusEffect(EFFECT_SUPER_BUFF)) then
return 1;
elseif (mob:hasStatusEffect(EFFECT_INVINCIBLE)) then
return 1;
elseif (mob:hasStatusEffect(EFFECT_BLOOD_WEAPON)) then
return 1;
elseif (target:isBehind(mob, 48) == true) then
return 1;
elseif (mob:AnimationSub() == 1) then
return 1;
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_TERROR;
local power = 30;
-- Three minutes is WAY too long, especially on Wyrms. Reduced to Wiki's definition of 'long time'. Reference: http://wiki.ffxiclopedia.org/wiki/Absolute_Terror
local duration = 30;
if (skill:isAoE()) then
duration = 10;
end;
skill:setMsg(MobStatusEffectMove(mob, target, typeEffect, power, 0, duration));
return typeEffect;
end
| gpl-3.0 |
area31/telegram-bot | plugins/vote.lua | 615 | 2128 | do
local _file_votes = './data/votes.lua'
function read_file_votes ()
local f = io.open(_file_votes, "r+")
if f == nil then
print ('Created voting file '.._file_votes)
serialize_to_file({}, _file_votes)
else
print ('Values loaded: '.._file_votes)
f:close()
end
return loadfile (_file_votes)()
end
function clear_votes (chat)
local _votes = read_file_votes ()
_votes [chat] = {}
serialize_to_file(_votes, _file_votes)
end
function votes_result (chat)
local _votes = read_file_votes ()
local results = {}
local result_string = ""
if _votes [chat] == nil then
_votes[chat] = {}
end
for user,vote in pairs (_votes[chat]) do
if (results [vote] == nil) then
results [vote] = user
else
results [vote] = results [vote] .. ", " .. user
end
end
for vote,users in pairs (results) do
result_string = result_string .. vote .. " : " .. users .. "\n"
end
return result_string
end
function save_vote(chat, user, vote)
local _votes = read_file_votes ()
if _votes[chat] == nil then
_votes[chat] = {}
end
_votes[chat][user] = vote
serialize_to_file(_votes, _file_votes)
end
function run(msg, matches)
if (matches[1] == "ing") then
if (matches [2] == "reset") then
clear_votes (tostring(msg.to.id))
return "Voting statistics reset.."
elseif (matches [2] == "stats") then
local votes_result = votes_result (tostring(msg.to.id))
if (votes_result == "") then
votes_result = "[No votes registered]\n"
end
return "Voting statistics :\n" .. votes_result
end
else
save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2])))
return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2]))
end
end
return {
description = "Plugin for voting in groups.",
usage = {
"!voting reset: Reset all the votes.",
"!vote [number]: Cast the vote.",
"!voting stats: Shows the statistics of voting."
},
patterns = {
"^!vot(ing) (reset)",
"^!vot(ing) (stats)",
"^!vot(e) ([0-9]+)$"
},
run = run
}
end | gpl-2.0 |
amir1213/tamir | plugins/vote.lua | 615 | 2128 | do
local _file_votes = './data/votes.lua'
function read_file_votes ()
local f = io.open(_file_votes, "r+")
if f == nil then
print ('Created voting file '.._file_votes)
serialize_to_file({}, _file_votes)
else
print ('Values loaded: '.._file_votes)
f:close()
end
return loadfile (_file_votes)()
end
function clear_votes (chat)
local _votes = read_file_votes ()
_votes [chat] = {}
serialize_to_file(_votes, _file_votes)
end
function votes_result (chat)
local _votes = read_file_votes ()
local results = {}
local result_string = ""
if _votes [chat] == nil then
_votes[chat] = {}
end
for user,vote in pairs (_votes[chat]) do
if (results [vote] == nil) then
results [vote] = user
else
results [vote] = results [vote] .. ", " .. user
end
end
for vote,users in pairs (results) do
result_string = result_string .. vote .. " : " .. users .. "\n"
end
return result_string
end
function save_vote(chat, user, vote)
local _votes = read_file_votes ()
if _votes[chat] == nil then
_votes[chat] = {}
end
_votes[chat][user] = vote
serialize_to_file(_votes, _file_votes)
end
function run(msg, matches)
if (matches[1] == "ing") then
if (matches [2] == "reset") then
clear_votes (tostring(msg.to.id))
return "Voting statistics reset.."
elseif (matches [2] == "stats") then
local votes_result = votes_result (tostring(msg.to.id))
if (votes_result == "") then
votes_result = "[No votes registered]\n"
end
return "Voting statistics :\n" .. votes_result
end
else
save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2])))
return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2]))
end
end
return {
description = "Plugin for voting in groups.",
usage = {
"!voting reset: Reset all the votes.",
"!vote [number]: Cast the vote.",
"!voting stats: Shows the statistics of voting."
},
patterns = {
"^!vot(ing) (reset)",
"^!vot(ing) (stats)",
"^!vot(e) ([0-9]+)$"
},
run = run
}
end | gpl-2.0 |
s-d-a/DCS-ExportScripts | Scripts/DCS-ExportScript/ExportsModules/F-5E-3.lua | 1 | 41216 | -- F-5E-3
ExportScript.FoundDCSModule = true
ExportScript.Version.F5E3 = "1.2.1"
ExportScript.ConfigEveryFrameArguments =
{
--[[
every frames arguments
based of "mainpanel_init.lua"
Example (http://www.lua.org/manual/5.1/manual.html#pdf-string.format)
[DeviceID] = "Format"
[4] = "%.4f", <- floating-point number with 4 digits after point
[19] = "%0.1f", <- floating-point number with 1 digit after point
[129] = "%1d", <- decimal number
[5] = "%.f", <- floating point number rounded to a decimal number
]]
-- Gear System
[97] = "%.4f", -- AlterReleaseRods
-- Cockpit mechanics
[712] = "%.4f", -- CanopyHandle
-- WEAPONS ----------------------------------------------------
-- CMDS
[401] = "%.4f", -- ChaffDrumCounter_10 {0.0, 1.0} {0.0, 10.0}
[402] = "%.4f", -- ChaffDrumCounter_1 {0.0, 1.0} {0.0, 10.0}
[405] = "%.4f", -- FlareDrumCounter_10 {0.0, 1.0} {0.0, 10.0}
[406] = "%.4f", -- FlareDrumCounter_1 {0.0, 1.0} {0.0, 10.0}
-- AN/ASG-31 Sight
[43] = "%.4f", -- RetDepressionDrum_100 {0.0, 1.0} {0.0, 10.0}
[44] = "%.4f", -- RetDepressionDrum_10 {0.0, 1.0} {0.0, 10.0}
[45] = "%.4f", -- RetDepressionDrum_1 {0.0, 1.0} {0.0, 10.0}
-- Slipball
[3] = "%.4f", -- Slipball {-1.0, 1.0}
-- Sight Camera
[85] = "%.4f", -- MotorRunKnob {1.0, 0.0}
-- AN/APQ-159 Radar
-- Range scale lights
[155] = "%.4f", -- RangeScale_5
[156] = "%.4f", -- RangeScale_10
[157] = "%.4f", -- RangeScale_20
[158] = "%.4f", -- RangeScale_40
[159] = "%.f", -- InRangeLight
[160] = "%.f", -- FailLight
[161] = "%.f", -- LockOnLight
[162] = "%.f", -- ExcessGLight
[163] = "%.4f", -- ScaleBrightness
-- INSTRUMENTS ------------------------------------------------
-- Angle-of-attack Indicator
[7] = "%.4f", -- AOA_Units {0.0, 1.0} {0.0, 30.0}
[704] = "%.f", -- AOA_poweroff_flag
-- Accelerometer
[6] = "%.4f", -- Accelerometer { 0.0, 0.323, 0.653, 1.0} {-5.0, 0.0, 5.0, 10.0}
[902] = "%.4f", -- AccelerometerMin { 0.0, 0.323, 0.653, 1.0} {-5.0, 0.0, 5.0, 10.0}
[903] = "%.4f", -- AccelerometerMax { 0.0, 0.323, 0.653, 1.0} {-5.0, 0.0, 5.0, 10.0}
-- AirSpeed/Mach Indicator
[8] = "%.4f", -- Airspeed {0.0, 0.0435, 0.1, 0.318, 0.3745, 0.397, 0.4495, 0.482, 0.54, 0.553, 0.6145, 0.658, 0.668, 0.761, 0.801, 0.877, 0.909, 0.942, 0.972, 1.0} {0.0, 80.0, 100.0, 170.0, 190.0, 200.0, 230.0, 250.0, 290.0, 300.0, 350.0, 390.0, 400.0, 500.0, 550.0, 650.0, 700.0, 750.0, 800.0, 850.0}
[178] = "%.4f", -- MaxAirspeed {0.0, 0.0435, 0.1, 0.318, 0.3745, 0.397, 0.4495, 0.482, 0.54, 0.553, 0.6145, 0.658, 0.668, 0.761, 0.801, 0.877, 0.909, 0.942, 0.972, 1.0} {0.0, 80.0, 100.0, 170.0, 190.0, 200.0, 230.0, 250.0, 290.0, 300.0, 350.0, 390.0, 400.0, 500.0, 550.0, 650.0, 700.0, 750.0, 800.0, 850.0}
[177] = "%.4f", -- SetAirspeed
[179] = "%.4f", -- MachIndicator {1.0, 0.957, 0.92, 0.631, 0.386} {0.0, 0.5, 1.0, 1.8, 2.5}
-- Vertical Velocity Indicator
[24] = "%.4f", -- Variometer {-1.0, -0.64, -0.5, -0.29, 0.0, 0.29, 0.5, 0.64, 1.0} {-6000.0, -3000.0, -2000.0, -1000.0, 0.0, 1000.0, 2000.0, 3000.0, 6000.0}
-- Altimeter AAU-34/A
[10] = "%.4f", -- Altimeter_100_footPtr {0.0, 1.0} {0.0, 1000.0}
[11] = "%.4f", -- Altimeter_10000_footCount {0.0, 1.0} {0.0, 10.0}
[520] = "%.4f", -- Altimeter_1000_footCount {0.0, 1.0} {0.0, 10.0}
[521] = "%.4f", -- Altimeter_100_footCount {0.0, 1.0} {0.0, 10.0}
[59] = "%.4f", -- pressure_setting_0 {0.0, 1.0} {0.0, 10.0}
[58] = "%.4f", -- pressure_setting_1 {0.0, 1.0} {0.0, 10.0}
[57] = "%.4f", -- pressure_setting_2 {0.0, 1.0} {0.0, 10.0}
[56] = "%.4f", -- pressure_setting_3 {0.0, 1.0} {0.0, 10.0}
[9] = "%.4f", -- AAU34_PNEU_flag {0.0, 1.0} {0.0, 0.4}
-- Attitude Indicator ARU-20
[81] = "%.4f", -- AI_Pitch {-0.507, 0.0, 0.507} {-rad_(90.0), 0.0, rad_(90.0)}
[30] = "%.4f", -- AI_Bank {-1.0, 1.0} { 0.0, math.pi * 2.0}
[149] = "%.4f", -- AI_OFF_flag
-- Horizontal Situation Indicator
[32] = "%.4f", -- HSI_CompassCard
[139] = "%.4f", -- HSI_BearingPtr
[35] = "%.4f", -- HSI_CourseArrow
[36] = "%.4f", -- HSI_CourseDevInd {-1.0, 1.0}
[144] = "%.4f", -- HSI_HeadingMark
[268] = "%.4f", -- HSI_Range_100 {0.0, 1.0} {0.0, 10.0}
[269] = "%.4f", -- HSI_Range_10 {0.0, 1.0} {0.0, 10.0}
[270] = "%.4f", -- HSI_Range_1 {0.0, 1.0} {0.0, 10.0}
[142] = "%.4f", -- HSI_Range_flag
[275] = "%.4f", -- HSI_CourseSel_100 {0.0, 1.0} {0.0, 10.0}
[276] = "%.4f", -- HSI_CourseSel_10 {0.0, 1.0} {0.0, 10.0}
[277] = "%.4f", -- HSI_CourseSel_1 {0.0, 1.0} {0.0, 10.0}
[146] = "%.4f", -- HSI_ToFrom
[143] = "%.4f", -- HSI_OFF_flag
[141] = "%.4f", -- HSI_DevDF_Win
-- Standby Attitude Indicator
[438] = "%.4f", -- SAI_Pitch {-0.665, -0.581, -0.5, 0.0, 0.5, 0.581, 0.676, 0.735} {-rad_(78.0), -rad_(60.0), -rad_(42.0), 0.0, rad_(42.0), rad_(60.0), rad_(80.0), rad_(92.0)}
[439] = "%.4f", -- SAI_Bank {1.0, -1.0} {-math.pi, math.pi}
[440] = "%.4f", -- SAI_OFF_flag
--[443] = "%.4f", -- SAI_knob_arrow {-1.0, 1.0} {0.0, 1.0}
-- Clock
[19] = "%.4f", -- CLOCK_currtime_hours
[18] = "%.4f", -- CLOCK_currtime_minutes
[509] = "%.4f", -- CLOCK_elapsed_time_minutes
[37] = "%.4f", -- CLOCK_elapsed_time_seconds
-- Pitch Trim Indicator
[52] = "%.4f", -- Pitch_Trim {1.0, 0.0, -0.1} {-10.0, 0.0, 1.0}
-- Flap Indicator
[51] = "%.4f", -- Flap_Indicator {0.0, 0.4} {0.0, 4.0}
-- Hydraulic Pressure Indicators
[109] = "%.4f", -- Utility_Pressure {0.0, 1.0} {0.0, 4000.0}
[110] = "%.4f", -- Flight_Pressure {0.0, 1.0} {0.0, 4000.0}
-- Engine Tachometers
[16] = "%.4f", -- Tachometer_Left {0.008, 0.475, 0.84, 0.94, 1.0} {0.0, 50.0, 90.0, 100.0, 107.0}
[425] = "%.4f", -- Tachometer_percent_Left {0.0, 1.0} {0.0, 10.0}
[17] = "%.4f", -- Tachometer_Right {0.008, 0.475, 0.84, 0.94, 1.0} {0.0, 50.0, 90.0, 100.0, 107.0}
[426] = "%.4f", -- Tachometer_percent_Right {0.0, 1.0} {0.0, 10.0}
-- Exhaust Gas Temperature Indicators
[12] = "%.4f", -- EGT_Left {0.0, 0.03, 0.1, 0.274, 0.78, 1.0} {0.0, 140.0, 200.0, 500.0, 800.0, 1200.0}
[14] = "%.4f", -- EGT_Right {0.0, 0.03, 0.1, 0.274, 0.78, 1.0} {0.0, 140.0, 200.0, 500.0, 800.0, 1200.0}
-- Aux Intake Doors Indicator
[111] = "%.4f", -- AuxIntakeDoors {0.0, 0.2} {0.0, 2.0}
-- Oil Pressure Indicator (Dual)
[112] = "%.4f", -- OilPressure_Left {0.0, 1.0} {0.0, 100.0}
[113] = "%.4f", -- OilPressure_Right {0.0, 1.0} {0.0, 100.0}
-- Nozzle Position Indicators
[107] = "%.4f", -- NozzlePos_Left {0.0, 1.0} {0.0, 100.0}
[108] = "%.4f", -- NozzlePos_Right {0.0, 1.0} {0.0, 100.0}
-- Cabin Pressure Altimeter
[114] = "%.4f", -- CabinPressure {0.0, 1.0} {0.0, 50.0}
-- Fuel Flow Indicator (Dual)
[525] = "%.4f", -- FuelFlow_Left {0.0, 0.67, 0.75, 0.83, 1.0} {0.0, 4000.0, 7000.0, 10000.0, 15000.0}
[526] = "%.4f", -- FuelFlow_Right {0.0, 0.67, 0.75, 0.83, 1.0} {0.0, 4000.0, 7000.0, 10000.0, 15000.0}
-- Fuel Quantity Indicator (Dual)
[22] = "%.4f", -- FuelQuantity_Left {0.0, 1.0} {0.0, 2500.0}
[23] = "%.4f", -- FuelQuantity_Right {0.0, 1.0} {0.0, 2500.0}
-- Oxygen Quantity Indicator
[390] = "%.4f", -- OxygenQuantity {0.0, 1.0} {0.0, 5.0}
-- Oxygen Flow Pressure Indicator
[604] = "%.4f", -- FlowPressure {0.0, 0.5, 1.0} {0.0, 100.0, 500.0}
-- Oxygen Flow Indicator
[600] = "%.4f", -- FlowBlinker
-- RADIO ------------------------------------------------------
-- UHF Radio AN/ARC-164
[326] = "%.2f", -- UHFRadioChannel
[302] = "%.1f", -- UHFRadio100MHz
[303] = "%.1f", -- UHFRadio10MHz {1.0, 0.0} {0.0, 1.0}
[304] = "%.1f", -- UHFRadio1MHz {1.0, 0.0} {0.0, 1.0}
[305] = "%.1f", -- UHFRadio01MHz {1.0, 0.0} {0.0, 1.0}
[306] = "%.1f", -- UHFRadio0025MHz {1.0, 0.0} {0.0, 1.0}
-- IFF/SIF APX72
[197] = "%.4f", -- IFF_Code4Sw_Pull
[198] = "%.4f", -- IFF_MasterSw_Pull
-- TACAN
[263] = "%.4f", -- TACAN_window_wheel.hundreds {0.0, 1.0} {0.0, 10.0}
[264] = "%.4f", -- TACAN_window_wheel.tens {0.0, 1.0} {0.0, 10.0}
[265] = "%.4f", -- TACAN_window_wheel.ones {0.0, 1.0} {0.0, 10.0}
--[266] = "%.4f", -- XYwheel
[260] = "%.f", -- TACAN_test_light
-- LAMPS
-- Engine Fire Lights
[167] = "%.f", -- lamp_LeftFire
[168] = "%.f", -- lamp_RightFire
-- AOA Indexer Lights
[48] = "%.f", -- lamp_AOA_Red
[49] = "%.f", -- lamp_AOA_Green
[50] = "%.f", -- lamp_AOA_Yellow
-- Landing Gear Lights
[96] = "%.f", -- lamp_GearWarning
[54] = "%.f", -- lamp_GearNose
[53] = "%.f", -- lamp_GearLeft
[55] = "%.f", -- lamp_GearRight
-- Hook Light
[90] = "%.f", -- lamp_Hook
-- Caution Lights panel
[530] = "%.f", -- lamp_LeftGenerator
[531] = "%.f", -- lamp_Canopy
[532] = "%.f", -- lamp_RightGenerator
[533] = "%.f", -- lamp_UtilityHyd
[534] = "%.f", -- lamp_Spare1
[535] = "%.f", -- lamp_FlightHyd
[536] = "%.f", -- lamp_ExtTanksEmpty
[537] = "%.f", -- lamp_IFF
[538] = "%.f", -- lamp_Oxygen
[539] = "%.f", -- lamp_LeftFuelLow
[540] = "%.f", -- lamp_EngineAntiIce
[541] = "%.f", -- lamp_RightFuelLow
[542] = "%.f", -- lamp_LeftFuelPress
[543] = "%.f", -- lamp_INS
[544] = "%.f", -- lamp_RightFuelPress
[545] = "%.f", -- lamp_AOA_Flaps
[546] = "%.f", -- lamp_AirDataComputer
[547] = "%.f", -- lamp_DirGyro
[548] = "%.f", -- lamp_Spare2
[549] = "%.f", -- lamp_DC_Overload
[550] = "%.f", -- lamp_Spare3
-- Master Caution Light
[169] = "%.f", -- lamp_MasterCaution
--IFF Panel lamps
[216] = "%.f", -- IFF_reply_lamp
[218] = "%.f", -- IFF_test_lamp
-- Internal Lights
[801] = "%.f", -- light_Flight
[802] = "%.f", -- light_Engine
[803] = "%.f", -- light_Console
[804] = "%.f", -- light_Compass
[805] = "%.f", -- light_Flood
[806] = "%.f", -- light_Sight
[807] = "%.f", -- light_Armt
[810] = "%.f", -- light_Tstorm
-- RWR button lights
[576] = "%.f", -- rwr_Power
[572] = "%.f", -- rwr_Ship_unkn
[571] = "%.f", -- rwr_Ship_U
[568] = "%.f", -- rwr_Sys_On
[569] = "%.f", -- rwr_Sys
[565] = "%.f", -- rwr_Sep_Up
[566] = "%.f", -- rwr_Sep_Down
[563] = "%.f", -- rwr_Alt
[562] = "%.f", -- rwr_Alt_Low
[557] = "%.f", -- rwr_Hand_Up
[558] = "%.f", -- rwr_Hand_H
[555] = "%.f", -- rwr_Search
[553] = "%.f", -- rwr_Mode_Open
[552] = "%.f", -- rwr_Mode_Pri
-- Brightness regulation
[808] = "%.f", -- brtRadarScale
[815] = "%.f", -- brtRwrLights
[816] = "%.f", -- brtFireLights
[817] = "%.f", -- brtMainLights
[818] = "%.f", -- brtIFFLights
[819] = "%.f" -- brtRadarLights
}
ExportScript.ConfigArguments =
{
--[[
arguments for export in low tick interval
based on "clickabledata.lua"
]]
-- Control System
[323] = "%1d", -- Yaw Damper Switch, YAW/OFF
[322] = "%1d", -- Pitch Damper Switch, PITCH/OFF
[324] = "%.4f", -- Rudder Trim Knob (Axis) {-1.0, 1.0} in 0.15 Steps
[116] = "%1d", -- Flaps Lever, EMER UP/THUMB SW/FULL {-1.0, 0.0, 1.0}
[132] = "%1d", -- Pitch Damper Cutoff Switch - Push to cutoff
[101] = "%1d", -- Speed Brake Switch, OUT/OFF/IN {-1.0, 0.0, 1.0}
[115] = "%1d", -- Auto Flap System Thumb Switch, UP/FIXED/AUTO {-1.0, 0.0, 1.0}
--[125] = "%1d", -- Trimmer Switch, PUSH(DESCEND) {0.0, 1.0}
--[125] = "%1d", -- Trimmer Switch, PULL(CLIMB) {-1.0, 0.0}
--[126] = "%1d", -- Trimmer Switch, LEFT WING DOWN {0.0, 1.0}
--[126] = "%1d", -- Trimmer Switch, RIGHT WING DOWN {-1.0, 0.0}
[125] = "%1d", -- Trimmer Switch, PUSH(DESCEND)/PULL(CLIMB) {1.0, 0.0, -1.0}
[126] = "%1d", -- Trimmer Switch, LEFT WING DOWN/RIGHT WING DOWN {1.0, 0.0, -1.0}
[278] = "%1d", -- Rudder Pedal Adjust T-Handle, PULL/STOW
-- Electric system
[387] = "%1d", -- attery Switch, BATT/OFF
[388] = "%1d", -- Left Generator Switch, L GEN/OFF/RESET {-1.0, 0.0, 1.0}
[389] = "%1d", -- Right Generator Switch, R GEN/OFF/RESET {-1.0, 0.0, 1.0}
[375] = "%1d", -- Pitot Anti-Ice Switch, PITOT/OFF
[230] = "%1d", -- Fuel & Oxygen Switch, GAGE TEST/OFF/QTY CHECK {-1.0, 0.0, 1.0}
-- Fuel System
[360] = "%1d", -- Left Fuel Shutoff Switch, OPEN/CLOSED
[362] = "%1d", -- Right Fuel Shutoff Switch, OPEN/CLOSED
[377] = "%1d", -- Ext Fuel Cl Switch, ON/OFF
[378] = "%1d", -- Ext Fuel Pylons Switch, ON/OFF
[380] = "%1d", -- Left Boost Pump Switch, ON/OFF
[381] = "%1d", -- Crossfeed Switch, OPEN/CLOSED
[382] = "%1d", -- Right Boost Pump Switch, ON/OFF
[383] = "%1d", -- Autobalance Switch, LEFT/NEUT/RIGHT {-1.0, 0.0, 1.0}
-- Engines
[357] = "%1d", -- Left Engine Start Button - Push to start
[358] = "%1d", -- Right Engine Start Button - Push to start
[376] = "%1d", -- Engine Anti-Ice Switch, ENGINE/OFF {1.0, -1.0}
-- Gear System
[83] = "%1d", -- Landing Gear Lever, LG UP/LG DOWN
[95] = "%1d", -- Landing Gear Alternate Release Handle, Pull and Hold
[98] = "%1d", -- Gear Alternate Release Reset Control, OFF/RESET
[88] = "%1d", -- Landing Gear Downlock Override Button - Push and hold to override locking solenoid
[87] = "%1d", -- Landing Gear And Flap Warning Silence Button
[250] = "%1d", -- Nose Strut Switch, EXTEND/RETRACT {1.0, -1.0}
[131] = "%1d", -- Nosewheel Steering Button - Press and Hold to engage nosewheel control
[92] = "%1d", -- Left Landing Gear Lamp - Press to test(LMB)
[93] = "%1d", -- Nose Landing Gear Lamp - Press to test(LMB)
[94] = "%1d", -- Right Landing Gear Lamp - Press to test(LMB)
[89] = "%1d", -- Arresting Hook Button
-- Oxygen System
[603] = "%1d", -- Oxygen Supply Lever, ON/OFF {1.0, -1.0}
[602] = "%1d", -- Diluter Lever
[601] = "%1d", -- Emergency Lever, EMERGENCY/NORMAL/TEST MASK {-1.0, 0.0, 1.0}
-- EC System
[371] = "%1d", -- Cabin Press Switch, DEFOG ONLY/NORMAL/RAM DUMP {0.0, 0.5, 1.0}
[372] = "%1d", -- Cabin Temp Switch, AUTO/CENTER/MAN COLD/MAN HOT {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6}
[373] = "%.2f", -- Cabin Temp Knob (Axis) {-1.0, 1.0} in 0.15 Steps
[374] = "%.2f", -- Canopy Defog Knob (Axis) {0.0, 1.0} in 0.15 Steps
[386] = "%.2f", -- Cockpit Air Inlet (Horizontal) (Axis) {-1.0, 1.0} in 0.1 Steps
[385] = "%.2f", -- Cockpit Air Inlet (Vertical) (Axis) {-1.0, 1.0} in 0.1 Steps
-- Cockpit Mechanics
--[0] = "%1d", -- Canopy Handle, OPEN/CLOSE
[772] = "%1d", -- Seat Adjust Switch, DOWN/NEUTRAL/UP {-1.0, 0.0, 1.0}
[384] = "%1d", -- Canopy Jettison T-Handle, PULL/PUSH
[91] = "%.1f", -- Drag Chute T-Handle, PULL/PUSH {0.1, -0.1}
-- External Lights
[227] = "%.2f", -- Navigation Lights Knob (Axis) {0.0, 1.0} in 0.15 Steps
[228] = "%.2d", -- Formation Lights Knob (Axis) {0.0, 1.0} in 0.15 Steps
[229] = "%1d", -- Beacon Switch, BEACON/OFF
[353] = "%1d", -- Landing & Taxi Light Switch, ON/OFF
-- Internal Lights
[46] = "%1d", -- AN/ASG-31 Sight Panel Light Button, ON/OFF
[613] = "%1d", -- Magnetic Compass Light Switch, LIGHT/OFF
[221] = "%.2f", -- Flood Lights Knob (Axis) {0.0, 1.0} in 0.15 Steps
[222] = "%.2f", -- Flight Instruments Lights Knob (Axis) {0.0, 1.0} in 0.15 Steps
[223] = "%.2f", -- Engine Instruments Lights Knob (Axis) {0.0, 1.0} in 0.15 Steps
[224] = "%.2f", -- Console Lights Knob (Axis) {0.0, 1.0} in 0.15 Steps
[363] = "%.2f", -- Armament Panel Lights Knob (Axis) {0.0, 1.0} in 0.15 Steps
[172] = "%1d", -- Master Caution Button - Push to reset
[226] = "%1d", -- Warning Test Switch, Press to test
[225] = "%1d", -- Bright/Dim Switch, BRT/NEUT/DIM {-1.0, 0.0, 1.0}
-- Countermeasures Dispensing System
[400] = "%1d", -- Chaff Mode Selector, OFF/SINGLE/PRGM/MULT {0.0, 0.1, 0.2, 0.3}
[404] = "%1d", -- Flare Mode Selector, OFF/SINGLE/PRGM {0.0, 0.1, 0.2}
[409] = "%1d", -- Flare Jettison Switch, OFF/UP
[403] = "%1d", -- Chaff Counter Reset Button - Push to reset
[407] = "%1d", -- Flare Counter Reset Button - Push to reset
[117] = "%1d", -- Flare-Chaff Button - Push to dispense
-- IFF
[199] = "%1d", -- IFF MODE 4 CODE Selector, ZERO(use MW to pull switch)/B/A/HOLD
[197] = "%1d", -- IFF MODE 4 CODE Selector, ZERO(use MW to pull switch)/B/A/HOLD
[200] = "%1d", -- IFF MASTER Control Selector, EMER(use MW to pull switch)/NORM/LOW/STBY/OFF
[198] = "%1d", -- IFF MASTER Control Selector, EMER(use MW to pull switch)/NORM/LOW/STBY/OFF
[201] = "%1d", -- IFF MODE 4 Monitor Control Switch, AUDIO/OUT/LIGHT {-1.0, 0.0, 1.0}
[202] = "%1d", -- IFF Mode Select/TEST Switch, M-1 /ON/OUT {-1.0, 0.0, 1.0}
[203] = "%1d", -- IFF Mode Select/TEST Switch, M-2 /ON/OUT {-1.0, 0.0, 1.0}
[204] = "%1d", -- IFF Mode Select/TEST Switch, M-3/A /ON/OUT {-1.0, 0.0, 1.0}
[205] = "%1d", -- IFF Mode Select/TEST Switch, M-C /ON/OUT {-1.0, 0.0, 1.0}
[206] = "%1d", -- IFF RAD TEST/MON Switch, RAD TEST/OUT/MON {-1.0, 0.0, 1.0}
[207] = "%1d", -- IFF Identification of Position (IP) Switch, IDENT/OUT/MIC {-1.0, 0.0, 1.0}
[208] = "%1d", -- IFF MODE 4 Control Switch, ON/OUT
[209] = "%.1f", -- IFF MODE 1 Code Selector Wheel 1 {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7}
[210] = "%.1f", -- IFF MODE 1 Code Selector Wheel 2 {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7}
[211] = "%.1f", -- IFF MODE 3/A Code Selector Wheel 1 {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7}
[212] = "%.1f", -- IFF MODE 3/A Code Selector Wheel 2 {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7}
[213] = "%.1f", -- IFF MODE 3/A Code Selector Wheel 3 {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7}
[214] = "%.1f", -- IFF MODE 3/A Code Selector Wheel 4 {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7}
[217] = "%1d", -- MODE 4 REPLY Light - Press to test(LMB)
[215] = "%1d", -- Radiation TEST and Monitor Light - Press to test(LMB)
-- Jettison System
[365] = "%1d", -- Emergency All Jettison Button - Push to jettison
[367] = "%1d", -- Select Jettison Switch, SELECT POSITION/OFF/ALL PYLONS {-1.0, 0.0, 1.0}
[366] = "%1d", -- Select Jettison Button - Push to jettison
-- Weapons Control
[346] = "%1d", -- Armament Position Selector Switch - LEFT WINGTIP, ON/OFF
[347] = "%1d", -- Armament Position Selector Switch - LEFT OUTBD, ON/OFF
[348] = "%1d", -- Armament Position Selector Switch - LEFT INBD, ON/OFF
[349] = "%1d", -- Armament Position Selector Switch - CENTERLINE, ON/OFF
[350] = "%1d", -- Armament Position Selector Switch - RIGHT INBD, ON/OFF
[351] = "%1d", -- Armament Position Selector Switch - RIGHT OUTBD, ON/OFF
[352] = "%1d", -- Armament Position Selector Switch - RIGHT WINGTIP, ON/OFF
[340] = "%1d", -- Interval Switch [sec], .06/.10/.14 {-1.0, 0.0, 1.0}
[341] = "%1d", -- Bombs Arm Switch, SAFE/TAIL/NOSE & TAIL/NOSE {0.0, 0.1, 0.2, 0.3}
[343] = "%1d", -- Guns, Missile and Camera Switch, GUNS MSL & CAMR/OFF/CAMR ONLY {-1.0, 0.0, 1.0}
[344] = "%.1f", -- External Stores Selector, RIPL/BOMB/SAFE/RKT DISP {0.0,0.1,0.2,0.3}
[345] = "%.2f", -- Missile Volume Knob - Rotate to adjust volume (Axis) {0.0, 1.0} in 0.15 Steps
[128] = "%1d", -- Weapon Release Button - Press to release (Stick)
[137] = "%1d", -- Missile Uncage Switch - Press and hold to uncage missile seeker head
-- Trigger
[127] = "%1d", -- Trigger Button, FIRST DETENT(LMB) {0.0, 0.5}
[127] = "%1d", -- Trigger Button, SECOND DETENT(RMB) {0.0, 1.0}
-- AHRS
[166] = "%1d", -- Fast Erect Button - Push to erect
[220] = "%1d", -- Compass Switch, DIR GYRO/MAG/FAST SLAVE
[273] = "%.1f", -- Nav Mode Selector Switch, DF/TACAN {0.1,-0.1}
-- AN/APQ-159 Radar Control Panel
[65] = "%.2f", -- AN/APQ-159 Radar Scale Knob - Rotate to adjust scale brightness (Axis) {0.0, 1.0} in 0.15 Steps
[321] = "%.2f", -- AN/APQ-159 Radar Elevation Antenna Tilt Control Knob - Rotate to adjust antenna elevation (Axis) {-1.0, 1.0} in 0.15 Steps
[315] = "%.1f", -- AN/APQ-159 Radar Range Selector Switch [nm], 5/10/20/40 {0.0, 0.1, 0.2, 0.3}
[316] = "%.1f", -- AN/APQ-159 Radar Mode Selector Switch, OFF/STBY/OPER/TEST {0.0, 0.1, 0.2, 0.3}
[317] = "%1d", -- AN/APQ-159 Radar Acquisition Button
[70] = "%.2f", -- AN/APQ-159 Radar Bright Knob - Rotate to adjust brightness (Axis) {0.0, 1.0} in 0.15 Steps
[69] = "%.2f", -- AN/APQ-159 Radar Persistence Knob - Rotate to adjust persistence (Axis) {0.0, 1.0} in 0.15 Steps
[68] = "%.2f", -- AN/APQ-159 Radar Video Knob - Rotate to adjust video intensity (Axis) {0.0, 1.0} in 0.15 Steps
[67] = "%.2f", -- AN/APQ-159 Radar Cursor Knob - Rotate to adjust indication brightness (Axis) {0.0, 1.0} in 0.15 Steps
[66] = "%.2f", -- AN/APQ-159 Radar Pitch Knob - Rotate to adjust horizon bar (Axis) {-0.75, 0.75} in 0.1 Steps
-- AN/ASG-31 Sight
[40] = "%.1f", -- AN/ASG-31 Sight Mode Selector, OFF/MSL/A/A1 GUNS/A/A2 GUNS/MAN {0.0, 0.1, 0.2, 0.3, 0.4}
[42] = "%.2f", -- AN/ASG-31 Sight Reticle Depression Knob - Rotate to adjust manual mode depression angle (Axis) {0.0, 1.0} in 0.10 Steps
[41] = "%.2f", -- AN/ASG-31 Sight Reticle Intensity Knob - Rotate to adjust brightness (Axis) {0.0, 1.0} in 0.15 Steps
[136] = "%1d", -- AN/ASG-31 Sight Cage Switch - Press and hold to cage
-- RWR-IC
[551] = "%1d", -- RWR Indicator Control MODE Button
[554] = "%1d", -- RWR Indicator Control SEARCH Button
[556] = "%1d", -- RWR Indicator Control HANDOFF Button
[559] = "%1d", -- RWR Indicator Control LAUNCH Button
[561] = "%1d", -- RWR Indicator Control ALTITUDE Button
[564] = "%1d", -- RWR Indicator Control T Button
[567] = "%1d", -- RWR Indicator Control SYS TEST Button
[570] = "%1d", -- RWR Indicator Control UNKNOWN SHIP Button
[573] = "%1d", -- RWR Indicator Control ACT/PWR Button
[575] = "%1d", -- RWR Indicator Control POWER Button {1.0,0.0,-1.0}
[577] = "%.1f", -- RWR Indicator Control AUDIO Knob (Axis) {0.0, 1.0} in 0.1 Steps
[578] = "%.1f", -- RWR Indicator Control DIM Knob (Axis) {0.0, 1.0} in 0.1 Steps
-- AN/ALR-87 RWR
[140] = "%.2f", -- Adjust Display Brightness (Axis) {0.15, 0.85} in 0.1 Steps
-- Instruments --------------------------
-- Accelerometer
[904] = "%1d", -- Accelerometer - Push to set
-- AirSpeed/Mach Indicator
[180] = "%.2f", -- Index Setting Pointer Knob (Axis) {0.0, 1.0} in 0.15 Steps
-- Altimeter AAU-34/A
[62] = "%.2f", -- Zero Setting Knob (Axis) {0.0, 1.0} in 0.04 Steps
[60] = "%1d", -- Altimeter Mode Control Lever, ELECT(rical)/PNEU(matic) {-1.0, 0.0, 1.0}
-- Attitude Indicator ARU-20
[150] = "%.3f", -- AI Pitch Trim Knob (Axis) {0.0, 1.0} in 0.083 Steps
-- Horizontal Situation Indicator
[272] = "%.5f", -- HSI Course Set Knob (Axis) {0.0, 1.0} in 0.05818 Steps
[271] = "%.5f", -- HSI Heading Set Knob (Axis) {0.0, 1.0} in 0.05818 Steps
-- Standby Attitude Indicator
[441] = "%1d", -- Cage/Pitch Trim (Button)
[442] = "%.1f", -- Cage/Pitch Trim Knob (Axis) {0.0, 1.0} in 0.5 Steps
-- Clock
[511] = "%1d", -- ABU-11 Clock Winding and Setting knob (Button)
[510] = "%1d", -- ABU-11 Clock Winding and Setting Knob (Axis) {0.0, 1.0} in 0.6 Steps
[512] = "%1d", -- ABU-11 Clock Elapsed Time Knob
-- Electric system - CB Front Panel
[280] = "%1d", -- CB WPN PWR LEFT INBD, ON/OFF {1.0, 0.0}
[281] = "%1d", -- CB WPN PWR CENTER LINE, ON/OFF {1.0, 0.0}
[282] = "%1d", -- CB WPN PWR RIGHT INBD, ON/OFF {1.0, 0.0}
[283] = "%1d", -- CB WPN PWR LEFT OUTBD, ON/OFF {1.0, 0.0}
[284] = "%1d", -- CB WPN ARMING, ON/OFF {1.0, 0.0}
[285] = "%1d", -- CB WPN PWR RIGHT OUTBD, ON/OFF {1.0, 0.0}
[286] = "%1d", -- CB JETTISON CONTROL, ON/OFF {1.0, 0.0}
[287] = "%1d", -- CB WPN RELEASE, ON/OFF {1.0, 0.0}
[288] = "%1d", -- CB WPN MODE SEL & AIM-9-INTLK, ON/OFF {1.0, 0.0}
[289] = "%1d", -- CB EMERGENCY ALL JETTISON, ON/OFF {1.0, 0.0}
[290] = "%1d", -- CB LEFT AIM-9 CONT, ON/OFF {1.0, 0.0}
[291] = "%1d", -- CB RIGHT AIM-9 CONT, ON/OFF {1.0, 0.0}
-- Electric system - CB Left Panel
[450] = "%1d", -- CB LEFT AIM-9 POWER, ON/OFF {1.0, 0.0}
[451] = "%1d", -- CB LEFT GUN FIRING, ON/OFF {1.0, 0.0}
[453] = "%1d", -- CB 26 VOLT AC POWER, ON/OFF {1.0, 0.0}
[454] = "%1d", -- CB ATTD & HDG REF SYS A, ON/OFF {1.0, 0.0}
[455] = "%1d", -- CB CENTRAL AIR DATA COMPUTER, ON/OFF {1.0, 0.0}
[456] = "%1d", -- CB ENG IGN L ENG INST & HYD IND, ON/OFF {1.0, 0.0}
[457] = "%1d", -- CB RIGHT AIM-9 POWER, ON/OFF {1.0, 0.0}
[458] = "%1d", -- CB RIGHT GUN FIRING, ON/OFF {1.0, 0.0}
[460] = "%1d", -- CB TRIM CONTROL, ON/OFF {1.0, 0.0}
[461] = "%1d", -- CB ATTD & HDG REF SYS B, ON/OFF {1.0, 0.0}
[462] = "%1d", -- CB TOTAL TEMP PROBE HTR, ON/OFF {1.0, 0.0}
[463] = "%1d", -- CB L ENG AUX DOOR, ON/OFF {1.0, 0.0}
[464] = "%1d", -- CB CABIN COND, ON/OFF {1.0, 0.0}
[467] = "%1d", -- CB FUEL QTY PRIMARY, ON/OFF {1.0, 0.0}
[468] = "%1d", -- CB ATTD & HDG REF SYS C, ON/OFF {1.0, 0.0}
[469] = "%1d", -- CB TACAN, ON/OFF {1.0, 0.0}
[471] = "%1d", -- CB PYLON TANK FUEL CONT, ON/OFF {1.0, 0.0}
[472] = "%1d", -- CB L BOOST CL & TIP TANK FUEL CONT, ON/OFF {1.0, 0.0}
[473] = "%1d", -- CB IGNITION INVERTER POWER, ON/OFF {1.0, 0.0}
[474] = "%1d", -- CB L ENG START & AB CONT, ON/OFF {1.0, 0.0}
[475] = "%1d", -- CB R ENG START & AB CONT, ON/OFF {1.0, 0.0}
[476] = "%1d", -- CB UHF COMMAND RADIO, ON/OFF {1.0, 0.0}
[477] = "%1d", -- CB LEFT LE FLAP CONT, ON/OFF {1.0, 0.0}
[478] = "%1d", -- CB RIGHT LE FLAP CONT, ON/OFF {1.0, 0.0}
[479] = "%1d", -- CB LEFT TE FLAP CONT, ON/OFF {1.0, 0.0}
[480] = "%1d", -- CB RIGHT TE FLAP CONT & IND, ON/OFF {1.0, 0.0}
-- Electric system - CB Right Panel
[231] = "%1d", -- CB PITOT HEATER, ON/OFF {1.0, 0.0}
[233] = "%1d", -- CB R OIL & HYD IND FUEL QTY SEL, ON/OFF {1.0, 0.0}
[234] = "%1d", -- CB CABIN AIR VALVES, ON/OFF {1.0, 0.0}
[238] = "%1d", -- CB INST LIGHTS, ON/OFF {1.0, 0.0}
[239] = "%1d", -- CB R ENG AUX DOORS, ON/OFF {1.0, 0.0}
[244] = "%1d", -- CB CAUTION & WARN LIGHTS-DIM, ON/OFF {1.0, 0.0}
[245] = "%1d", -- CB OXY QTY & CANOPY SEAL, ON/OFF {1.0, 0.0}
[246] = "%1d", -- CB LDG-TAXI LAMP PWR, ON/OFF {1.0, 0.0}
--UHF Radio AN/ARC-164
[300] = "%.2f", -- AN/ARC-164, UHF Radio Preset Channel Selector Knob {0.0, 0.1, 0.2, 0.3, 0.4, ... 0.15, 0.16, 0.17, 0.18, 0.19}
--[327] = "%.1f", -- AN/ARC-164, UHF Radio 100 MHz Frequency Selector Knob {0.0, 0.1, 0.2, 0.3}
--[328] = "%.1f", -- AN/ARC-164, UHF Radio 10 MHz Frequency Selector Knob {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9}
--[329] = "%.1f", -- AN/ARC-164, UHF Radio 1 MHz Frequency Selector Knob {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9}
--[330] = "%.1f", -- AN/ARC-164, UHF Radio 0.1 MHz Frequency Selector Knob {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9}
--[331] = "%.2f", -- AN/ARC-164, UHF Radio 0.025 MHz Frequency Selector Knob {0.0, 0.25, 0.5, 0.75}
[307] = "%.1f", -- AN/ARC-164, UHF Radio Frequency Mode Selector Switch, MANUAL/PRESET/GUARD {0.0, 0.1, 0.2}
[311] = "%.1f", -- AN/ARC-164, UHF Radio Function Selector Switch, OFF/MAIN/BOTH/ADF {0.0, 0.1, 0.2}
[310] = "%1d", -- AN/ARC-164, UHF Radio Tone Button
[308] = "%1d", -- AN/ARC-164, UHF Radio Squelch Switch, ON/OFF
[309] = "%.1f", -- AN/ARC-164, UHF Radio Volume Knob (Axis) {0.0, 1.0} in 0.1 Steps
[336] = "%.1f", -- AN/ARC-164, UHF Radio Antenna Selector Switch, UPPER/AUTO/LOWER {0.0, 0.5, 1.0}
[135] = "%1d", -- AN/ARC-164, UHF Radio Microphone Button
--TACAN
[256] = "%.1f", -- TACAN Channel Selector (Tens) - Rotate mouse wheel to select (Axis) {0.0, 1.0} in 0.1 Steps
[257] = "%.1f", -- TACAN Channel Selector (Ones) / X/Y Mode - Right mouse click to select X/Y. Rotate mouse wheel to make channel selection (Axis) {0.0, 1.0} in 0.1 Steps
[258] = "%.2f", -- TACAN Channel Selector (Ones) / X/Y Mode - Right mouse click to select X/Y. Rotate mouse wheel to make channel selection (Button) {0.87, 0.93}
[259] = "%1d", -- TACAN Signal on HSI Test Button
[261] = "%1d", -- TACAN Signal Volume Knob (Axis) {0.0, 1.0} in 0.1 Steps
[262] = "%.1f", -- TACAN Mode Selector Switch {0.0, 0.1, 0.2, 0.3, 0.4}
-- Sight Camera
[82] = "%.1f", -- Sight Camera Lens f-Stop Selector, 2.8(dull)..22(bright) (Axis) {0.0, 0.3} in 0.1 Steps
[80] = "%1d", -- Sight Camera FPS Select Switch, 24/48
[84] = "%.1f", -- Sight Camera Overrun Selector, 0/3/10/20 {0.0, 0.1, 0.2, 0.3}
[79] = "%1d" -- Sight Camera Run (Test) Switch, ON/OFF
}
-----------------------------
-- HIGH IMPORTANCE EXPORTS --
-- done every export event --
-----------------------------
-- Pointed to by ProcessIkarusDCSHighImportance
function ExportScript.ProcessIkarusDCSConfigHighImportance(mainPanelDevice)
--[[
every frame export to Ikarus
Example from A-10C
Get Radio Frequencies
get data from device
local lUHFRadio = GetDevice(54)
ExportScript.Tools.SendData("ExportID", "Format")
ExportScript.Tools.SendData(2000, string.format("%7.3f", lUHFRadio:get_frequency()/1000000)) -- <- special function for get frequency data
ExportScript.Tools.SendData(2000, ExportScript.Tools.RoundFreqeuncy((UHF_RADIO:get_frequency()/1000000))) -- ExportScript.Tools.RoundFreqeuncy(frequency (MHz|KHz), format ("7.3"), PrefixZeros (false), LeastValue (0.025))
]]
--[443] = "%.4f", -- SAI_knob_arrow {-1.0, 1.0} {0.0, 1.0}
ExportScript.Tools.SendData(443, ExportScript.Tools.negate(mainPanelDevice:get_argument_value(443)))
end
function ExportScript.ProcessDACConfigHighImportance(mainPanelDevice)
--[[
every frame export to DAC
Example from A-10C
Get Radio Frequencies
get data from device
local UHF_RADIO = GetDevice(54)
ExportScript.Tools.SendDataDAC("ExportID", "Format")
ExportScript.Tools.SendDataDAC("ExportID", "Format", HardwareConfigID)
ExportScript.Tools.SendDataDAC("2000", string.format("%7.3f", UHF_RADIO:get_frequency()/1000000))
ExportScript.Tools.SendDataDAC("2000", ExportScript.Tools.RoundFreqeuncy((UHF_RADIO:get_frequency()/1000000))) -- ExportScript.Tools.RoundFreqeuncy(frequency (MHz|KHz), format ("7.3"), PrefixZeros (false), LeastValue (0.025))
]]
end
-----------------------------------------------------
-- LOW IMPORTANCE EXPORTS --
-- done every gExportLowTickInterval export events --
-----------------------------------------------------
-- Pointed to by ExportScript.ProcessIkarusDCSConfigLowImportance
function ExportScript.ProcessIkarusDCSConfigLowImportance(mainPanelDevice)
--[[
export in low tick interval to Ikarus
Example from A-10C
Get Radio Frequencies
get data from device
local lUHFRadio = GetDevice(54)
ExportScript.Tools.SendData("ExportID", "Format")
ExportScript.Tools.SendData(2000, string.format("%7.3f", lUHFRadio:get_frequency()/1000000)) -- <- special function for get frequency data
ExportScript.Tools.SendData(2000, ExportScript.Tools.RoundFreqeuncy((UHF_RADIO:get_frequency()/1000000))) -- ExportScript.Tools.RoundFreqeuncy(frequency (MHz|KHz), format ("7.3"), PrefixZeros (false), LeastValue (0.025))
]]
--AN/ARC-164 UHF
---------------------------------------------------
local lUHFRadio = GetDevice(23)
if lUHFRadio:is_on() then
--ExportScript.Tools.SendData(2000, string.format("%.3f", lUHFRadio:get_frequency()/1000000))
ExportScript.Tools.SendData(2000, ExportScript.Tools.RoundFreqeuncy(lUHFRadio:get_frequency()/1000000))
local lUHFRadio_PRESET = {[0]="01",[0.05]="02",[0.1]="03",[0.15]="04",[0.2]="05",[0.25]="06",[0.3]="07",[0.35]="08",[0.4]="09",[0.45]="10",[0.5]="11",[0.55]="12",[0.6]="13",[0.65]="14",[0.7]="15",[0.75]="16",[0.80]="17",[0.85]="18",[0.90]="19",[0.95]="20"}
ExportScript.Tools.SendData(2001, lUHFRadio_PRESET[ExportScript.Tools.round(mainPanelDevice:get_argument_value(300), 2)])
end
--[327] = "%.1f", -- AN/ARC-164, UHF Radio 100 MHz Frequency Selector Knob {0.0, 0.1, 0.2, 0.3}
--[328] = "%.1f", -- AN/ARC-164, UHF Radio 10 MHz Frequency Selector Knob {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9}
--[329] = "%.1f", -- AN/ARC-164, UHF Radio 1 MHz Frequency Selector Knob {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9}
--[330] = "%.1f", -- AN/ARC-164, UHF Radio 0.1 MHz Frequency Selector Knob {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9}
--[331] = "%.2f", -- AN/ARC-164, UHF Radio 0.025 MHz Frequency Selector Knob {0.0, 0.25, 0.5, 0.75}
--F5E_UHF
--327: 0.0=A, 0.1=3, 0.2=2, 0.3=T
--1: 0.0=A, 0.1=T, 0.2=2, 0.3=3
--328: 0.0=0, 0.1=9, 0.2=8, 0.3=7, 0.4=6, 0.5=5, 0.6=4, 0.7=3, 0.8=2, 0.9=1, 1.0=0
--2: 0.0=0, 0.1=1, 0.2=2, 0.3=3, 0.4=4, 0.5=5, 0.6=6, 0.7=7, 0.8=8, 0.9=9, 1.0=0
--329: 0.0=0, 0.1=9, 0.2=8, 0.3=7, 0.4=6, 0.5=5, 0.6=4, 0.7=3, 0.8=2, 0.9=1, 1.0=0
--3: 0.0=0, 0.1=1, 0.2=2, 0.3=3, 0.4=4, 0.5=5, 0.6=6, 0.7=7, 0.8=8, 0.9=9, 1.0=0
--330: 0.0=0, 0.1=9, 0.2=8, 0.3=7, 0.4=6, 0.5=5, 0.6=4, 0.7=3, 0.8=2, 0.9=1, 1.0=0
--4: 0.0=0, 0.1=1, 0.2=2, 0.3=3, 0.4=4, 0.5=5, 0.6=6, 0.7=7, 0.8=8, 0.9=9, 1.0=0
--331: 0.0=00, 0.25=75, 0.5=50, 0.75=25, 1.0=00
--5: 0.0=00, 0.25=25, 0.5=50, 0.75=75
local lTmp327 = tonumber(string.format("%0.1f", mainPanelDevice:get_argument_value(327)))
local lTmp327_2 = lTmp327
if lTmp327 == 0.0 then lTmp327_2 = 0.0
elseif lTmp327 == 0.1 then lTmp327_2 = 0.3
elseif lTmp327 == 0.2 then lTmp327_2 = 0.2
elseif lTmp327 == 0.3 then lTmp327_2 = 0.1
else lTmp327_2 = lTmp327 end
local lTmp328_2 = 1 - mainPanelDevice:get_argument_value(328)
local lTmp329_2 = 1 - mainPanelDevice:get_argument_value(329)
local lTmp330_2 = 1 - mainPanelDevice:get_argument_value(330)
local lTmp331 = mainPanelDevice:get_argument_value(331)
local lTmp331_2 = 0
if lTmp331 == 0.0 then lTmp331_2 = 0.0
elseif lTmp331 == 0.25 then lTmp331_2 = 0.75
elseif lTmp331 == 0.5 then lTmp331_2 = 0.5
elseif lTmp331 == 0.75 then lTmp331_2 = 0.25
else lTmp331_2 = lTmp331 end
ExportScript.Tools.SendData(327, lTmp327_2)
ExportScript.Tools.SendData(328, lTmp328_2)
ExportScript.Tools.SendData(329, lTmp329_2)
ExportScript.Tools.SendData(330, lTmp330_2)
ExportScript.Tools.SendData(331, lTmp331_2)
-- TACAN Channel
-------------------------------------------------
ExportScript.Tools.SendData(2002, (string.format("%0.2f", (mainPanelDevice:get_argument_value(263))) == "1.00" and "0" or "1")..ExportScript.Tools.round(mainPanelDevice:get_argument_value(264) * 10, 0)..ExportScript.Tools.round(mainPanelDevice:get_argument_value(265) * 10, 0)..(string.format("%1d", (mainPanelDevice:get_argument_value(266))) == "0" and "X" or "Y"))
--[266] = "%.4f", -- XYwheel
ExportScript.Tools.SendData(266, mainPanelDevice:get_argument_value(266) == 0 and 0 or 1)
end
function ExportScript.ProcessDACConfigLowImportance(mainPanelDevice)
--[[
export in low tick interval to DAC
Example from A-10C
Get Radio Frequencies
get data from device
local UHF_RADIO = GetDevice(54)
ExportScript.Tools.SendDataDAC("ExportID", "Format")
ExportScript.Tools.SendDataDAC("ExportID", "Format", HardwareConfigID)
ExportScript.Tools.SendDataDAC("2000", string.format("%7.3f", UHF_RADIO:get_frequency()/1000000))
ExportScript.Tools.SendDataDAC("2000", ExportScript.Tools.RoundFreqeuncy((UHF_RADIO:get_frequency()/1000000))) -- ExportScript.Tools.RoundFreqeuncy(frequency (MHz|KHz), format ("7.3"), PrefixZeros (false), LeastValue (0.025))
]]
--AN/ARC-164 UHF
---------------------------------------------------
local lUHFRadio = GetDevice(23)
if lUHFRadio:is_on() then
--ExportScript.Tools.SendDataDAC(2000, string.format("%.3f", lUHFRadio:get_frequency()/1000000))
ExportScript.Tools.SendDataDAC(2000, ExportScript.Tools.RoundFreqeuncy(lUHFRadio:get_frequency()/1000000))
local lUHFRadio_PRESET = {[0]="01",[0.05]="02",[0.1]="03",[0.15]="04",[0.2]="05",[0.25]="06",[0.3]="07",[0.35]="08",[0.4]="09",[0.45]="10",[0.5]="11",[0.55]="12",[0.6]="13",[0.65]="14",[0.7]="15",[0.75]="16",[0.80]="17",[0.85]="18",[0.90]="19",[0.95]="20"}
ExportScript.Tools.SendDataDAC(2001, lUHFRadio_PRESET[ExportScript.Tools.round(mainPanelDevice:get_argument_value(300), 2)])
end
-- TACAN Channel
-------------------------------------------------
ExportScript.Tools.SendDataDAC(2002, (string.format("%0.2f", (mainPanelDevice:get_argument_value(263))) == "1.00" and "0" or "1")..ExportScript.Tools.round(mainPanelDevice:get_argument_value(264) * 10, 0)..ExportScript.Tools.round(mainPanelDevice:get_argument_value(265) * 10, 0)..(string.format("%1d", (mainPanelDevice:get_argument_value(266))) == "0" and "X" or "Y"))
-- Fuel Quantity Indicator (Dual)
local lLeftFuel = ExportScript.Tools.round(mainPanelDevice:get_argument_value(22) * 2500, 0)
local lRightFuel = ExportScript.Tools.round(mainPanelDevice:get_argument_value(23) * 2500, 0)
ExportScript.Tools.SendDataDAC(2003, lLeftFuel)
ExportScript.Tools.SendDataDAC(2004, lRightFuel)
ExportScript.Tools.SendDataDAC(2005, lLeftFuel + lRightFuel)
-- generic Radio display and frequency rotarys
-------------------------------------------------
-- genericRadioConf
ExportScript.genericRadioConf = {}
ExportScript.genericRadioConf['maxRadios'] = 1 -- numbers of aviables/supported radios
ExportScript.genericRadioConf[1] = {} -- first radio
ExportScript.genericRadioConf[1]['Name'] = "AN/ARC-164 UHF" -- name of radio
ExportScript.genericRadioConf[1]['DeviceID'] = 23 -- DeviceID for GetDevice from device.lua
ExportScript.genericRadioConf[1]['setFrequency'] = true -- change frequency active
ExportScript.genericRadioConf[1]['FrequencyMultiplicator'] = 1000000 -- Multiplicator from Hz to MHz
ExportScript.genericRadioConf[1]['FrequencyFormat'] = "%7.3f" -- frequency view format LUA style
ExportScript.genericRadioConf[1]['FrequencyStep'] = 25 -- minimal step for frequency change
ExportScript.genericRadioConf[1]['minFrequency'] = 220.000 -- lowest frequency
ExportScript.genericRadioConf[1]['maxFrequency'] = 399.975 -- highest frequency
ExportScript.genericRadioConf[1]['Power'] = {} -- power button active
ExportScript.genericRadioConf[1]['Power']['ButtonID'] = 3008 -- power button id from cklickable.lua
ExportScript.genericRadioConf[1]['Power']['ValueOn'] = 0.1 -- power on value from cklickable.lua
ExportScript.genericRadioConf[1]['Power']['ValueOff'] = 0.0 -- power off value from cklickable.lua
ExportScript.genericRadioConf[1]['Volume'] = {} -- volume knob active
ExportScript.genericRadioConf[1]['Volume']['ButtonID'] = 3011 -- volume button id from cklickable.lua
ExportScript.genericRadioConf[1]['Preset'] = {} -- preset knob active
ExportScript.genericRadioConf[1]['Preset']['ArgumentID'] = 300 -- ManualPreset argument id from cklickable.lua
ExportScript.genericRadioConf[1]['Preset']['ButtonID'] = 3001 -- preset button id from cklickable.lua
-- Preset based on switchlogic on clickabledata.lua
ExportScript.genericRadioConf[1]['Preset']['List'] = {[0.0]="01",[0.1]="02",[0.2]="03",[0.3]="04",[0.4]="05",[0.5]="06",[0.6]="07",[0.7]="08",[0.8]="09",[0.9]="10",[0.10]="11",[0.11]="12",[0.12]="13",[0.13]="14",[0.14]="15",[0.15]="16",[0.16]="17",[0.17]="18",[0.18]="19",[0.19]="20"}
ExportScript.genericRadioConf[1]['Preset']['Step'] = 0.1 -- minimal step for preset change
ExportScript.genericRadioConf[1]['Squelch'] = {} -- squelch switch active
ExportScript.genericRadioConf[1]['Squelch']['ArgumentID'] = 308 -- ManualPreset argument id from cklickable.lua
ExportScript.genericRadioConf[1]['Squelch']['ButtonID'] = 3010 -- squelch button id from cklickable.lua
ExportScript.genericRadioConf[1]['Squelch']['ValueOn'] = 0.0 -- squelch on value from cklickable.lua
ExportScript.genericRadioConf[1]['Squelch']['ValueOff'] = 1.0 -- squelch off value from cklickable.lua
--ExportScript.genericRadioConf[1]['Load'] = {} -- load button preset
--ExportScript.genericRadioConf[1]['Load']['ButtonID'] = 3015 -- load button id from cklickable.lua
ExportScript.genericRadioConf[1]['ManualPreset'] = {} -- switch manual or preset active
ExportScript.genericRadioConf[1]['ManualPreset']['ArgumentID'] = 307 -- ManualPreset argument id from cklickable.lua
ExportScript.genericRadioConf[1]['ManualPreset']['ButtonID'] = 3007 -- ManualPreset button id from cklickable.lua
ExportScript.genericRadioConf[1]['ManualPreset']['ValueManual'] = 0.0-- ManualPreset Manual value from cklickable.lua
ExportScript.genericRadioConf[1]['ManualPreset']['ValuePreset'] = 0.1-- ManualPreset Preset value from cklickable.lua
--=====================================================================================
--[[
ExportScript.Tools.WriteToLog('list_cockpit_params(): '..ExportScript.Tools.dump(list_cockpit_params()))
ExportScript.Tools.WriteToLog('CMSP: '..ExportScript.Tools.dump(list_indication(7)))
-- list_indication get tehe value of cockpit displays
local ltmp1 = 0
for ltmp2 = 0, 20, 1 do
ltmp1 = list_indication(ltmp2)
ExportScript.Tools.WriteToLog(ltmp2..': '..ExportScript.Tools.dump(ltmp1))
end
]]
--[[
-- getmetatable get function name from devices
local ltmp1 = 0
for ltmp2 = 1, 70, 1 do
ltmp1 = GetDevice(ltmp2)
ExportScript.Tools.WriteToLog(ltmp2..': '..ExportScript.Tools.dump(ltmp1))
ExportScript.Tools.WriteToLog(ltmp2..' (metatable): '..ExportScript.Tools.dump(getmetatable(ltmp1)))
end
]]
end
-----------------------------
-- Custom functions --
-----------------------------
| lgpl-3.0 |
Ninjistix/darkstar | scripts/zones/Ilrusi_Atoll/npcs/Excaliace.lua | 5 | 4147 | -----------------------------------
-- Area: Periqia
-- NPC: Excaliace
-----------------------------------
require("scripts/zones/Periqia/IDs");
require("scripts/globals/pathfind");
local start = {-322,-16.5,380};
local startToChoice1 = {
-320.349548, -16.046591, 379.684570
-318.312317, -16.046591, 379.579865
-316.286530, -16.046591, 379.472992
-314.249298, -16.048323, 379.368164
-312.212616, -16.050047, 379.263855
-310.348267, -16.057688, 378.513367
-309.100250, -16.063747, 376.912720
-307.959656, -16.077335, 375.221832
-306.816345, -16.077335, 373.532349
-305.671082, -16.077335, 371.846008
-304.516022, -16.077335, 370.168579
-303.362549, -16.077335, 368.489624
-302.209167, -16.087559, 366.807190
-301.054626, -16.087715, 365.125336
-299.976593, -16.119972, 363.402710
-299.820740, -16.189123, 361.399994
-300.012909, -16.189123, 359.369080
-300.204407, -16.189123, 357.341705
-300.397125, -16.189123, 355.314880
-300.588409, -16.189123, 353.283936
-300.780060, -16.189123, 351.253296
-300.971313, -16.191444, 349.222321
-301.163574, -16.214754, 347.192749
-301.389923, -16.229296, 345.167511
-302.813599, -16.249445, 343.574554
-304.622406, -16.276562, 342.632568
-306.459869, -16.276562, 341.757172
-308.455261, -16.276562, 341.393158
-310.489380, -16.276562, 341.389252
-312.521088, -16.279837, 341.571747
-314.551819, -16.298687, 341.754822
-316.585144, -15.753593, 341.876556
-318.621338, -15.789236, 341.765198
-320.658966, -15.779417, 341.662872
-322.697296, -15.765886, 341.574463
-324.727234, -15.980421, 341.479340
-326.660187, -16.012735, 342.099487
-328.550476, -15.933064, 342.860687
-330.435150, -15.771011, 343.625427
-332.294006, -15.696083, 344.450684
-333.912903, -16.043205, 345.705078
-335.720062, -15.788860, 346.616364
-337.668945, -15.706074, 347.100769
-339.570679, -15.741604, 346.444336
-340.824524, -15.691669, 344.865021
-341.839478, -15.428291, 343.124268
-342.645996, -15.079435, 341.120239
-342.902252, -15.113903, 339.113068
-342.625366, -15.397438, 337.113739
-342.355469, -15.772522, 335.126404
-341.725372, -16.081879, 333.186157
-341.358307, -16.052465, 331.183319
-340.988190, -15.890514, 329.183777
-340.739380, -15.852081, 327.166229
-340.652344, -15.829269, 325.153931
-340.602631, -15.811451, 323.125397
-340.650421, -15.682171, 321.093201
-340.440063, -15.661972, 318.978729
-340.534454, -15.702602, 316.816895
-340.532501, -15.702147, 314.776947
-340.536591, -15.697933, 312.737244
-340.542572, -15.670002, 310.697632
-340.545624, -15.678772, 308.657776
-340.554047, -15.631170, 306.619476
-340.412598, -15.624416, 304.459137
-340.379303, -15.661182, 302.420258
};
function onSpawn(npc)
npc:initNpcAi();
npc:pathThrough(start, PATHFLAG_REPEAT);
end;
function onPath(npc)
local instance = npc:getInstance();
local progress = instance:getProgress();
local chars = instance:getChars();
if (progress == 0) then
for tid,player in pairs(chars) do
if (npc:checkDistance(player) < 10) then
instance:setProgress(1);
npc:messageText(npc,Periqia.text.EXCALIACE_START);
npc:pathThrough(startToChoice1);
end
end
elseif (progress == 1) then
local run = true;
for tid,player in pairs(chars) do
if (npc:checkDistance(player) < 10) then
run = false;
end
end
if (run) then
npc:messageText(npc,Periqia.text.EXCALIACE_RUN);
end
end
-- go back and forth the set path
-- pathfind.patrol(npc, path);
end;
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option,npc)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
TRex22/hawkthorne-journey | src/nodes/info.lua | 1 | 1163 | local Dialog = require 'dialog'
local Info = {}
Info.__index = Info
function Info.new(node, collider)
local info = {}
setmetatable(info, Info)
info.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
info.bb.node = info
info.info = split( node.properties.info, '|' )
info.x = node.x
info.y = node.y
info.height = node.height
info.width = node.width
info.foreground = 'true'
collider:setPassive(info.bb)
info.current = nil
return info
end
function Info:update(dt, player)
end
function Info:draw()
end
function Info:collide(node, dt, mtv_x, mtv_y)
if node.isPlayer then
node.interactive_collide = true
end
end
function Info:collide_end(node, dt)
if node.isPlayer then
node.interactive_collide = false
end
end
function Info:keypressed( button, player )
if button == 'INTERACT' and self.dialog == nil and not player.freeze then
player.freeze = true
self.dialog = Dialog.new(self.info, function()
player.freeze = false
Dialog.currentDialog = nil
end)
return true
end
end
return Info
| mit |
ccyphers/kong | spec/03-plugins/007-loggly/01-log_spec.lua | 3 | 4995 | local helpers = require "spec.helpers"
local cjson = require "cjson"
local UDP_PORT = 20000
describe("Plugin: loggly (log)", function()
local client
setup(function()
local api1 = assert(helpers.dao.apis:insert {
name = "api-1",
hosts = { "logging.com" },
upstream_url = "http://mockbin.com"
})
local api2 = assert(helpers.dao.apis:insert {
name = "api-2",
hosts = { "logging1.com" },
upstream_url = "http://mockbin.com"
})
local api3 = assert(helpers.dao.apis:insert {
name = "api-3",
hosts = { "logging2.com" },
upstream_url = "http://mockbin.com"
})
local api4 = assert(helpers.dao.apis:insert {
name = "api-4",
hosts = { "logging3.com" },
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
api_id = api1.id,
name = "loggly",
config = {
host = "127.0.0.1",
port = UDP_PORT,
key = "123456789",
log_level = "info",
successful_severity = "warning"
}
})
assert(helpers.dao.plugins:insert {
api_id = api2.id,
name = "loggly",
config = {
host = "127.0.0.1",
port = UDP_PORT,
key = "123456789",
log_level = "debug",
timeout = 2000,
successful_severity = "info"
}
})
assert(helpers.dao.plugins:insert {
api_id = api3.id,
name = "loggly",
config = {
host = "127.0.0.1",
port = UDP_PORT,
key = "123456789",
log_level = "crit",
successful_severity = "crit",
client_errors_severity = "warning"
}
})
assert(helpers.dao.plugins:insert {
api_id = api4.id,
name = "loggly",
config = {
host = "127.0.0.1",
port = UDP_PORT,
key = "123456789"
}
})
assert(helpers.start_kong())
end)
teardown(function()
helpers.stop_kong()
end)
before_each(function()
client = helpers.proxy_client()
end)
after_each(function()
if client then client:close() end
end)
-- Helper; performs a single http request and catches the udp log output.
-- @param message the message table for the http client
-- @param status expected status code from the request, defaults to 200 if omitted
-- @return 2 values; 'pri' field (string) and the decoded json content (table)
local function run(message, status)
local thread = assert(helpers.udp_server(UDP_PORT))
local response = assert(client:send(message))
assert.res_status(status or 200, response)
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
local pri = assert(res:match("^<(%d-)>"))
local json = assert(res:match("{.*}"))
return pri, cjson.decode(json)
end
it("logs to UDP when severity is warning and log level info", function()
local pri, message = run({
method = "GET",
path = "/request",
headers = {
host = "logging.com"
}
})
assert.equal("12", pri)
assert.equal("127.0.0.1", message.client_ip)
end)
it("logs to UDP when severity is info and log level debug", function()
local pri, message = run({
method = "GET",
path = "/request",
headers = {
host = "logging1.com"
}
})
assert.equal("14", pri)
assert.equal("127.0.0.1", message.client_ip)
end)
it("logs to UDP when severity is critical and log level critical", function()
local pri, message = run({
method = "GET",
path = "/request",
headers = {
host = "logging2.com"
}
})
assert.equal("10", pri)
assert.equal("127.0.0.1", message.client_ip)
end)
it("logs to UDP when severity and log level are default values", function()
local pri, message = run({
method = "GET",
path = "/",
headers = {
host = "logging3.com"
}
})
assert.equal("14", pri)
assert.equal("127.0.0.1", message.client_ip)
end)
it("logs to UDP when severity and log level are default values and response status is 200", function()
local pri, message = run({
method = "GET",
path = "/",
headers = {
host = "logging3.com"
}
})
assert.equal("14", pri)
assert.equal("127.0.0.1", message.client_ip)
end)
it("logs to UDP when severity and log level are default values and response status is 401", function()
local pri, message = run({
method = "GET",
path = "/status/401/",
headers = {
host = "logging3.com"
}
}, 401)
assert.equal("14", pri)
assert.equal("127.0.0.1", message.client_ip)
end)
it("logs to UDP when severity and log level are default values and response status is 500", function()
local pri, message = run({
method = "GET",
path = "/status/500/",
headers = {
host = "logging3.com"
}
}, 500)
assert.equal("14", pri)
assert.equal("127.0.0.1", message.client_ip)
end)
end)
| apache-2.0 |
Ninjistix/darkstar | scripts/zones/Norg/npcs/Fouvia.lua | 5 | 1292 | -----------------------------------
-- Area: Norg
-- NPC: Fouvia
-- Type: Wyvern Name Changer
-- @zone 252
-- !pos -84.066 -6.414 47.826
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/pets");
require("scripts/zones/Norg/TextIDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (player:getMainJob() ~= JOBS.DRG) then
player:showText(npc,FOUIVA_DIALOG); -- Oi 'av naw business wi' de likes av you.
elseif (player:getGil() < 9800) then
player:showText(npc,FOUIVA_DIALOG + 9); -- You don't 'av enough gil. Come back when you do.
else
player:startEvent(130,0,0,0,0,0,0,player:getVar("ChangedWyvernName"));
end
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 130 and option ~= 1073741824) then -- Player didn't cancel out
player:delGil(9800);
player:setVar("ChangedWyvernName",1);
player:setPetName(PETTYPE_WYVERN,option+1);
end
end;
| gpl-3.0 |
Ninjistix/darkstar | scripts/zones/Northern_San_dOria/npcs/Vavegallet.lua | 5 | 1122 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Vavegallet
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Northern_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
function onTrigger(player,npc)
player:startEvent(673);
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
fgeorgatos/bic | lmodrc.lua | 3 | 1829 | # -*- lua -*-
propT = {
state = {
validT = { experimental = 1, testing = 1, obsolete = 1 },
displayT = {
experimental = { short = "(E)", long = "(E)", color = "blue", doc = "Experimental", },
testing = { short = "(T)", long = "(T)", color = "green", doc = "Testing", },
obsolete = { short = "(O)", long = "(O)", color = "red", doc = "Obsolete", },
},
},
lmod = {
validT = { sticky = 1 },
displayT = {
sticky = { short = "(S)", long = "(S)", color = "red", doc = "Module is Sticky, requires --force to unload or purge", },
},
},
arch = {
validT = { mic = 1, offload = 1, gpu = 1, },
displayT = {
["mic:offload"] = { short = "(*)", long = "(m,o)", color = "blue", doc = "built for host, native MIC and offload to the MIC", },
["mic"] = { short = "(m)", long = "(m)", color = "blue", doc = "built for host and native MIC", },
["offload"] = { short = "(o)", long = "(o)", color = "blue", doc = "built for offload to the MIC only",},
["gpu"] = { short = "(g)", long = "(g)", color = "red" , doc = "built for GPU",},
["gpu:mic"] = { short = "(gm)", long = "(g,m)", color = "red" , doc = "built natively for MIC and GPU",},
["gpu:mic:offload"] = { short = "(@)", long = "(g,m,o)", color = "red" , doc = "built natively for MIC and GPU and offload to the MIC",},
},
},
status = {
validT = { active = 1, },
displayT = {
active = { short = "(L)", long = "(L)", color = "yellow", doc = "Module is loaded", },
},
},
}
scDescriptT = {
{
["dir"] = "/dev/shm/lmod/cacheDir",
["timestamp"] = "/dev/shm/lmod/system.txt",
},
}
| gpl-2.0 |
davidbuzz/ardupilot | libraries/AP_Scripting/examples/mission-edit-demo.lua | 18 | 9732 | -- mission editing demo lua script.
-- by Buzz 2020
current_pos = nil
home = 0
a = {}
demostage = 0
eventcounter = 0
function update () -- periodic function that will be called
current_pos = ahrs:get_location()
-- adds new/extra mission item at the end by copying the last one and modifying it
-- get number of last mission item
wp_num = mission:num_commands()-1
--get last item from mission
m = mission:get_item(wp_num)
-- get first item from mission
m1 = mission:get_item(1)
if wp_num > 0 then
gcs:send_text(0, string.format("LUA - Please clear misn to continue demo. size:%d",wp_num+1))
return update, 1000
end
-- no mission, just home at [0] means user has cleared any mission in the system, and this demo is clear to write something new.
-- it's not required that the mission be empty before we do things, but this script is multi-stage demo so its conveneient
if ( mission:num_commands() == 1) then
if demostage == 0 then
demostage = 1
gcs:send_text(0, string.format("LUA demo stage 1 starting"))
return stage1, 1000
end
if demostage == 2 then
demostage = 3
gcs:send_text(0, string.format("LUA demo stage 3 starting"))
return stage3, 1000
end
if demostage == 4 then
demostage = 5
gcs:send_text(0, string.format("LUA demo stage 5 starting"))
return stage5, 1000
end
if demostage == 6 then
demostage = 7
gcs:send_text(0, string.format("LUA demo stage 7 starting"))
return stage7, 1000
end
if demostage == 8 then
demostage = 9
gcs:send_text(0, string.format("LUA MISSION demo all COMPLETED."))
--return update, 1000
end
end
return update, 1000
end
function read_table_from_sd()
-- Opens a file in read mode
file = io.open("miss.txt", "r")
-- sets the default input file as xxxx.txt
io.input(file)
-- read whole file, or get empty string
content = io.read("*all")
if (content == nil) then
gcs:send_text(0, string.format("file not found, skipping read of miss.txt from sd"))
return update(), 1000
end
local pat = "wp:(%S+)%s+lat:(%S+)%s+lon:(%S+)%s+alt:(%S+)"
for s1, s2 ,s3,s4 in string.gmatch(content, pat) do
--s = string.format("wp:%s lat:%s lon:%s alt:%s",s1,s2,s3,s4)
--gcs:send_text(0, s)
n1 = tonumber(s1)
n2 = math.floor(tonumber(s2*10000000))
n3 = math.floor(tonumber(s3*10000000))
n4 = tonumber(s4)
-- use previous item as template...
m = mission:get_item(mission:num_commands()-1)
m:command(16) -- 16 = normal WAYPOINT
m:x(n2)
m:y(n3)
m:z(n4)
-- write as a new item to the end of the list.
mission:set_item(mission:num_commands(),m)
end
gcs:send_text(0, '...loaded file from SD')
-- closes the open file
io.close(file)
return update(), 1000
end
function stage1 ()
-- demo stage 1 implementation.
if (demostage == 1 ) and ( mission:num_commands() == 1 ) then
demostage = 2
return read_table_from_sd(), 1000
end
end
function stage3 ()
-- demo stage 3 implementation.
--get number of 'last' mission item
wp_num = mission:num_commands()-1
-- get HOME item from mission as the 'reference' for future items
m1 = mission:get_item(0)
--get last item from mission
m = mission:get_item(wp_num)
if (demostage == 3 ) then
-- demo stage 3 starts by writing 10 do-JUMPS over 10 seconds, just for fun
if mission:num_commands() < 10 then
m:command(177) -- 177 = DO_JUMP
m:param1(m:param1()+1) -- some increments for fun/demo
m:param2(m:param2()+1)
gcs:send_text(0, string.format("LUA new miss-item DO_JUMP %d ", wp_num+1))
mission:set_item(mission:num_commands(),m)
return stage3, 100 -- stay in stage 3 for now
end
-- change copy of last item slightly, for giggles and demo.
-- This is reading a copy of whatever is currently the last item in the mission, do_jump
-- and changing/ensuring its type is a 'normal' waypoint, and setting its lat/long/alt
-- to data we earlier took from HOME, adding an offset and then writing it
-- as a NEW mission item at the end
if mission:num_commands() == 10 then
m:command(16) -- 16 = normal WAYPOINT
m:x(m1:x()+200)
m:y(m1:y()+200)
m:z(m1:z()+1)
gcs:send_text(0, string.format("LUA new miss-item WAYPOINT a %d ", wp_num+1))
mission:set_item(mission:num_commands(),m)
return stage3, 100 -- stay in stage 3 for now
end
-- change copy of last item slightly, for giggles, and append as a new item
if (mission:num_commands() > 10) and (mission:num_commands() < 20) then
m:command(16) -- 16 = normal WAYPOINT
m:x(m:x()+200)
m:y(m:y()+200)
m:z(m:z()+1)
gcs:send_text(0, string.format("LUA new miss-item WAYPOINT b %d ", wp_num+1))
mission:set_item(mission:num_commands(),m)
return stage3, 100 -- stay in stage 3 for now
end
-- change copy of last item slightly, for giggles.
if (mission:num_commands() >= 20) and (mission:num_commands() < 30) then
m:command(16) -- 16 = normal WAYPOINT
m:x(m:x()+200)
m:y(m:y()+200)
m:z(m:z()+1)
gcs:send_text(0, string.format("LUA new miss-item WAYPOINT c %d ", wp_num+1))
mission:set_item(mission:num_commands(),m)
return stage3, 100 -- stay in stage 3 for now
end
-- move on at end of this dempo stage
if (mission:num_commands() >= 30) then
gcs:send_text(0, string.format("LUA DEMO stage 3 done. ", wp_num+1))
demostage = 4
return update, 100 -- drop to next stage via an update() call
end
end
end
function stage5 ()
-- demo stage 5 implementation for when there's only one wp , HOME, in th system
if (demostage == 5 ) then
-- when no mission, uses home as reference point, otherwise its the 'last item'
m = mission:get_item(mission:num_commands()-1)
m:x(m:x())
m:y(m:y()-400)
m:z(m:z())
mission:set_item(1,m)
gcs:send_text(0, string.format("LUA mode 5 single wp nudge %d",eventcounter))
eventcounter = eventcounter+1
if eventcounter > 50 then
demostage = 6
eventcounter = 0
gcs:send_text(0, string.format("LUA DEMO stage 5 done. "))
return update, 100 -- drop to next stage via an update() call
end
return stage5, 100 -- stay in stage 3 for now
end
end
function stage7 ()
-- demo stage 5 implementation for when there's more than wp in the system
if (demostage == 7 ) then --and (mission:num_commands() >= 3) and (mission:num_commands() < 50) then
-- fiurst time in , there's no mission, lets throw a few wps in to play with later..
-- change copy of last item slightly, for giggles, and append as a new item
if (mission:num_commands() == 1) then
for x = 1, 10 do
m:command(16) -- 16 = normal WAYPOINT
m:x(m:x()+math.random(-10000,10000)) -- add something random
m:y(m:y()+math.random(-10000,10000))
m:z(m:z()+1)
gcs:send_text(0, string.format("LUA stage 7 making 10 new nearby random wp's %d ", wp_num+1))
mission:set_item(mission:num_commands(),m)
end
gcs:send_text(0, string.format("LUA scattering complete. %d ", wp_num+1))
return stage7, 100 -- stay in stage 3 for now
end
-- things that are further away from this one than distance X..
m1 = mission:get_item(1)
-- leave item 0 alone, always
for x = 1, mission:num_commands()-1 do
mitem = mission:get_item(x)
-- look at each mission item above 1, and get the distance from it to the copter.
local target = Location()
target:lat(mitem:x())
target:lng(mitem:y())
local cur_d = current_pos:get_distance(target)
if cur_d > 100 then
if mitem:x() > m1:x() then
mitem:x(mitem:x()+400)
end
if mitem:x() < m1:x() then
mitem:x(mitem:x()-400)
end
if mitem:y() > m1:y() then
mitem:y(mitem:y()+400)
end
if mitem:y() < m1:y() then
mitem:y(mitem:y()-400)
end
end
-- write as a new item to the end of the list.
mission:set_item(x,mitem)
end
gcs:send_text(0, string.format("LUA mode 7 scattering existing wp's.. %d",eventcounter))
end
-- do it 50 times then consider it done
eventcounter = eventcounter+1
if eventcounter > 50 then
demostage = 8
eventcounter = 0
gcs:send_text(0, string.format("LUA DEMO stage 7 done. "))
return update, 100 -- drop to next stage via an update() call
end
return stage7, 500
end
function wait_for_home()
current_pos = ahrs:get_location()
if current_pos == nil then
return wait_for_home, 1000
end
home = ahrs:get_home()
if home == nil then
return wait_for_home, 1000
end
if home:lat() == 0 then
return wait_for_home, 1000
end
gcs:send_text(0, string.format("LUA MISSION Waiting for Home."))
return update, 1000
end
function delayed_boot()
gcs:send_text(0, string.format("LUA MISSION DEMO START"))
return wait_for_home, 1000
end
return delayed_boot, 5000
| gpl-3.0 |
wangyi0226/skynet | test/testsmg.lua | 1 | 2233 | local skynet = require "skynet"
local snax = require "skynet.smg"
skynet.start(function()
--skynet.trace()
local ps = snax.newservice ("pingserver_smg", "hello world")
print(ps.req.ping("foobar"))
print("AAAAAAAAAAAAAAAAAAAAAAAAAAA:",ps.wait.ping2("foobar"))
print(ps.post.hello())
--print(pcall(ps.req.error))
--skynet.exit()
print("Hotfix (i) :", snax.hotfix(ps, [[
local i
local hello2_old_uv
local test_smg_hotfix
local lock
local skynet
function wait.ping2(hello)
local r=skynet.response()
r(true,hello.."#2")
end
function accept.hello()
i = i + 1
print ("fix", i, hello)
end
function accept.hello2(...)
print("========================== hello2_old_uv",hello2_old_uv,...)
if not hello2_old_uv then
local i,data
local new_p=function(p)
if data == 100 then
data=1000
end
print("test_smg_hotfix----",i,data,p)
i=i+1
end
__patch(new_p,test_smg_hotfix.print)
test_smg_hotfix.print=new_p
end
test_smg_hotfix.print(...)
end
function dispatch(method, ... )
print("=======================================dispatch2:",method[1],method[2],method[3],method[4],...)
method[4](...)
end
function exit(...)
print ("ping server exit2:", ...)
end
function hotfix(...)
local temp = i
i = 100
print("hotfix call hello2",hotfix_val)
accept.hello2()
print("hotfix:",i,hello,accept)
accept.hello3=function(p)
print("accept.hello3",hello,p)
test_smg_hotfix.print2(p)
end
response.hello3=function(p)
return p
end
wait.ping3=function(p)
local r=skynet.response()
r(true,p.."#")
end
return temp
end
]]))
print(ps.post.hello())
print(ps.post.hello2("HHHHHHHHHHHHHHHHHHHHHHH1"))
print("wait==========",ps.wait.ping2("HHHHHHHHHHHHHHHHHHHHHHH2"))
print(ps.hpost.hello3("HHHHHHHHHHHHHHpost hello3"))
print("PPPPPP",ps.hwait.ping3("HHHHHHHHHHHHHHwait ping3"))
print("................",ps.hreq.hello3("HHHHHHHHHHHHHHreq hello3"))
skynet.exit()
local info = skynet.call(ps.handle, "debug", "INFO")
for name,v in pairs(info) do
print(string.format("%s\tcount:%d time:%f", name, v.count, v.time))
end
print(ps.post.exit("exit")) -- == snax.kill(ps, "exit")
skynet.exit()
end)
| mit |
DEVll190ll/DEV_HR | plugins/DEV_2.lua | 1 | 2657 | --[[
BY-@ll190ll
BY_CH : @llSNLL
]]
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
}
-- @l190ll
| gpl-2.0 |
THEGENRRAL/GENERAL | plugins/me.lua | 2 | 3447 | --[[ -- تم التعديل و التعريب بواسطه @KNSLTHM
--[[
Dev @KNSLTHM
Dev @NAHAR2_BOT
CH > @NENO_CH
--]]
do
local function mohammedboss(msg, matches)
if matches[1] == 'موقعي' then
if is_sudo(msg) then
send_document(get_receiver(msg), "./files/me/sudo.webp", ok_cb, false)
return "انـ🗣ـت الـمـطـور مـ💋ـال انـي\n🔰| اســمــك | "..msg.from.first_name.."\n"
.."🎐| ايـديـك | ("..msg.from.id..")\n"
.."📌| ايدي الكروب | ("..msg.to.id..")\n"
.."👥| اسم الكروب | ("..msg.to.title..")\n"
.."📍| معرفك | (@"..(msg.from.username or "لا يوجد")..")\n"
.."📝| رقمك | ("..(msg.from.phone or " لا يوجد ")..")\n"
elseif is_admin1(msg) then
send_document(get_receiver(msg), "./files/me/support.webp", ok_cb, false)
return "انـ🗣ـت اداري😍\n🔰| اســمــك | "..msg.from.first_name.."\n"
.."🎐| ايـديـك | ("..msg.from.id..")\n"
.."📌| ايدي الكروب | ("..msg.to.id..")\n"
.."👥| اسم الكروب | ("..msg.to.title..")\n"
.."📍| معرفك | (@"..(msg.from.username or "لا يوجد")..")\n"
.."📝| رقمك | ("..(msg.from.phone or " لا يوجد ")..")\n"
elseif is_owner(msg) then
send_document(get_receiver(msg), "./files/me/owner.webp", ok_cb, false)
return "انـ🗣ـت مـديـ🌝ـرهـم\n🔰| اســمــك | "..msg.from.first_name.."\n"
.."🎐| ايـديـك | ("..msg.from.id..")\n"
.."📌| ايدي الكروب | ("..msg.to.id..")\n"
.."👥| اسم الكروب | ("..msg.to.title..")\n"
.."📍| معرفك | (@"..(msg.from.username or "لا يوجد")..")\n"
.."📝| رقمك | ("..(msg.from.phone or " لا يوجد ")..")\n"
elseif is_momod(msg) then
send_document(get_receiver(msg), "./files/me/moderator.webp", ok_cb, false)
return " انـ🗣ـت ادمن😸بـس لـتـ⚠️ـشـمـر\n🔰| اســمــك | "..msg.from.first_name.."\n"
.."🎐| ايـديـك | ("..msg.from.id..")\n"
.."📌| ايدي الكروب | ("..msg.to.id..")\n"
.."👥| اسم الكروب | ("..msg.to.title..")\n"
.."📍| معرفك | (@"..(msg.from.username or "لا يوجد")..")\n"
.."📝| رقمك | ("..(msg.from.phone or " لا يوجد ")..")\n"
else
send_document(get_receiver(msg), "./files/me/member.webp", ok_cb, false)
return "خـطـ⚠️ـيـه انـ🗣ـت عــضــو 😸\n🔰| اســمــك | "..msg.from.first_name.."\n"
.."🎐| ايـديـك | ("..msg.from.id..")\n"
.."📌| ايدي الكروب | ("..msg.to.id..")\n"
.."👥| اسم الكروب | ("..msg.to.title..")\n"
.."📍| معرفك | (@"..(msg.from.username or "لا يوجد")..")\n"
.."📝| رقمك | ("..(msg.from.phone or " لا يوجد ")..")\n"
end
end
end
return {
patterns = {
"^(موقعي)$",
"^(موقعي)$",
"^[#!/](موقعي)$",
"^[#!/](موقعي)$"
},
run = mohammedboss
}
end
--[[ -- تم التعديل و التعريب بواسطه @KNSLTHM
--[[
Dev @KNSLTHM
Dev @NAHAR2_BOT
CH > @NENO_CH
--]]
| gpl-3.0 |
premake/premake-4.x | src/actions/vstudio/vs2010_vcxproj_filters.lua | 17 | 2473 | --
-- vs2010_vcxproj_filters.lua
-- Generate a Visual Studio 2010 C/C++ filters file.
-- Copyright (c) 2009-2011 Jason Perkins and the Premake project
--
local vc2010 = premake.vstudio.vc2010
local project = premake.project
--
-- The first portion of the filters file assigns unique IDs to each
-- directory or virtual group. Would be cool if we could automatically
-- map vpaths like "**.h" to an <Extensions>h</Extensions> element.
--
function vc2010.filteridgroup(prj)
local filters = { }
local filterfound = false
for file in project.eachfile(prj) do
-- split the path into its component parts
local folders = string.explode(file.vpath, "/", true)
local path = ""
for i = 1, #folders - 1 do
-- element is only written if there *are* filters
if not filterfound then
filterfound = true
_p(1,'<ItemGroup>')
end
path = path .. folders[i]
-- have I seen this path before?
if not filters[path] then
filters[path] = true
_p(2, '<Filter Include="%s">', path)
_p(3, '<UniqueIdentifier>{%s}</UniqueIdentifier>', os.uuid())
_p(2, '</Filter>')
end
-- prepare for the next subfolder
path = path .. "\\"
end
end
if filterfound then
_p(1,'</ItemGroup>')
end
end
--
-- The second portion of the filters file assigns filters to each source
-- code file, as needed. Section is one of "ClCompile", "ClInclude",
-- "ResourceCompile", or "None".
--
function vc2010.filefiltergroup(prj, section)
local files = vc2010.getfilegroup(prj, section)
if #files > 0 then
_p(1,'<ItemGroup>')
for _, file in ipairs(files) do
local filter
if file.name ~= file.vpath then
filter = path.getdirectory(file.vpath)
else
filter = path.getdirectory(file.name)
end
if filter ~= "." then
_p(2,'<%s Include=\"%s\">', section, path.translate(file.name, "\\"))
_p(3,'<Filter>%s</Filter>', path.translate(filter, "\\"))
_p(2,'</%s>', section)
else
_p(2,'<%s Include=\"%s\" />', section, path.translate(file.name, "\\"))
end
end
_p(1,'</ItemGroup>')
end
end
--
-- Output the VC2010 filters file
--
function vc2010.generate_filters(prj)
io.indent = " "
vc2010.header()
vc2010.filteridgroup(prj)
vc2010.filefiltergroup(prj, "None")
vc2010.filefiltergroup(prj, "ClInclude")
vc2010.filefiltergroup(prj, "ClCompile")
vc2010.filefiltergroup(prj, "ResourceCompile")
_p('</Project>')
end
| bsd-3-clause |
Ninjistix/darkstar | scripts/zones/Kazham/npcs/Magriffon.lua | 5 | 3966 | -----------------------------------
-- Area: Kazham
-- NPC: Magriffon
-- Involved in Quest: Gullible's Travels, Even More Gullible's Travels,
-- Location: (I-7)
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/zones/Kazham/TextIDs");
function onTrade(player,npc,trade)
if (player:getQuestStatus(OUTLANDS, GULLIBLES_TRAVELS) == QUEST_ACCEPTED) then
if (trade:getGil() >= player:getVar("MAGRIFFON_GIL_REQUEST")) then
player:startEvent(146);
end
elseif (player:getQuestStatus(OUTLANDS, EVEN_MORE_GULLIBLES_TRAVELS) == QUEST_ACCEPTED and player:getVar("EVEN_MORE_GULLIBLES_PROGRESS") == 0) then
if (trade:getGil() >= 35000) then
player:startEvent(150, 0, 256);
end
end
end;
function onTrigger(player,npc)
local gulliblesTravelsStatus = player:getQuestStatus(OUTLANDS, GULLIBLES_TRAVELS);
local evenmoreTravelsStatus = player:getQuestStatus(OUTLANDS, EVEN_MORE_GULLIBLES_TRAVELS);
if (gulliblesTravelsStatus == QUEST_ACCEPTED) then
local magriffonGilRequest = player:getVar("MAGRIFFON_GIL_REQUEST");
player:startEvent(145, 0, magriffonGilRequest);
elseif (gulliblesTravelsStatus == QUEST_AVAILABLE and player:getFameLevel(KAZHAM) >= 6) then
local gil = math.random(10, 30) * 1000;
player:setVar("MAGRIFFON_GIL_REQUEST", gil);
player:startEvent(144, 0, gil);
elseif (evenmoreTravelsStatus == QUEST_ACCEPTED and player:getVar("EVEN_MORE_GULLIBLES_PROGRESS") == 0) then
player:startEvent(149, 0, 256, 0, 0, 0, 35000);
elseif (evenmoreTravelsStatus == QUEST_ACCEPTED and player:getVar("EVEN_MORE_GULLIBLES_PROGRESS") == 1) then
player:startEvent(151);
elseif (evenmoreTravelsStatus == QUEST_ACCEPTED and player:getVar("EVEN_MORE_GULLIBLES_PROGRESS") == 2) then
player:startEvent(152, 0, 1144, 256);
elseif (gulliblesTravelsStatus == QUEST_COMPLETED) then
if (evenmoreTravelsStatus == QUEST_AVAILABLE and player:getFameLevel(KAZHAM) >= 7 and player:needToZone() == false) then
player:startEvent(148, 0, 256, 0, 0, 35000);
else
player:startEvent(147);
end
else
player:startEvent(143);
end
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
if (csid == 144 and option == 1) then -- Gullible's Travels: First CS
player:addQuest(OUTLANDS, GULLIBLES_TRAVELS);
elseif (csid == 146) then -- Gullible's Travels: Final CS
player:confirmTrade();
player:delGil(player:getVar("MAGRIFFON_GIL_REQUEST"));
player:setVar("MAGRIFFON_GIL_REQUEST", 0);
player:addFame(KAZHAM, 30);
player:setTitle(285); -- Global Variable not working for this quest
player:completeQuest(OUTLANDS, GULLIBLES_TRAVELS);
player:needToZone(true);
elseif (csid == 148 and option == 1) then -- Even More Guillible's Travels First CS
player:addQuest(OUTLANDS, EVEN_MORE_GULLIBLES_TRAVELS);
elseif (csid == 150) then -- Even More Guillible's Travels Second CS
player:confirmTrade();
player:delGil(35000);
player:setVar("EVEN_MORE_GULLIBLES_PROGRESS", 1);
player:setTitle(286);
player:addKeyItem(256);
player:messageSpecial(KEYITEM_OBTAINED,TREASURE_MAP);
elseif (csid == 152) then
player:setVar("EVEN_MORE_GULLIBLES_PROGRESS", 0);
player:addFame(KAZHAM, 30);
player:completeQuest(OUTLANDS, EVEN_MORE_GULLIBLES_TRAVELS);
end
end;
| gpl-3.0 |
kazupon/kyototycoon | example/ktscrex.lua | 11 | 6137 | kt = __kyototycoon__
db = kt.db
-- log the start-up message
if kt.thid == 0 then
kt.log("system", "the Lua script has been loaded")
end
-- echo back the input data as the output data
function echo(inmap, outmap)
for key, value in pairs(inmap) do
outmap[key] = value
end
return kt.RVSUCCESS
end
-- report the internal state of the server
function report(inmap, outmap)
outmap["__kyototycoon__.VERSION"] = kt.VERSION
outmap["__kyototycoon__.thid"] = kt.thid
outmap["__kyototycoon__.db"] = tostring(kt.db)
for i = 1, #kt.dbs do
local key = "__kyototycoon__.dbs[" .. i .. "]"
outmap[key] = tostring(kt.dbs[i])
end
local names = ""
for name, value in pairs(kt.dbs) do
if #names > 0 then names = names .. "," end
names = names .. name
end
outmap["names"] = names
return kt.RVSUCCESS
end
-- log a message
function log(inmap, outmap)
local kind = inmap.kind
local message = inmap.message
if not message then
return kt.RVEINVALID
end
if not kind then
kind = "info"
end
kt.log(kind, message)
return kt.RVSUCCESS
end
-- store a record
function set(inmap, outmap)
local key = inmap.key
local value = inmap.value
if not key or not value then
return kt.RVEINVALID
end
local xt = inmap.xt
if not db:set(key, value, xt) then
return kt.RVEINTERNAL
end
return kt.RVSUCCESS
end
-- remove a record
function remove(inmap, outmap)
local key = inmap.key
if not key then
return kt.RVEINVALID
end
if not db:remove(key) then
local err = db:error()
if err:code() == kt.Error.NOREC then
return kt.RVELOGIC
end
return kt.RVEINTERNAL
end
return kt.RVSUCCESS
end
-- increment the numeric string value
function increment(inmap, outmap)
local key = inmap.key
local num = inmap.num
if not key or not num then
return kt.RVEINVALID
end
local function visit(rkey, rvalue, rxt)
rvalue = tonumber(rvalue)
if not rvalue then rvalue = 0 end
num = rvalue + num
return num
end
if not db:accept(key, visit) then
return kt.REINTERNAL
end
outmap.num = num
return kt.RVSUCCESS
end
-- retrieve the value of a record
function get(inmap, outmap)
local key = inmap.key
if not key then
return kt.RVEINVALID
end
local value, xt = db:get(key)
if value then
outmap.value = value
outmap.xt = xt
else
local err = db:error()
if err:code() == kt.Error.NOREC then
return kt.RVELOGIC
end
return kt.RVEINTERNAL
end
return kt.RVSUCCESS
end
-- store records at once
function setbulk(inmap, outmap)
local num = db:set_bulk(inmap)
if num < 0 then
return kt.RVEINTERNAL
end
outmap["num"] = num
return kt.RVSUCCESS
end
-- remove records at once
function removebulk(inmap, outmap)
local keys = {}
for key, value in pairs(inmap) do
table.insert(keys, key)
end
local num = db:remove_bulk(keys)
if num < 0 then
return kt.RVEINTERNAL
end
outmap["num"] = num
return kt.RVSUCCESS
end
-- retrieve records at once
function getbulk(inmap, outmap)
local keys = {}
for key, value in pairs(inmap) do
table.insert(keys, key)
end
local res = db:get_bulk(keys)
if not res then
return kt.RVEINTERNAL
end
for key, value in pairs(res) do
outmap[key] = value
end
return kt.RVSUCCESS
end
-- move the value of a record to another
function move(inmap, outmap)
local srckey = inmap.src
local destkey = inmap.dest
if not srckey or not destkey then
return kt.RVEINVALID
end
local keys = { srckey, destkey }
local first = true
local srcval = nil
local srcxt = nil
local function visit(key, value, xt)
if first then
srcval = value
srcxt = xt
first = false
return kt.Visitor.REMOVE
end
if srcval then
return srcval, srcxt
end
return kt.Visitor.NOP
end
if not db:accept_bulk(keys, visit) then
return kt.REINTERNAL
end
if not srcval then
return kt.RVELOGIC
end
return kt.RVSUCCESS
end
-- list all records
function list(inmap, outmap)
local cur = db:cursor()
cur:jump()
while true do
local key, value, xt = cur:get(true)
if not key then break end
outmap[key] = value
end
return kt.RVSUCCESS
end
-- upcate all characters in the value of a record
function upcase(inmap, outmap)
local key = inmap.key
if not key then
return kt.RVEINVALID
end
local function visit(key, value, xt)
if not value then
return kt.Visitor.NOP
end
return string.upper(value)
end
if not db:accept(key, visit) then
return kt.RVEINTERNAL
end
return kt.RVSUCCESS
end
-- prolong the expiration time of a record
function survive(inmap, outmap)
local key = inmap.key
if not key then
return kt.RVEINVALID
end
local function visit(key, value, xt)
if not value then
return kt.Visitor.NOP
end
outmap.old_xt = xt
if xt > kt.time() + 3600 then
return kt.Visitor.NOP
end
return value, 3600
end
if not db:accept(key, visit) then
return kt.RVEINTERNAL
end
return kt.RVSUCCESS
end
-- count words with the MapReduce framework
function countwords(inmap, outmap)
local function map(key, value, emit)
local values = kt.split(value, " ")
for i = 1, #values do
local word = kt.regex(values[i], "[ .?!:;]", "")
word = string.lower(word)
if #word > 0 then
if not emit(word, "") then
return false
end
end
end
return true
end
local function reduce(key, iter)
local count = 0
while true do
local value = iter()
if not value then
break
end
count = count + 1
end
outmap[key] = count
return true
end
if not db:mapreduce(map, reduce, nil, kt.DB.XNOLOCK) then
return kt.RVEINTERNAL
end
return kt.RVSUCCESS
end
| gpl-3.0 |
gmorishere/s | plugins/lyrics.lua | 695 | 2113 | do
local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs'
local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5'
local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect'
local function getInfo(query)
print('Getting info of ' .. query)
local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY
..'&q='..URL.escape(query)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local result = json:decode(b)
local artist = result[1].artist.name
local track = result[1].title
return artist, track
end
local function getLyrics(query)
local artist, track = getInfo(query)
if artist and track then
local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist)
..'&song='..URL.escape(track)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local xml = require("xml")
local result = xml.load(b)
if not result then
return nil
end
if xml.find(result, 'LyricSong') then
track = xml.find(result, 'LyricSong')[1]
end
if xml.find(result, 'LyricArtist') then
artist = xml.find(result, 'LyricArtist')[1]
end
local lyric
if xml.find(result, 'Lyric') then
lyric = xml.find(result, 'Lyric')[1]
else
lyric = nil
end
local cover
if xml.find(result, 'LyricCovertArtUrl') then
cover = xml.find(result, 'LyricCovertArtUrl')[1]
else
cover = nil
end
return artist, track, lyric, cover
else
return nil
end
end
local function run(msg, matches)
local artist, track, lyric, cover = getLyrics(matches[1])
if track and artist and lyric then
if cover then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, cover)
end
return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric
else
return 'Oops! Lyrics not found or something like that! :/'
end
end
return {
description = 'Getting lyrics of a song',
usage = '!lyrics [track or artist - track]: Search and get lyrics of the song',
patterns = {
'^!lyrics? (.*)$'
},
run = run
}
end
| gpl-2.0 |
jinks/LuaMeat | luameat.lua | 1 | 2066 | require "luarocks.loader"
local irc = require 'irc'
sqlite3 = require "lsqlite3"
plugin = {}
callback = {}
on_join = {}
on_part = {}
DB = sqlite3.open("bot.db")
require('config')
irc.DEBUG = true
irc.register_callback("connect", function()
irc.send("CAP REQ :twitch.tv/membership") -- request twitch to send join/paty notices...
--irc.send("CAP REQ :twitch.tv/tags") -- request twitch to send userinfo...
for i,v in ipairs(defaulChannels) do
irc.join(v)
end
end)
irc.register_callback("channel_msg", function(channel, from, message)
local is_cmd, cmd, arg = message:match("^([@!])(%w+)%s*(.*)$")
if is_cmd and plugin[cmd] then
plugin[cmd](channel.name, from, arg)
end
for k,v in pairs(callback) do
if type(v) == "function" then
v(channel.name, from, message)
end
end
end)
irc.register_callback("join", function(channel, from)
for k,v in pairs(on_join) do
if type(v) == "function" then
v(channel.name, from)
end
end
end)
irc.register_callback("part", function(channel, from, message)
for k,v in pairs(on_part) do
if type(v) == "function" then
v(channel.name, from)
end
end
end)
-- irc.register_callback("private_msg", function(from, message)
-- local is_cmd, cmd, arg = message:match("^(!)(%w+) (.*)$")
-- if is_cmd and plugin[cmd] then
-- plugin[cmd](from, from, arg)
-- end
-- for k,v in pairs(callback) do
-- if type(v) == "function" then
-- v(from, from, message)
-- end
-- end
-- end)
--[[
irc.register_callback("nick_change", function(from, old_nick)
end)
--]]
while true do
irc.connect{network = network, port = port, nick = nick, username = username, realname = realname, pass = password}
print("Disconnected...")
os.execute("sleep 10")
end
| apache-2.0 |
premake/premake-4.x | tests/actions/vstudio/cs2005/projectelement.lua | 51 | 1664 | --
-- tests/actions/vstudio/cs2005/projectelement.lua
-- Validate generation of <Project/> element in Visual Studio 2005+ .csproj
-- Copyright (c) 2009-2011 Jason Perkins and the Premake project
--
T.vstudio_cs2005_projectelement = { }
local suite = T.vstudio_cs2005_projectelement
local cs2005 = premake.vstudio.cs2005
--
-- Setup
--
local sln, prj
function suite.setup()
sln = test.createsolution()
end
local function prepare()
premake.bake.buildconfigs()
prj = premake.solution.getproject(sln, 1)
cs2005.projectelement(prj)
end
--
-- Tests
--
function suite.On2005()
_ACTION = "vs2005"
prepare()
test.capture [[
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
]]
end
function suite.On2008()
_ACTION = "vs2008"
prepare()
test.capture [[
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
]]
end
function suite.On2010()
_ACTION = "vs2010"
prepare()
test.capture [[
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
]]
end
function suite.On2012()
_ACTION = "vs2012"
prepare()
test.capture [[
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
]]
end
function suite.On2013()
_ACTION = "vs2013"
prepare()
test.capture [[
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
]]
end
| bsd-3-clause |
Ninjistix/darkstar | scripts/zones/Promyvion-Holla/Zone.lua | 3 | 3052 | -----------------------------------
--
-- Zone: Promyvion-Holla (16)
--
-----------------------------------
package.loaded["scripts/zones/Promyvion-Holla/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Promyvion-Holla/TextIDs");
require("scripts/zones/Promyvion-Holla/MobIDs");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/globals/settings");
require("scripts/globals/status");
function onInitialize(zone)
for k, v in pairs(HOLLA_MEMORY_STREAMS) do
zone:registerRegion(k,v[1],v[2],v[3],v[4],v[5],v[6]);
end
end;
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(92.033, 0, 80.380, 255); -- To Floor 1 {R}
end
if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") == 2) then
player:completeMission(COP,BELOW_THE_ARKS);
player:addMission(COP,THE_MOTHERCRYSTALS); -- start mission 1.3
player:setVar("PromathiaStatus",0);
elseif (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS) then
if (player:hasKeyItem(LIGHT_OF_DEM) and player:hasKeyItem(LIGHT_OF_MEA)) then
if (player:getVar("cslastpromy") == 1) then
player:setVar("cslastpromy",0)
cs = 52;
end
elseif (player:hasKeyItem(LIGHT_OF_DEM) or player:hasKeyItem(LIGHT_OF_MEA)) then
if (player:getVar("cs2ndpromy") == 1) then
player:setVar("cs2ndpromy",0)
cs = 51;
end
end
end
if (player:getVar("FirstPromyvionHolla") == 1) then
cs = 50;
end
return cs;
end;
function afterZoneIn(player)
if (ENABLE_COP_ZONE_CAP == 1) then -- ZONE WIDE LEVEL RESTRICTION
player:addStatusEffect(EFFECT_LEVEL_RESTRICTION,30,0,0); -- LV30 cap
end
end;
function onRegionEnter(player,region)
if (player:getAnimation() == 0) then
local regionId = region:GetRegionID();
local event = nil;
if (regionId < 100) then
event = HOLLA_MEMORY_STREAMS[regionId][7][1];
else
local stream = GetNPCByID(regionId);
if (stream ~= nil and stream:getAnimation() == ANIMATION_OPEN_DOOR) then
event = stream:getLocalVar("destination");
if (event == nil or event == 0) then -- this should never happen, but sanity check
event = HOLLA_MEMORY_STREAMS[regionId][7][1];
end
end
end
if (event ~= nil) then
player:startEvent(event);
end
end
end;
function onRegionLeave(player,region)
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 46 and option == 1) then
player:setPos(-225.682, -6.459, 280.002, 128, 14); -- To Hall of Transference {R}
elseif (csid == 50) then
player:setVar("FirstPromyvionHolla",0);
end
end; | gpl-3.0 |
dinodeck/ninety_nine_days_of_dev | 002_bitmap_numbers/code/fx/CombatTextFx.lua | 6 | 1579 | -- Used to display "miss", "critical", "posioned", etc
CombatTextFx = {}
CombatTextFx.__index = CombatTextFx
function CombatTextFx:Create(x, y, text, color)
local this =
{
mX = x or 0,
mY = y or 0,
mText = text or "", -- to display
mColor = color or Vector.Create(1,1,1,1),
mGravity = 700, -- pixels per second
mScale = 1.1,
mAlpha = 1,
mHoldTime = 0.175,
mHoldCounter = 0,
mFadeSpeed = 6,
mPriority = 2,
}
this.mCurrentY = this.mY
this.mVelocityY = 125,
setmetatable(this, self)
return this
end
function CombatTextFx:IsFinished()
-- Has it passed the fade out point?
return self.mAlpha == 0
end
function CombatTextFx:Update(dt)
self.mCurrentY = self.mCurrentY + (self.mVelocityY * dt)
self.mVelocityY = self.mVelocityY - (self.mGravity * dt)
if self.mCurrentY <= self.mY then
self.mCurrentY = self.mY
self.mHoldCounter = self.mHoldCounter + dt
if self.mHoldCounter > self.mHoldTime then
self.mAlpha = math.max(0, self.mAlpha - (dt * self.mFadeSpeed))
self.mColor:SetW(self.mAlpha)
end
end
end
function CombatTextFx:Render(renderer)
renderer:ScaleText(self.mScale, self.mScale)
renderer:AlignText("center", "center")
local x = self.mX
local y = math.floor(self.mCurrentY)
local shadowColor = Vector.Create(0,0,0, self.mColor:W())
renderer:DrawText2d(x + 2, y - 2, self.mText, shadowColor)
renderer:DrawText2d(x, y, self.mText, self.mColor)
end | mit |
Ninjistix/darkstar | scripts/zones/Port_Windurst/npcs/Kucha_Malkobhi.lua | 5 | 1199 | -----------------------------------
-- Area: Port Windurst
-- NPC: Kucha Malkobhi
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
player:showText(npc,KUCHAMALKOBHI_SHOP_DIALOG);
stock = {
0x315b, 273, --Tarutaru Kaftan
0x31d4, 163, --Tarutaru Mitts
0x3256, 236, --Tarutaru Braccae
0x32cf, 163, --Tarutaru Clomps
0x315c, 273, --Mithran Separates
0x31d5, 163, --Mithran Gauntlets
0x3257, 236, --Mithran Loincloth
0x32d0, 163 --Mithran Gaiters
}
showShop(player, STATIC, stock);
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
karczewa/BolScripts | TristanaMechanics.lua | 3 | 24290 | --[[
_____ _____ __ .__
/ \_______ / _ \________/ |_|__| ____ __ __ ____ ____
/ \ / \_ __ \ / /_\ \_ __ \ __\ |/ ___\| | \/ \ / _ \
/ Y \ | \/ / | \ | \/| | | \ \___| | / | ( <_> )
\____|__ /__| \____|__ /__| |__| |__|\___ >____/|___| /\____/
\/ \/ \/ \/
]]
if myHero.charName ~= "Tristana" then return end
local version = 0.63
local AUTOUPDATE = true
local SCRIPT_NAME = "TristanaMechanics"
local SOURCELIB_URL = "https://raw.github.com/TheRealSource/public/master/common/SourceLib.lua"
local SOURCELIB_PATH = LIB_PATH.."SourceLib.lua"
if FileExist(SOURCELIB_PATH) then
require("SourceLib")
else
DOWNLOADING_SOURCELIB = true
DownloadFile(SOURCELIB_URL, SOURCELIB_PATH, function() print("Required libraries downloaded successfully, please reload") end)
end
if DOWNLOADING_SOURCELIB then print("Downloading required libraries, please wait...") return end
if AUTOUPDATE then
SourceUpdater(SCRIPT_NAME, version, "raw.github.com", "/gmlyra/BolScripts/master/"..SCRIPT_NAME..".lua", SCRIPT_PATH .. GetCurrentEnv().FILE_NAME, "/gmlyra/BolScripts/master/VersionFiles/"..SCRIPT_NAME..".version"):CheckUpdate()
end
local RequireI = Require("SourceLib")
RequireI:Add("vPrediction", "https://raw.github.com/Hellsing/BoL/master/common/VPrediction.lua")
RequireI:Add("SOW", "https://raw.github.com/Hellsing/BoL/master/common/SOW.lua")
--RequireI:Add("mrLib", "https://raw.githubusercontent.com/gmlyra/BolScripts/master/common/mrLib.lua")
RequireI:Check()
if RequireI.downloadNeeded == true then return end
require 'VPrediction'
require 'SOW'
-- Constants --
local ignite, igniteReady = nil, nil
local ts = nil
local VP = nil
local qMode = false
local qOff, wOff, eOff, rOff = 0,0,0,0
local abilitySequence = {3, 2, 3, 1, 4, 1, 1, 1, 1, 3, 4, 2, 2, 2, 2, 4, 3, 3}
local Ranges = { AA = 550 }
local skills = {
SkillQ = { ready = false, name = myHero:GetSpellData(_Q).name, range = Ranges.AA, delay = myHero:GetSpellData(_Q).delayTotalTimePercent, speed = myHero:GetSpellData(_Q).missileSpeed, width = myHero:GetSpellData(_Q).lineWidth },
SkillW = { ready = false, name = myHero:GetSpellData(_W).name, range = myHero:GetSpellData(_W).range, delay = myHero:GetSpellData(_W).delayTotalTimePercent, speed = myHero:GetSpellData(_W).missileSpeed, width = myHero:GetSpellData(_W).lineWidth },
SkillE = { ready = false, name = myHero:GetSpellData(_E).name, range = Ranges.AA, delay = myHero:GetSpellData(_E).delayTotalTimePercent, speed = myHero:GetSpellData(_E).missileSpeed, width = myHero:GetSpellData(_E).lineWidth },
SkillR = { ready = false, name = myHero:GetSpellData(_R).name, range = Ranges.AA, delay = myHero:GetSpellData(_R).delayTotalTimePercent, speed = myHero:GetSpellData(_R).missileSpeed, width = myHero:GetSpellData(_R).lineWidth },
}
local AnimationCancel =
{
[1]=function() myHero:MoveTo(mousePos.x,mousePos.z) end, --"Move"
[2]=function() SendChat('/l') end, --"Laugh"
[3]=function() SendChat('/d') end, --"Dance"
[4]=function() SendChat('/t') end, --"Taunt"
[5]=function() SendChat('/j') end, --"joke"
[6]=function() end,
}
--[[ Slots Itens ]]--
local tiamatSlot, hydraSlot, youmuuSlot, bilgeSlot, bladeSlot, dfgSlot, divineSlot = nil, nil, nil, nil, nil, nil, nil
local tiamatReady, hydraReady, youmuuReady, bilgeReady, bladeReady, dfgReady, divineReady = nil, nil, nil, nil, nil, nil, nil
--[[Auto Attacks]]--
local lastBasicAttack = 0
local swingDelay = 0.25
local swing = false
--[[Misc]]--
local lastSkin = 0
local isSAC = false
local isMMA = false
local target = nil
--Credit Trees
function GetCustomTarget()
ts:update()
if _G.MMA_Target and _G.MMA_Target.type == myHero.type then return _G.MMA_Target end
if _G.AutoCarry and _G.AutoCarry.Crosshair and _G.AutoCarry.Attack_Crosshair and _G.AutoCarry.Attack_Crosshair.target and _G.AutoCarry.Attack_Crosshair.target.type == myHero.type then return _G.AutoCarry.Attack_Crosshair.target end
return ts.target
end
function OnLoad()
if _G.ScriptLoaded then return end
_G.ScriptLoaded = true
initComponents()
analytics()
end
function initComponents()
-- VPrediction Start
VP = VPrediction()
-- SOW Declare
Orbwalker = SOW(VP)
-- Target Selector
ts = TargetSelector(TARGET_LESS_CAST_PRIORITY, 900)
Menu = scriptConfig("Tristana Mechanics by Mr Articuno", "TristanaMA")
if _G.MMA_Loaded ~= nil then
PrintChat("<font color = \"#33CCCC\">MMA Status:</font> <font color = \"#fff8e7\"> Loaded</font>")
isMMA = true
elseif _G.AutoCarry ~= nil then
PrintChat("<font color = \"#33CCCC\">SAC Status:</font> <font color = \"#fff8e7\"> Loaded</font>")
isSAC = true
else
PrintChat("<font color = \"#33CCCC\">OrbWalker not found:</font> <font color = \"#fff8e7\"> Loading SOW</font>")
Menu:addSubMenu("["..myHero.charName.." - Orbwalker]", "SOWorb")
Orbwalker:LoadToMenu(Menu.SOWorb)
end
Menu:addSubMenu("["..myHero.charName.." - Combo]", "TristanaCombo")
Menu.TristanaCombo:addParam("combo", "Combo mode", SCRIPT_PARAM_ONKEYDOWN, false, 32)
Menu.TristanaCombo:addSubMenu("Q Settings", "qSet")
Menu.TristanaCombo.qSet:addParam("useQ", "Use Q in combo", SCRIPT_PARAM_ONOFF, true)
Menu.TristanaCombo:addSubMenu("W Settings", "wSet")
Menu.TristanaCombo.wSet:addParam("useW", "Use W", SCRIPT_PARAM_ONOFF, false)
Menu.TristanaCombo.wSet:addParam("wAp", "AP Tristana", SCRIPT_PARAM_ONOFF, false)
Menu.TristanaCombo:addSubMenu("E Settings", "eSet")
Menu.TristanaCombo.eSet:addParam("useE", "Use E in combo", SCRIPT_PARAM_ONOFF, true)
Menu.TristanaCombo:addSubMenu("R Settings", "rSet")
Menu.TristanaCombo.rSet:addParam("useR", "Use Smart Ultimate", SCRIPT_PARAM_ONOFF, true)
Menu:addSubMenu("["..myHero.charName.." - Harass]", "Harass")
Menu.Harass:addParam("harass", "Harass", SCRIPT_PARAM_ONKEYDOWN, false, string.byte("G"))
Menu.Harass:addParam("useQ", "Use Q in Harass", SCRIPT_PARAM_ONOFF, true)
Menu.Harass:addParam("useW", "Use W in Harass", SCRIPT_PARAM_ONOFF, false)
Menu.Harass:addParam("useE", "Use E in Harass", SCRIPT_PARAM_ONOFF, true)
Menu:addSubMenu("["..myHero.charName.." - Laneclear]", "Laneclear")
Menu.Laneclear:addParam("lclr", "Laneclear Key", SCRIPT_PARAM_ONKEYDOWN, false, string.byte("V"))
Menu.Laneclear:addParam("useClearQ", "Use Q in Laneclear", SCRIPT_PARAM_ONOFF, true)
Menu.Laneclear:addParam("useClearW", "Use W in Laneclear", SCRIPT_PARAM_ONOFF, false)
Menu.Laneclear:addParam("useClearE", "Use E in Laneclear", SCRIPT_PARAM_ONOFF, true)
Menu:addSubMenu("["..myHero.charName.." - Jungleclear]", "Jungleclear")
Menu.Jungleclear:addParam("jclr", "Jungleclear Key", SCRIPT_PARAM_ONKEYDOWN, false, string.byte("V"))
Menu.Jungleclear:addParam("useClearQ", "Use Q in Jungleclear", SCRIPT_PARAM_ONOFF, true)
Menu.Jungleclear:addParam("useClearW", "Use W in Jungleclear", SCRIPT_PARAM_ONOFF, false)
Menu.Jungleclear:addParam("useClearE", "Use E in Jungleclear", SCRIPT_PARAM_ONOFF, true)
Menu:addSubMenu("["..myHero.charName.." - Additionals]", "Ads")
Menu.Ads:addParam("cancel", "Animation Cancel", SCRIPT_PARAM_LIST, 1, { "Move","Laugh","Dance","Taunt","joke","Nothing" })
AddProcessSpellCallback(function(unit, spell)
animationCancel(unit,spell)
end)
Menu.Ads:addParam("antiGapCloser", "Anti Gap Closer", SCRIPT_PARAM_ONOFF, false)
Menu.Ads:addParam("autoLevel", "Auto-Level Spells", SCRIPT_PARAM_ONOFF, false)
Menu.Ads:addSubMenu("Killsteal", "KS")
Menu.Ads.KS:addParam("useW", "Use W", SCRIPT_PARAM_ONOFF, false)
Menu.Ads.KS:addParam("useR", "Use R", SCRIPT_PARAM_ONOFF, false)
Menu.Ads.KS:addParam("ignite", "Use Ignite", SCRIPT_PARAM_ONOFF, false)
Menu.Ads.KS:addParam("igniteRange", "Minimum range to cast Ignite", SCRIPT_PARAM_SLICE, 470, 0, 600, 0)
Menu.Ads:addSubMenu("VIP", "VIP")
--Menu.Ads.VIP:addParam("spellCast", "Spell by Packet", SCRIPT_PARAM_ONOFF, true)
Menu.Ads.VIP:addParam("skin", "Use custom skin", SCRIPT_PARAM_ONOFF, false)
Menu.Ads.VIP:addParam("skin1", "Skin changer", SCRIPT_PARAM_SLICE, 1, 1, 7)
Menu:addSubMenu("["..myHero.charName.." - Target Selector]", "targetSelector")
Menu.targetSelector:addTS(ts)
ts.name = "Focus"
Menu:addSubMenu("["..myHero.charName.." - Drawings]", "drawings")
local DManager = DrawManager()
DManager:CreateCircle(myHero, Ranges.AA + (myHero.level * 8.5), 1, {255, 0, 255, 0}):AddToMenu(Menu.drawings,"AA range", true, true, true)
DManager:CreateCircle(myHero, skills.SkillQ.range, 1, {255, 0, 255, 0}):AddToMenu(Menu.drawings,"Q range", true, true, true)
DManager:CreateCircle(myHero, skills.SkillW.range, 1, {255, 0, 255, 0}):AddToMenu(Menu.drawings,"W range", true, true, true)
DManager:CreateCircle(myHero, Ranges.AA + (myHero.level * 8.5), 1, {255, 0, 255, 0}):AddToMenu(Menu.drawings,"E range", true, true, true)
DManager:CreateCircle(myHero, Ranges.AA + (myHero.level * 8.5), 1, {255, 0, 255, 0}):AddToMenu(Menu.drawings,"R range", true, true, true)
targetMinions = minionManager(MINION_ENEMY, 360, myHero, MINION_SORT_MAXHEALTH_DEC)
allyMinions = minionManager(MINION_ALLY, 360, myHero, MINION_SORT_MAXHEALTH_DEC)
jungleMinions = minionManager(MINION_JUNGLE, 360, myHero, MINION_SORT_MAXHEALTH_DEC)
if Menu.Ads.VIP.skin and VIP_USER then
GenModelPacket("Tristana", Menu.Ads.VIP.skin1)
lastSkin = Menu.Ads.VIP.skin1
end
PrintChat("<font color = \"#33CCCC\">Tristana Mechanics by</font> <font color = \"#fff8e7\">Mr Articuno V"..version.."</font>")
PrintChat("<font color = \"#4693e0\">Sponsored by www.RefsPlea.se</font> <font color = \"#d6ebff\"> - A League of Legends Referrals service. Get RP cheaper!</font>")
end
function OnTick()
target = GetCustomTarget()
targetMinions:update()
allyMinions:update()
jungleMinions:update()
CDHandler()
KillSteal()
if Menu.Ads.VIP.skin and VIP_USER and skinChanged() then
GenModelPacket("Tristana", Menu.Ads.VIP.skin1)
lastSkin = Menu.Ads.VIP.skin1
end
if Menu.Ads.autoLevel then
AutoLevel()
end
if Menu.TristanaCombo.combo then
Combo()
end
if Menu.Harass.harass then
Harass()
end
if Menu.Laneclear.lclr then
LaneClear()
end
if Menu.Jungleclear.jclr then
JungleClear()
end
end
function CDHandler()
-- Spells
skills.SkillQ.ready = (myHero:CanUseSpell(_Q) == READY)
skills.SkillW.ready = (myHero:CanUseSpell(_W) == READY)
skills.SkillE.ready = (myHero:CanUseSpell(_E) == READY)
skills.SkillR.ready = (myHero:CanUseSpell(_R) == READY)
Ranges.AA = myHero.range
-- Items
tiamatSlot = GetInventorySlotItem(3077)
hydraSlot = GetInventorySlotItem(3074)
youmuuSlot = GetInventorySlotItem(3142)
bilgeSlot = GetInventorySlotItem(3144)
bladeSlot = GetInventorySlotItem(3153)
dfgSlot = GetInventorySlotItem(3128)
divineSlot = GetInventorySlotItem(3131)
tiamatReady = (tiamatSlot ~= nil and myHero:CanUseSpell(tiamatSlot) == READY)
hydraReady = (hydraSlot ~= nil and myHero:CanUseSpell(hydraSlot) == READY)
youmuuReady = (youmuuSlot ~= nil and myHero:CanUseSpell(youmuuSlot) == READY)
bilgeReady = (bilgeSlot ~= nil and myHero:CanUseSpell(bilgeSlot) == READY)
bladeReady = (bladeSlot ~= nil and myHero:CanUseSpell(bladeSlot) == READY)
dfgReady = (dfgSlot ~= nil and myHero:CanUseSpell(dfgSlot) == READY)
divineReady = (divineSlot ~= nil and myHero:CanUseSpell(divineSlot) == READY)
Ranges.AA = 550 + (myHero.level * 8.5)
skills.SkillE.range = Ranges.AA
skills.SkillR.range = Ranges.AA
skills.SkillQ.range = Ranges.AA
-- Summoners
if myHero:GetSpellData(SUMMONER_1).name:find("SummonerDot") then
ignite = SUMMONER_1
elseif myHero:GetSpellData(SUMMONER_2).name:find("SummonerDot") then
ignite = SUMMONER_2
end
igniteReady = (ignite ~= nil and myHero:CanUseSpell(ignite) == READY)
end
-- Harass --
function Harass()
if target ~= nil and ValidTarget(target) then
if Menu.Harass.useE and ValidTarget(target, skills.SkillE.range) and skills.SkillE.ready then
CastSpell(_E, target)
end
if Menu.Harass.useQ and ValidTarget(target, Ranges.AA) and skills.SkillQ.ready then
CastSpell(_Q)
end
end
end
-- End Harass --
-- Combo Selector --
function Combo()
local typeCombo = 0
if target ~= nil then
AllInCombo(target, 0)
end
end
-- Combo Selector --
-- All In Combo --
function AllInCombo(target, typeCombo)
if target ~= nil and typeCombo == 0 then
ItemUsage(target)
if skills.SkillR.ready and Menu.TristanaCombo.rSet.useR and ValidTarget(target, skills.SkillR.range) then
rDmg = getDmg("R", target, myHero)
if skills.SkillR.ready and target ~= nil and ValidTarget(target, 645) and target.health < rDmg then
CastSpell(_R, target)
end
end
if Menu.TristanaCombo.eSet.useE and ValidTarget(target, Ranges.AA) and skills.SkillE.ready then
CastSpell(_E, target)
end
if Menu.TristanaCombo.qSet.useQ and ValidTarget(target, Ranges.AA) and skills.SkillQ.ready then
CastSpell(_Q)
end
if Menu.TristanaCombo.wSet.useW and ValidTarget(target, skills.SkillW.range) and skills.SkillW.ready then
if Menu.TristanaCombo.wSet.wAp then
local wPosition, wChance = VP:GetCircularCastPosition(target, skills.SkillW.delay, skills.SkillW.width, skills.SkillW.range, skills.SkillW.speed, myHero, true)
if wPosition ~= nil and GetDistance(wPosition) < skills.SkillW.range and wChance >= 2 then
CastSpell(_W, wPosition.x, wPosition.z)
end
else
wDmg = getDmg("W", target, myHero)
if skills.SkillW.ready and target ~= nil and ValidTarget(target, skills.SkillW.range) and target.health < wDmg then
local wPosition, wChance = VP:GetCircularCastPosition(target, skills.SkillW.delay, skills.SkillW.width, skills.SkillW.range, skills.SkillW.speed, myHero, true)
if wPosition ~= nil and GetDistance(wPosition) < skills.SkillW.range and wChance >= 2 then
CastSpell(_W, wPosition.x, wPosition.z)
end
end
end
end
end
end
-- All In Combo --
function LaneClear()
for i, targetMinion in pairs(targetMinions.objects) do
if targetMinion ~= nil then
if Menu.Laneclear.useClearQ and skills.SkillQ.ready and ValidTarget(targetMinion, Ranges.AA) then
CastSpell(_Q)
end
if Menu.Laneclear.useClearW and skills.SkillW.ready and ValidTarget(targetMinion, skills.SkillW.range) then
CastSpell(_W, targetMinion)
end
if Menu.Laneclear.useClearE and skills.SkillE.ready and ValidTarget(targetMinion, Ranges.AA) then
CastSpell(_E, targetMinion)
end
end
end
end
function JungleClear()
for i, jungleMinion in pairs(jungleMinions.objects) do
if jungleMinion ~= nil then
if Menu.Jungleclear.useClearQ and skills.SkillQ.ready and ValidTarget(jungleMinion, Ranges.AA) then
CastSpell(_Q)
end
if Menu.Jungleclear.useClearW and skills.SkillW.ready and ValidTarget(jungleMinion, skills.SkillW.range) then
CastSpell(_W, jungleMinion)
end
if Menu.Jungleclear.useClearE and skills.SkillE.ready and ValidTarget(jungleMinion, Ranges.AA) then
CastSpell(_E, jungleMinion)
end
if jungleMinion.name == "Dragon6.1.1" or jungleMinion.name == "Worm12.1.1" then
rDmg = getDmg("R", jungleMinion, myHero)
if skills.SkillR.ready and jungleMinion ~= nil and ValidTarget(jungleMinion, skills.SkillR.range) and jungleMinion.health < rDmg then
CastSpell(_R, jungleMinion)
end
end
end
end
end
function AutoLevel()
local qL, wL, eL, rL = player:GetSpellData(_Q).level + qOff, player:GetSpellData(_W).level + wOff, player:GetSpellData(_E).level + eOff, player:GetSpellData(_R).level + rOff
if qL + wL + eL + rL < player.level then
local spellSlot = { SPELL_1, SPELL_2, SPELL_3, SPELL_4, }
local level = { 0, 0, 0, 0 }
for i = 1, player.level, 1 do
level[abilitySequence[i]] = level[abilitySequence[i]] + 1
end
for i, v in ipairs({ qL, wL, eL, rL }) do
if v < level[i] then LevelSpell(spellSlot[i]) end
end
end
end
function KillSteal()
if Menu.Ads.KS.useR then
KSR()
end
if Menu.Ads.KS.ignite then
IgniteKS()
end
end
-- Use Ultimate --
function KSR()
for i, target in ipairs(GetEnemyHeroes()) do
rDmg = getDmg("R", target, myHero)
if skills.SkillR.ready and target ~= nil and ValidTarget(target, 645) and target.health < rDmg then
CastSpell(_R, target)
elseif skills.SkillR.ready and skills.SkillW.ready and target ~= nil and ValidTarget(target, 645 + skills.SkillW.range) and target.health < rDmg and Menu.Ads.KS.useW then
CastSpell(_W, target.x, target.z)
CastSpell(_R, target)
end
end
end
-- Use Ultimate --
-- Auto Ignite get the maximum range to avoid over kill --
function IgniteKS()
if igniteReady then
local Enemies = GetEnemyHeroes()
for i, val in ipairs(Enemies) do
if ValidTarget(val, 600) then
if getDmg("IGNITE", val, myHero) > val.health and GetDistance(val) >= Menu.Ads.KS.igniteRange then
CastSpell(ignite, val)
end
end
end
end
end
-- Auto Ignite --
function HealthCheck(unit, HealthValue)
if unit.health > (unit.maxHealth * (HealthValue/100)) then
return true
else
return false
end
end
function animationCancel(unit, spell)
if not unit.isMe then return end
end
function ItemUsage(target)
if dfgReady then CastSpell(dfgSlot, target) end
if youmuuReady then CastSpell(youmuuSlot, target) end
if bilgeReady then CastSpell(bilgeSlot, target) end
if bladeReady then CastSpell(bladeSlot, target) end
if divineReady then CastSpell(divineSlot, target) end
end
function animationCancel(unit, spell)
if not unit.isMe then return end
if spell.name == 'BusterShot' then -- _R
AnimationCancel[Menu.Ads.cancel]()
end
end
-- Change skin function, made by Shalzuth
function GenModelPacket(champ, skinId)
p = CLoLPacket(0x97)
p:EncodeF(myHero.networkID)
p.pos = 1
t1 = p:Decode1()
t2 = p:Decode1()
t3 = p:Decode1()
t4 = p:Decode1()
p:Encode1(t1)
p:Encode1(t2)
p:Encode1(t3)
p:Encode1(bit32.band(t4,0xB))
p:Encode1(1)--hardcode 1 bitfield
p:Encode4(skinId)
for i = 1, #champ do
p:Encode1(string.byte(champ:sub(i,i)))
end
for i = #champ + 1, 64 do
p:Encode1(0)
end
p:Hide()
RecvPacket(p)
end
function skinChanged()
return Menu.Ads.VIP.skin1 ~= lastSkin
end
HWID = Base64Encode(tostring(os.getenv("PROCESSOR_IDENTIFIER")..os.getenv("USERNAME")..os.getenv("COMPUTERNAME")..os.getenv("PROCESSOR_LEVEL")..os.getenv("PROCESSOR_REVISION")))
id = 31
ScriptName = SCRIPT_NAME
assert(load(Base64Decode("G0x1YVIAAQQEBAgAGZMNChoKAAAAAAAAAAAAAQIDAAAAJQAAAAgAAIAfAIAAAQAAAAQKAAAAVXBkYXRlV2ViAAEAAAACAAAADAAAAAQAETUAAAAGAUAAQUEAAB2BAAFGgUAAh8FAAp0BgABdgQAAjAHBAgFCAQBBggEAnUEAAhsAAAAXwAOAjMHBAgECAgBAAgABgUICAMACgAEBgwIARsNCAEcDwwaAA4AAwUMDAAGEAwBdgwACgcMDABaCAwSdQYABF4ADgIzBwQIBAgQAQAIAAYFCAgDAAoABAYMCAEbDQgBHA8MGgAOAAMFDAwABhAMAXYMAAoHDAwAWggMEnUGAAYwBxQIBQgUAnQGBAQgAgokIwAGJCICBiIyBxQKdQQABHwCAABcAAAAECAAAAHJlcXVpcmUABAcAAABzb2NrZXQABAcAAABhc3NlcnQABAQAAAB0Y3AABAgAAABjb25uZWN0AAQQAAAAYm9sLXRyYWNrZXIuY29tAAMAAAAAAABUQAQFAAAAc2VuZAAEGAAAAEdFVCAvcmVzdC9uZXdwbGF5ZXI/aWQ9AAQHAAAAJmh3aWQ9AAQNAAAAJnNjcmlwdE5hbWU9AAQHAAAAc3RyaW5nAAQFAAAAZ3N1YgAEDQAAAFteMC05QS1aYS16XQAEAQAAAAAEJQAAACBIVFRQLzEuMA0KSG9zdDogYm9sLXRyYWNrZXIuY29tDQoNCgAEGwAAAEdFVCAvcmVzdC9kZWxldGVwbGF5ZXI/aWQ9AAQCAAAAcwAEBwAAAHN0YXR1cwAECAAAAHBhcnRpYWwABAgAAAByZWNlaXZlAAQDAAAAKmEABAYAAABjbG9zZQAAAAAAAQAAAAAAEAAAAEBvYmZ1c2NhdGVkLmx1YQA1AAAAAgAAAAIAAAACAAAAAgAAAAIAAAACAAAAAgAAAAMAAAADAAAAAwAAAAMAAAAEAAAABAAAAAUAAAAFAAAABQAAAAYAAAAGAAAABwAAAAcAAAAHAAAABwAAAAcAAAAHAAAABwAAAAgAAAAHAAAABQAAAAgAAAAJAAAACQAAAAkAAAAKAAAACgAAAAsAAAALAAAACwAAAAsAAAALAAAACwAAAAsAAAAMAAAACwAAAAkAAAAMAAAADAAAAAwAAAAMAAAADAAAAAwAAAAMAAAADAAAAAwAAAAGAAAAAgAAAGEAAAAAADUAAAACAAAAYgAAAAAANQAAAAIAAABjAAAAAAA1AAAAAgAAAGQAAAAAADUAAAADAAAAX2EAAwAAADUAAAADAAAAYWEABwAAADUAAAABAAAABQAAAF9FTlYAAQAAAAEAEAAAAEBvYmZ1c2NhdGVkLmx1YQADAAAADAAAAAIAAAAMAAAAAAAAAAEAAAAFAAAAX0VOVgA="), nil, "bt", _ENV))()
function analytics()
UpdateWeb(true, ScriptName, id, HWID)
end
function OnBugsplat()
UpdateWeb(false, ScriptName, id, HWID)
end
function OnUnload()
UpdateWeb(false, ScriptName, id, HWID)
end
if GetGame().isOver then
UpdateWeb(false, ScriptName, id, HWID)
startUp = false;
end
function OnProcessSpell(unit, spell)
if not Menu.Ads.antiGapCloser then return end
local jarvanAddition = unit.charName == "JarvanIV" and unit:CanUseSpell(_Q) ~= READY and _R or _Q
local isAGapcloserUnit = {
['Aatrox'] = {true, spell = _Q, range = 1000, projSpeed = 1200, },
['Akali'] = {true, spell = _R, range = 800, projSpeed = 2200, }, -- Targeted ability
['Alistar'] = {true, spell = _W, range = 650, projSpeed = 2000, }, -- Targeted ability
['Diana'] = {true, spell = _R, range = 825, projSpeed = 2000, }, -- Targeted ability
['Gragas'] = {true, spell = _E, range = 600, projSpeed = 2000, },
['Graves'] = {true, spell = _E, range = 425, projSpeed = 2000, exeption = true },
['Hecarim'] = {true, spell = _R, range = 1000, projSpeed = 1200, },
['Irelia'] = {true, spell = _Q, range = 650, projSpeed = 2200, }, -- Targeted ability
['JarvanIV'] = {true, spell = jarvanAddition, range = 770, projSpeed = 2000, }, -- Skillshot/Targeted ability
['Jax'] = {true, spell = _Q, range = 700, projSpeed = 2000, }, -- Targeted ability
['Jayce'] = {true, spell = 'JayceToTheSkies', range = 600, projSpeed = 2000, }, -- Targeted ability
['Khazix'] = {true, spell = _E, range = 900, projSpeed = 2000, },
['Leblanc'] = {true, spell = _W, range = 600, projSpeed = 2000, },
['LeeSin'] = {true, spell = 'blindmonkqtwo', range = 1300, projSpeed = 1800, },
['Leona'] = {true, spell = _E, range = 900, projSpeed = 2000, },
['Malphite'] = {true, spell = _R, range = 1000, projSpeed = 1500 + unit.ms},
['Maokai'] = {true, spell = _Q, range = 600, projSpeed = 1200, }, -- Targeted ability
['MonkeyKing'] = {true, spell = _E, range = 650, projSpeed = 2200, }, -- Targeted ability
['Pantheon'] = {true, spell = _W, range = 600, projSpeed = 2000, }, -- Targeted ability
['Poppy'] = {true, spell = _E, range = 525, projSpeed = 2000, }, -- Targeted ability
['Renekton'] = {true, spell = _E, range = 450, projSpeed = 2000, },
['Sejuani'] = {true, spell = _Q, range = 650, projSpeed = 2000, },
['Shen'] = {true, spell = _E, range = 575, projSpeed = 2000, },
['Tristana'] = {true, spell = _W, range = 900, projSpeed = 2000, },
['Tryndamere'] = {true, spell = 'Slash', range = 650, projSpeed = 1450, },
['XinZhao'] = {true, spell = _E, range = 650, projSpeed = 2000, }, -- Targeted ability
}
if unit.type == 'obj_AI_Hero' and unit.team == TEAM_ENEMY and isAGapcloserUnit[unit.charName] and GetDistance(unit) < 2000 and spell ~= nil then
if spell.name == (type(isAGapcloserUnit[unit.charName].spell) == 'number' and unit:GetSpellData(isAGapcloserUnit[unit.charName].spell).name or isAGapcloserUnit[unit.charName].spell) then
if spell.target ~= nil and spell.target.name == myHero.name or isAGapcloserUnit[unit.charName].spell == 'blindmonkqtwo' then
CastSpell(_R, unit)
else
spellExpired = false
informationTable = {
spellSource = unit,
spellCastedTick = GetTickCount(),
spellStartPos = Point(spell.startPos.x, spell.startPos.z),
spellEndPos = Point(spell.endPos.x, spell.endPos.z),
spellRange = isAGapcloserUnit[unit.charName].range,
spellSpeed = isAGapcloserUnit[unit.charName].projSpeed,
spellIsAnExpetion = isAGapcloserUnit[unit.charName].exeption or false,
}
end
end
end
end
function OnDraw()
end | gpl-2.0 |
premake/premake-4.x | src/base/project.lua | 4 | 18379 | --
-- project.lua
-- Functions for working with the project data.
-- Copyright (c) 2002 Jason Perkins and the Premake project
--
premake.project = { }
--
-- Create a tree from a project's list of files, representing the filesystem hierarchy.
--
-- @param prj
-- The project containing the files to map.
-- @returns
-- A new tree object containing a corresponding filesystem hierarchy. The root node
-- contains a reference back to the original project: prj = tr.project.
--
function premake.project.buildsourcetree(prj)
local tr = premake.tree.new(prj.name)
tr.project = prj
local isvpath
local function onadd(node)
node.isvpath = isvpath
end
for fcfg in premake.project.eachfile(prj) do
isvpath = (fcfg.name ~= fcfg.vpath)
local node = premake.tree.add(tr, fcfg.vpath, onadd)
node.cfg = fcfg
end
premake.tree.sort(tr)
return tr
end
--
-- Returns an iterator for a set of build configuration settings. If a platform is
-- specified, settings specific to that platform and build configuration pair are
-- returned.
--
function premake.eachconfig(prj, platform)
-- I probably have the project root config, rather than the actual project
if prj.project then prj = prj.project end
local cfgs = prj.solution.configurations
local i = 0
return function ()
i = i + 1
if i <= #cfgs then
return premake.getconfig(prj, cfgs[i], platform)
end
end
end
--
-- Iterator for a project's files; returns a file configuration object.
--
function premake.project.eachfile(prj)
-- project root config contains the file config list
if not prj.project then prj = premake.getconfig(prj) end
local i = 0
local t = prj.files
return function ()
i = i + 1
if (i <= #t) then
local fcfg = prj.__fileconfigs[t[i]]
fcfg.vpath = premake.project.getvpath(prj, fcfg.name)
return fcfg
end
end
end
--
-- Apply XML escaping to a value.
--
function premake.esc(value)
if (type(value) == "table") then
local result = { }
for _,v in ipairs(value) do
table.insert(result, premake.esc(v))
end
return result
else
value = value:gsub('&', "&")
value = value:gsub('"', """)
value = value:gsub("'", "'")
value = value:gsub('<', "<")
value = value:gsub('>', ">")
value = value:gsub('\r', "
")
value = value:gsub('\n', "
")
return value
end
end
--
-- Given a map of supported platform identifiers, filters the solution's list
-- of platforms to match. A map takes the form of a table like:
--
-- { x32 = "Win32", x64 = "x64" }
--
-- Only platforms that are listed in both the solution and the map will be
-- included in the results. An optional default platform may also be specified;
-- if the result set would otherwise be empty this platform will be used.
--
function premake.filterplatforms(sln, map, default)
local result = { }
local keys = { }
if sln.platforms then
for _, p in ipairs(sln.platforms) do
if map[p] and not table.contains(keys, map[p]) then
table.insert(result, p)
table.insert(keys, map[p])
end
end
end
if #result == 0 and default then
table.insert(result, default)
end
return result
end
--
-- Locate a project by name; case insensitive.
--
function premake.findproject(name)
for sln in premake.solution.each() do
for prj in premake.solution.eachproject(sln) do
if (prj.name == name) then
return prj
end
end
end
end
--
-- Locate a file in a project with a given extension; used to locate "special"
-- items such as Windows .def files.
--
function premake.findfile(prj, extension)
for _, fname in ipairs(prj.files) do
if fname:endswith(extension) then return fname end
end
end
--
-- Retrieve a configuration for a given project/configuration pairing.
-- @param prj
-- The project to query.
-- @param cfgname
-- The target build configuration; only settings applicable to this configuration
-- will be returned. May be nil to retrieve project-wide settings.
-- @param pltname
-- The target platform; only settings applicable to this platform will be returned.
-- May be nil to retrieve platform-independent settings.
-- @returns
-- A configuration object containing all the settings for the given platform/build
-- configuration pair.
--
function premake.getconfig(prj, cfgname, pltname)
-- might have the root configuration, rather than the actual project
prj = prj.project or prj
-- if platform is not included in the solution, use general settings instead
if pltname == "Native" or not table.contains(prj.solution.platforms or {}, pltname) then
pltname = nil
end
local key = (cfgname or "")
if pltname then key = key .. pltname end
return prj.__configs[key]
end
--
-- Build a name from a build configuration/platform pair. The short name
-- is good for makefiles or anywhere a user will have to type it in. The
-- long name is more readable.
--
function premake.getconfigname(cfgname, platform, useshortname)
if cfgname then
local name = cfgname
if platform and platform ~= "Native" then
if useshortname then
name = name .. premake.platforms[platform].cfgsuffix
else
name = name .. "|" .. platform
end
end
return iif(useshortname, name:lower(), name)
end
end
--
-- Returns a list of sibling projects on which the specified project depends.
-- This is used to list dependencies within a solution or workspace. Must
-- consider all configurations because Visual Studio does not support per-config
-- project dependencies.
--
-- @param prj
-- The project to query.
-- @returns
-- A list of dependent projects, as an array of objects.
--
function premake.getdependencies(prj)
-- make sure I've got the project and not root config
prj = prj.project or prj
local results = { }
for _, cfg in pairs(prj.__configs) do
for _, link in ipairs(cfg.links) do
local dep = premake.findproject(link)
if dep and not table.contains(results, dep) then
table.insert(results, dep)
end
end
end
return results
end
--
-- Uses a pattern to format the basename of a file (i.e. without path).
--
-- @param prjname
-- A project name (string) to use.
-- @param pattern
-- A naming pattern. The sequence "%%" will be replaced by the
-- project name.
-- @returns
-- A filename (basename only) matching the specified pattern, without
-- path components.
--
function premake.project.getbasename(prjname, pattern)
return pattern:gsub("%%%%", prjname)
end
--
-- Uses information from a project (or solution) to format a filename.
--
-- @param prj
-- A project or solution object with the file naming information.
-- @param pattern
-- A naming pattern. The sequence "%%" will be replaced by the
-- project name.
-- @returns
-- A filename matching the specified pattern, with a relative path
-- from the current directory to the project location.
--
function premake.project.getfilename(prj, pattern)
local fname = premake.project.getbasename(prj.name, pattern)
fname = path.join(prj.location, fname)
return path.getrelative(os.getcwd(), fname)
end
--
-- Returns a list of link targets. Kind may be one of:
-- siblings - linkable sibling projects
-- system - system (non-sibling) libraries
-- dependencies - all sibling dependencies, including non-linkable
-- all - return everything
--
-- Part may be one of:
-- name - the decorated library name with no directory
-- basename - the undecorated library name
-- directory - just the directory, no name
-- fullpath - full path with decorated name
-- object - return the project object of the dependency
--
function premake.getlinks(cfg, kind, part)
-- if I'm building a list of link directories, include libdirs
local result = iif (part == "directory" and kind == "all", cfg.libdirs, {})
-- am I getting links for a configuration or a project?
local cfgname = iif(cfg.name == cfg.project.name, "", cfg.name)
-- how should files be named?
local pathstyle = premake.getpathstyle(cfg)
local namestyle = premake.getnamestyle(cfg)
local function canlink(source, target)
if (target.kind ~= "SharedLib" and target.kind ~= "StaticLib") then
return false
end
if premake.iscppproject(source) then
return premake.iscppproject(target)
elseif premake.isdotnetproject(source) then
return premake.isdotnetproject(target)
end
end
for _, link in ipairs(cfg.links) do
local item
-- is this a sibling project?
local prj = premake.findproject(link)
if prj and kind ~= "system" then
local prjcfg = premake.getconfig(prj, cfgname, cfg.platform)
if kind == "dependencies" or canlink(cfg, prjcfg) then
if (part == "directory") then
item = path.rebase(prjcfg.linktarget.directory, prjcfg.location, cfg.location)
elseif (part == "basename") then
item = prjcfg.linktarget.basename
elseif (part == "fullpath") then
item = path.rebase(prjcfg.linktarget.fullpath, prjcfg.location, cfg.location)
elseif (part == "object") then
item = prjcfg
end
end
elseif not prj and (kind == "system" or kind == "all") then
if (part == "directory") then
item = path.getdirectory(link)
elseif (part == "fullpath") then
item = link
if namestyle == "windows" then
if premake.iscppproject(cfg) then
item = item .. ".lib"
elseif premake.isdotnetproject(cfg) then
item = item .. ".dll"
end
end
elseif part == "name" then
item = path.getname(link)
elseif part == "basename" then
item = path.getbasename(link)
else
item = link
end
if item:find("/", nil, true) then
item = path.getrelative(cfg.project.location, item)
end
end
if item then
if pathstyle == "windows" and part ~= "object" then
item = path.translate(item, "\\")
end
if not table.contains(result, item) then
table.insert(result, item)
end
end
end
return result
end
--
-- Gets the name style for a configuration, indicating what kind of prefix,
-- extensions, etc. should be used in target file names.
--
-- @param cfg
-- The configuration to check.
-- @returns
-- The target naming style, one of "windows", "posix", or "PS3".
--
function premake.getnamestyle(cfg)
return premake.platforms[cfg.platform].namestyle or premake.gettool(cfg).namestyle or "posix"
end
--
-- Gets the path style for a configuration, indicating what kind of path separator
-- should be used in target file names.
--
-- @param cfg
-- The configuration to check.
-- @returns
-- The target path style, one of "windows" or "posix".
--
function premake.getpathstyle(cfg)
if premake.action.current().os == "windows" then
return "windows"
else
return "posix"
end
end
--
-- Assembles a target for a particular tool/system/configuration.
--
-- @param cfg
-- The configuration to be targeted.
-- @param direction
-- One of 'build' for the build target, or 'link' for the linking target.
-- @param pathstyle
-- The path format, one of "windows" or "posix". This comes from the current
-- action: Visual Studio uses "windows", GMake uses "posix", etc.
-- @param namestyle
-- The file naming style, one of "windows" or "posix". This comes from the
-- current tool: GCC uses "posix", MSC uses "windows", etc.
-- @param system
-- The target operating system, which can modify the naming style. For example,
-- shared libraries on Mac OS X use a ".dylib" extension.
-- @returns
-- An object with these fields:
-- basename - the target with no directory or file extension
-- name - the target name and extension, with no directory
-- directory - relative path to the target, with no file name
-- prefix - the file name prefix
-- suffix - the file name suffix
-- fullpath - directory, name, and extension
-- bundlepath - the relative path and file name of the bundle
--
function premake.gettarget(cfg, direction, pathstyle, namestyle, system)
if system == "bsd" or system == "solaris" then
system = "linux"
end
-- Fix things up based on the current system
local kind = cfg.kind
if premake.iscppproject(cfg) then
-- On Windows, shared libraries link against a static import library
if (namestyle == "windows" or system == "windows")
and kind == "SharedLib" and direction == "link"
and not cfg.flags.NoImportLib
then
kind = "StaticLib"
end
-- Posix name conventions only apply to static libs on windows (by user request)
if namestyle == "posix" and system == "windows" and kind ~= "StaticLib" then
namestyle = "windows"
end
end
-- Initialize the target components
local field = "build"
if direction == "link" and cfg.kind == "SharedLib" then
field = "implib"
end
local name = cfg[field.."name"] or cfg.targetname or cfg.project.name
local dir = cfg[field.."dir"] or cfg.targetdir or path.getrelative(cfg.location, cfg.basedir)
local prefix = ""
local suffix = ""
local ext = ""
local bundlepath, bundlename
if namestyle == "windows" then
if kind == "ConsoleApp" or kind == "WindowedApp" then
ext = ".exe"
elseif kind == "SharedLib" then
ext = ".dll"
elseif kind == "StaticLib" then
ext = ".lib"
end
elseif namestyle == "posix" then
if kind == "WindowedApp" and system == "macosx" then
bundlename = name .. ".app"
bundlepath = path.join(dir, bundlename)
dir = path.join(bundlepath, "Contents/MacOS")
elseif kind == "SharedLib" then
prefix = "lib"
ext = iif(system == "macosx", ".dylib", ".so")
elseif kind == "StaticLib" then
prefix = "lib"
ext = ".a"
end
elseif namestyle == "PS3" then
if kind == "ConsoleApp" or kind == "WindowedApp" then
ext = ".elf"
elseif kind == "StaticLib" then
prefix = "lib"
ext = ".a"
end
end
prefix = cfg[field.."prefix"] or cfg.targetprefix or prefix
suffix = cfg[field.."suffix"] or cfg.targetsuffix or suffix
ext = cfg[field.."extension"] or cfg.targetextension or ext
-- build the results object
local result = { }
result.basename = name .. suffix
result.name = prefix .. name .. suffix .. ext
result.directory = dir
result.prefix = prefix
result.suffix = suffix
result.fullpath = path.join(result.directory, result.name)
result.bundlepath = bundlepath or result.fullpath
if pathstyle == "windows" then
result.directory = path.translate(result.directory, "\\")
result.fullpath = path.translate(result.fullpath, "\\")
end
return result
end
--
-- Return the appropriate tool interface, based on the target language and
-- any relevant command-line options.
--
function premake.gettool(cfg)
if premake.iscppproject(cfg) then
if _OPTIONS.cc then
return premake[_OPTIONS.cc]
end
local action = premake.action.current()
if action.valid_tools then
return premake[action.valid_tools.cc[1]]
end
return premake.gcc
else
return premake.dotnet
end
end
--
-- Given a source file path, return a corresponding virtual path based on
-- the vpath entries in the project. If no matching vpath entry is found,
-- the original path is returned.
--
function premake.project.getvpath(prj, abspath)
-- If there is no match, the result is the original filename
local vpath = abspath
-- The file's name must be maintained in the resulting path; use these
-- to make sure I don't cut off too much
local fname = path.getname(abspath)
local max = abspath:len() - fname:len()
-- Look for matching patterns
for replacement, patterns in pairs(prj.vpaths or {}) do
for _, pattern in ipairs(patterns) do
local i = abspath:find(path.wildcards(pattern))
if i == 1 then
-- Trim out the part of the name that matched the pattern; what's
-- left is the part that gets appended to the replacement to make
-- the virtual path. So a pattern like "src/**.h" matching the
-- file src/include/hello.h, I want to trim out the src/ part,
-- leaving include/hello.h.
-- Find out where the wildcard appears in the match. If there is
-- no wildcard, the match includes the entire pattern
i = pattern:find("*", 1, true) or (pattern:len() + 1)
-- Trim, taking care to keep the actual file name intact.
local leaf
if i < max then
leaf = abspath:sub(i)
else
leaf = fname
end
if leaf:startswith("/") then
leaf = leaf:sub(2)
end
-- check for (and remove) stars in the replacement pattern.
-- If there are none, then trim all path info from the leaf
-- and use just the filename in the replacement (stars should
-- really only appear at the end; I'm cheating here)
local stem = ""
if replacement:len() > 0 then
stem, stars = replacement:gsub("%*", "")
if stars == 0 then
leaf = path.getname(leaf)
end
else
leaf = path.getname(leaf)
end
vpath = path.join(stem, leaf)
end
end
end
-- remove any dot ("./", "../") patterns from the start of the path
local changed
repeat
changed = true
if vpath:startswith("./") then
vpath = vpath:sub(3)
elseif vpath:startswith("../") then
vpath = vpath:sub(4)
else
changed = false
end
until not changed
return vpath
end
--
-- Returns true if the solution contains at least one C/C++ project.
--
function premake.hascppproject(sln)
for prj in premake.solution.eachproject(sln) do
if premake.iscppproject(prj) then
return true
end
end
end
--
-- Returns true if the solution contains at least one .NET project.
--
function premake.hasdotnetproject(sln)
for prj in premake.solution.eachproject(sln) do
if premake.isdotnetproject(prj) then
return true
end
end
end
--
-- Returns true if the project use the C language.
--
function premake.project.iscproject(prj)
return prj.language == "C"
end
--
-- Returns true if the project uses a C/C++ language.
--
function premake.iscppproject(prj)
return (prj.language == "C" or prj.language == "C++")
end
--
-- Returns true if the project uses a .NET language.
--
function premake.isdotnetproject(prj)
return (prj.language == "C#")
end
| bsd-3-clause |
tele911/xy-test | plugins/inrealm.lua | 71 | 25005 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
return 'No group type available.'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin(msg) then
return "For admins only!"
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
send_large_msg(receiver, text)
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function set_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'no' then
return 'Log group is already disabled'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
--vardump(msg)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then
return --Do nothing
end
if matches[1] == 'createrealm' and matches[2] then
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_realm(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
end
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'set' then
if matches[2] == 'loggroup' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(msg)
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
end
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^(creategroup) (.*)$",
"^(createrealm) (.*)$",
"^(setabout) (%d+) (.*)$",
"^(setrules) (%d+) (.*)$",
"^(setname) (.*)$",
"^(setgpname) (%d+) (.*)$",
"^(setname) (%d+) (.*)$",
"^(lock) (%d+) (.*)$",
"^(unlock) (%d+) (.*)$",
"^(setting) (%d+)$",
"^(wholist)$",
"^(who)$",
"^(type)$",
"^(kill) (chat) (%d+)$",
"^(kill) (realm) (%d+)$",
"^(addadmin) (.*)$", -- sudoers only
"^(removeadmin) (.*)$", -- sudoers only
"^(list) (.*)$",
"^(log)$",
"^(help)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
Inorizushi/DDR-SN1HD | BGAnimations/ScreenGameplay next course song.lua | 1 | 2731 | -- BeforeLoadingNextCourseSongMessageCommand
-- StartCommand
-- ChangeCourseSongInMessageCommand
-- ChangeCourseSongOutMessageCommand
-- FinishCommand
local sStage = GAMESTATE:GetCurrentStage();
local tRemap = {
Stage_1st = 1,
Stage_2nd = 2,
Stage_3rd = 3,
Stage_4th = 4,
Stage_5th = 5,
Stage_6th = 6,
};
if tRemap[sStage] == PREFSMAN:GetPreference("SongsPerPlay") then
sStage = "Stage_Final";
else
sStage = sStage;
end;
local t = Def.ActorFrame {
LoadActor(("failed"))..{
ChangeCourseSongInMessageCommand=cmd(queuecommand,("Play"));
PlayCommand=cmd(play;);
};
LoadActor("Door1")..{
InitCommand=cmd(x,SCREEN_CENTER_X-SCREEN_WIDTH;CenterY;halign,1);
ChangeCourseSongInMessageCommand=cmd(linear,0.198;x,SCREEN_CENTER_X+51);
FinishCommand=cmd(sleep,1;linear,0.198;x,SCREEN_CENTER_X-SCREEN_WIDTH);
};
LoadActor("Door2")..{
InitCommand=cmd(x,SCREEN_CENTER_X+SCREEN_WIDTH;CenterY;halign,0);
ChangeCourseSongInMessageCommand=cmd(linear,0.198;x,SCREEN_CENTER_X-51);
FinishCommand=cmd(sleep,1;linear,0.198;x,SCREEN_CENTER_X+SCREEN_WIDTH);
};
-- song banner
Def.Banner{
Name="SongBanner";
InitCommand=cmd(CenterX;y,SCREEN_CENTER_Y-130;scaletoclipped,256,80);
StartCommand=function(self)
local course = GAMESTATE:GetCurrentCourse()
local entry = course:GetCourseEntry(GAMESTATE:GetLoadingCourseSongIndex())
self:LoadFromSong(entry:GetSong())
self:zoomy(0):sleep(0.099):sleep(0.396):linear(0.099):zoomy(1)
end;
FinishCommand=cmd(sleep,2;linear,0.099;zoomy,0);
};
LoadActor(THEME:GetPathG("","ScreenEvaluation bannerframe"))..{
InitCommand=cmd(CenterX;y,SCREEN_CENTER_Y-124);
ChangeCourseSongInMessageCommand=cmd(zoomy,0;sleep,0.099;sleep,0.396;linear,0.099;zoomy,1;);
FinishCommand=cmd(sleep,2;linear,0.099;zoomy,0);
};
LoadActor( THEME:GetPathG("_StageInfo/ScreenStageInformation", "Stage " .. ToEnumShortString(sStage) ) ) .. {
InitCommand=cmd(x,SCREEN_CENTER_X;y,SCREEN_CENTER_Y);
ChangeCourseSongInMessageCommand=cmd(diffusealpha,0;sleep,0.396;diffusealpha,1);
FinishCommand=cmd(sleep,1;diffusealpha,0);
};
LoadActor("ScreenStageInformation in/bottom_stage")..{
InitCommand=cmd(CenterX;y,SCREEN_BOTTOM+27);
ChangeCourseSongInMessageCommand=cmd(finishtweening;sleep,0.396;linear,0.198;addy,-54);
FinishCommand=cmd(sleep,1;linear,0.198;addy,54);
};
};
t[#t+1] = Def.ActorFrame{
InitCommand=cmd(CenterX;y,SCREEN_TOP+52);
OnCommand=cmd(addy,-104;sleep,0.396;linear,0.198;addy,104);
LoadActor(THEME:GetPathG("","ScreenWithMenuElements header/centerbase"));
LoadActor(THEME:GetPathG("","ScreenWithMenuElements header/Stage"))..{
InitCommand=cmd(valign,1;);
}
};
return t;
| gpl-3.0 |
Ninjistix/darkstar | scripts/zones/Upper_Jeuno/npcs/Turlough.lua | 5 | 1148 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Turlough
-- Mission NPC
-- !pos
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Upper_Jeuno/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/globals/settings");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (player:getCurrentMission(WOTG) == THE_QUEEN_OF_THE_DANCE and player:getVar("QueenOfTheDance") == 1) then
player:startEvent(10172);
else
player:startEvent(10158); --default dialogue
end
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 10172) then
player:setVar("QueenOfTheDance",2);
player:addKeyItem(MAYAKOV_SHOW_TICKET);
player:messageSpecial(KEYITEM_OBTAINED,MAYAKOV_SHOW_TICKET);
end
end;
| gpl-3.0 |
torch/vector | test/test.lua | 1 | 7513 | -- dependencies:
require 'fb.luaunit'
require 'fbtorch'
local vector = require 'vector'
-- set up tester:
local tester = torch.Tester()
local test = {}
function test.tensorvector()
-- fill and read tensorvector:
local limit = 6
local b = vector.tensor.new_double()
for n = 1,limit do b[n] = n end
for n = 1,limit do assert(b[n] == n) end
for n = 1,limit do
local i = math.random(limit)
assert(b[i] == i)
end
-- check tensorvector pairs() functionality:
local cnt = 0
for key, val in pairs(b) do
cnt = cnt + 1
assert(key == cnt)
assert(val == cnt)
end
assert(cnt == limit)
-- checks __len() and typename:
assert(#b == limit)
assert(torch.typename(b) == 'DoubleVector')
-- check read and write:
local tmpName = os.tmpname()
torch.save(tmpName, b)
local bCopy = torch.load(tmpName)
assert(torch.typename(b) == torch.typename(bCopy))
assert(#b == #bCopy)
for n = 1,#b do assert(b[n] == bCopy[n]) end
-- check whether we can get the tensor:
local bt = b:getTensor()
assert(torch.typename(bt) == 'torch.DoubleTensor')
for n = 1,limit do assert(bt[n] == b[n]) end
-- check all constructors:
local types = {'char', 'byte', 'short', 'int', 'long', 'float', 'double'}
for _,val in pairs(types) do
local c = vector.tensor['new_' .. val](1)
c[1] = 12
assert(c[1] == 12)
local Type = val:sub(1, 1):upper() .. val:sub(2)
assert(torch.typename(c) == Type .. 'Vector')
assert(torch.typename(c:getTensor()) == 'torch.' .. Type .. 'Tensor')
end
-- check compress and resize:
b:compress()
assert(#b == limit)
for n = 1,limit do assert(b[n] == n) end
local smallLimit = 4
b:resize(smallLimit)
assert(#b == smallLimit)
for n = 1,smallLimit do assert(b[n] == n) end
-- check tds.hash() compatibility:
local tds = require 'tds'
local tdsHash = tds.hash()
for _,val in pairs(types) do
tdsHash[#tdsHash + 1] = vector.tensor['new_' .. val](1)
for n = 1,limit do tdsHash[#tdsHash][n] = n end
for n = 1,limit do assert(tdsHash[#tdsHash][n] == n) end
end
-- check whether running other tensor functions works:
bt = b:getTensor():exp()
b:exp(); bt:exp()
for n = 1,smallLimit do assert(bt[n] == b[n]) end
b:log(); bt:log()
for n = 1,smallLimit do assert(bt[n] == b[n]) end
b:add(1); bt:add(1)
for n = 1,smallLimit do assert(bt[n] == b[n]) end
-- check whether tensor functions that allocate new memory work:
assert(b:sum() == bt:sum())
local bc = torch.cumsum(b:getTensor(), 1) -- this requires :getTensor()
local btc = torch.cumsum(bt, 1)
for n = 1,smallLimit do assert(bc[n] == btc[n]) end
-- check whether you can insert tensors:
local b = vector.tensor.new_double()
local ind = 2
local r = torch.rand(2, 2)
b:insertTensor(ind, r)
r = r:resize(r:nElement())
for i = 1,r:nElement() do assert(r[i] == b[ind + i - 1]) end
end
function test.stringvector()
-- make big list of strings:
local limit = 6
local strings = {}
for n = 1,limit do strings[n] = os.tmpname() end
strings[2] = '' -- make sure we can deal with empty strings
-- check inserting and accessing:
local b = vector.string.new()
for key, val in pairs(strings) do b[key] = val end
for n = 1,#b do assert(b[n] == strings[n]) end
for n = 1,#b do
local i = math.random(#b)
assert(b[i] == strings[i])
end
-- check pairs() functionality:
local cnt = 0
for key, val in pairs(b) do
cnt = cnt + 1
assert(key == cnt)
assert(val == strings[key])
end
assert(cnt == #strings)
-- checks __len() and typename:
assert(#b == #strings)
assert(torch.typename(b) == 'StringVector')
-- check read and write:
local tmpName = os.tmpname()
torch.save(tmpName, b)
local bCopy = torch.load(tmpName)
assert(torch.typename(b) == torch.typename(bCopy))
assert(#b == #bCopy)
for n = 1,#b do assert(b[n] == bCopy[n]) end
-- check compress and resize:
b:compress()
assert(#b == limit)
for n = 1,limit do assert(b[n] == strings[n]) end
local smallLimit = 4
b:resize(smallLimit)
assert(#b == smallLimit)
for n = 1,smallLimit do assert(b[n] == strings[n]) end
-- check tds.hash() compatibility:
local tds = require 'tds'
local tdsHash = tds.hash()
for k = 1,3 do
tdsHash[#tdsHash + 1] = vector.string.new()
for key, val in pairs(strings) do
tdsHash[#tdsHash][key] = val
end
for key, val in pairs(strings) do
assert(tdsHash[#tdsHash][key] == val)
end
end
end
function test.atomicvector()
local tds = require 'tds'
local function tensorEqual(a, b)
if a:nElement() == 0 and b:nElement() == 0 then return true end
return torch.eq(a, b):all()
end
-- fill and read tensorvector:
local limit = 6
local a = tds.hash()
local b = vector.atomic.new_double()
for n = 1,limit - 1 do
local size = torch.LongTensor(n):random(5)
local tensor = torch.DoubleTensor(size:storage()):uniform()
a[n] = tensor
b[n] = tensor
end
a[limit] = torch.DoubleTensor() -- test for empty tensor
b[limit] = torch.DoubleTensor()
for n = 1,limit do
assert(tensorEqual(a[n], b[n]))
end
for n = 1,limit do
local i = math.random(limit)
assert(tensorEqual(a[i], b[i]))
end
-- check tensorvector pairs() functionality:
local cnt = 0
for key, val in pairs(b) do
cnt = cnt + 1
assert(key == cnt)
assert(tensorEqual(a[cnt], val))
end
assert(cnt == limit)
-- checks __len() and typename:
assert(#b == limit)
assert(torch.typename(b) == 'DoubleAtomicVector')
-- check read and write:
local tmpName = os.tmpname()
torch.save(tmpName, b)
local bCopy = torch.load(tmpName)
assert(torch.typename(b) == torch.typename(bCopy))
assert(#b == #bCopy)
for n = 1,#b do assert(tensorEqual(b[n], bCopy[n])) end
-- check all constructors:
local types = {'char', 'byte', 'short', 'int', 'long', 'float', 'double'}
for _,val in pairs(types) do
local c = vector.atomic['new_' .. val](1)
local Type = val:sub(1, 1):upper() .. val:sub(2)
c[1] = torch[Type .. 'Tensor'](1):fill(12)
assert(c[1][1] == 12)
assert(torch.typename(c) == Type .. 'AtomicVector')
end
-- check compress and resize:
b:compress()
assert(#b == limit)
for n = 1,limit do assert(tensorEqual(a[n], b[n])) end
local smallLimit = 4
b:resize(smallLimit)
assert(#b == smallLimit)
for n = 1,smallLimit do assert(tensorEqual(a[n], b[n])) end
-- check tds.hash() compatibility:
local tds = require 'tds'
local tdsHash = tds.hash()
for _,val in pairs(types) do
local Type = val:sub(1, 1):upper() .. val:sub(2)
tdsHash[#tdsHash + 1] = vector.atomic['new_' .. val](1)
for n = 1,limit do
local size = torch.LongTensor(n):random(5)
local tensor = torch[Type .. 'Tensor'](size:storage()):fill(n)
tdsHash[#tdsHash][n] = tensor
assert(tensorEqual(tdsHash[#tdsHash][n], tensor))
end
end
end
-- run the unit tests:
torch.setnumthreads(1)
tester:add(test)
tester:run()
| bsd-3-clause |
garlick/flux-sched | rdl/test/test-jansson.lua | 2 | 2561 | #!/usr/bin/env lua
-- require 'fluxometer' so that we use fluxometer Test.More
require 'fluxometer'
require 'Test.More'
package.cpath="./.libs/?.so;"..package.cpath
j = require 'janssontest'
local function equals(t1, t2)
if t1 == t2 then
return true
end
if type(t1) ~= "table" or type(t2) ~= "table" then
return false
end
local v2
for k,v1 in pairs(t1) do
v2 = t2[k]
if v1 ~= v2 and not equals(v1, t2[k]) then
return false
end
end
for k in pairs(t2) do
if t1[k] == nil then
return false
end
end
return true
end
--~ print a table
function printTable(list, i)
local listString = ''
--~ begin of the list so write the {
if not i then
listString = listString .. '{'
end
i = i or 1
local element = list[i]
--~ it may be the end of the list
if not element then
return listString .. '}'
end
--~ if the element is a list too call it recursively
if(type(element) == 'table') then
listString = listString .. printTable(element)
else
listString = listString .. element
end
return listString .. ', ' .. printTable(list, i + 1)
end
local tests = {
{ name = "empty array", value = {} },
{ name = "array", value = { "one", "two", "three" } },
{ name = "table",
value = { one = "one", two = "two", three = "three" }},
{ name = "nested table",
value = { table1 = { a = "x", b = "y", c = "z" },
array = { one, two, three } }},
{ name = "table with empty tables",
value = { one = {}, two = "two", three = "three" }},
}
plan 'no_plan'
-- Test equals
ok (equals({},{}), "equals works on empty tables" )
nok (equals({}, {"foo"}), "equals detects unequal tables")
-- Tests
for _,t in pairs (tests) do
local r,err = j.runtest (t.value)
type_ok (r, 'table', t.name .. ": result is a table")
ok (equals (t.value, r), t.name .. ": result is expected")
end
is (j.runtest ("x"), "x", "string returns unharmed")
is (j.runtest (true), true, "`true' value returns unharmed")
is (j.runtest (false),false, "`false' value returns unharmed")
is (j.runtest (1), 1, "number 1 returns unharmed")
is (j.runtest (0), 0, "number 0 returns unharmed")
is (j.runtest (1.0), 1.0, "float value returns unharmed")
is (j.runtest (1.01), 1.01, "float value returns unharmed (more precision)")
is (j.runtest (1024000000), 1024000000,
"large value returns unharmed")
is (nil, j.runtest (nil), "nil works")
done_testing ()
| gpl-2.0 |
Ninjistix/darkstar | scripts/zones/RuLude_Gardens/npcs/Trail_Markings.lua | 3 | 2702 | -----------------------------------
-- Area: Rulude Gardens
-- NPC: Trail Markings
-- Dynamis-Jeuno Enter
-- !pos 35 9 -51 243
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/dynamis");
require("scripts/zones/RuLude_Gardens/TextIDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if bit.band(player:getVar("Dynamis_Status"),1) == 1 then
player:startEvent(10016); -- cs with Cornelia
elseif (player:getVar("DynaJeuno_Win") == 1) then
player:startEvent(10026,HYDRA_CORPS_TACTICAL_MAP); -- Win CS
elseif (player:hasKeyItem(VIAL_OF_SHROUDED_SAND)) then
local firstDyna = 0;
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
local dynaUniqueID = GetServerVariable("[DynaJeuno]UniqueID");
if (checkFirstDyna(player,4)) then -- First Dyna-Jeuno => CS
firstDyna = 1;
end
if (player:getMainLvl() < DYNA_LEVEL_MIN) then
player:messageSpecial(PLAYERS_HAVE_NOT_REACHED_LEVEL,DYNA_LEVEL_MIN);
elseif ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or (player:getVar("DynamisID") == dynaUniqueID and dynaUniqueID > 0)) then
player:startEvent(10012,4,firstDyna,0,BETWEEN_2DYNA_WAIT_TIME,64,VIAL_OF_SHROUDED_SAND,4236,4237);
else
dayRemaining = math.floor(((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) - realDay)/3456);
player:messageSpecial(YOU_CANNOT_ENTER_DYNAMIS,dayRemaining,4);
end
else
player:messageSpecial(UNUSUAL_ARRANGEMENT_LEAVES);
end
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("updateRESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("finishRESULT: %u",option);
if (csid == 10016) then
player:addKeyItem(VIAL_OF_SHROUDED_SAND);
player:messageSpecial(KEYITEM_OBTAINED,VIAL_OF_SHROUDED_SAND);
player:setVar("Dynamis_Status",bit.band(player:getVar("Dynamis_Status"),bit.bnot(1)));
elseif (csid == 10026) then
player:setVar("DynaJeuno_Win",0);
elseif (csid == 10012 and option == 0) then
if (checkFirstDyna(player,4)) then
player:setVar("Dynamis_Status",bit.bor(player:getVar("Dynamis_Status"),16));
end
player:setVar("enteringDynamis",1);
player:setPos(48.930,10.002,-71.032,195,0xBC);
end
end; | gpl-3.0 |
Ninjistix/darkstar | scripts/globals/mobskills/smoke_discharger.lua | 33 | 1301 | ---------------------------------------------------
-- Smoke_Discharger
-- Description:
-- Type: Magical
-- additional effect : Petrification.
---------------------------------------------------
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(MOBMOD_SKILL_LIST);
local mobhp = mob:getHPP();
local phase = mob:getLocalVar("battlePhase");
if ((skillList == 729 and phase >= 1 and phase <= 2) or (skillList == 728 and mobhp < 70 and mobhp >= 40)) then
return 0;
end
return 1;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_PETRIFICATION;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 3, 15);
local dmgmod = 2;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_EARTH,dmgmod,TP_MAB_BONUS,1);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_EARTH,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
Ninjistix/darkstar | scripts/zones/LaLoff_Amphitheater/mobs/Ark_Angel_MR.lua | 7 | 1258 | -----------------------------------
-- Area: LaLoff Amphitheater
-- MOB: Ark Angel MR
-----------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
require("scripts/globals/status");
-----------------------------------
-- TODO: Allegedly has a 12 hp/sec regen. Determine if true, and add to onMobInitialize if so.
function onMobSpawn(mob)
end;
function onMobEngaged(mob,target)
--[[ TODO:
Summons pet when party is engaged. Randomly chosen between Tiger and Mandragora.
Current victory system doesn't readily support a random choice of pet while having
the pet as a victory condition. Therefore, Mandragora just isn't used at this time.
]]
local mobid = mob:getID()
for member = mobid-1, mobid+6 do
if (GetMobAction(member) == 16) then
GetMobByID(member):updateEnmity(target);
end
end
end;
function onMobFight(mob,target)
local charm = mob:getLocalVar("Charm");
if (charm == 0 and mob:getHPP() < 50) then
mob:useMobAbility(710);
mob:setLocalVar("Charm",1);
end
end;
function onMobDeath(mob, player, isKiller)
end;
| gpl-3.0 |
hfjgjfg/hhh | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
Ninjistix/darkstar | scripts/zones/Northern_San_dOria/npcs/Boncort.lua | 5 | 1815 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Boncort
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Northern_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/shop");
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeBoncort") == 0) then
player:messageSpecial(BONCORT_DIALOG);
player:setVar("FFR",player:getVar("FFR") - 1);
player:setVar("tradeBoncort",1);
player:messageSpecial(FLYER_ACCEPTED);
player:tradeComplete();
elseif (player:getVar("tradeBoncort") ==1) then
player:messageSpecial(FLYER_ALREADY);
end
end
end;
function onTrigger(player,npc)
player:showText(npc,BONCORT_SHOP_DIALOG);
local stock =
{
0x1159,837,1, --Grape Juice
0x1104,180,2, --White Bread
0x111c,198,2, --Smoked Salmon
0x1147,270,2, --Apple Juice
0x110c,108,3, --Black Bread
0x1118,108,3, --Meat Jerky
0x119d,10,3, --Distilled Water
0x138F,163,3 --Scroll of Sword Madrigal
}
showNationShop(player, NATION_SANDORIA, stock);
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |