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 |
|---|---|---|---|---|---|
PhearNet/scanner | bin/nmap-openshift/nselib/ipp.lua | 6 | 12844 | local bin = require "bin"
local http = require "http"
local nmap = require "nmap"
local os = require "os"
local stdnse = require "stdnse"
local tab = require "tab"
local table = require "table"
_ENV = stdnse.module("ipp", stdnse.seeall)
---
--
-- A small CUPS ipp (Internet Printing Protocol) library implementation
--
-- @author Patrik Karlsson
--
-- The IPP layer
IPP = {
StatusCode = {
OK = 0,
},
State = {
IPP_JOB_PENDING = 3,
IPP_JOB_HELD = 4,
IPP_JOB_PROCESSING = 5,
IPP_JOB_STOPPED = 6,
IPP_JOB_CANCELED = 7,
IPP_JOB_ABORTED = 8,
IPP_JOB_COMPLETED = 9,
},
StateName = {
[3] = "Pending",
[4] = "Held",
[5] = "Processing",
[6] = "Stopped",
[7] = "Canceled",
[8] = "Aborted",
[9] = "Completed",
},
OperationID = {
IPP_CANCEL_JOB = 0x0008,
IPP_GET_JOB_ATTRIBUTES = 0x0009,
IPP_GET_JOBS = 0x000a,
CUPS_GET_PRINTERS = 0x4002,
CUPS_GET_DOCUMENT = 0x4027
},
PrinterState = {
IPP_PRINTER_IDLE = 3,
IPP_PRINTER_PROCESSING = 4,
IPP_PRINTER_STOPPED = 5,
},
Attribute = {
IPP_TAG_OPERATION = 0x01,
IPP_TAG_JOB = 0x02,
IPP_TAG_END = 0x03,
IPP_TAG_PRINTER = 0x04,
IPP_TAG_INTEGER = 0x21,
IPP_TAG_ENUM = 0x23,
IPP_TAG_NAME = 0x42,
IPP_TAG_KEYWORD = 0x44,
IPP_TAG_URI = 0x45,
IPP_TAG_CHARSET = 0x47,
IPP_TAG_LANGUAGE = 0x48,
new = function(self, tag, name, value)
local o = { tag = tag, name = name, value = value }
setmetatable(o, self)
self.__index = self
return o
end,
parse = function(data, pos)
local attrib = IPP.Attribute:new()
local val
pos, attrib.tag, attrib.name, val = bin.unpack(">CPP", data, pos)
-- print(attrib.name, stdnse.tohex(val))
attrib.value = {}
table.insert(attrib.value, { tag = attrib.tag, val = val })
repeat
local tag, name_len, val
if ( #data < pos + 3 ) then
break
end
pos, tag, name_len = bin.unpack(">CS", data, pos)
if ( name_len == 0 ) then
pos, val = bin.unpack(">P", data, pos)
table.insert(attrib.value, { tag = tag, val = val })
else
pos = pos - 3
end
until( name_len ~= 0 )
-- do minimal decoding
for i=1, #attrib.value do
if ( attrib.value[i].tag == IPP.Attribute.IPP_TAG_INTEGER ) then
attrib.value[i].val = select(2, bin.unpack(">I", attrib.value[i].val))
elseif ( attrib.value[i].tag == IPP.Attribute.IPP_TAG_ENUM ) then
attrib.value[i].val = select(2, bin.unpack(">I", attrib.value[i].val))
end
end
if ( 1 == #attrib.value ) then
attrib.value = attrib.value[1].val
end
--print(attrib.name, attrib.value, stdnse.tohex(val))
return pos, attrib
end,
__tostring = function(self)
if ( "string" == type(self.value) ) then
return bin.pack(">CSASA", self.tag, #self.name, self.name, #self.value, self.value)
else
local data = bin.pack(">CSASA", self.tag, #self.name, self.name, #self.value[1].val, self.value[1].val)
for i=2, #self.value do
data = data .. bin.pack(">CSP", self.value[i].tag, 0, self.value[i].val)
end
return data
end
end
},
-- An attribute group, groups several attributes
AttributeGroup = {
new = function(self, tag, attribs)
local o = { tag = tag, attribs = attribs or {} }
setmetatable(o, self)
self.__index = self
return o
end,
addAttribute = function(self, attrib)
table.insert(self.attribs, attrib)
end,
--
-- Gets the first attribute matching name and optionally tag from the
-- attribute group.
--
-- @param name string containing the attribute name
-- @param tag number containing the attribute tag
getAttribute = function(self, name, tag)
for _, attrib in ipairs(self.attribs) do
if ( attrib.name == name ) then
if ( not(tag) ) then
return attrib
elseif ( tag and attrib.tag == tag ) then
return attrib
end
end
end
end,
getAttributeValue = function(self, name, tag)
for _, attrib in ipairs(self.attribs) do
if ( attrib.name == name ) then
if ( not(tag) ) then
return attrib.value
elseif ( tag and attrib.tag == tag ) then
return attrib.value
end
end
end
end,
__tostring = function(self)
local data = bin.pack("C", self.tag)
for _, attrib in ipairs(self.attribs) do
data = data .. tostring(attrib)
end
return data
end
},
-- The IPP request
Request = {
new = function(self, opid, reqid)
local o = {
version = 0x0101,
opid = opid,
reqid = reqid,
attrib_groups = {},
}
setmetatable(o, self)
self.__index = self
return o
end,
addAttributeGroup = function(self, group)
table.insert( self.attrib_groups, group )
end,
__tostring = function(self)
local data = bin.pack(">SSI", self.version, self.opid, self.reqid )
for _, group in ipairs(self.attrib_groups) do
data = data .. tostring(group)
end
data = data .. bin.pack("C", IPP.Attribute.IPP_TAG_END)
return data
end,
},
-- A class to handle responses from the server
Response = {
-- Creates a new instance of response
new = function(self)
local o = {}
setmetatable(o, self)
self.__index = self
return o
end,
getAttributeGroups = function(self, tag)
local groups = {}
for _, v in ipairs(self.attrib_groups or {}) do
if ( v.tag == tag ) then
table.insert(groups, v)
end
end
return groups
end,
parse = function(data)
local resp = IPP.Response:new()
local pos
pos, resp.version, resp.status, resp.reqid = bin.unpack(">SSI", data)
resp.attrib_groups = {}
local group
repeat
local tag, attrib
pos, tag = bin.unpack(">C", data, pos)
if ( tag == IPP.Attribute.IPP_TAG_OPERATION or
tag == IPP.Attribute.IPP_TAG_JOB or
tag == IPP.Attribute.IPP_TAG_PRINTER or
tag == IPP.Attribute.IPP_TAG_END ) then
if ( group ) then
table.insert(resp.attrib_groups, group)
group = IPP.AttributeGroup:new(tag)
else
group = IPP.AttributeGroup:new(tag)
end
else
pos = pos - 1
end
if ( not(group) ) then
stdnse.debug2("Unexpected tag: %d", tag)
return
end
pos, attrib = IPP.Attribute.parse(data, pos)
group:addAttribute(attrib)
until( pos == #data + 1)
return resp
end,
},
}
HTTP = {
Request = function(host, port, request)
local headers = {
['Content-Type'] = 'application/ipp',
['User-Agent'] = 'CUPS/1.5.1',
}
port.version.service_tunnel = "ssl"
local http_resp = http.post(host, port, '/', { header = headers }, nil, tostring(request))
if ( http_resp.status ~= 200 ) then
return false, "Unexpected response from server"
end
local response = IPP.Response.parse(http_resp.body)
if ( not(response) ) then
return false, "Failed to parse response"
end
return true, response
end,
}
Helper = {
new = function(self, host, port, options)
local o = { host = host, port = port, options = options or {} }
setmetatable(o, self)
self.__index = self
return o
end,
connect = function(self)
self.socket = nmap.new_socket()
self.socket:set_timeout(self.options.timeout or 10000)
return self.socket:connect(self.host, self.port)
end,
getPrinters = function(self)
local attribs = {
IPP.Attribute:new(IPP.Attribute.IPP_TAG_CHARSET, "attributes-charset", "utf-8" ),
IPP.Attribute:new(IPP.Attribute.IPP_TAG_LANGUAGE, "attributes-natural-language", "en"),
}
local ag = IPP.AttributeGroup:new(IPP.Attribute.IPP_TAG_OPERATION, attribs)
local request = IPP.Request:new(IPP.OperationID.CUPS_GET_PRINTERS, 1)
request:addAttributeGroup(ag)
local status, response = HTTP.Request( self.host, self.port, tostring(request) )
if ( not(response) ) then
return status, response
end
local printers = {}
for _, ag in ipairs(response:getAttributeGroups(IPP.Attribute.IPP_TAG_PRINTER)) do
local attrib = {
["printer-name"] = "name",
["printer-location"] = "location",
["printer-make-and-model"] = "model",
["printer-state"] = "state",
["queued-job-count"] = "queue_count",
["printer-dns-sd-name"] = "dns_sd_name",
}
local printer = {}
for k, v in pairs(attrib) do
if ( ag:getAttributeValue(k) ) then
printer[v] = ag:getAttributeValue(k)
end
end
table.insert(printers, printer)
end
return true, printers
end,
getQueueInfo = function(self, uri)
local uri = uri or ("ipp://%s/"):format(self.host.ip)
local attribs = {
IPP.Attribute:new(IPP.Attribute.IPP_TAG_CHARSET, "attributes-charset", "utf-8" ),
IPP.Attribute:new(IPP.Attribute.IPP_TAG_LANGUAGE, "attributes-natural-language", "en-us"),
IPP.Attribute:new(IPP.Attribute.IPP_TAG_URI, "printer-uri", uri),
IPP.Attribute:new(IPP.Attribute.IPP_TAG_KEYWORD, "requested-attributes", {
-- { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-originating-host-name"},
{ tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "com.apple.print.JobInfo.PMJobName"},
{ tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "com.apple.print.JobInfo.PMJobOwner"},
{ tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-id" },
{ tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-k-octets" },
{ tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-name" },
{ tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-state" },
{ tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "printer-uri" },
-- { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-originating-user-name" },
-- { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-printer-state-message" },
-- { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-printer-uri" },
{ tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "time-at-creation" } } ),
IPP.Attribute:new(IPP.Attribute.IPP_TAG_KEYWORD, "which-jobs", "not-completed" )
}
local ag = IPP.AttributeGroup:new(IPP.Attribute.IPP_TAG_OPERATION, attribs)
local request = IPP.Request:new(IPP.OperationID.IPP_GET_JOBS, 1)
request:addAttributeGroup(ag)
local status, response = HTTP.Request( self.host, self.port, tostring(request) )
if ( not(response) ) then
return status, response
end
local results = {}
for _, ag in ipairs(response:getAttributeGroups(IPP.Attribute.IPP_TAG_JOB)) do
local uri = ag:getAttributeValue("printer-uri")
local printer = uri:match(".*/(.*)$") or "Unknown"
-- some jobs have multiple state attributes, so far the ENUM ones have been correct
local state = ag:getAttributeValue("job-state", IPP.Attribute.IPP_TAG_ENUM) or ag:getAttributeValue("job-state")
-- some jobs have multiple id tag, so far the INTEGER type have shown the correct ID
local id = ag:getAttributeValue("job-id", IPP.Attribute.IPP_TAG_INTEGER) or ag:getAttributeValue("job-id")
local attr = ag:getAttribute("time-at-creation")
local tm = ag:getAttributeValue("time-at-creation")
local size = ag:getAttributeValue("job-k-octets") .. "k"
local jobname = ag:getAttributeValue("com.apple.print.JobInfo.PMJobName") or "Unknown"
local owner = ag:getAttributeValue("com.apple.print.JobInfo.PMJobOwner") or "Unknown"
results[printer] = results[printer] or {}
table.insert(results[printer], {
id = id,
time = os.date("%Y-%m-%d %H:%M:%S", tm),
state = ( IPP.StateName[tonumber(state)] or "Unknown" ),
size = size,
owner = owner,
jobname = jobname })
end
local output = {}
for name, entries in pairs(results) do
local t = tab.new(5)
tab.addrow(t, "id", "time", "state", "size (kb)", "owner", "jobname")
for _, entry in ipairs(entries) do
tab.addrow(t, entry.id, entry.time, entry.state, entry.size, entry.owner, entry.jobname)
end
if ( 1<#t ) then
table.insert(output, { name = name, tab.dump(t) })
end
end
return output
end,
close = function(self)
return self.socket:close()
end,
}
return _ENV;
| mit |
geanux/darkstar | scripts/zones/Al_Zahbi/npcs/Banjanu.lua | 38 | 1025 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Banjanu
-- Type: Standard NPC
-- @zone: 48
-- @pos -75.954 0.999 105.367
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0106);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
h0tw1r3/mame | 3rdparty/genie/tests/actions/vstudio/sln2005/header.lua | 51 | 1327 | --
-- tests/actions/vstudio/sln2005/header.lua
-- Validate generation of Visual Studio 2005+ solution header.
-- Copyright (c) 2009-2011 Jason Perkins and the Premake project
--
T.vstudio_sln2005_header = { }
local suite = T.vstudio_sln2005_header
local sln2005 = premake.vstudio.sln2005
--
-- Setup
--
local sln, prj
function suite.setup()
sln = test.createsolution()
end
local function prepare()
premake.bake.buildconfigs()
sln2005.header()
end
--
-- Tests
--
function suite.On2005()
_ACTION = "vs2005"
prepare()
test.capture [[
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
]]
end
function suite.On2008()
_ACTION = "vs2008"
prepare()
test.capture [[
Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008
]]
end
function suite.On2010()
_ACTION = "vs2010"
prepare()
test.capture [[
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
]]
end
function suite.On2012()
_ACTION = "vs2012"
prepare()
test.capture [[
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
]]
end
function suite.On2013()
_ACTION = "vs2013"
prepare()
test.capture [[
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
]]
end
| gpl-2.0 |
bungle/lua-resty-nettle | lib/resty/nettle/umac.lua | 1 | 2933 | local types = require "resty.nettle.types.common"
local context = require "resty.nettle.types.umac"
local lib = require "resty.nettle.library"
local ffi = require "ffi"
local ffi_new = ffi.new
local ffi_str = ffi.string
local setmetatable = setmetatable
local umacs = {
umac32 = {
length = 4,
context = context.umac32,
buffer = types.uint8_t_4,
setkey = lib.nettle_umac32_set_key,
setnonce = lib.nettle_umac32_set_nonce,
update = lib.nettle_umac32_update,
digest = lib.nettle_umac32_digest
},
umac64 = {
length = 8,
context = context.umac64,
buffer = types.uint8_t_8,
setkey = lib.nettle_umac64_set_key,
setnonce = lib.nettle_umac64_set_nonce,
update = lib.nettle_umac64_update,
digest = lib.nettle_umac64_digest
},
umac96 = {
length = 12,
context = context.umac96,
buffer = types.uint8_t_12,
setkey = lib.nettle_umac96_set_key,
setnonce = lib.nettle_umac96_set_nonce,
update = lib.nettle_umac96_update,
digest = lib.nettle_umac96_digest
},
umac128 = {
length = 16,
context = context.umac128,
buffer = types.uint8_t_16,
setkey = lib.nettle_umac128_set_key,
setnonce = lib.nettle_umac128_set_nonce,
update = lib.nettle_umac128_update,
digest = lib.nettle_umac128_digest
},
}
umacs[32] = umacs.umac32
umacs[64] = umacs.umac64
umacs[96] = umacs.umac96
umacs[128] = umacs.umac128
local umac = {}
umac.__index = umac
function umac:update(data, len)
return self.umac.update(self.context, len or #data, data)
end
function umac:digest()
local umc = self.umac
umc.digest(self.context, umc.length, umc.buffer)
return ffi_str(umc.buffer, umc.length)
end
local function factory(mac)
return setmetatable({
new = function(key, nonce)
local ctx = ffi_new(mac.context)
mac.setkey(ctx, key)
if nonce then
mac.setnonce(ctx, #nonce, nonce)
end
return setmetatable({ context = ctx, umac = mac }, umac)
end
}, {
__call = function(_, key, nonce, data, len)
local ctx = ffi_new(mac.context)
mac.setkey(ctx, key)
if nonce then
mac.setnonce(ctx, #nonce, nonce)
end
mac.update(ctx, len or #data, data)
mac.digest(ctx, mac.length, mac.buffer)
return ffi_str(mac.buffer, mac.length)
end
})
end
return setmetatable({
umac32 = factory(umacs[32]),
umac64 = factory(umacs[64]),
umac96 = factory(umacs[96]),
umac128 = factory(umacs[128])
}, {
__call = function(_, bits, key, nonce, data, len)
local mac = umacs[bits]
if not mac then
return nil, "the supported UMAC algorithm output sizes are 32, 64, 96, and 128 bits"
end
local ctx = ffi_new(mac.context)
mac.setkey(ctx, key)
if nonce then
mac.setnonce(ctx, #nonce, nonce)
end
mac.update(ctx, len or #data, data)
mac.digest(ctx, mac.length, mac.buffer)
return ffi_str(mac.buffer, mac.length)
end
})
| bsd-2-clause |
GuiltyNeko/GuiltyNeko-s-Factorio-Tweaks | prototypes/GNFT-electric-furnace.lua | 1 | 1686 | if settings.startup["GNFT-electric-furnace-tech"].value then
table.insert(data.raw.technology["logistics"].effects,{type = "unlock-recipe", recipe = "electric-furnace"}) --Move electric furnace to logistics tech
for i, effect in pairs(data.raw.technology["advanced-material-processing-2"].effects) do --Remove electric furnace from advanced material processing 2
if effect.type == "unlock-recipe" and effect.recipe == "electric-furnace" then
table.remove(data.raw.technology["advanced-material-processing-2"].effects,i)
end
end
if mods["mini-machines"]then
if not settings.startup["mini-tech"].value then
table.insert(data.raw.technology["logistics"].effects,{type = "unlock-recipe", recipe = "mini-furnace-1"})
end
for i, effect in pairs(data.raw.technology["advanced-material-processing-2"].effects) do --Remove mini electric furnace from advanced material processing 2
if effect.type == "unlock-recipe" and effect.recipe == "mini-furnace-1" then
table.remove(data.raw.technology["advanced-material-processing-2"].effects,i)
end
end
end
end
if settings.startup["GNFT-electric-furnace-recipe"] then
local recipe = data.raw.recipe["electric-furnace"] --Overwrite recipe. Completely.
if recipe.ingredients then
recipe.ingredients = {
{"electronic-circuit", 5},
{"steel-plate", 10},
{"stone-brick", 10}
}
end
if recipe.normal then
recipe.normal.ingredients = {
{"electronic-circuit", 5},
{"steel-plate", 10},
{"stone-brick", 10}
}
end
if recipe.expensive then
recipe.expensive.ingredients = {
{"electronic-circuit", 5},
{"steel-plate", 10},
{"stone-brick", 10}
}
end
end
| mit |
kaen/Zero-K | scripts/chickenflyerqueen.lua | 11 | 7563 | include "constants.lua"
local spGetUnitHealth = Spring.GetUnitHealth
--pieces
local body, head, tail, leftWing1, rightWing1, leftWing2, rightWing2 = piece("body","head","tail","lwing1","rwing1","lwing2","rwing2")
local leftThigh, leftKnee, leftShin, leftFoot, rightThigh, rightKnee, rightShin, rightFoot = piece("lthigh", "lknee", "lshin", "lfoot", "rthigh", "rknee", "rshin", "rfoot")
local lforearml,lbladel,rforearml,rbladel,lforearmu,lbladeu,rforearmu,rbladeu = piece("lforearml", "lbladel", "rforearml", "rbladel", "lforearmu", "lbladeu", "rforearmu", "rbladeu")
local spike1, spike2, spike3, firepoint, spore1, spore2, spore3 = piece("spike1", "spike2", "spike3", "firepoint", "spore1", "spore2", "spore3")
local smokePiece = {}
local turretIndex = {
}
--constants
local wingAngle = math.rad(40)
local wingSpeed = math.rad(120)
local tailAngle = math.rad(20)
local bladeExtendSpeed = math.rad(600)
local bladeRetractSpeed = math.rad(120)
local bladeAngle = math.rad(140)
--variables
local isMoving = false
local feet = true
local malus = GG.malus or 1
--maximum HP for additional weapons
local healthSpore3 = 0.55
local healthDodoDrop = 0.65
local healthDodo2Drop = 0.3
local healthBasiliskDrop = 0.5
local healthTiamatDrop = 0.2
--signals
local SIG_Aim = 1
local SIG_Aim2 = 2
local SIG_Fly = 16
--cob values
----------------------------------------------------------
local function RestoreAfterDelay()
Sleep(1000)
end
-- used for queen morph - blank in this case as it does nothing
function MorphFunc()
end
local function Fly()
Signal(SIG_Fly)
SetSignalMask(SIG_Fly)
while true do
--Spring.Echo("Wings down (before Turn)", Spring.GetGameFrame(), Spring.UnitScript.IsInTurn(leftWing1, z_axis))
Turn(leftWing1, z_axis, -wingAngle, wingSpeed)
Turn(rightWing1, z_axis, wingAngle, wingSpeed)
Turn(leftWing2, z_axis, -wingAngle/3, wingSpeed)
Turn(rightWing2, z_axis, wingAngle/3, wingSpeed)
Turn(tail, x_axis, tailAngle, math.rad(40))
Move(body, y_axis, -60, 45)
--Spring.Echo("Wings down (after Turn)", Spring.GetGameFrame(), Spring.UnitScript.IsInTurn(leftWing1, z_axis))
WaitForTurn(leftWing1, z_axis)
Sleep(0)
--Spring.Echo("Wings up (before Turn)", Spring.GetGameFrame(), Spring.UnitScript.IsInTurn(leftWing1, z_axis))
Turn(leftWing1, z_axis, wingAngle, wingSpeed)
Turn(rightWing1, z_axis, -wingAngle, wingSpeed)
Turn(leftWing2, z_axis, wingAngle/3, wingSpeed*2)
Turn(rightWing2, z_axis, -wingAngle/3, wingSpeed*2)
Turn(tail, x_axis, -tailAngle, math.rad(40))
Move(body, y_axis, 0, 45)
WaitForTurn(leftWing1, z_axis)
Sleep(0)
--Spring.Echo("Wings up (after Turn)", Spring.GetGameFrame(), Spring.UnitScript.IsInTurn(leftWing1, z_axis))
end
end
local function StopFly()
Signal(SIG_Fly)
SetSignalMask(SIG_Fly)
Turn(leftWing1, z_axis, 0, wingSpeed)
Turn(rightWing1, z_axis, 0, wingSpeed)
end
local function DropDodoLoop()
while true do
local health, maxHealth = spGetUnitHealth(unitID)
if (health/maxHealth) < healthDodoDrop then
for i=1,malus do
if (feet) then EmitSfx(leftFoot,2048+4)
else EmitSfx(rightFoot,2048+4) end
feet = not feet
Sleep(500)
end
end
Sleep(1500)
if (health/maxHealth) < healthDodo2Drop then
for i=1,malus do
if (feet) then EmitSfx(leftFoot,2048+4)
else EmitSfx(rightFoot,2048+4) end
feet = not feet
Sleep(500)
end
end
Sleep(4500)
end
end
local function DropBasiliskLoop()
while true do
local health, maxHealth = spGetUnitHealth(unitID)
if (health/maxHealth) < healthTiamatDrop then
for i=1,malus do
EmitSfx(body,2048+6)
Sleep(1000)
end
elseif (health/maxHealth) < healthBasiliskDrop then
for i=1,malus do
EmitSfx(body,2048+5)
Sleep(1000)
end
end
Sleep(8000)
end
end
local function Moving()
Signal(SIG_Fly)
SetSignalMask(SIG_Fly)
StartThread(Fly)
Turn(leftFoot, x_axis, math.rad(-20), math.rad(420))
Turn(rightFoot, x_axis, math.rad(-20), math.rad(420))
Turn(leftShin, x_axis, math.rad(-40), math.rad(420))
Turn(rightShin, x_axis, math.rad(-40), math.rad(420))
end
function script.StartMoving()
isMoving = true
StartThread(Moving)
end
function script.StopMoving()
isMoving = false
StartThread(StopFly)
end
function script.Create()
Turn(rightWing1, x_axis, math.rad(15))
Turn(leftWing1, x_axis, math.rad(15))
Turn(rightWing1, x_axis, math.rad(0), math.rad(60))
Turn(leftWing1, x_axis, math.rad(0), math.rad(60))
Turn(rightWing1, z_axis, math.rad(-60))
Turn(rightWing2, z_axis, math.rad(100))
Turn(leftWing1, z_axis, math.rad(60))
Turn(leftWing2, z_axis, math.rad(-100))
EmitSfx(body, 1026)
EmitSfx(head, 1026)
EmitSfx(tail, 1026)
EmitSfx(firepoint, 1026)
EmitSfx(leftWing1, 1026)
EmitSfx(rightWing1, 1026)
EmitSfx(spike1, 1026)
EmitSfx(spike2, 1026)
EmitSfx(spike3, 1026)
Turn(spore1, x_axis, math.rad(90))
Turn(spore2, x_axis, math.rad(90))
Turn(spore3, x_axis, math.rad(90))
StartThread(DropDodoLoop)
StartThread(DropBasiliskLoop)
end
function script.AimFromWeapon(weaponNum)
if weaponNum == 1 then return firepoint
elseif weaponNum == 2 then return spore1
elseif weaponNum == 3 then return spore2
elseif weaponNum == 4 then return spore3
--elseif weaponNum == 5 then return body
else return body end
end
function script.AimWeapon(weaponNum, heading, pitch)
if weaponNum == 1 then
Signal(SIG_Aim)
SetSignalMask(SIG_Aim)
Turn(head, y_axis, heading, math.rad(250))
Turn(head, x_axis, pitch, math.rad(200))
WaitForTurn(head, y_axis)
WaitForTurn(head, x_axis)
StartThread(RestoreAfterDelay)
return true
elseif weaponNum == 4 then
local health, maxHealth = spGetUnitHealth(unitID)
if (health/maxHealth) < healthSpore3 then return true end
elseif weaponNum >= 2 and weaponNum <= 4 then return true
else return false
end
end
function script.QueryWeapon(weaponNum)
if weaponNum == 1 then return firepoint
elseif weaponNum == 2 then return spore1
elseif weaponNum == 3 then return spore2
elseif weaponNum == 4 then return spore3
--elseif weaponNum == 5 then
-- if feet then return leftFoot
-- else return rightFoot end
else return body end
end
function script.FireWeapon(weaponNum)
if weaponNum == 1 then
Turn(lforearmu, y_axis, -bladeAngle, bladeExtendSpeed)
Turn(lbladeu, y_axis, bladeAngle, bladeExtendSpeed)
Turn(lforearml, y_axis, -bladeAngle, bladeExtendSpeed)
Turn(lbladel, y_axis, bladeAngle, bladeExtendSpeed)
Turn(rforearmu, y_axis, bladeAngle, bladeExtendSpeed)
Turn(rbladeu, y_axis, -bladeAngle, bladeExtendSpeed)
Turn(rforearml, y_axis, bladeAngle, bladeExtendSpeed)
Turn(rbladel, y_axis, -bladeAngle, bladeExtendSpeed)
Sleep(500)
Turn(lforearmu, y_axis, 0, bladeRetractSpeed)
Turn(lbladeu, y_axis, 0, bladeRetractSpeed)
Turn(lforearml, y_axis, 0, bladeRetractSpeed)
Turn(lbladel, y_axis, 0, bladeRetractSpeed)
Turn(rforearmu, y_axis, 0, bladeRetractSpeed)
Turn(rbladeu, y_axis, 0, bladeRetractSpeed)
Turn(rforearml, y_axis, 0, bladeRetractSpeed)
Turn(rbladel, y_axis, 0, bladeRetractSpeed)
--WaitForTurn(lbladeu, y_axis)
end
return true
end
function script.Killed(recentDamage, maxHealth)
EmitSfx(body, 1025)
Explode(body, sfxFall)
Explode(head, sfxFall)
Explode(tail, sfxFall)
Explode(leftWing1, sfxFall)
Explode(rightWing1, sfxFall)
Explode(spike1, sfxFall)
Explode(spike2, sfxFall)
Explode(spike3, sfxFall)
Explode(leftThigh, sfxFall)
Explode(rightThigh, sfxFall)
Explode(leftShin, sfxFall)
Explode(rightShin, sfxFall)
end
function script.HitByWeapon(x, z, weaponID, damage)
EmitSfx(body, 1024)
--return 100
end
| gpl-2.0 |
bungle/lua-resty-nettle | lib/resty/nettle/types/siv-cmac.lua | 1 | 1978 | require "resty.nettle.types.aes"
require "resty.nettle.types.cmac"
local ffi = require "ffi"
local ffi_cdef = ffi.cdef
local ffi_typeof = ffi.typeof
ffi_cdef [[
void
nettle_siv_cmac_aes128_set_key(struct siv_cmac_aes128_ctx *ctx, const uint8_t *key);
void
nettle_siv_cmac_aes128_encrypt_message(const struct siv_cmac_aes128_ctx *ctx,
size_t nlength, const uint8_t *nonce,
size_t alength, const uint8_t *adata,
size_t clength, uint8_t *dst, const uint8_t *src);
int
nettle_siv_cmac_aes128_decrypt_message(const struct siv_cmac_aes128_ctx *ctx,
size_t nlength, const uint8_t *nonce,
size_t alength, const uint8_t *adata,
size_t mlength, uint8_t *dst, const uint8_t *src);
void
nettle_siv_cmac_aes256_set_key(struct siv_cmac_aes256_ctx *ctx, const uint8_t *key);
void
nettle_siv_cmac_aes256_encrypt_message(const struct siv_cmac_aes256_ctx *ctx,
size_t nlength, const uint8_t *nonce,
size_t alength, const uint8_t *adata,
size_t clength, uint8_t *dst, const uint8_t *src);
int
nettle_siv_cmac_aes256_decrypt_message(const struct siv_cmac_aes256_ctx *ctx,
size_t nlength, const uint8_t *nonce,
size_t alength, const uint8_t *adata,
size_t mlength, uint8_t *dst, const uint8_t *src);
]]
return {
aes128 = ffi_typeof [[
struct siv_cmac_aes128_ctx {
struct cmac128_key cmac_key;
struct aes128_ctx cmac_cipher;
struct aes128_ctx ctr_cipher;
}]],
aes256 = ffi_typeof [[
struct siv_cmac_aes256_ctx {
struct cmac128_key cmac_key;
struct aes256_ctx cmac_cipher;
struct aes256_ctx ctr_cipher;
}]]
}
| bsd-2-clause |
forward619/luci | protocols/luci-proto-ppp/luasrc/model/cbi/admin_network/proto_ppp.lua | 47 | 3692 | -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
local device, username, password
local ipv6, defaultroute, metric, peerdns, dns,
keepalive_failure, keepalive_interval, demand, mtu
device = section:taboption("general", Value, "device", translate("Modem device"))
device.rmempty = false
local device_suggestions = nixio.fs.glob("/dev/tty*S*")
or nixio.fs.glob("/dev/tts/*")
if device_suggestions then
local node
for node in device_suggestions do
device:value(node)
end
end
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
if luci.model.network:has_ipv6() then
ipv6 = section:taboption("advanced", ListValue, "ipv6")
ipv6:value("auto", translate("Automatic"))
ipv6:value("0", translate("Disabled"))
ipv6:value("1", translate("Manual"))
ipv6.default = "auto"
end
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure",
translate("LCP echo failure threshold"),
translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures"))
function keepalive_failure.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^(%d+)[ ,]+%d+") or v)
end
end
keepalive_failure.placeholder = "0"
keepalive_failure.datatype = "uinteger"
keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval",
translate("LCP echo interval"),
translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold"))
function keepalive_interval.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^%d+[ ,]+(%d+)"))
end
end
function keepalive_interval.write(self, section, value)
local f = tonumber(keepalive_failure:formvalue(section)) or 0
local i = tonumber(value) or 5
if i < 1 then i = 1 end
if f > 0 then
m:set(section, "keepalive", "%d %d" %{ f, i })
else
m:del(section, "keepalive")
end
end
keepalive_interval.remove = keepalive_interval.write
keepalive_failure.write = keepalive_interval.write
keepalive_failure.remove = keepalive_interval.write
keepalive_interval.placeholder = "5"
keepalive_interval.datatype = "min(1)"
demand = section:taboption("advanced", Value, "demand",
translate("Inactivity timeout"),
translate("Close inactive connection after the given amount of seconds, use 0 to persist connection"))
demand.placeholder = "0"
demand.datatype = "uinteger"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(9200)"
| apache-2.0 |
geanux/darkstar | scripts/zones/LaLoff_Amphitheater/npcs/qm0_1.lua | 35 | 1154 | -----------------------------------
-- Area: LaLoff_Amphitheater
-- NPC: qm0 (warp player outside after they win fight)
-------------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
-------------------------------------
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0C);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if (csid == 0x0C and option == 1) then
player:setPos(291.459,-42.088,-401.161,163,130);
end
end; | gpl-3.0 |
SirFrancisBillard/lua-projects | workshop/meth_cooking/meth_cooking/lua/entities/billard_meth_pot/init.lua | 2 | 1526 | AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
function ENT:Initialize()
self:SetModel("models/props_c17/metalPot001a.mdl")
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
local phys = self:GetPhysicsObject()
if phys:IsValid() then
phys:Wake()
end
self:SetUseType(3)
self:SetHasChloride(false)
self:SetHasSodium(false)
end
function ENT:Touch(toucher)
if IsValid(toucher) then
if toucher:GetClass() == "billard_chem_chloride" and !self:GetHasChloride() then
self:SetHasChloride(true)
self:EmitSound("fizz.wav")
toucher:Remove()
elseif toucher:GetClass() == "billard_chem_sodium" and !self:GetHasSodium() then
self:SetHasSodium(true)
self:EmitSound("fizz.wav")
toucher:Remove()
end
end
end
function ENT:Use(activator, caller)
if IsValid(caller) and caller:IsPlayer() then
if self:GetHasChloride() and self:GetHasSodium() then
caller:ChatPrint("Your meth has been cooked")
local meth = ents.Create("billard_meth")
meth:SetPos(self:GetPos() + Vector(0, 0, 20))
meth:Spawn()
self:SetHasChloride(false)
self:SetHasSodium(false)
elseif self:GetHasChloride() then
caller:ChatPrint("You need to put Sodium in the pot!")
elseif self:GetHasSodium() then
caller:ChatPrint("You need to put Chloride in the pot!")
else
caller:ChatPrint("You need to put Chloride and Sodium in the pot!")
end
DoGenericUseEffect(caller)
end
end | gpl-3.0 |
kaen/Zero-K | units/corhlt.lua | 4 | 6799 | unitDef = {
unitname = [[corhlt]],
name = [[Stinger]],
description = [[High-Energy Laser Tower]],
acceleration = 0,
brakeRate = 0,
buildAngle = 4096,
buildCostEnergy = 420,
buildCostMetal = 420,
builder = false,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 4,
buildingGroundDecalSizeY = 4,
buildingGroundDecalType = [[corhlt_aoplane.dds]],
buildPic = [[CORHLT.png]],
buildTime = 420,
canAttack = true,
canstop = [[1]],
category = [[FLOAT TURRET]],
collisionVolumeOffsets = [[0 17 0]],
collisionVolumeScales = [[36 110 36]],
collisionVolumeTest = 1,
collisionVolumeType = [[CylY]],
corpse = [[DEAD]],
customParams = {
description_fr = [[Tourelle Laser Moyenne HLT]],
description_de = [[Hochenergetischer Laserturm]],
description_pl = [[Ciezka wieza laserowa]],
helptext = [[The Stinger is a medium laser turret. Its three rotating laser guns can kill almost any small unit, but its low rate of fire makes it vulnerable to swarms when unassisted.]],
helptext_fr = [[Le Gaat Gun est compos? de trois canons lasers rotatifs lourd. Oblig?s de se refroidir apr?s chaque tir, il n'en d?livrent pas moins une forte puissance de feu instann?e. Tr?s utile sur des grosses cibles, elle aura besoin d'assistance en cas de nombreux ennemis.]],
helptext_de = [[Der Stinger ist ein durchschnittlicher Lasergesch?zturm. Seine drei rotierenden Laserkanonen können so gut wie jede kleine Einheit töten, aber die langsame Feuerrate macht den Stinger anfällig f? große Gruppen, sobald er nicht gen?end abgesichert ist.]],
helptext_pl = [[Stinger to wieza laserowa, ktora zadaje ciezkie obrazenia przy kazdym strzale i ma dosyc dobry zasieg, jednak dlugi czas przeladowania oznacza, ze latwo ja zniszczyc grupami mniejszych jednostek.]],
aimposoffset = [[0 55 0]],
},
explodeAs = [[MEDIUM_BUILDINGEX]],
floater = true,
footprintX = 3,
footprintZ = 3,
iconType = [[defenseheavy]],
idleAutoHeal = 5,
idleTime = 1800,
levelGround = false,
losEmitHeight = 80,
mass = 267,
maxDamage = 2475,
maxSlope = 36,
maxVelocity = 0,
minCloakDistance = 150,
noAutoFire = false,
noChaseCategory = [[FIXEDWING LAND SHIP SATELLITE SWIM GUNSHIP SUB HOVER]],
objectName = [[hlt.s3o]],
script = [[corhlt.lua]],
seismicSignature = 4,
selfDestructAs = [[MEDIUM_BUILDINGEX]],
sfxtypes = {
explosiongenerators = {
[[custom:HLTRADIATE0]],
[[custom:beamlaser_hit_blue]],
},
},
side = [[CORE]],
sightDistance = 660,
smoothAnim = true,
turnRate = 0,
useBuildingGroundDecal = true,
workerTime = 0,
yardMap = [[ooo ooo ooo]],
weapons = {
{
def = [[LASER]],
badTargetCategory = [[FIXEDWING]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
},
weaponDefs = {
LASER = {
name = [[High-Energy Laserbeam]],
areaOfEffect = 14,
beamTime = 0.8,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
customParams = {
statsprojectiles = 1,
statsdamage = 850,
},
damage = {
default = 170.1,
planes = 170.1,
subs = 9,
},
explosionGenerator = [[custom:flash1bluedark]],
fireStarter = 90,
fireTolerance = 8192, -- 45 degrees
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
largeBeamLaser = true,
laserFlareSize = 10.4,
minIntensity = 1,
noSelfDamage = true,
projectiles = 5,
range = 620,
reloadtime = 4.5,
rgbColor = [[0 0 1]],
scrollSpeed = 5,
soundStart = [[weapon/laser/heavy_laser3]],
soundStartVolume = 3,
sweepfire = false,
texture1 = [[largelaserdark]],
texture2 = [[flaredark]],
texture3 = [[flaredark]],
texture4 = [[smallflaredark]],
thickness = 10.4024486300101,
tileLength = 300,
tolerance = 10000,
turret = true,
weaponType = [[BeamLaser]],
weaponVelocity = 2250,
},
},
featureDefs = {
DEAD = {
description = [[Wreckage - Stinger]],
blocking = true,
category = [[corpses]],
damage = 2475,
energy = 0,
featureDead = [[HEAP]],
featurereclamate = [[SMUDGE01]],
footprintX = 3,
footprintZ = 3,
height = [[20]],
hitdensity = [[100]],
metal = 168,
object = [[corhlt_d.s3o]],
reclaimable = true,
reclaimTime = 168,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
HEAP = {
description = [[Debris - Stinger]],
blocking = false,
category = [[heaps]],
damage = 2475,
energy = 0,
featurereclamate = [[SMUDGE01]],
footprintX = 3,
footprintZ = 3,
height = [[4]],
hitdensity = [[100]],
metal = 84,
object = [[debris3x3a.s3o]],
reclaimable = true,
reclaimTime = 84,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
},
}
return lowerkeys({ corhlt = unitDef })
| gpl-2.0 |
kaen/Zero-K | units/armamd.lua | 2 | 6140 | unitDef = {
unitname = [[armamd]],
name = [[Protector]],
description = [[Anti-Nuke System]],
acceleration = 0,
activateWhenBuilt = true,
antiweapons = [[1]],
bmcode = [[0]],
brakeRate = 0,
buildAngle = 4096,
buildCostEnergy = 3000,
buildCostMetal = 3000,
builder = false,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 6,
buildingGroundDecalSizeY = 6,
buildingGroundDecalType = [[antinuke_decal.dds]],
buildPic = [[ARMAMD.png]],
buildTime = 3000,
category = [[SINK]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[70 70 110]],
collisionVolumeTest = 1,
collisionVolumeType = [[CylZ]],
corpse = [[DEAD]],
customParams = {
description_de = [[Antinukleares System (Anti-Nuke)]],
description_fr = [[Syst?me de D?fense Anti Missile (AntiNuke)]],
description_pl = [[Tarcza Antyrakietowa]],
helptext = [[The Protector automatically intercepts enemy nuclear ICBMs aimed within its coverage radius.]],
helptext_de = [[Der Protector fängt automatisch gegnerische, atomare Interkontinentalraketen, welche in den, vom System abgedeckten, Bereich zielen, ab.]],
helptext_fr = [[Le Protector est un b?timent indispensable dans tout conflit qui dure. Il est toujours malvenu de voir sa base r?duite en cendres ? cause d'un missile nucl?aire. Le Protector est un syst?me de contre mesure capable de faire exploser en vol les missiles nucl?aires ennemis.]],
helptext_pl = [[Protector automatycznie wysy³a przeciwrakiety, aby zniszczyæ przelatuj¹ce nad jego obszarem ochrony g³owice nuklearne przeciwników.]],
removewait = 1,
nuke_coverage = 2500,
},
explodeAs = [[LARGE_BUILDINGEX]],
footprintX = 5,
footprintZ = 8,
iconType = [[antinuke]],
idleAutoHeal = 5,
idleTime = 1800,
levelGround = false,
mass = 561,
maxDamage = 3300,
maxSlope = 18,
maxVelocity = 0,
maxWaterDepth = 0,
minCloakDistance = 150,
objectName = [[antinuke.s3o]],
radarDistance = 2500,
script = [[armamd.lua]],
seismicSignature = 4,
selfDestructAs = [[LARGE_BUILDINGEX]],
side = [[ARM]],
sightDistance = 660,
smoothAnim = true,
TEDClass = [[FORT]],
turnRate = 0,
useBuildingGroundDecal = true,
workerTime = 0,
weapons = {
{
def = [[AMD_ROCKET]],
},
},
weaponDefs = {
AMD_ROCKET = {
name = [[Anti-Nuke Missile Fake]],
areaOfEffect = 420,
collideFriendly = false,
collideGround = false,
coverage = 100000,
craterBoost = 1,
craterMult = 2,
customParams = {
nuke_coverage = 2500,
},
damage = {
default = 1500,
subs = 75,
},
explosionGenerator = [[custom:ANTINUKE]],
fireStarter = 100,
flightTime = 20,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
interceptor = 1,
model = [[antinukemissile.s3o]],
noautorange = [[1]],
noSelfDamage = true,
range = 3800,
reloadtime = 6,
selfprop = true,
smokedelay = [[0.1]],
smokeTrail = true,
soundHit = [[weapon/missile/vlaunch_hit]],
soundStart = [[weapon/missile/missile_launch]],
startsmoke = [[1]],
startVelocity = 400,
tolerance = 4000,
tracks = true,
turnrate = 65535,
twoPhase = true,
vlaunch = true,
weaponAcceleration = 800,
weaponTimer = 0.4,
weaponType = [[StarburstLauncher]],
weaponVelocity = 1600,
},
},
featureDefs = {
DEAD = {
description = [[Wreckage - Protector]],
blocking = true,
category = [[corpses]],
damage = 3300,
energy = 0,
featureDead = [[HEAP]],
featurereclamate = [[SMUDGE01]],
footprintX = 5,
footprintZ = 8,
height = [[20]],
hitdensity = [[100]],
metal = 1200,
object = [[antinuke_dead.s3o]],
reclaimable = true,
reclaimTime = 1200,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
HEAP = {
description = [[Debris - Protector]],
blocking = false,
category = [[heaps]],
damage = 3300,
energy = 0,
featurereclamate = [[SMUDGE01]],
footprintX = 5,
footprintZ = 8,
height = [[4]],
hitdensity = [[100]],
metal = 600,
object = [[debris4x4a.s3o]],
reclaimable = true,
reclaimTime = 600,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
},
}
return lowerkeys({ armamd = unitDef })
| gpl-2.0 |
mrxhacker/BDReborn | plugins/msg-checks.lua | 26 | 13860 | --Begin msg_checks.lua By @SoLiD
local function pre_process(msg)
local data = load_data(_config.moderation.data)
local chat = msg.to.id
local user = msg.from.id
local is_channel = msg.to.type == "channel"
local is_chat = msg.to.type == "chat"
local auto_leave = 'auto_leave_bot'
local hash = "gp_lang:"..chat
local lang = redis:get(hash)
if not redis:get('autodeltime') then
redis:setex('autodeltime', 14400, true)
run_bash("rm -rf ~/.telegram-cli/data/sticker/*")
run_bash("rm -rf ~/.telegram-cli/data/photo/*")
run_bash("rm -rf ~/.telegram-cli/data/animation/*")
run_bash("rm -rf ~/.telegram-cli/data/video/*")
run_bash("rm -rf ~/.telegram-cli/data/audio/*")
run_bash("rm -rf ~/.telegram-cli/data/voice/*")
run_bash("rm -rf ~/.telegram-cli/data/temp/*")
run_bash("rm -rf ~/.telegram-cli/data/thumb/*")
run_bash("rm -rf ~/.telegram-cli/data/document/*")
run_bash("rm -rf ~/.telegram-cli/data/profile_photo/*")
run_bash("rm -rf ~/.telegram-cli/data/encrypted/*")
run_bash("rm -rf ./data/photos/*")
end
if is_channel or is_chat then
local TIME_CHECK = 2
if data[tostring(chat)] then
if data[tostring(chat)]['settings']['time_check'] then
TIME_CHECK = tonumber(data[tostring(chat)]['settings']['time_check'])
end
end
if msg.text then
if msg.text:match("(.*)") then
if not data[tostring(msg.to.id)] and not redis:get(auto_leave) and not is_admin(msg) then
tdcli.sendMessage(msg.to.id, "", 0, "_This Is Not One Of My_ *Groups*", 0, "md")
tdcli.changeChatMemberStatus(chat, our_id, 'Left', dl_cb, nil)
end
end
end
if data[tostring(chat)] and data[tostring(chat)]['mutes'] then
mutes = data[tostring(chat)]['mutes']
else
return
end
if mutes.mute_all then
mute_all = mutes.mute_all
else
mute_all = 'no'
end
if mutes.mute_gif then
mute_gif = mutes.mute_gif
else
mute_gif = 'no'
end
if mutes.mute_photo then
mute_photo = mutes.mute_photo
else
mute_photo = 'no'
end
if mutes.mute_sticker then
mute_sticker = mutes.mute_sticker
else
mute_sticker = 'no'
end
if mutes.mute_contact then
mute_contact = mutes.mute_contact
else
mute_contact = 'no'
end
if mutes.mute_inline then
mute_inline = mutes.mute_inline
else
mute_inline = 'no'
end
if mutes.mute_game then
mute_game = mutes.mute_game
else
mute_game = 'no'
end
if mutes.mute_text then
mute_text = mutes.mute_text
else
mute_text = 'no'
end
if mutes.mute_keyboard then
mute_keyboard = mutes.mute_keyboard
else
mute_keyboard = 'no'
end
if mutes.mute_forward then
mute_forward = mutes.mute_forward
else
mute_forward = 'no'
end
if mutes.mute_location then
mute_location = mutes.mute_location
else
mute_location = 'no'
end
if mutes.mute_document then
mute_document = mutes.mute_document
else
mute_document = 'no'
end
if mutes.mute_voice then
mute_voice = mutes.mute_voice
else
mute_voice = 'no'
end
if mutes.mute_audio then
mute_audio = mutes.mute_audio
else
mute_audio = 'no'
end
if mutes.mute_video then
mute_video = mutes.mute_video
else
mute_video = 'no'
end
if mutes.mute_tgservice then
mute_tgservice = mutes.mute_tgservice
else
mute_tgservice = 'no'
end
if data[tostring(chat)] and data[tostring(chat)]['settings'] then
settings = data[tostring(chat)]['settings']
else
return
end
if settings.lock_link then
lock_link = settings.lock_link
else
lock_link = 'no'
end
if settings.lock_join then
lock_join = settings.lock_join
else
lock_join = 'no'
end
if settings.lock_tag then
lock_tag = settings.lock_tag
else
lock_tag = 'no'
end
if settings.lock_pin then
lock_pin = settings.lock_pin
else
lock_pin = 'no'
end
if settings.lock_arabic then
lock_arabic = settings.lock_arabic
else
lock_arabic = 'no'
end
if settings.lock_mention then
lock_mention = settings.lock_mention
else
lock_mention = 'no'
end
if settings.lock_edit then
lock_edit = settings.lock_edit
else
lock_edit = 'no'
end
if settings.lock_spam then
lock_spam = settings.lock_spam
else
lock_spam = 'no'
end
if settings.flood then
lock_flood = settings.flood
else
lock_flood = 'no'
end
if settings.lock_markdown then
lock_markdown = settings.lock_markdown
else
lock_markdown = 'no'
end
if settings.lock_webpage then
lock_webpage = settings.lock_webpage
else
lock_webpage = 'no'
end
if msg.adduser or msg.joinuser or msg.deluser then
if mute_tgservice == "yes" then
del_msg(chat, tonumber(msg.id))
end
end
if not is_mod(msg) and not is_whitelist(msg.from.id, msg.to.id) and msg.from.id ~= our_id then
if msg.adduser or msg.joinuser then
if lock_join == "yes" then
function join_kick(arg, data)
kick_user(data.id_, msg.to.id)
end
if msg.adduser then
tdcli.getUser(msg.adduser, join_kick, nil)
elseif msg.joinuser then
tdcli.getUser(msg.joinuser, join_kick, nil)
end
end
end
end
if msg.pinned and is_channel then
if lock_pin == "yes" then
if is_owner(msg) then
return
end
if tonumber(msg.from.id) == our_id then
return
end
local pin_msg = data[tostring(chat)]['pin']
if pin_msg then
tdcli.pinChannelMessage(msg.to.id, pin_msg, 1)
elseif not pin_msg then
tdcli.unpinChannelMessage(msg.to.id)
end
if lang then
tdcli.sendMessage(msg.to.id, msg.id, 0, '<b>User ID :</b> <code>'..msg.from.id..'</code>\n<b>Username :</b> '..('@'..msg.from.username or '<i>No Username</i>')..'\n<i>شما اجازه دسترسی به سنجاق پیام را ندارید، به همین دلیل پیام قبلی مجدد سنجاق میگردد</i>', 0, "html")
elseif not lang then
tdcli.sendMessage(msg.to.id, msg.id, 0, '<b>User ID :</b> <code>'..msg.from.id..'</code>\n<b>Username :</b> '..('@'..msg.from.username or '<i>No Username</i>')..'\n<i>You Have Not Permission To Pin Message, Last Message Has Been Pinned Again</i>', 0, "html")
end
end
end
if not is_mod(msg) and not is_whitelist(msg.from.id, msg.to.id) and msg.from.id ~= our_id then
if msg.edited and lock_edit == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.forward_info_ and mute_forward == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.photo_ and mute_photo == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.video_ and mute_video == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.document_ and mute_document == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.sticker_ and mute_sticker == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.animation_ and mute_gif == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.contact_ and mute_contact == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.location_ and mute_location == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.voice_ and mute_voice == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.content_ and mute_keyboard == "yes" then
if msg.reply_markup_ and msg.reply_markup_.ID == "ReplyMarkupInlineKeyboard" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if tonumber(msg.via_bot_user_id_) ~= 0 and mute_inline == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.game_ and mute_game == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.audio_ and mute_audio == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.media.caption then
local link_caption = msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Dd][Oo][Gg]/") or msg.media.caption:match("[Tt].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/")
if link_caption
and lock_link == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
local tag_caption = msg.media.caption:match("@") or msg.media.caption:match("#")
if tag_caption and lock_tag == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if is_filter(msg, msg.media.caption) then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
local arabic_caption = msg.media.caption:match("[\216-\219][\128-\191]")
if arabic_caption and lock_arabic == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if msg.text then
local _nl, ctrl_chars = string.gsub(msg.text, '%c', '')
local max_chars = 40
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['set_char'] then
max_chars = tonumber(data[tostring(msg.to.id)]['settings']['set_char'])
end
end
local _nl, real_digits = string.gsub(msg.text, '%d', '')
local max_real_digits = tonumber(max_chars) * 50
local max_len = tonumber(max_chars) * 51
if lock_spam == "yes" then
if string.len(msg.text) > max_len or ctrl_chars > max_chars or real_digits > max_real_digits then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
local link_msg = msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Dd][Oo][Gg]/") or msg.text:match("[Tt].[Mm][Ee]/") or msg.text:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/")
if link_msg
and lock_link == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
local tag_msg = msg.text:match("@") or msg.text:match("#")
if tag_msg and lock_tag == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if is_filter(msg, msg.text) then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
local arabic_msg = msg.text:match("[\216-\219][\128-\191]")
if arabic_msg and lock_arabic == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.text:match("(.*)")
and mute_text == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if mute_all == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.content_.entities_ and msg.content_.entities_[0] then
if msg.content_.entities_[0].ID == "MessageEntityMentionName" then
if lock_mention == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if msg.content_.entities_[0].ID == "MessageEntityUrl" or msg.content_.entities_[0].ID == "MessageEntityTextUrl" then
if lock_webpage == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if msg.content_.entities_[0].ID == "MessageEntityBold" or msg.content_.entities_[0].ID == "MessageEntityCode" or msg.content_.entities_[0].ID == "MessageEntityPre" or msg.content_.entities_[0].ID == "MessageEntityItalic" then
if lock_markdown == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
end
if msg.to.type ~= 'pv' then
if lock_flood == "yes" and not is_mod(msg) and not is_whitelist(msg.from.id, msg.to.id) and not msg.adduser and msg.from.id ~= our_id then
local hash = 'user:'..user..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
local NUM_MSG_MAX = 5
if data[tostring(chat)] then
if data[tostring(chat)]['settings']['num_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(chat)]['settings']['num_msg_max'])
end
end
if msgs > NUM_MSG_MAX then
if msg.from.username then
user_name = "@"..msg.from.username
else
user_name = msg.from.first_name
end
if redis:get('sender:'..user..':flood') then
return
else
del_msg(chat, msg.id)
kick_user(user, chat)
if not lang then
tdcli.sendMessage(chat, msg.id, 0, "_User_ "..user_name.." `[ "..user.." ]` _has been_ *kicked* _because of_ *flooding*", 0, "md")
elseif lang then
tdcli.sendMessage(chat, msg.id, 0, "_کاربر_ "..user_name.." `[ "..user.." ]` _به دلیل ارسال پیام های مکرر اخراج شد_", 0, "md")
end
redis:setex('sender:'..user..':flood', 30, true)
end
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
end
end
end
end
return {
patterns = {},
pre_process = pre_process
}
--End msg_checks.lua--
| gpl-3.0 |
forward619/luci | libs/luci-lib-nixio/docsrc/nixio.bit.lua | 171 | 2044 | --- Bitfield operators and mainpulation functions.
-- Can be used as a drop-in replacement for bitlib.
module "nixio.bit"
--- Bitwise OR several numbers.
-- @class function
-- @name bor
-- @param oper1 First Operand
-- @param oper2 Second Operand
-- @param ... More Operands
-- @return number
--- Invert given number.
-- @class function
-- @name bnot
-- @param oper Operand
-- @return number
--- Bitwise AND several numbers.
-- @class function
-- @name band
-- @param oper1 First Operand
-- @param oper2 Second Operand
-- @param ... More Operands
-- @return number
--- Bitwise XOR several numbers.
-- @class function
-- @name bxor
-- @param oper1 First Operand
-- @param oper2 Second Operand
-- @param ... More Operands
-- @return number
--- Left shift a number.
-- @class function
-- @name lshift
-- @param oper number
-- @param shift bits to shift
-- @return number
--- Right shift a number.
-- @class function
-- @name rshift
-- @param oper number
-- @param shift bits to shift
-- @return number
--- Arithmetically right shift a number.
-- @class function
-- @name arshift
-- @param oper number
-- @param shift bits to shift
-- @return number
--- Integer division of 2 or more numbers.
-- @class function
-- @name div
-- @param oper1 Operand 1
-- @param oper2 Operand 2
-- @param ... More Operands
-- @return number
--- Cast a number to the bit-operating range.
-- @class function
-- @name cast
-- @param oper number
-- @return number
--- Sets one or more flags of a bitfield.
-- @class function
-- @name set
-- @param bitfield Bitfield
-- @param flag1 First Flag
-- @param ... More Flags
-- @return altered bitfield
--- Unsets one or more flags of a bitfield.
-- @class function
-- @name unset
-- @param bitfield Bitfield
-- @param flag1 First Flag
-- @param ... More Flags
-- @return altered bitfield
--- Checks whether given flags are set in a bitfield.
-- @class function
-- @name check
-- @param bitfield Bitfield
-- @param flag1 First Flag
-- @param ... More Flags
-- @return true when all flags are set, otherwise false | apache-2.0 |
geanux/darkstar | scripts/zones/Tahrongi_Canyon/npcs/Excavation_Point.lua | 29 | 1114 | -----------------------------------
-- Area: Tahrongi Canyon
-- NPC: Excavation Point
-----------------------------------
package.loaded["scripts/zones/Tahrongi_Canyon/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/excavation");
require("scripts/zones/Tahrongi_Canyon/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startExcavation(player,player:getZoneID(),npc,trade,0x0385);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(MINING_IS_POSSIBLE_HERE,605);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
mrxhacker/BDReborn | bot/bot.lua | 1 | 11342 | -- #Beyond Reborn Robot
-- #
tdcli = dofile('./tg/tdcli.lua')
serpent = (loadfile "./libs/serpent.lua")()
feedparser = (loadfile "./libs/feedparser.lua")()
require('./bot/utils')
require('./libs/lua-redis')
URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
local lgi = require ('lgi')
local notify = lgi.require('Notify')
notify.init ("Telegram updates")
chats = {}
plugins = {}
helper_id = 437450588 --Put Your Helper Bot ID Here
function do_notify (user, msg)
local n = notify.Notification.new(user, msg)
n:show ()
end
function dl_cb (arg, data)
-- vardump(data)
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
function whoami()
local usr = io.popen("whoami"):read('*a')
usr = string.gsub(usr, '^%s+', '')
usr = string.gsub(usr, '%s+$', '')
usr = string.gsub(usr, '[\n\r]+', ' ')
if usr:match("^root$") then
tcpath = '/root/.telegram-cli'
elseif not usr:match("^root$") then
tcpath = '/home/'..usr..'/.telegram-cli'
end
print('>> Download Path = '..tcpath)
end
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
function create_config( )
io.write('\n\27[1;33m>> Input your Telegram ID for set Sudo : \27[0;39;49m')
local sudo_id = tonumber(io.read())
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"banhammer",
"groupmanager",
"msg-checks",
"plugins",
"tools",
"fun",
},
sudo_users = {214976329, 174216458, sudo_id},
admins = {},
disabled_channels = {},
moderation = {data = './data/moderation.json'},
info_text = [[》Reborn v6.0
]],
}
serialize_to_file(config, './data/config.lua')
print ('saved config into config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: ./data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("SUDO USER: " .. user)
end
return config
end
whoami()
_config = load_config()
function load_plugins()
local config = loadfile ("./data/config.lua")()
for k, v in pairs(config.enabled_plugins) do
print("Loaded Plugin ", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugins '..v..'\27[39m')
print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all')))
print('\27[31m'..err..'\27[39m')
end
end
print('\n'..#config.enabled_plugins..' Plugins Are Active\n\nStarting BDReborn Robot...\n')
end
load_plugins()
function msg_valid(msg)
if tonumber(msg.date_) < (tonumber(os.time()) - 60) then
print('\27[36m>>-- OLD MESSAGE --<<\27[39m')
return false
end
if is_silent_user(msg.sender_user_id_, msg.chat_id_) then
del_msg(msg.chat_id_, msg.id_)
return false
end
if is_banned(msg.sender_user_id_, msg.chat_id_) then
del_msg(msg.chat_id_, tonumber(msg.id_))
kick_user(msg.sender_user_id_, msg.chat_id_)
return false
end
if is_gbanned(msg.sender_user_id_) then
del_msg(msg.chat_id_, tonumber(msg.id_))
kick_user(msg.sender_user_id_, msg.chat_id_)
return false
end
return true
end
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = '_Plugin_ *'..check_markdown(disabled_plugin)..'* _is disabled on this chat_'
print(warning)
tdcli.sendMessage(receiver, "", 0, warning, 0, "md")
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
if plugin.pre_process then
--If plugin is for privileged users only
local result = plugin.pre_process(msg)
if result then
print("pre process: ", plugin_name)
-- tdcli.sendMessage(msg.chat_id_, "", 0, result, 0, "md")
end
end
for k, pattern in pairs(plugin.patterns) do
matches = match_pattern(pattern, msg.content_.text_ or msg.content_.caption_)
if matches then
if is_plugin_disabled_on_chat(plugin_name, msg.chat_id_) then
return nil
end
print("Message matches: ", pattern..' | Plugin: '..plugin_name)
if plugin.run then
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
tdcli.sendMessage(msg.chat_id_, msg.id_, 0, result, 0, "md")
end
end
end
return
end
end
end
function file_cb(msg)
if msg.content_.ID == "MessagePhoto" then
photo_id = ''
local function get_cb(arg, data)
if data.content_.photo_.sizes_[2] then
photo_id = data.content_.photo_.sizes_[2].photo_.id_
else
photo_id = data.content_.photo_.sizes_[1].photo_.id_
end
tdcli.downloadFile(photo_id, dl_cb, nil)
end
tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil)
elseif msg.content_.ID == "MessageVideo" then
video_id = ''
local function get_cb(arg, data)
video_id = data.content_.video_.video_.id_
tdcli.downloadFile(video_id, dl_cb, nil)
end
tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil)
elseif msg.content_.ID == "MessageAnimation" then
anim_id, anim_name = '', ''
local function get_cb(arg, data)
anim_id = data.content_.animation_.animation_.id_
anim_name = data.content_.animation_.file_name_
tdcli.downloadFile(anim_id, dl_cb, nil)
end
tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil)
elseif msg.content_.ID == "MessageVoice" then
voice_id = ''
local function get_cb(arg, data)
voice_id = data.content_.voice_.voice_.id_
tdcli.downloadFile(voice_id, dl_cb, nil)
end
tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil)
elseif msg.content_.ID == "MessageAudio" then
audio_id, audio_name, audio_title = '', '', ''
local function get_cb(arg, data)
audio_id = data.content_.audio_.audio_.id_
audio_name = data.content_.audio_.file_name_
audio_title = data.content_.audio_.title_
tdcli.downloadFile(audio_id, dl_cb, nil)
end
tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil)
elseif msg.content_.ID == "MessageSticker" then
sticker_id = ''
local function get_cb(arg, data)
sticker_id = data.content_.sticker_.sticker_.id_
tdcli.downloadFile(sticker_id, dl_cb, nil)
end
tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil)
elseif msg.content_.ID == "MessageDocument" then
document_id, document_name = '', ''
local function get_cb(arg, data)
document_id = data.content_.document_.document_.id_
document_name = data.content_.document_.file_name_
tdcli.downloadFile(document_id, dl_cb, nil)
end
tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil)
end
end
function tdcli_update_callback (data)
if data.message_ then
if msg_caption ~= get_text_msg() then
msg_caption = get_text_msg()
end
end
if (data.ID == "UpdateNewMessage") then
local msg = data.message_
local d = data.disable_notification_
local chat = chats[msg.chat_id_]
local hash = 'msgs:'..msg.sender_user_id_..':'..msg.chat_id_
redis:incr(hash)
if redis:get('markread') == 'on' then
tdcli.viewMessages(msg.chat_id_, {[0] = msg.id_}, dl_cb, nil)
end
if ((not d) and chat) then
if msg.content_.ID == "MessageText" then
do_notify (chat.title_, msg.content_.text_)
else
do_notify (chat.title_, msg.content_.ID)
end
end
if msg_valid(msg) then
var_cb(msg, msg)
file_cb(msg)
if msg.content_.ID == "MessageText" then
msg.text = msg.content_.text_
msg.edited = false
msg.pinned = false
elseif msg.content_.ID == "MessagePinMessage" then
msg.pinned = true
elseif msg.content_.ID == "MessagePhoto" then
msg.photo_ = true
elseif msg.content_.ID == "MessageVideo" then
msg.video_ = true
elseif msg.content_.ID == "MessageAnimation" then
msg.animation_ = true
elseif msg.content_.ID == "MessageVoice" then
msg.voice_ = true
elseif msg.content_.ID == "MessageAudio" then
msg.audio_ = true
elseif msg.content_.ID == "MessageForwardedFromUser" then
msg.forward_info_ = true
elseif msg.content_.ID == "MessageSticker" then
msg.sticker_ = true
elseif msg.content_.ID == "MessageContact" then
msg.contact_ = true
elseif msg.content_.ID == "MessageDocument" then
msg.document_ = true
elseif msg.content_.ID == "MessageLocation" then
msg.location_ = true
elseif msg.content_.ID == "MessageGame" then
msg.game_ = true
elseif msg.content_.ID == "MessageChatAddMembers" then
for i=0,#msg.content_.members_ do
msg.adduser = msg.content_.members_[i].id_
end
elseif msg.content_.ID == "MessageChatJoinByLink" then
msg.joinuser = msg.sender_user_id_
elseif msg.content_.ID == "MessageChatDeleteMember" then
msg.deluser = true
end
end
elseif data.ID == "UpdateMessageContent" then
cmsg = data
local function edited_cb(arg, data)
msg = data
msg.media = {}
if cmsg.new_content_.text_ then
msg.text = cmsg.new_content_.text_
end
if cmsg.new_content_.caption_ then
msg.media.caption = cmsg.new_content_.caption_
end
msg.edited = true
if msg_valid(msg) then
var_cb(msg, msg)
end
end
tdcli_function ({ ID = "GetMessage", chat_id_ = data.chat_id_, message_id_ = data.message_id_ }, edited_cb, nil)
elseif data.ID == "UpdateFile" then
file_id = data.file_.id_
elseif (data.ID == "UpdateChat") then
chat = data.chat_
chats[chat.id_] = chat
elseif (data.ID == "UpdateOption" and data.name_ == "my_id") then
tdcli_function ({ID="GetChats", offset_order_="9223372036854775807", offset_chat_id_=0, limit_=20}, dl_cb, nil)
end
end
| gpl-3.0 |
ld-test/lua-cassandra | doc/examples/ssl.lua | 1 | 1472 | --------
-- Example of SSL enabled connection using luasocket
local cassandra = require "cassandra"
local PasswordAuthenticator = require "cassandra.authenticators.PasswordAuthenticator"
local session = cassandra:new()
local auth = PasswordAuthenticator("cassandra", "cassandra")
local ok, err = session:connect({"x.x.x.x", "y.y.y.y"}, nil, {
authenticator = auth,
ssl = true,
ssl_verify = true,
ca_file = "/path/to/your/ca-certificate.pem"
})
if not ok then
print(err.message)
end
local res, err = session:execute("SELECT * FROM system_auth.users")
--------
-- Example of SSL enabled connection from nginx
worker_processes 1;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
server {
listen 8080;
location / {
lua_ssl_trusted_certificate "/path/to/your/ca-certificate.pem";
default_type text/html;
content_by_lua '
local cassandra = require "cassandra"
local PasswordAuthenticator = require "cassandra.authenticators.PasswordAuthenticator"
local session = cassandra:new()
local auth = PasswordAuthenticator("cassandra", "cassandra")
local ok, err = session:connect({"x.x.x.x", "y.y.y.y"}, nil, {
authenticator = auth,
ssl = true,
ssl_verify = true
})
if not ok then
ngx.log(ngx.ERR, err.message)
end
local res, err = session:execute("SELECT * FROM system_auth.users")
';
}
}
}
| mit |
tonylauCN/tutorials | openresty/debugger/lualibs/luainspect/init.lua | 3 | 50289 | -- luainspect.init - core LuaInspect source analysis.
--
-- This module is a bit more high level than luainspect.ast. It deals more with
-- interpretation/inference of semantics of an AST. It also uses luainspect.globals,
-- which does the basic semantic interpretation of globals/locals.
--
-- (c) 2010 David Manura, MIT License.
local M = {}
-- This is the API version. It is an ISO8601 date expressed as a fraction.
M.APIVERSION = 0.20100805
local LA = require "luainspect.ast"
local LD = require "luainspect.dump"
local LG = require "luainspect.globals"
local LS = require "luainspect.signatures"
local T = require "luainspect.types"
local COMPAT = require "luainspect.compat_env"
--! require 'luainspect.typecheck' (context)
local ENABLE_RETURN_ANALYSIS = true
local DETECT_DEADCODE = false -- may require more validation (false positives)
-- Functional forms of Lua operators.
-- Note: variable names like _1 are intentional. These affect debug info and
-- will display in any error messages.
local ops = {}
ops['add'] = function(_1,_2) return _1+_2 end
ops['sub'] = function(_1,_2) return _1-_2 end
ops['mul'] = function(_1,_2) return _1*_2 end
ops['div'] = function(_1,_2) return _1/_2 end
ops['mod'] = function(_1,_2) return _1%_2 end
ops['pow'] = function(_1,_2) return _1^_2 end
ops['concat'] = function(_1,_2) return _1.._2 end
ops['eq'] = function(_1,_2) return _1==_2 end
ops['lt'] = function(_1,_2) return _1<_2 end
ops['le'] = function(_1,_2) return _1<=_2 end
ops['and'] = function(_1,_2) return _1 and _2 end
ops['or'] = function(_1,_2) return _1 or _2 end
ops['not'] = function(_1) return not _1 end
ops['len'] = function(_1) return #_1 end
ops['unm'] = function(_1) return -_1 end
-- Performs binary operation. Supports types.
local function dobinop(opid, a, b)
if (a == T.number or b == T.number) and
(a == T.number or type(a) == 'number' ) and
(b == T.number or type(b) == 'number' )
then
if opid == 'eq' or opid == 'lt' or opid == 'le' then
return T.boolean
elseif opid == 'concat' then
return T.string
else
return T.number
end
elseif (a == T.string or b == T.string) and
(a == T.string or type(a) == 'string' ) and
(b == T.string or type(b) == 'string' )
then
if opid == 'concat' or opid == 'and' or opid == 'or' then
return T.string
elseif opid == 'eq' or opid == 'lt' or opid == 'le' then
return T.boolean
else
return T.number
end
elseif (a == T.boolean or b == T.boolean) and
(a == T.boolean or type(a) == 'boolean' ) and
(b == T.boolean or type(b) == 'boolean' )
then
if opid == 'eq' or opid == 'and' or opid == 'or' then
return T.boolean
else
error('invalid operation on booleans: ' .. opid, 0)
end
elseif T.istype[a] or T.istype[b] then
return T.universal
else
return ops[opid](a, b)
end
end
-- Performs unary operation. Supports types.
local function dounop(opid, a)
if opid == 'not' then
if T.istype[a] then
return T.boolean
else
return ops[opid](a)
end
elseif a == T.number then
if opid == 'unm' then
return T.number
else -- 'len'
error('invalid operation on number: ' .. opid, 0)
end
elseif a == T.string then
return T.number
elseif a == T.boolean then
error('invalid operation on boolean: ' .. opid, 0)
elseif T.istype[a] then
return nil, 'unknown'
else
return ops[opid](a)
end
end
-- Like info in debug.getinfo but inferred by static analysis.
-- object -> {fpos=fpos, source="@" .. source, fast=ast, tokenlist=tokenlist}
-- Careful: value may reference key (affects pre-5.2 which lacks emphemerons).
-- See also ast.nocollect.
M.debuginfo = setmetatable({}, {__mode='v'})
-- Modules loaded via require_inspect.
-- module name string -> {return value, AST node}
-- note: AST node is maintained to prevent nocollect fields in ast being collected.
-- note: not a weak table.
M.package_loaded = {}
-- Stringifies interpreted value for debugging.
-- CATEGORY: debug
local function debugvalue(ast)
local s
if ast then
s = ast.value ~= T.universal and 'known:' .. tostring(ast.value) or 'unknown'
else
s = '?'
end
return s
end
-- Reads contents of text file in path, in binary mode.
-- On error, returns nil and error message.
local function readfile(path)
local fh, err = io.open(path, 'rb')
if fh then
local data; data, err = fh:read'*a'
if data then return data end
end
return nil, err
end
-- Similar to string.gsub but with plain replacement (similar to option in string.match)
-- http://lua-users.org/lists/lua-l/2002-04/msg00118.html
-- CATEGORY: utility/string
local function plain_gsub(s, pattern, repl)
repl = repl:gsub('(%%)', '%%%%')
return s:gsub(pattern, repl)
end
-- Infer name of variable or literal that AST node represents.
-- This is for debugging messages.
local function infer_name(ast)
if ast == nil then return nil
elseif ast.tag == 'Id' then return "'"..ast[1].."'"
elseif ast.tag == 'Number' then return 'number'
elseif ast.tag == 'String' then return 'string'
elseif ast.tag == 'True' then return 'true'
elseif ast.tag == 'False' then return 'false'
elseif ast.tag == 'Nil' then return 'nil'
else return nil end
end
--[[
This is like `pcall` but any error string returned does not contain the
"chunknamem:currentline: " prefix (based on luaL_where) if the error occurred
in the current file. This avoids error messages in user code (f)
being reported as being inside this module if this module calls user code.
Also, local variable names _1, _2, etc. in error message are replaced with names
inferred (if any) from corresponding AST nodes in list `asts` (note: nil's in asts skip replacement).
--]]
local _prefix
local _clean
local function pzcall(f, asts, ...)
_prefix = _prefix or select(2, pcall(function() error'' end)):gsub(':%d+: *$', '') -- note: specific to current file.
_clean = _clean or function(asts, ok, ...)
if ok then return true, ...
else
local err = ...
if type(err) == 'string' then
if err:sub(1,#_prefix) == _prefix then
local more = err:match('^:%d+: *(.*)', #_prefix+1)
if more then
err = more
err = err:gsub([[local '_(%d+)']], function(name) return infer_name(asts[tonumber(name)]) end)
end
end
end
return ok, err
end
end
return _clean(asts, pcall(f, ...))
end
-- Loads source code of given module name.
-- Returns code followed by path.
-- note: will also search in the directory `spath` and its parents.
-- This should preferrably be an absolute path or it might not work correctly.
-- It must be slash terminated.
-- CATEGORY: utility/package
local function load_module_source(name, spath)
-- Append parent directories to list of paths to search.
local package_path = package.path
local ppath = spath
repeat
package_path = package_path .. ';' .. ppath .. '?.lua;' .. ppath .. '?/init.lua'
local nsub
ppath, nsub = ppath:gsub('[^\\/]+[\\/]$', '')
until nsub == 0
for spec in package_path:gmatch'[^;]+' do
local testpath = plain_gsub(spec, '%?', (name:gsub('%.', '/')))
local src, err_ = readfile(testpath)
if src then return src, testpath end
end
return nil
end
-- Clears global state.
-- This includes cached inspected modules.
function M.clear_cache()
for k,v in pairs(M.package_loaded) do
M.package_loaded[k] = nil
end
end
-- Gets all keywords related to AST `ast`, where `top_ast` is the root of `ast`
-- and `src` is source code of `top_ast`
-- Related keywords are defined as all keywords directly associated with block containing node
-- `ast`. Furthermore, break statements are related to containing loop statements,
-- and return statements are related to containing function statement (if any).
-- function declaration syntactic sugar is handled specially too to ensure the 'function' keyword
-- is highlighted even though it may be outside of the `Function AST.
--
-- Returns token list or nil if not applicable. Returned `ast` is AST containing related keywords.
-- CATEGORY: keyword comprehension
local iskeystat = {Do=true, While=true, Repeat=true, If=true, Fornum=true, Forin=true,
Local=true, Localrec=true, Return=true, Break=true, Function=true,
Set=true -- note: Set for `function name`
}
local isloop = {While=true, Repeat=true, Fornum=true, Forin=true}
local isblock = {Do=true, While=true, Repeat=true, If=true, Fornum=true, Forin=true, Function=true}
function M.related_keywords(ast, top_ast, tokenlist, src)
-- Expand or contract AST for certain contained statements.
local more
if ast.tag == 'Return' then
-- if `return` selected, that consider containing function selected (if any)
if not ast.parent then LA.mark_parents(top_ast) end
local ancestor_ast = ast.parent
while ancestor_ast ~= nil and ancestor_ast.tag ~= 'Function' do
ancestor_ast = ancestor_ast.parent
end
if ancestor_ast then ast = ancestor_ast end -- but only change if exists
elseif ast.tag == 'Break' then
-- if `break` selected, that consider containing loop selected
if not ast.parent then LA.mark_parents(top_ast) end
local ancestor_ast = ast.parent
while ancestor_ast ~= nil and not isloop[ancestor_ast.tag] do
ancestor_ast = ancestor_ast.parent
end
ast = ancestor_ast
elseif ast.tag == 'Set' then
local val1_ast = ast[2][1]
if val1_ast.tag == 'Function' then
local token = tokenlist[LA.ast_idx_range_in_tokenlist(tokenlist, ast)]
if token.tag == 'Keyword' and token[1] == 'function' then -- function with syntactic sugar `function f`
ast = ast[2][1] -- select `Function node
else
more = true
end
else
more = true
end
elseif ast.tag == 'Localrec' and ast[2][1].tag == 'Function' then
-- if `local function f` selected, which becomes a `Localrec, consider `Function node.
ast = ast[2][1]
--IMPROVE: only contract ast if `function` part of `local function` is selected.
else
more = true
end
if more then -- not yet handled
-- Consider containing block.
if not ast.parent then LA.mark_parents(top_ast) end
local ancestor_ast = ast
while ancestor_ast ~= top_ast and not isblock[ancestor_ast.tag] do
ancestor_ast = ancestor_ast.parent
end
ast = ancestor_ast
end
-- keywords in statement/block.
if iskeystat[ast.tag] then
local keywords = {}
for i=1,#tokenlist do
local token = tokenlist[i]
if token.ast == ast and token.tag == 'Keyword' then
keywords[#keywords+1] = token
end
end
-- Expand keywords for certaining statements.
if ast.tag == 'Function' then
-- if `Function, also select 'function' and 'return' keywords
local function f(ast)
for _,cast in ipairs(ast) do
if type(cast) == 'table' then
if cast.tag == 'Return' then
local token = tokenlist[LA.ast_idx_range_in_tokenlist(tokenlist, cast)]
keywords[#keywords+1] = token
elseif cast.tag ~= 'Function' then f(cast) end
end
end
end
f(ast)
if not ast.parent then LA.mark_parents(top_ast) end
local grand_ast = ast.parent.parent
if grand_ast.tag == 'Set' then
local token = tokenlist[LA.ast_idx_range_in_tokenlist(tokenlist, grand_ast)]
if token.tag == 'Keyword' and token[1] == 'function' then
keywords[#keywords+1] = token
end
elseif grand_ast.tag == 'Localrec' then
local tidx = LA.ast_idx_range_in_tokenlist(tokenlist, grand_ast)
repeat tidx = tidx + 1 until not tokenlist[tidx] or (tokenlist[tidx].tag == 'Keyword' and tokenlist[tidx][1] == 'function')
local token = tokenlist[tidx]
keywords[#keywords+1] = token
end
elseif isloop[ast.tag] then
-- if loop, also select 'break' keywords
local function f(ast)
for _,cast in ipairs(ast) do
if type(cast) == 'table' then
if cast.tag == 'Break' then
local tidx = LA.ast_idx_range_in_tokenlist(tokenlist, cast)
keywords[#keywords+1] = tokenlist[tidx]
elseif not isloop[cast.tag] then f(cast) end
end
end
end
f(ast)
end
return keywords, ast
end
return nil, ast
end
-- Mark tokenlist (top_ast/tokenlist/src) with keywordid AST attributes.
-- All keywords related to each other have the same keyword ID integer.
-- NOTE: This is not done/undone by inspect/uninspect.
-- CATEGORY: keyword comprehension
function M.mark_related_keywords(top_ast, tokenlist, src)
local id = 0
local idof = {}
for _, token in ipairs(tokenlist) do
if token.tag == 'Keyword' and not idof[token] then
id = id + 1
local match_ast =
LA.smallest_ast_containing_range(top_ast, tokenlist, token.fpos, token.lpos)
local ktokenlist = M.related_keywords(match_ast, top_ast, tokenlist, src)
if ktokenlist then
for _, ktoken in ipairs(ktokenlist) do
ktoken.keywordid = id
idof[ktoken] = true
end
end
-- note: related_keywords may return a keyword set not containing given keyword.
end
end
end
-- function for t[k]
local function tindex(_1, _2) return _1[_2] end
local unescape = {['d'] = '.'}
-- Sets known value on ast to v if ast not pegged.
-- CATEGORY: utility function for infer_values.
local function set_value(ast, v)
if not ast.isvaluepegged then
ast.value = v
end
end
local function known(o)
return not T.istype[o]
end
local function unknown(o)
return T.istype[o]
end
-- CATEGORY: utility function for infer_values.
local function tastnewindex(t_ast, k_ast, v_ast)
if known(t_ast.value) and known(k_ast.value) and known(v_ast.value) then
local _1, _2, _3 = t_ast.value, k_ast.value, v_ast.value
if _1[_2] ~= nil and _3 ~= _1[_2] then -- multiple values
return T.universal
else
_1[_2] = _3
return _3
end
else
return T.universal
end
end
-- Gets expected number of parameters for function (min, max) values.
-- In case of vararg, max is unknown and set to nil.
local function function_param_range(ast)
local names_ast = ast[1]
if #names_ast >= 1 and names_ast[#names_ast].tag == 'Dots' then
return #names_ast-1, nil
else
return #names_ast, #names_ast
end
end
-- Gets number of arguments to function call: (min, max) range.
-- In case of trailing vararg or function call, max is unknown and set to nil.
local function call_arg_range(ast)
if ast.tag == 'Invoke' then
if #ast >= 3 and
(ast[#ast].tag == 'Dots' or ast[#ast].tag == 'Call' or ast[#ast].tag == 'Invoke')
then
return #ast-2, nil
else
return #ast-1, #ast-1
end
else
if #ast >= 2 and
(ast[#ast].tag == 'Dots' or ast[#ast].tag == 'Call' or ast[#ast].tag == 'Invoke')
then
return #ast-2, nil
else
return #ast-1, #ast-1
end
end
end
-- Reports warning. List of strings.
local function warn(report, ...)
report('warning: ' .. table.concat({...}, ' '))
end
-- Reports status messages. List of strings.
local function status(report, ...)
report('status: ' .. table.concat({...}, ' '))
end
-- unique value used to detect require loops (A require B require A)
local REQUIRE_SENTINEL = function() end
-- Gets single return value of chunk ast. Assumes ast is inspected.
local function chunk_return_value(ast)
local vinfo
if ENABLE_RETURN_ANALYSIS then
local info = M.debuginfo[ast.value]
local retvals = info and info.retvals
if retvals then
vinfo = retvals[1]
else
vinfo = T.universal
end
else
if ast[#ast] and ast[#ast].tag == 'Return' and ast[#ast][1] then
vinfo = ast[#ast][1]
else
vinfo = T.universal
end
end
return vinfo
end
-- Version of require that does source analysis (inspect) on module.
function M.require_inspect(name, report, spath)
local plinfo = M.package_loaded[name]
if plinfo == REQUIRE_SENTINEL then
warn(report, "loop in require when loading " .. name)
return nil
end
if plinfo then return plinfo[1] end
status(report, 'loading:' .. name)
M.package_loaded[name] = REQUIRE_SENTINEL -- avoid recursion on require loops
local msrc, mpath = load_module_source(name, spath)
local vinfo, mast
if msrc then
local err; mast, err = LA.ast_from_string(msrc, mpath)
if mast then
local mtokenlist = LA.ast_to_tokenlist(mast, msrc)
M.inspect(mast, mtokenlist, msrc, report)
vinfo = chunk_return_value(mast)
else
vinfo = T.error(err)
warn(report, err, " ", mpath) --Q:error printing good?
end
else
warn(report, 'module not found: ' .. name)
vinfo = T.error'module not found' --IMPROVE: include search paths?
end
M.package_loaded[name] = {vinfo, mast}
return vinfo, mast
end
-- Marks AST node and all children as dead (ast.isdead).
local function mark_dead(ast)
LA.walk(ast, function(bast) bast.isdead = true end)
end
-- Gets list of `Return statement ASTs in `Function (or chunk) f_ast, not including
-- return's in nested functions. Also returns boolean `has_implicit` indicating
-- whether function may return by exiting the function without a return statement.
-- Returns that are never exected are omitted (e.g. last return is omitted in
-- `function f() if x then return 1 else return 2 end return 3 end`).
-- Also marks AST nodes with ast.isdead (dead-code).
local function get_func_returns(f_ast)
local isalwaysreturn = {}
local returns = {}
local function f(ast, isdead)
for _,cast in ipairs(ast) do if type(cast) == 'table' then
if isdead then mark_dead(cast) end -- even if DETECT_DEADCODE disabled
if cast.tag ~= 'Function' and not isdead then -- skip nested functions
f(cast, isdead) -- depth-first traverse
end
if ast.tag ~= 'If' and isalwaysreturn[cast] then isdead = true end
-- subsequent statements in block never executed
end end
-- Code on walking up AST: propagate children to parents
if ast.tag == 'Return' then
returns[#returns+1] = ast
isalwaysreturn[ast] = true
elseif ast.tag == 'If' then
if #ast%2 ~= 0 then -- has 'else' block
local isreturn = true
for i=2,#ast do
if (i%2==0 or i==#ast) and not isalwaysreturn[ast[i]] then isreturn = nil; break end
end
isalwaysreturn[ast] = isreturn
end
else -- note: iterates not just blocks, but should be ok
for i=1,#ast do
if isalwaysreturn[ast[i]] then
isalwaysreturn[ast] = true; break
end
end
end
end
f(f_ast, false)
local block_ast = f_ast.tag == 'Function' and f_ast[2] or f_ast
local has_implicit = not isalwaysreturn[block_ast]
return returns, has_implicit
end
-- temporary hack?
local function valnode_normalize(valnode)
if valnode then
return valnode.value
else
return T.none
end
end
-- Gets return value at given return argument index, given list of `Return statements.
-- Return value is a superset of corresponding types in list of statements.
-- Example: {`Return{1,2,3}, `Return{1,3,'z'}} would return
-- 1, T.number, and T.universal for retidx 1, 2 and 3 respectively.
local function get_return_value(returns, retidx)
if #returns == 0 then return T.none
elseif #returns == 1 then
return valnode_normalize(returns[1][retidx])
else
local combined_value = valnode_normalize(returns[1][retidx])
for i=2,#returns do
local cur_value = valnode_normalize(returns[i][retidx])
combined_value = T.superset_types(combined_value, cur_value)
if combined_value == T.universal then -- can't expand set further
return combined_value
end
end
return combined_value
--TODO: handle values with possibly any number of return values, like f()
end
end
-- Gets return values (or types) on `Function (or chunk) represented by given AST.
local function get_func_return_values(f_ast)
local returns, has_implicit = get_func_returns(f_ast)
if has_implicit then returns[#returns+1] = {tag='Return'} end
local returnvals = {n=0}
for retidx=1,math.huge do
local value = get_return_value(returns, retidx)
if value == T.none then break end
returnvals[#returnvals+1] = value
returnvals.n = returnvals.n + 1
end
return returnvals
end
-- Example: AST of `function(x) if x then return 1,2,3 else return 1,3,"z" end end`
-- returns {1, T.number, T.universal}.
-- Given list of values, return the first nvalues values plus the rest of the values
-- as a tuple. Useful for things like
-- local ok, values = valuesandtuple(1, pcall(f))
-- CATEGORY: utility function (list)
local function valuesandtuple(nvalues, ...)
if nvalues >= 1 then
return (...), valuesandtuple(nvalues-1, select(2, ...))
else
return {n=select('#', ...), ...}
end
end
-- Infers values of variables. Also marks dead code (ast.isdead).
--FIX/WARNING - this probably needs more work
-- Sets top_ast.valueglobals, ast.value, ast.valueself
-- CATEGORY: code interpretation
function M.infer_values(top_ast, tokenlist, src, report)
if not top_ast.valueglobals then top_ast.valueglobals = {} end
-- infer values
LA.walk(top_ast, function(ast) -- walk down
if ast.tag == 'Function' then
local paramlist_ast = ast[1]
for i=1,#paramlist_ast do local param_ast = paramlist_ast[i]
if param_ast.value == nil then param_ast.value = T.universal end
end
end
end, function(ast) -- walk up
-- process `require` statements.
if ast.tag == 'Local' or ast.tag == 'Localrec' then
local vars_ast, values_ast = ast[1], ast[2]
local valuelist = #values_ast > 0 and values_ast[#values_ast].valuelist
for i=1,#vars_ast do
local var_ast, value_ast = vars_ast[i], values_ast[i]
local value
if value_ast then
value = value_ast.value
elseif valuelist then
local vlidx = i - #values_ast + 1
value = valuelist.sizeunknown and vlidx > valuelist.n and T.universal or valuelist[vlidx]
end
set_value(var_ast, value)
end
elseif ast.tag == 'Set' then -- note: implementation similar to 'Local'
local vars_ast, values_ast = ast[1], ast[2]
local valuelist = #values_ast > 0 and values_ast[#values_ast].valuelist
for i=1,#vars_ast do
local var_ast, value_ast = vars_ast[i], values_ast[i]
local value
if value_ast then
value = value_ast.value
elseif valuelist then
local vlidx = i - #values_ast + 1
value = valuelist.sizeunknown and vlidx > valuelist.n and T.universal or valuelist[vlidx]
end
if var_ast.tag == 'Index' then
local t_ast, k_ast = var_ast[1], var_ast[2]
if not T.istype[t_ast.value] then -- note: don't mutate types
local v_ast = {value=value}
local ok; ok, var_ast.value = pzcall(tastnewindex, {t_ast, k_ast, v_ast}, t_ast, k_ast, v_ast)
if not ok then var_ast.value = T.error(var_ast.value) end
--FIX: propagate to localdefinition?
end
else
assert(var_ast.tag == 'Id', var_ast.tag)
if var_ast.localdefinition then
set_value(var_ast, value)
else -- global
local name = var_ast[1]
top_ast.valueglobals[name] = value
end
end
--FIX: propagate to definition or localdefinition?
end
elseif ast.tag == 'Fornum' then
local var_ast = ast[1]
set_value(var_ast, T.number)
elseif ast.tag == 'Forin' then
local varlist_ast, iter_ast = ast[1], ast[2]
if #iter_ast == 1 and iter_ast[1].tag == 'Call' and iter_ast[1][1].value == ipairs then
for i, var_ast in ipairs(varlist_ast) do
if i == 1 then set_value(var_ast, T.number)
-- handle the type of the value as the type of the first element
-- in the table that is a parameter for ipairs
elseif i == 2 then
local t_ast = iter_ast[1][2]
local value = T.universal
if (known(t_ast.value) or T.istabletype[t_ast.value]) then
local ok; ok, value = pzcall(tindex, {t_ast, {tag='Number', 1}}, t_ast.value, 1)
if not ok then value = T.error(t_ast.value) end
end
set_value(var_ast, value)
else set_value(var_ast, nil) end
end
elseif #iter_ast == 1 and iter_ast[1].tag == 'Call' and iter_ast[1][1].value == pairs then
local t_ast = iter_ast[1][2]
local value = T.universal
local key
if t_ast.value and (known(t_ast.value) or T.istabletype[t_ast.value]) then
key = next(t_ast.value)
local ok; ok, value = pzcall(tindex, {t_ast, {tag='String', key}}, t_ast.value, key)
if not ok then value = T.error(t_ast.value) end
end
for i, var_ast in ipairs(varlist_ast) do
if i == 1 then set_value(var_ast, type(key))
elseif i == 2 then set_value(var_ast, value)
else set_value(var_ast, nil) end
end
else -- general case, unknown iterator
for _, var_ast in ipairs(varlist_ast) do
set_value(var_ast, T.universal)
end
end
elseif ast.tag == 'Id' then
if ast.localdefinition then
local localdefinition = ast.localdefinition
if not localdefinition.isset then -- IMPROVE: support non-const (isset false) too
set_value(ast, localdefinition.value)
end
else -- global
local name = ast[1]
local v = top_ast.valueglobals[name]
if v ~= nil then
ast.value = v
else
local ok; ok, ast.value = pzcall(tindex, {{tag='Id', '_G'}, {tag='String', name}}, _G, name)
if not ok then ast.value = T.error(ast.value) end
end
end
elseif ast.tag == 'Index' then
local t_ast, k_ast = ast[1], ast[2]
if (known(t_ast.value) or T.istabletype[t_ast.value]) and known(k_ast.value) then
local ok; ok, ast.value = pzcall(tindex, {t_ast, k_ast}, t_ast.value, k_ast.value)
if not ok then ast.value = T.error(ast.value) end
end
elseif ast.tag == 'Call' or ast.tag == 'Invoke' then
-- Determine function to call (infer via index if method call).
local isinvoke = ast.tag == 'Invoke'
if isinvoke then
local t, k = ast[1].value, ast[2].value
if known(t) and known(k) then
local ok; ok, ast.valueself = pzcall(tindex, {ast[1], ast[2]}, t, k)
if not ok then ast.valueself = T.error(ast.valueself) end
end
end
local func; if isinvoke then func = ast.valueself else func = ast[1].value end
-- Handle function call.
local argvalues_concrete = true; do -- true iff all arguments known precisely.
if #ast >= 2 then
local firstargvalue; if isinvoke then firstargvalue = ast.valueself else firstargvalue = ast[2].value end
if unknown(firstargvalue) then
argvalues_concrete = false
else -- test remaining args
for i=3,#ast do if unknown(ast[i].value) then argvalues_concrete = false; break end end
end
end
end
local found
if known(func) and argvalues_concrete then -- attempt call with concrete args
-- Get list of values of arguments.
local argvalues; do
argvalues = {n=#ast-1}; for i=1,argvalues.n do argvalues[i] = ast[i+1].value end
if isinvoke then argvalues[1] = ast.valueself end -- `self`
end
-- Any call to require is handled specially (source analysis).
if func == require and type(argvalues[1]) == 'string' then
local spath = tostring(ast.lineinfo.first):gsub('<C|','<'):match('<([^|]+)') -- a HACK? relies on AST lineinfo
local val, mast = M.require_inspect(argvalues[1], report, spath:gsub('[^\\/]+$', ''))
if known(val) and val ~= nil then
ast.value = val
found = true
end -- note: on nil value, assumes analysis failed (not found). This is a heuristic only.
if mast and mast.valueglobals then ast.valueglobals = mast.valueglobals end
end
-- Attempt call if safe.
if not found and (LS.safe_function[func] or func == pcall and LS.safe_function[argvalues[1]]) then
local ok; ok, ast.valuelist = valuesandtuple(1, pcall(func, unpack(argvalues,1,argvalues.n)))
ast.value = ast.valuelist[1]; if not ok then ast.value = T.error(ast.value) end
found = true
end
end
if not found then
-- Attempt mock function. Note: supports nonconcrete args too.
local mf = LS.mock_functions[func]
if mf then
ast.valuelist = mf.outputs; ast.value = ast.valuelist[1]
else
-- Attempt infer from return statements in function source.
local info = M.debuginfo[func]
if not info then -- try match from dynamic debug info
local dinfo = type(func) == 'function' and debug.getinfo(func)
if dinfo then
local source, linedefined = dinfo.source, dinfo.linedefined
if source and linedefined then
local sourceline = source .. ':' .. linedefined
info = M.debuginfo[sourceline]
end
end
end
local retvals = info and info.retvals
if retvals then
ast.valuelist = retvals; ast.value = ast.valuelist[1]
else
-- Could not infer.
ast.valuelist = {n=0, sizeunknown=true}; ast.value = T.universal
end
end
end
elseif ast.tag == 'String' or ast.tag == 'Number' then
ast.value = ast[1]
elseif ast.tag == 'True' or ast.tag == 'False' then
ast.value = (ast.tag == 'True')
elseif ast.tag == 'Function' or ast == top_ast then -- includes chunk
if ast.value == nil then -- avoid redefinition
local x
local val = function() x=nil end
local fpos = LA.ast_pos_range(ast, tokenlist)
local source, linenum = tostring(ast.lineinfo.first):gsub('<C|','<'):match('<([^|]+)|L(%d+)') -- a HACK? relies on AST lineinfo
local retvals
if ENABLE_RETURN_ANALYSIS then
retvals = get_func_return_values(ast) --Q:move outside of containing conditional?
end
local info = {fpos=fpos, source="@" .. source, fast=ast, tokenlist=tokenlist, retvals=retvals, top_ast = top_ast}
M.debuginfo[val] = info
local sourceline = '@' .. source .. ':' .. linenum
local oldinfo = M.debuginfo[sourceline]
if oldinfo then
if oldinfo.fast ~= ast then
-- Two functions on the same source line cannot necessarily be disambiguated.
-- Unfortuntely, Lua debuginfo lacks exact character position.
-- http://lua-users.org/lists/lua-l/2010-08/msg00273.html
-- So, just disable info if ambiguous. Note: a slight improvement is to use the lastlinedefined.
M.debuginfo[sourceline] = false
end
else
if oldinfo == nil then
M.debuginfo[sourceline] = info -- store by sourceline too for quick lookup from dynamic debug info
end -- else false (do nothing)
end
ast.value = val
ast.nocollect = info -- prevents garbage collection while ast exists
end
elseif ast.tag == 'Table' then
if ast.value == nil then -- avoid redefinition
local value = {}
local n = 1
for _,east in ipairs(ast) do
if east.tag == 'Pair' then
local kast, vast = east[1], east[2]
if known(kast.value) and known(vast.value) then
if kast.value == nil then
-- IMPROVE? warn in some way?
else
value[kast.value] = vast.value
end
end
else
if known(east.value) then
value[n] = east.value
end
n = n + 1
end
end
--table.foreach(value, print)
ast.value = value
end
elseif ast.tag == 'Paren' then
ast.value = ast[1].value
elseif ast.tag == 'Op' then
local opid, aast, bast = ast[1], ast[2], ast[3]
local ok
if bast then
ok, ast.value = pzcall(dobinop, {aast, bast}, opid, aast.value, bast.value)
else
ok, ast.value = pzcall(dounop, {aast}, opid, aast.value)
end
if not ok then ast.value = T.error(ast.value) end
elseif ast.tag == 'If' then
-- detect dead-code
if DETECT_DEADCODE then
for i=2,#ast,2 do local valnode = ast[i-1]
local bval = T.boolean_cast(valnode.value)
if bval == false then -- certainly false
mark_dead(ast[i])
elseif bval == true then -- certainly true
for ii=i+1,#ast do if ii%2 == 0 or ii==#ast then -- following blocks are dead
mark_dead(ast[ii])
end end
break
end
end
end
-- IMPROVE? `if true return end; f()` - f could be marked as deadcode
elseif ast.tag == 'While' then
-- detect dead-code
if DETECT_DEADCODE then
local expr_ast, body_ast = ast[1], ast[2]
if T.boolean_cast(expr_ast.value) == false then
mark_dead(body_ast)
end
end
end
end)
end
-- Labels variables with unique identifiers.
-- Sets ast.id, ast.resolvedname
-- CATEGORY: code interpretation
function M.mark_identifiers(ast)
local id = 0
local seen_globals = {}
LA.walk(ast, function(ast)
if ast.tag == 'Id' or ast.isfield then
if ast.localdefinition then
if ast.localdefinition == ast then -- lexical definition
id = id + 1
ast.id = id
else
ast.id = ast.localdefinition.id
end
elseif ast.isfield then
local previousid = ast.previous.id
if not previousid then -- note: ("abc"):upper() has no previous ID
id = id + 1
previousid = id
end
local name = previousid .. '.' .. ast[1]:gsub('%%', '%%'):gsub('%.', '%d')
if not seen_globals[name] then
id = id + 1
seen_globals[name] = id
end
ast.id = seen_globals[name]
-- also resolve name
local previousresolvedname = ast.previous.resolvedname
if previousresolvedname then
ast.resolvedname = previousresolvedname .. '.' .. ast[1]:gsub('%%', '%%'):gsub('%.', '%d')
end
else -- global
local name = ast[1]
if not seen_globals[name] then
id = id + 1
seen_globals[name] = id
end
ast.id = seen_globals[name]
-- also resolve name
ast.resolvedname = ast[1]
end
end
end)
end
-- Environment in which to execute special comments (see below).
local env = setmetatable({}, {__index=_G})
env.context = env
env.number = T.number
env.string = T.string
env.boolean = T.boolean
env.error = T.error
-- Applies value to all identifiers with name matching pattern.
-- This command is callable inside special comments.
-- CATEGORY: code interpretation / special comment command
function env.apply_value(pattern, val)
local function f(ast)
if ast.tag == 'Id' and ast[1]:match(pattern) then
ast.value = val; ast.isvaluepegged = true
end
for _,bast in ipairs(ast) do
if type(bast) == 'table' then
f(bast)
end
end
end
f(env.ast) -- ast from environment
--UNUSED:
-- for i=env.asti, #env.ast do
-- local bast = env.ast[i]
-- if type(bast) == 'table' then f(bast) end
--end
end
-- Evaluates all special comments (i.e. comments prefixed by '!') in code.
-- This is similar to luaanalyze.
-- CATEGORY: code interpretation / special comments
function M.eval_comments(ast, tokenlist, report)
local function eval(command, ast)
--DEBUG('!', command:gsub('%s+$', ''), ast.tag)
local f, err = COMPAT.load(command, nil, 't', env)
if f then
env.ast = ast
local ok, err = pcall(f, ast)
if not ok then warn(report, err, ': ', command) end
env.ast = nil
else
warn(report, err, ': ', command)
end
end
for idx=1,#tokenlist do
local token = tokenlist[idx]
if token.tag == 'Comment' then
local command = token[1]:match'^!(.*)'
if command then
local mast = LA.smallest_ast_containing_range(ast, tokenlist, token.fpos, token.lpos)
eval(command, mast)
end
end
end
end
--IMPROVE: in `do f() --[[!g()]] h()` only apply g to h.
-- Partially undoes effects of inspect().
-- Note: does not undo mark_tag2 and mark_parents (see replace_statements).
-- CATEGORY: code interpretation
function M.uninspect(top_ast)
-- remove ast from M.debuginfo
for k, info in pairs(M.debuginfo) do
if info and info.top_ast == top_ast then
M.debuginfo[k] = nil
end
end
-- Clean ast.
LA.walk(top_ast, function(ast)
-- undo inspect_globals.globals
ast.localdefinition = nil
ast.functionlevel = nil
ast.isparam = nil
ast.isset = nil
ast.isused = nil
ast.isignore = nil
ast.isfield = nil
ast.previous = nil
ast.localmasked = nil
ast.localmasking = nil
-- undo mark_identifiers
ast.id = nil
ast.resolvedname = nil
-- undo infer_values
ast.value = nil
ast.valueself = nil
ast.valuelist = nil
ast.isdead = nil -- via get_func_returns
ast.isvaluepegged = nil
-- undo walk setting ast.seevalue
ast.seevalue = nil
-- undo walk setting ast.definedglobal
ast.definedglobal = nil
-- undo notes
ast.note = nil
ast.nocollect = nil
-- undo infer_values
ast.valueglobals = nil
end)
end
-- Main inspection routine. Inspects top_ast/tokenlist.
-- Error/status messages are sent to function `report`.
-- CATEGORY: code interpretation
function M.inspect(top_ast, tokenlist, src, report)
--DEBUG: local t0 = os.clock()
if not report then -- compat for older version of lua-inspect
assert('inspect signature changed; please upgrade your code')
end
report = report or function() end
local globals = LG.globals(top_ast)
M.mark_identifiers(top_ast)
M.eval_comments(top_ast, tokenlist, report)
M.infer_values(top_ast, tokenlist, src, report)
M.infer_values(top_ast, tokenlist, src, report) -- two passes to handle forward declarations of globals (IMPROVE: more passes?)
-- Make some nodes as having values related to its parent.
-- This allows clicking on `bar` in `foo.bar` to display
-- the value of `foo.bar` rather than just "bar".
LA.walk(top_ast, function(ast)
if ast.tag == 'Index' then
ast[2].seevalue = ast
elseif ast.tag == 'Invoke' then
ast[2].seevalue = {value=ast.valueself, parent=ast}
end
end)
local function eval_name_helper(name)
local var = _G
for part in (name .. '.'):gmatch("([^.]*)%.") do
part = part:gsub('%%(.)', unescape)
if type(var) ~= 'table' and type(var) ~= 'userdata' then return nil end --TODO:improve?
var = var[part]
if var == nil then return nil end
end
return var
end
local function eval_name(name)
local ok, o = pzcall(eval_name_helper, {}, name)
if ok then return o else return nil end
end
LA.walk(top_ast, function(ast)
if top_ast ~= ast and ast.valueglobals then
for k in pairs(ast.valueglobals) do globals[k] = {set = ast} end
ast.valueglobals = nil
end
if ast.tag == 'Id' or ast.isfield then
local vname = ast[1]
--TODO: rename definedglobal to definedfield for clarity
local atype = ast.localdefinition and 'local' or ast.isfield and 'field' or 'global'
local definedglobal = ast.resolvedname and eval_name(ast.resolvedname) ~= nil or
atype == 'global' and (globals[vname] and globals[vname].set) or nil
ast.definedglobal = definedglobal
-- FIX: _G includes modules imported by inspect.lua, which is not desired
elseif ast.tag == 'Call' or ast.tag == 'Invoke' then
-- Argument count check.
local value = ast.valueself or ast[1].value
local info = M.debuginfo[value]
local fast = info and info.fast
if fast or LS.argument_counts[value] then
local nparammin, nparammax
if fast then
nparammin, nparammax = function_param_range(info.fast)
else
nparammin, nparammax = unpack(LS.argument_counts[value])
end
local nargmin, nargmax = call_arg_range(ast)
--print('DEBUG:', nparammin, nparammax, nargmin, nargmax)
local iswarn
local target_ast = ast.tag == 'Call' and ast[1] or ast[2]
if (nargmax or math.huge) < nparammin then
ast.note = "Too few arguments; "
iswarn = true
elseif nargmin > (nparammax or math.huge) then
ast.note = "Too many arguments; "
iswarn = true
end
if iswarn then
ast.note = ast.note .. "expected "
.. nparammin .. (nparammax == nparammin and "" or " to " .. (nparammax or "infinity"))
.. " but got "
.. nargmin .. (nargmax == nargmin and "" or " to " .. (nargmax or "infinity")) .. "."
end
end
end
end)
end
-- Resolves identifier to value [*]
function M.resolve_id(id, scope, valueglobals, _G)
local val
if scope[id] then
val = scope[id].value
elseif valueglobals[id] ~= nil then
val = valueglobals[id]
else
val = _G[id] -- assumes not raise
end
return val
end
-- Resolves prefix chain expression to value. [*]
-- On error returns nil and error object
function M.resolve_prefixexp(ids, scope, valueglobals, _G)
local _1 = M.resolve_id(ids[1], scope, valueglobals, _G)
local ok, err = pzcall(function()
for i=2,#ids do
_1 = _1[ids[i]]
end
end, {})
if err then return nil, err or '?' end
return _1
end
-- Gets local scope at given 1-indexed char position
function M.get_scope(pos1, ast, tokenlist)
local mast, isafter = LA.current_statementblock(ast, tokenlist, pos1)
local scope = LG.variables_in_scope(mast, isafter)
return scope
end
-- Gets names in prefix expression ids (as returned by resolve_prefixexp). [*]
function M.names_in_prefixexp(ids, pos, ast, tokenlist)
local scope = M.get_scope(pos, ast, tokenlist)
--FIX: above does not handle `for x=1,2 do| print(x) end` where '|' is cursor position.
local names = {}
if #ids == 0 then -- global
for name in pairs(scope) do names[#names+1] = name end
for name in pairs(ast.valueglobals) do names[#names+1] = name end
for name in pairs(_G) do names[#names+1] = name end
else -- field
local t, err_ = M.resolve_prefixexp(ids, scope, ast.valueglobals, _G)
if type(t) == 'table' then -- note: err_ implies false here
for name in pairs(t) do names[#names+1] = name end
end
end
return names
end
-- Gets signature (function argument string or helpinfo string) on value.
-- Returns nil on not found.
function M.get_signature_of_value(value)
local info = M.debuginfo[value] -- first try this
if info and info.fast then
local fidx, lidx = LA.ast_idx_range_in_tokenlist(info.tokenlist, info.fast[1])
local ts = {}
if fidx then
for i=fidx,lidx do
local token = info.tokenlist[i]
ts[#ts+1] = token.tag == 'Dots' and '...' or token[1]
end
end
local sig = 'function(' .. table.concat(ts, ' ') .. ')'
if info.retvals then
local vals = info.retvals
local ts = {}
if vals.n == 0 then
sig = sig .. " no returns"
else
for i=1,vals.n do local val = vals[i]
ts[#ts+1] = T.istype[val] and tostring(val) or LD.dumpstring(val) --Q:dumpstring too verbose?
end
sig = sig .. " returns " .. table.concat(ts, ", ")
end
end
return sig
end
local sig = LS.value_signatures[value] -- else try this
return sig
end
-- Gets signature (function argument string or helpinfo string) on variable ast.
-- Returns nil on not found.
function M.get_signature(ast)
if known(ast.value) then
return M.get_signature_of_value(ast.value)
end
end
-- Gets 1-indexed character (or line) position and filename of
-- definition associated with AST node (if any).
function M.ast_to_definition_position(ast, tokenlist)
local local_ast = ast.localdefinition
local fpos, fline, path
if local_ast then
local tidx = LA.ast_idx_range_in_tokenlist(tokenlist, local_ast)
if tidx then
local spath = tostring(ast.lineinfo.first):gsub('<C|','<'):match('<([^|]+)') -- a HACK? using lineinfo
fpos = tokenlist[tidx].fpos; path = spath
end
end
if not fpos then
local valueast = ast.seevalue or ast
local val = valueast and valueast.value
local info = M.debuginfo[val] or type(val) == 'function' and debug.getinfo(val)
if info then
if info.source:match'^@' then
path = info.source:match'@(.*)'
if info.linedefined then
fline = info.linedefined
else
fpos = info.fpos
end
end
end
end
return fpos, fline, path
end
-- Returns true iff value in ast node is known in some way.
function M.is_known_value(ast)
local vast = ast.seevalue or ast
return vast.definedglobal or known(vast.value) and vast.value ~= nil
end
-- Gets list of variable attributes for AST node.
function M.get_var_attributes(ast)
local vast = ast.seevalue or ast
local attributes = {}
if ast.localdefinition then
attributes[#attributes+1] = "local"
if ast.localdefinition.functionlevel < ast.functionlevel then
attributes[#attributes+1] = 'upvalue'
end
if ast.localdefinition.isparam then
attributes[#attributes+1] = "param"
end
if not ast.localdefinition.isused then attributes[#attributes+1] = 'unused' end
if ast.isignore then attributes[#attributes+1] = 'ignore' end
if ast.localdefinition.isset then attributes[#attributes+1] = 'mutatebind'
else attributes[#attributes+1] = 'constbind' end
if ast.localmasking then
attributes[#attributes+1] = "masking"
end
if ast.localmasked then
attributes[#attributes+1] = "masked"
end
elseif ast.tag == 'Id' then -- global
attributes[#attributes+1] = (M.is_known_value(vast) and "known" or "unknown")
attributes[#attributes+1] = "global"
elseif ast.isfield then
attributes[#attributes+1] = (M.is_known_value(vast) and "known" or "unknown")
attributes[#attributes+1] = "field"
else
attributes[#attributes+1] = "FIX" -- shouldn't happen?
end
if vast.parent and (vast.parent.tag == 'Call' or vast.parent.tag == 'Invoke')
and vast.parent.note
then
attributes[#attributes+1] = 'warn'
end
return attributes
end
-- Gets detailed information about value in AST node, as string.
function M.get_value_details(ast, tokenlist, src)
local lines = {}
if not ast then return '?' end
local vast = ast.seevalue or ast
lines[#lines+1] = "attributes: " .. table.concat(M.get_var_attributes(ast), " ")
lines[#lines+1] = "value: " .. tostring(vast.value)
local sig = M.get_signature(vast)
if sig then
local kind = sig:find '%w%s*%b()$' and 'signature' or 'description'
lines[#lines+1] = kind .. ": " .. sig
end
local fpos, fline, path = M.ast_to_definition_position(ast, tokenlist)
if fpos or fline then
local fcol
if fpos then
fline, fcol = LA.pos_to_linecol(fpos, src)
end
local location = path .. ":" .. (fline) .. (fcol and ":" .. fcol or "")
lines[#lines+1] = "location defined: " .. location
end
if ast.localdefinition and ast.localmasking then
local fpos = LA.ast_pos_range(ast.localmasking, tokenlist)
if fpos then
local linenum = LA.pos_to_linecol(fpos, src)
lines[#lines+1] = "masking definition at line: " .. linenum
end
end
-- Render warning notes attached to calls/invokes.
local note = vast.parent and (vast.parent.tag == 'Call' or vast.parent.tag == 'Invoke')
and vast.parent.note
if note then
lines[#lines+1] = "WARNING: " .. note
end
return table.concat(lines, "\n")
end
-- Gets list of all warnings, as strings.
-- In HTML Tidy format (which supports column numbers in SciTE, although is
-- slightly verbose and lacks filename).
function M.list_warnings(tokenlist, src)
local warnings = {}
local ttoken
local function warn(msg)
local linenum, colnum = LA.pos_to_linecol(ttoken.fpos, src)
warnings[#warnings+1] = "line " .. linenum .. " column " .. colnum .. " - " .. msg
end
local isseen = {}
for i,token in ipairs(tokenlist) do ttoken = token
if token.ast then
local ast = token.ast
if ast.localmasking then
local pos = LA.ast_pos_range(ast.localmasking, tokenlist)
local linenum = pos and LA.pos_to_linecol(pos, src)
warn("local " .. ast[1] .. " masks another local" .. (pos and " on line " .. linenum or ""))
end
if ast.localdefinition == ast and not ast.isused and not ast.isignore then
warn("unused local " .. ast[1])
end
if ast.isfield and not(known(ast.seevalue.value) and ast.seevalue.value ~= nil) then
warn("unknown field " .. ast[1])
elseif ast.tag == 'Id' and not ast.localdefinition and not ast.definedglobal then
warn("unknown global " .. ast[1])
end
local vast = ast.seevalue or ast
local note = vast.parent and (vast.parent.tag == 'Call' or vast.parent.tag == 'Invoke')
and vast.parent.note
if note and not isseen[vast.parent] then
isseen[vast.parent] = true
local esrc = LA.ast_to_text(vast.parent, tokenlist, src)
-- IMPROVE: large items like `f(function() ... end)` may be shortened.
warn(note .. (esrc and "for " .. esrc or ""))
end
end
end
return warnings
end
return M
| apache-2.0 |
geanux/darkstar | scripts/zones/Port_Bastok/npcs/Kurando.lua | 38 | 2161 | -----------------------------------
-- Area: Port Bastok
-- NPC: Kurando
-- Type: Quest Giver
-- @zone: 236
-- @pos -23.887 3.898 0.870
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_Bastok/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/titles");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(BASTOK,FEAR_OF_FLYING) == QUEST_ACCEPTED) then
if (trade:hasItemQty(4526,1) and trade:getItemCount() == 1) then
player:startEvent(0x00AB); -- Quest Completion Dialogue
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local FearofFlying = player:getQuestStatus(BASTOK,FEAR_OF_FLYING);
-- csid 0x00Ad ?
if (FearofFlying == QUEST_AVAILABLE and player:getFameLevel(BASTOK) >=3) then
player:startEvent(0x00AA); -- Quest Start Dialogue
elseif (FearofFlying == QUEST_COMPLETED) then
player:startEvent(0x00AC); -- Dialogue after Completion
else
player:startEvent(0x001c); -- Default Dialogue
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00AA) then
player:addQuest(BASTOK,FEAR_OF_FLYING);
elseif (csid == 0x00AB) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13113);
else
player:tradeComplete();
player:addItem(13113,1);
player:messageSpecial(ITEM_OBTAINED,13113);
player:setTitle(AIRSHIP_DENOUNCER);
player:completeQuest(BASTOK,FEAR_OF_FLYING);
player:addFame(BASTOK,BAS_FAME*30);
end
end
end; | gpl-3.0 |
geanux/darkstar | scripts/globals/items/bowl_of_tender_navarin.lua | 35 | 1884 | -----------------------------------------
-- ID: 4284
-- Item: Bowl of Tender Navarin
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Health % 3
-- Strength 3
-- Agility 1
-- Vitality 1
-- Intelligence -1
-- Attack % 27
-- Attack Cap 35
-- Evasion 6
-- Ranged ATT % 27
-- Ranged ATT Cap 35
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,4284);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HPP, 3);
target:addMod(MOD_STR, 3);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_VIT, 1);
target:addMod(MOD_INT, -1);
target:addMod(MOD_FOOD_ATTP, 27);
target:addMod(MOD_FOOD_ATT_CAP, 35);
target:addMod(MOD_EVA, 6);
target:addMod(MOD_FOOD_RATTP, 27);
target:addMod(MOD_FOOD_RATT_CAP, 35);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HPP, 3);
target:delMod(MOD_STR, 3);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_VIT, 1);
target:delMod(MOD_INT, -1);
target:delMod(MOD_FOOD_ATTP, 27);
target:delMod(MOD_FOOD_ATT_CAP, 35);
target:delMod(MOD_EVA, 6);
target:delMod(MOD_FOOD_RATTP, 27);
target:delMod(MOD_FOOD_RATT_CAP, 35);
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/Port_Jeuno/npcs/Chudigrimane.lua | 29 | 1189 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Chudigrimane
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local vHour = VanadielHour();
local vMin = VanadielMinute();
while vHour >= 6 do
vHour = vHour - 6;
end
local seconds = math.floor(2.4 * ((vHour * 60) + vMin));
player:startEvent( 0x0006, seconds, 0, 0, 0, 0, 0, 0, 0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/Grand_Palace_of_HuXzoi/Zone.lua | 19 | 4371 | -----------------------------------
--
-- Zone: Grand_Palace_of_HuXzoi (34)
--
-----------------------------------
package.loaded["scripts/zones/Grand_Palace_of_HuXzoi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Grand_Palace_of_HuXzoi/TextIDs");
require("scripts/zones/Grand_Palace_of_HuXzoi/MobIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
zone:registerRegion(1, -102, -4, 541, -97, 4, 546); -- elvaan tower L-6 52??
zone:registerRegion(2, 737, -4, 541, 742, 4, 546); -- elvaan tower L-6 52??
zone:registerRegion(3, 661, -4, 87, 667, 4, 103);
zone:registerRegion(4, -178, -4, 97, -173, 4, 103);
zone:registerRegion(5, 340, -4, 97, 347, 4, 102);
zone:registerRegion(6, -497, -4, 97, -492, 4, 102);
zone:registerRegion(7, 97, -4, 372, 103, 4, 378);
zone:registerRegion(8, -742, -4, 372, -736, 4, 379);
zone:registerRegion(9, 332, -4, 696, 338, 4, 702);
zone:registerRegion(10, -507, -4, 697, -501, 4, 702);
-- Give Temperance a random PH
local JoT_PH = math.random(1,5);
SetServerVariable("[SEA]Jailer_of_Temperance_PH", Jailer_of_Temperance_PH[JoT_PH]);
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-20,-1.5,-355.482,192);
end
player:setVar("Hu-Xzoi-TP",0);
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
if (player:getVar("Hu-Xzoi-TP") == 0 and player:getAnimation() == 0) then -- prevent 2cs at same time
switch (region:GetRegionID()): caseof
{
[1] = function (x) player:startEvent(0x0097); end,
[2] = function (x) player:startEvent(0x009c); end,
[3] = function (x) player:startEvent(0x009D); end,
[4] = function (x) player:startEvent(0x0098); end,
[5] = function (x) player:startEvent(0x009E); end,
[6] = function (x) player:startEvent(0x0099); end,
[7] = function (x) player:startEvent(0x009F); end,
[8] = function (x) player:startEvent(0x009A); end,
[9] = function (x) player:startEvent(0x009B); end,
[10] = function (x) player:startEvent(0x0096); end,
}
end
end;
-----------------------------------
-- onRegionLeave
-----------------------------------
function onRegionLeave(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid >0x0095 and csid < 0x00A0) then
player:setVar("Hu-Xzoi-TP",1);
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid >0x0095 and csid < 0x00A0) then
player:setVar("Hu-Xzoi-TP",0);
end
end;
-----------------------------------
-- onGameHour
-----------------------------------
function onGameHour(npc, mob, player)
local VanadielHour = VanadielHour();
if (VanadielHour % 6 == 0) then -- Change the Jailer of Temperance PH every 6 hours (~15 mins).
JoT_ToD = GetServerVariable("[SEA]Jailer_of_Temperance_POP");
if (GetMobAction(Jailer_of_Temperance) == 0 and JoT_ToD <= os.time(t)) then -- Don't want to set a PH if it's already up; also making sure it's been 15 mins since it died last
local JoT_PH = math.random(1,5);
SetServerVariable("[SEA]Jailer_of_Temperance_PH", Jailer_of_Temperance_PH[JoT_PH]);
end
end
end; | gpl-3.0 |
geanux/darkstar | scripts/zones/Northern_San_dOria/npcs/Chasalvige.lua | 19 | 1712 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Chasalvige
-- Type: Standard Info NPC
-- Involved in Mission: The Road Forks
-- Involved in Mission: Promathia Mission 5 - Three Paths
-- @zone: 231
-- @pos 96.432 -0.520 134.046
--
-----------------------------------
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("EMERALD_WATERS_Status") == 3) then
player:startEvent(0x0026); --COP event
elseif (player:getCurrentMission(COP) == THE_ENDURING_TUMULT_OF_WAR and player:getVar("COP_optional_CS_chasalvigne") == 0) then
player:startEvent(0x02F9);
elseif (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") == 2) then
player:startEvent(0x02FA);
else
player:startEvent(0x0006);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0026) then
player:setVar("EMERALD_WATERS_Status",4);
elseif (csid == 0x02F9) then
player:setVar("COP_optional_CS_chasalvigne",1);
elseif (csid == 0x02FA) then
player:setVar("COP_Ulmia_s_Path",3);
end
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/North_Gustaberg/npcs/Shigezane_IM.lua | 28 | 3150 | -----------------------------------
-- Area: North Gustaberg
-- NPC: Shigezane, I.M.
-- Type: Outpost Conquest Guards
-- @pos -584.687 39.107 54.281 106
-------------------------------------
package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/conquest");
require("scripts/zones/North_Gustaberg/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = GUSTABERG;
local csid = 0x7ff9;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
Greentwip/CodyCobain | src/app/objects/characters/enemies/sheriff/jetbird.lua | 1 | 1734 | -- Copyright 2014-2015 Greentwip. All Rights Reserved.
local enemy = import("app.objects.characters.enemies.base.enemy")
local mob = class("jetbird", enemy)
function mob:onCreate()
self.super:onCreate()
self.movement_is_non_blockable_ = true
self.default_health_ = 2
self.shooting_ = false
self.moving_ = false
self.orientation_set_ = false
end
function mob:animate(cname)
local fly = {name = "fly", animation = {name = cname .. "_" .. "fly", forever = true, delay = 0.10} }
self.sprite_:load_action(fly, false)
self.sprite_:set_animation(fly.animation.name)
return self
end
function mob:onRespawn()
self.shooting_ = false
self.moving_ = false
self.orientation_set_ = false
self.current_speed_.x = 0
end
function mob:flip(x_normal)
if not self.orientation_set_ then
if x_normal == 1 and self.current_speed_.x > 0 then
self.orientation_set_ = true
self.sprite_:setFlippedX(true)
elseif x_normal == -1 and self.current_speed_.x < 0 then
self.orientation_set_ = true
self.sprite_:setFlippedX(false)
end
end
self.is_flipping_ = false
end
function mob:walk()
if not self.moving_ then
self.moving_ = true
if self.player_:getPositionX() >= self:getPositionX() then
self.current_speed_.x = self.walk_speed_
else
self.current_speed_.x = -self.walk_speed_
end
end
end
function mob:jump()
self.current_speed_.y = 0
end
function mob:attack()
if self.status_ == cc.enemy_.status_.fighting_ and not self.is_flipping_ and not self.shooting_ then
-- this enemy throws projectiles
end
end
return mob | gpl-3.0 |
371816210/vlc_vlc | share/lua/playlist/anevia_streams.lua | 112 | 3664 | --[[
$Id$
Parse list of available streams on Anevia Toucan servers.
The URI http://ipaddress:554/list_streams.idp describes a list of
available streams on the server.
Copyright © 2009 M2X BV
Authors: Jean-Paul Saman <jpsaman@videolan.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "list_streams.idp" )
end
-- Parse function.
function parse()
p = {}
_,_,server = string.find( vlc.path, "(.*)/list_streams.idp" )
while true do
line = vlc.readline()
if not line then break end
if string.match( line, "<streams[-]list> </stream[-]list>" ) then
break
elseif string.match( line, "<streams[-]list xmlns=\"(.*)\">" ) then
while true do
line = vlc.readline()
if not line then break end
if string.match( line, "<streamer name=\"(.*)\"> </streamer>" ) then
break;
elseif string.match( line, "<streamer name=\"(.*)\">" ) then
_,_,streamer = string.find( line, "name=\"(.*)\"" )
while true do
line = vlc.readline()
if not line then break end
-- ignore <host name=".." /> tags
-- ignore <port number=".." /> tags
if string.match( line, "<input name=\"(.*)\">" ) then
_,_,path = string.find( line, "name=\"(.*)\"" )
while true do
line = vlc.readline()
if not line then break end
if string.match( line, "<stream id=\"(.*)\" />" ) then
_,_,media = string.find( line, "id=\"(.*)\"" )
video = "rtsp://" .. tostring(server) .. "/" .. tostring(path) .. "/" .. tostring(media)
vlc.msg.dbg( "adding to playlist " .. tostring(video) )
table.insert( p, { path = video; name = media, url = video } )
end
-- end of input tag found
if string.match( line, "</input>" ) then
break
end
end
end
end
if not line then break end
-- end of streamer tag found
if string.match( line, "</streamer>" ) then
break
end
end
if not line then break end
-- end of streams-list tag found
if string.match( line, "</streams-list>" ) then
break
end
end
end
end
return p
end
| gpl-2.0 |
geanux/darkstar | scripts/globals/abilities/pets/frost_breath.lua | 25 | 1248 | ---------------------------------------------------
-- Frost Breath
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill, master)
---------- Deep Breathing ----------
-- 0 for none
-- 1 for first merit
-- 0.25 for each merit after the first
-- TODO: 0.1 per merit for augmented AF2 (10663 *w/ augment*)
local deep = 1;
if (pet:hasStatusEffect(EFFECT_MAGIC_ATK_BOOST) == true) then
deep = deep + 1 + (master:getMerit(MERIT_DEEP_BREATHING)-1)*0.25;
pet:delStatusEffect(EFFECT_MAGIC_ATK_BOOST);
end
local gear = master:getMod(MOD_WYVERN_BREATH)/256; -- Master gear that enhances breath
local dmgmod = MobBreathMove(pet, target, 0.185, pet:getMainLvl()*15, ELE_ICE); -- Works out to (hp/6) + 15, as desired
dmgmod = (dmgmod * (1+gear))*deep;
local dmg = MobFinalAdjustments(dmgmod,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_ICE,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end | gpl-3.0 |
mohammadclashclash/elll2014 | plugins/bugzilla.lua | 611 | 3983 | do
local BASE_URL = "https://bugzilla.mozilla.org/rest/"
local function bugzilla_login()
local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password
print("accessing " .. url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_check(id)
-- data = bugzilla_login()
local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey
-- print(url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_listopened(email)
local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey
local res,code = https.request( url )
print(res)
local data = json:decode(res)
return data
end
local function run(msg, matches)
local response = ""
if matches[1] == "status" then
local data = bugzilla_check(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
response = response .. "\n Last update: "..data.bugs[1].last_change_time
response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
print(response)
end
elseif matches[1] == "list" then
local data = bugzilla_listopened(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
-- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
-- response = response .. "\n Last update: "..data.bugs[1].last_change_time
-- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
-- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
-- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
local total = table.map_length(data.bugs)
print("total bugs: " .. total)
local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2]
if total > 0 then
response = response .. ": "
for tableKey, bug in pairs(data.bugs) do
response = response .. "\n #" .. bug.id
response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution
response = response .. "\n Whiteboard: " .. bug.whiteboard
response = response .. "\n Summary: " .. bug.summary
end
end
end
end
return response
end
-- (table)
-- [bugs] = (table)
-- [1] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 927704
-- [whiteboard] = (string) [approved][full processed]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/
-- [2] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 1049337
-- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/
-- total bugs: 2
return {
description = "Lookup bugzilla status update",
usage = "/bot bugzilla [bug number]",
patterns = {
"^/bugzilla (status) (.*)$",
"^/bugzilla (list) (.*)$"
},
run = run
}
end | gpl-2.0 |
xeranas/happy_weather | light_rain.lua | 1 | 3214 | ------------------------------
-- Happy Weather: Light Rain
-- License: MIT
-- Credits: xeranas
------------------------------
local light_rain = {}
-- Weather identification code
light_rain.code = "light_rain"
-- Keeps sound handler references
local sound_handlers = {}
-- Manual triggers flags
local manual_trigger_start = false
local manual_trigger_end = false
-- Skycolor layer id
local SKYCOLOR_LAYER = "happy_weather_light_rain_sky"
light_rain.is_starting = function(dtime, position)
if manual_trigger_start then
manual_trigger_start = false
return true
end
return false
end
light_rain.is_ending = function(dtime)
if manual_trigger_end then
manual_trigger_end = false
return true
end
return false
end
local set_sky_box = function(player_name)
local sl = {}
sl.name = SKYCOLOR_LAYER
sl.clouds_data = {
gradient_colors = {
{r=50, g=50, b=50},
{r=120, g=120, b=120},
{r=200, g=200, b=200},
{r=120, g=120, b=120},
{r=50, g=50, b=50}
},
density = 0.6
}
skylayer.add_layer(player_name, sl)
end
local set_rain_sound = function(player)
return minetest.sound_play("light_rain_drop", {
object = player,
max_hear_distance = 2,
loop = true,
})
end
local remove_rain_sound = function(player)
local sound = sound_handlers[player:get_player_name()]
if sound ~= nil then
minetest.sound_stop(sound)
sound_handlers[player:get_player_name()] = nil
end
end
light_rain.add_player = function(player)
sound_handlers[player:get_player_name()] = set_rain_sound(player)
set_sky_box(player:get_player_name())
end
light_rain.remove_player = function(player)
remove_rain_sound(player)
skylayer.remove_layer(player:get_player_name(), SKYCOLOR_LAYER)
end
-- Random texture getter
local choice_random_rain_drop_texture = function()
local texture_name
local random_number = math.random()
if random_number > 0.33 then
texture_name = "happy_weather_light_rain_raindrop_1.png"
elseif random_number > 0.66 then
texture_name = "happy_weather_light_rain_raindrop_2.png"
else
texture_name = "happy_weather_light_rain_raindrop_3.png"
end
return texture_name;
end
local add_rain_particle = function(player)
local offset = {
front = 5,
back = 2,
top = 4
}
local random_pos = hw_utils.get_random_pos(player, offset)
if hw_utils.is_outdoor(random_pos) then
minetest.add_particle({
pos = {x=random_pos.x, y=random_pos.y, z=random_pos.z},
velocity = {x=0, y=-10, z=0},
acceleration = {x=0, y=-30, z=0},
expirationtime = 2,
size = math.random(0.5, 3),
collisiondetection = true,
collision_removal = true,
vertical = true,
texture = choice_random_rain_drop_texture(),
playername = player:get_player_name()
})
end
end
local display_rain_particles = function(player)
if hw_utils.is_underwater(player) then
return
end
add_rain_particle(player)
end
light_rain.in_area = function(position)
if position.y > -10 then
return true
end
return false
end
light_rain.render = function(dtime, player)
display_rain_particles(player)
end
light_rain.start = function()
manual_trigger_start = true
end
light_rain.stop = function()
manual_trigger_end = true
end
happy_weather.register_weather(light_rain) | mit |
geanux/darkstar | scripts/zones/Gusgen_Mines/Zone.lua | 30 | 1811 | -----------------------------------
--
-- Zone: Gusgen_Mines (196)
--
-----------------------------------
package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil;
----------------------------------
require("scripts/globals/settings");
require("scripts/globals/zone");
require("scripts/zones/Gusgen_Mines/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local tomes = {17580412,17580413,17580414};
SetGroundsTome(tomes);
UpdateTreasureSpawnPoint(17580399);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(100.007,-61.63,-237.441,187);
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
tonylauCN/tutorials | openresty/debugger/lualibs/ssl.lua | 3 | 5220 | ------------------------------------------------------------------------------
-- LuaSec 0.6
-- Copyright (C) 2006-2016 Bruno Silvestre
--
------------------------------------------------------------------------------
if package.config:sub(1,1) == "\\" then -- Windows only
-- this hack is needed because OpenSSL libraries may be available elsewhere
-- in PATH and un/loading them may lead to crashes in the application.
-- loading them using the full path ensures that the right versions are un/loaded.
-- don't need to request any function as only need to load libraries. -- PK
local bindir = debug.getinfo(1,'S').source:gsub("[^/\\]+$",""):gsub("^@","").."../bin/"
package.loadlib(bindir.."libeay32.dll", "")
package.loadlib(bindir.."ssleay32.dll", "")
end
local core = require("ssl.core")
local context = require("ssl.context")
local x509 = require("ssl.x509")
local unpack = table.unpack or unpack
-- We must prevent the contexts to be collected before the connections,
-- otherwise the C registry will be cleared.
local registry = setmetatable({}, {__mode="k"})
--
--
--
local function optexec(func, param, ctx)
if param then
if type(param) == "table" then
return func(ctx, unpack(param))
else
return func(ctx, param)
end
end
return true
end
--
--
--
local function newcontext(cfg)
local succ, msg, ctx
-- Create the context
ctx, msg = context.create(cfg.protocol)
if not ctx then return nil, msg end
-- Mode
succ, msg = context.setmode(ctx, cfg.mode)
if not succ then return nil, msg end
-- Load the key
if cfg.key then
if cfg.password and
type(cfg.password) ~= "function" and
type(cfg.password) ~= "string"
then
return nil, "invalid password type"
end
succ, msg = context.loadkey(ctx, cfg.key, cfg.password)
if not succ then return nil, msg end
end
-- Load the certificate
if cfg.certificate then
succ, msg = context.loadcert(ctx, cfg.certificate)
if not succ then return nil, msg end
if cfg.key and context.checkkey then
succ = context.checkkey(ctx)
if not succ then return nil, "private key does not match public key" end
end
end
-- Load the CA certificates
if cfg.cafile or cfg.capath then
succ, msg = context.locations(ctx, cfg.cafile, cfg.capath)
if not succ then return nil, msg end
end
-- Set SSL ciphers
if cfg.ciphers then
succ, msg = context.setcipher(ctx, cfg.ciphers)
if not succ then return nil, msg end
end
-- Set the verification options
succ, msg = optexec(context.setverify, cfg.verify, ctx)
if not succ then return nil, msg end
-- Set SSL options
succ, msg = optexec(context.setoptions, cfg.options, ctx)
if not succ then return nil, msg end
-- Set the depth for certificate verification
if cfg.depth then
succ, msg = context.setdepth(ctx, cfg.depth)
if not succ then return nil, msg end
end
-- NOTE: Setting DH parameters and elliptic curves needs to come after
-- setoptions(), in case the user has specified the single_{dh,ecdh}_use
-- options.
-- Set DH parameters
if cfg.dhparam then
if type(cfg.dhparam) ~= "function" then
return nil, "invalid DH parameter type"
end
context.setdhparam(ctx, cfg.dhparam)
end
-- Set elliptic curve
if cfg.curve then
succ, msg = context.setcurve(ctx, cfg.curve)
if not succ then return nil, msg end
end
-- Set extra verification options
if cfg.verifyext and ctx.setverifyext then
succ, msg = optexec(ctx.setverifyext, cfg.verifyext, ctx)
if not succ then return nil, msg end
end
return ctx
end
--
--
--
local function wrap(sock, cfg)
local ctx, msg
if type(cfg) == "table" then
ctx, msg = newcontext(cfg)
if not ctx then return nil, msg end
else
ctx = cfg
end
local s, msg = core.create(ctx)
if s then
core.setfd(s, sock:getfd())
sock:setfd(-1)
registry[s] = ctx
return s
end
return nil, msg
end
--
-- Extract connection information.
--
local function info(ssl, field)
local str, comp, err, protocol
comp, err = core.compression(ssl)
if err then
return comp, err
end
-- Avoid parser
if field == "compression" then
return comp
end
local info = {compression = comp}
str, info.bits, info.algbits, protocol = core.info(ssl)
if str then
info.cipher, info.protocol, info.key,
info.authentication, info.encryption, info.mac =
string.match(str,
"^(%S+)%s+(%S+)%s+Kx=(%S+)%s+Au=(%S+)%s+Enc=(%S+)%s+Mac=(%S+)")
info.export = (string.match(str, "%sexport%s*$") ~= nil)
end
if protocol then
info.protocol = protocol
end
if field then
return info[field]
end
-- Empty?
return ( (next(info)) and info )
end
--
-- Set method for SSL connections.
--
core.setmethod("info", info)
--------------------------------------------------------------------------------
-- Export module
--
local _M = {
_VERSION = "0.6",
_COPYRIGHT = core.copyright(),
loadcertificate = x509.load,
newcontext = newcontext,
wrap = wrap,
}
return _M
| apache-2.0 |
geanux/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Hagakoff.lua | 34 | 1998 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Hagakoff
-- Standard Merchant NPC
-- Partitionally Implemented
-- Difficult Shop Script needed
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,HAGAKOFF_SHOP_DIALOG);
stock = {0x400f,15448, -- Katars (Not available if beastmen have the AC.)
0x4010,67760, -- Darksteel Katars
0x4023,45760, -- Patas (Not available if beastmen have the AC.)
0x4040,156, -- Bronze Dagger
0x4042,2030, -- Dagger
0x40a7,776, -- Sapara
0x40a8,4525, -- Scimitar
0x40a9,38800, -- Tulwar (Not available if beastmen have the AC.)
0x4111,6600, -- Tabar
0x4112,124305, -- Darksteel Tabar (Not available if beastmen have the AC.)
0x4140,672, -- Butterfly Axe
0x4141,4550, -- Greataxe (Not available if beastmen have the AC.)
0x4180,344, -- Bronze Zaghnal
0x4182,12540, -- Zaghnal (Not available if beastmen have the AC.)
0x4280,72, -- Ash Club
0x4281,1740, -- Chestnut Club (Not available if beastmen have the AC.)
0x4753,238} -- Angon
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
mirkix/ardupilot | libraries/AP_Scripting/examples/plane_guided_follow.lua | 8 | 3624 | -- support follow in GUIDED mode in plane
local PARAM_TABLE_KEY = 11
local PARAM_TABLE_PREFIX = "GFOLL_"
local MODE_MANUAL = 0
local MODE_GUIDED = 15
local ALT_FRAME_ABSOLUTE = 0
-- bind a parameter to a variable
function bind_param(name)
local p = Parameter()
assert(p:init(name), string.format('could not find %s parameter', name))
return p
end
-- add a parameter and bind it to a variable
function bind_add_param(name, idx, default_value)
assert(param:add_param(PARAM_TABLE_KEY, idx, name, default_value), string.format('could not add param %s', name))
return bind_param(PARAM_TABLE_PREFIX .. name)
end
-- setup SHIP specific parameters
assert(param:add_table(PARAM_TABLE_KEY, PARAM_TABLE_PREFIX, 3), 'could not add param table')
GFOLL_ENABLE = bind_add_param('ENABLE', 1, 0)
-- current target
local target_pos = Location()
local current_pos = Location()
local target_velocity = Vector3f()
local target_heading = 0.0
-- other state
local vehicle_mode = MODE_MANUAL
local have_target = false
-- check key parameters
function check_parameters()
--[[
parameter values which are auto-set on startup
--]]
local key_params = {
FOLL_ENABLE = 1,
FOLL_OFS_TYPE = 1,
FOLL_ALT_TYPE = 0,
}
for p, v in pairs(key_params) do
local current = param:get(p)
assert(current, string.format("Parameter %s not found", p))
if math.abs(v-current) > 0.001 then
param:set_and_save(p, v)
gcs:send_text(0,string.format("Parameter %s set to %.2f was %.2f", p, v, current))
end
end
end
function wrap_360(angle)
local res = math.fmod(angle, 360.0)
if res < 0 then
res = res + 360.0
end
return res
end
function wrap_180(angle)
local res = wrap_360(angle)
if res > 180 then
res = res - 360
end
return res
end
-- update target state
function update_target()
if not follow:have_target() then
if have_target then
gcs:send_text(0,"Lost beacon")
end
have_target = false
return
end
if not have_target then
gcs:send_text(0,"Have beacon")
end
have_target = true
target_pos, target_velocity = follow:get_target_location_and_velocity_ofs()
target_heading = follow:get_target_heading_deg()
end
-- main update function
function update()
if GFOLL_ENABLE:get() < 1 then
return
end
update_target()
if not have_target then
return
end
current_pos = ahrs:get_position()
if not current_pos then
return
end
current_pos:change_alt_frame(ALT_FRAME_ABSOLUTE)
if vehicle:get_mode() ~= MODE_GUIDED then
return
end
local next_WP = vehicle:get_target_location()
if not next_WP then
-- not in a flight mode with a target location
return
end
-- update the target position from the follow library, which includes the offsets
target_pos:change_alt_frame(ALT_FRAME_ABSOLUTE)
vehicle:update_target_location(next_WP, target_pos)
end
function loop()
update()
-- run at 20Hz
return loop, 50
end
check_parameters()
-- wrapper around update(). This calls update() at 20Hz,
-- and if update faults then an error is displayed, but the script is not
-- stopped
function protected_wrapper()
local success, err = pcall(update)
if not success then
gcs:send_text(0, "Internal Error: " .. err)
-- when we fault we run the update function again after 1s, slowing it
-- down a bit so we don't flood the console with errors
return protected_wrapper, 1000
end
return protected_wrapper, 50
end
-- start running update loop
return protected_wrapper()
| gpl-3.0 |
sodzawic/tk | epan/wslua/template-init.lua | 4 | 4791 | -- init.lua
--
-- initialize wireshark's lua
--
-- This file is going to be executed before any other lua script.
-- It can be used to load libraries, disable functions and more.
--
-- Wireshark - Network traffic analyzer
-- By Gerald Combs <gerald@wireshark.org>
-- Copyright 1998 Gerald Combs
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-- Set disable_lua to true to disable Lua support.
disable_lua = false
if disable_lua then
return
end
-- If set and we are running with special privileges this setting
-- tells whether scripts other than this one are to be run.
run_user_scripts_when_superuser = false
-- disable potentialy harmful lua functions when running superuser
if running_superuser then
local hint = "has been disabled due to running Wireshark as superuser. See http://wiki.wireshark.org/CaptureSetup/CapturePrivileges for help in running Wireshark as an unprivileged user."
local disabled_lib = {}
setmetatable(disabled_lib,{ __index = function() error("this package ".. hint) end } );
dofile = function() error("dofile " .. hint) end
loadfile = function() error("loadfile " .. hint) end
loadlib = function() error("loadlib " .. hint) end
require = function() error("require " .. hint) end
os = disabled_lib
io = disabled_lib
file = disabled_lib
end
-- to avoid output to stdout which can cause problems lua's print ()
-- has been suppresed so that it yields an error.
-- have print() call info() instead.
if gui_enabled() then
print = info
end
function typeof(obj)
local mt = getmetatable(obj)
return mt and mt.__typeof or obj.__typeof or type(obj)
end
-- the following function checks if a file exists
-- since 1.11.3
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then io.close(f) return true else return false end
end
-- the following function prepends the given directory name to
-- the package.path, so that a 'require "foo"' will work if 'foo'
-- is in the directory name given to this function. For example,
-- if your Lua file will do a 'require "foo"' and the foo.lua
-- file is in a local directory (local to your script) named 'bar',
-- then call this function before doing your 'require', by doing
-- package.prepend_path("bar")
-- and that will let Wireshark's Lua find the file "bar/foo.lua"
-- when you later do 'require "foo"'
--
-- Because this function resides here in init.lua, it does not
-- have the same environment as your script, so it has to get it
-- using the debug library, which is why the code appears so
-- cumbersome.
--
-- since 1.11.3
function package.prepend_path(name)
local debug = require "debug"
-- get the function calling this package.prepend_path function
local dt = debug.getinfo(2, "f")
if not dt then
error("could not retrieve debug info table")
end
-- get its upvalue
local _, val = debug.getupvalue(dt.func, 1)
if not val or type(val) ~= 'table' then
error("No calling function upvalue or it is not a table")
end
-- get the __DIR__ field in its upvalue table
local dir = val["__DIR__"]
-- get the platform-specific directory separator character
local sep = package.config:sub(1,1)
-- prepend the dir and given name to path
if dir and dir:len() > 0 then
package.path = dir .. sep .. name .. sep .. "?.lua;" .. package.path
end
-- also prepend just the name as a directory
package.path = name .. sep .. "?.lua;" .. package.path
end
-- %WTAP_ENCAPS%
-- %WTAP_FILETYPES%
-- %WTAP_COMMENTTYPES%
-- %FT_TYPES%
-- the following table is since 1.12
-- %WTAP_REC_TYPES%
-- the following table is since 1.11.3
-- %WTAP_PRESENCE_FLAGS%
-- %BASES%
-- %ENCODINGS%
-- %EXPERT%
-- the following table is since 1.11.3
-- %EXPERT_TABLE%
-- %MENU_GROUPS%
-- other useful constants
GUI_ENABLED = gui_enabled()
DATA_DIR = Dir.global_config_path()
USER_DIR = Dir.personal_config_path()
-- deprecated function names
datafile_path = Dir.global_config_path
persconffile_path = Dir.personal_config_path
dofile(DATA_DIR.."console.lua")
--dofile(DATA_DIR.."dtd_gen.lua")
| gpl-2.0 |
forward619/luci | applications/luci-app-ddns/luasrc/controller/ddns.lua | 29 | 7451 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Copyright 2013 Manuel Munz <freifunk at somakoma dot de>
-- Copyright 2014 Christian Schoenebeck <christian dot schoenebeck at gmail dot com>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.ddns", package.seeall)
local NX = require "nixio"
local NXFS = require "nixio.fs"
local DISP = require "luci.dispatcher"
local HTTP = require "luci.http"
local UCI = require "luci.model.uci"
local SYS = require "luci.sys"
local DDNS = require "luci.tools.ddns" -- ddns multiused functions
local UTIL = require "luci.util"
DDNS_MIN = "2.4.2-1" -- minimum version of service required
function index()
local nxfs = require "nixio.fs" -- global definitions not available
local sys = require "luci.sys" -- in function index()
local ddns = require "luci.tools.ddns" -- ddns multiused functions
local verinst = ddns.ipkg_ver_installed("ddns-scripts")
local verok = ddns.ipkg_ver_compare(verinst, ">=", "2.0.0-0")
-- do NOT start it not ddns-scripts version 2.x
if not verok then
return
end
-- no config create an empty one
if not nxfs.access("/etc/config/ddns") then
nxfs.writefile("/etc/config/ddns", "")
end
entry( {"admin", "services", "ddns"}, cbi("ddns/overview"), _("Dynamic DNS"), 59)
entry( {"admin", "services", "ddns", "detail"}, cbi("ddns/detail"), nil ).leaf = true
entry( {"admin", "services", "ddns", "hints"}, cbi("ddns/hints",
{hideapplybtn=true, hidesavebtn=true, hideresetbtn=true}), nil ).leaf = true
entry( {"admin", "services", "ddns", "global"}, cbi("ddns/global"), nil ).leaf = true
entry( {"admin", "services", "ddns", "logview"}, call("logread") ).leaf = true
entry( {"admin", "services", "ddns", "startstop"}, call("startstop") ).leaf = true
entry( {"admin", "services", "ddns", "status"}, call("status") ).leaf = true
end
-- function to read all sections status and return data array
local function _get_status()
local uci = UCI.cursor()
local service = SYS.init.enabled("ddns") and 1 or 0
local url_start = DISP.build_url("admin", "system", "startup")
local data = {} -- Array to transfer data to javascript
data[#data+1] = {
enabled = service, -- service enabled
url_up = url_start, -- link to enable DDS (System-Startup)
}
uci:foreach("ddns", "service", function (s)
-- Get section we are looking at
-- and enabled state
local section = s[".name"]
local enabled = tonumber(s["enabled"]) or 0
local datelast = "_empty_" -- formatted date of last update
local datenext = "_empty_" -- formatted date of next update
-- get force seconds
local force_seconds = DDNS.calc_seconds(
tonumber(s["force_interval"]) or 72 ,
s["force_unit"] or "hours" )
-- get/validate pid and last update
local pid = DDNS.get_pid(section)
local uptime = SYS.uptime()
local lasttime = DDNS.get_lastupd(section)
if lasttime > uptime then -- /var might not be linked to /tmp
lasttime = 0 -- and/or not cleared on reboot
end
-- no last update happen
if lasttime == 0 then
datelast = "_never_"
-- we read last update
else
-- calc last update
-- sys.epoch - sys uptime + lastupdate(uptime)
local epoch = os.time() - uptime + lasttime
-- use linux date to convert epoch
datelast = DDNS.epoch2date(epoch)
-- calc and fill next update
datenext = DDNS.epoch2date(epoch + force_seconds)
end
-- process running but update needs to happen
-- problems if force_seconds > uptime
force_seconds = (force_seconds > uptime) and uptime or force_seconds
if pid > 0 and ( lasttime + force_seconds - uptime ) <= 0 then
datenext = "_verify_"
-- run once
elseif force_seconds == 0 then
datenext = "_runonce_"
-- no process running and NOT enabled
elseif pid == 0 and enabled == 0 then
datenext = "_disabled_"
-- no process running and enabled
elseif pid == 0 and enabled ~= 0 then
datenext = "_stopped_"
end
-- get/set monitored interface and IP version
local iface = s["interface"] or "_nonet_"
local use_ipv6 = tonumber(s["use_ipv6"]) or 0
if iface ~= "_nonet_" then
local ipv = (use_ipv6 == 1) and "IPv6" or "IPv4"
iface = ipv .. " / " .. iface
end
-- try to get registered IP
local domain = s["domain"] or "_nodomain_"
local dnsserver = s["dns_server"] or ""
local force_ipversion = tonumber(s["force_ipversion"] or 0)
local force_dnstcp = tonumber(s["force_dnstcp"] or 0)
local command = [[/usr/lib/ddns/dynamic_dns_lucihelper.sh]]
command = command .. [[ get_registered_ip ]] .. domain .. [[ ]] .. use_ipv6 ..
[[ ]] .. force_ipversion .. [[ ]] .. force_dnstcp .. [[ ]] .. dnsserver
local reg_ip = SYS.exec(command)
if reg_ip == "" then
reg_ip = "_nodata_"
end
-- fill transfer array
data[#data+1] = {
section = section,
enabled = enabled,
iface = iface,
domain = domain,
reg_ip = reg_ip,
pid = pid,
datelast = datelast,
datenext = datenext
}
end)
uci:unload("ddns")
return data
end
-- called by XHR.get from detail_logview.htm
function logread(section)
-- read application settings
local uci = UCI.cursor()
local log_dir = uci:get("ddns", "global", "log_dir") or "/var/log/ddns"
local lfile = log_dir .. "/" .. section .. ".log"
local ldata = NXFS.readfile(lfile)
if not ldata or #ldata == 0 then
ldata="_nodata_"
end
uci:unload("ddns")
HTTP.write(ldata)
end
-- called by XHR.get from overview_status.htm
function startstop(section, enabled)
local uci = UCI.cursor()
local pid = DDNS.get_pid(section)
local data = {} -- Array to transfer data to javascript
-- if process running we want to stop and return
if pid > 0 then
local tmp = NX.kill(pid, 15) -- terminate
NX.nanosleep(2) -- 2 second "show time"
-- status changed so return full status
data = _get_status()
HTTP.prepare_content("application/json")
HTTP.write_json(data)
return
end
-- read uncommitted changes
-- we don't save and commit data from other section or other options
-- only enabled will be done
local exec = true
local changed = uci:changes("ddns")
for k_config, v_section in pairs(changed) do
-- security check because uci.changes only gets our config
if k_config ~= "ddns" then
exec = false
break
end
for k_section, v_option in pairs(v_section) do
-- check if only section of button was changed
if k_section ~= section then
exec = false
break
end
for k_option, v_value in pairs(v_option) do
-- check if only enabled was changed
if k_option ~= "enabled" then
exec = false
break
end
end
end
end
-- we can not execute because other
-- uncommitted changes pending, so exit here
if not exec then
HTTP.write("_uncommitted_")
return
end
-- save enable state
uci:set("ddns", section, "enabled", ( (enabled == "true") and "1" or "0") )
uci:save("ddns")
uci:commit("ddns")
uci:unload("ddns")
-- start dynamic_dns_updater.sh script
os.execute ([[/usr/lib/ddns/dynamic_dns_updater.sh %s 0 > /dev/null 2>&1 &]] % section)
NX.nanosleep(3) -- 3 seconds "show time"
-- status changed so return full status
data = _get_status()
HTTP.prepare_content("application/json")
HTTP.write_json(data)
end
-- called by XHR.poll from overview_status.htm
function status()
local data = _get_status()
HTTP.prepare_content("application/json")
HTTP.write_json(data)
end
| apache-2.0 |
geanux/darkstar | scripts/globals/weaponskills/flaming_arrow.lua | 30 | 1398 | -----------------------------------
-- Flaming Arrow
-- Archery weapon skill
-- Skill level: 5
-- Deals fire elemental damage. Damage varies with TP.
-- Aligned with the Flame Gorget & Light Gorget.
-- Aligned with the Flame Belt & Light Belt.
-- Element: Fire
-- Modifiers: STR:16% ; AGI:25%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.16; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.25; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 0.5; params.ftp200 = 0.75; params.ftp300 = 1;
params.str_wsc = 0.2; params.agi_wsc = 0.5;
end
local damage, tpHits, extraHits = doRangedWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
kaen/Zero-K | LuaUI/Widgets/gui_chili_docking.lua | 4 | 12127 | local version = "v1.001"
function widget:GetInfo()
return {
name = "Chili Docking",
desc = version .." Provides docking and position saving for chili windows",
author = "Licho",
date = "@2010",
license = "GNU GPL, v2 or later",
layer = 50,
experimental = false,
handler = true, -- to read widget status. eg: "widgetHandler.knownWidgets[name]"
enabled = true -- loaded by default?
}
end
local Chili
local Window
local screen0
local lastPos = {} -- "windows" indexed array of {x,y,x2,y2}
local settings = {} -- "window name" indexed array of {x,y,x2,y,2}
local buttons = {} -- "window name" indexed array of minimize buttons
local forceUpdate = false
local frameCounter = 0
local lastCount = 0
local lastWidth = 0
local lastHeight = 0
----------------------------------------------------
-- Options
----------------------------------------------------
options_path = 'Settings/HUD Panels/Docking'
options_order = { 'dockEnabled', 'minimizeEnabled', 'dockThreshold'}
options = {
dockThreshold = {
name = "Docking distance",
type = 'number',
advanced = true,
value = 5,
min=1,max=50,step=1,
OnChange = {function()
forceUpdate = true
end },
},
dockEnabled = {
name = 'Use docking',
advanced = false,
type = 'bool',
value = true,
desc = 'Dock windows to screen edges and each other to prevent overlaps',
},
minimizeEnabled = {
name = 'Minimizable windows',
advanced = false,
type = 'bool',
value = true,
desc = 'When enabled certain windows will have minimization tabs.',
},
}
----------------------------------------------------
----------------------------------------------------
local function Docking_GetWindowSettings(name)
if name and settings and settings[name] then
local settingsPos = settings[name]
local x = settingsPos[1]
local y = settingsPos[2]
local w = settingsPos[3] - x
local h = settingsPos[4] - y
return x,y,w,h
end
end
function WG.SetWindowPosAndSize(window,x,y,w,h)
lastPos[window] = nil
settings[window] = {x,y,x+w,y+h}
end
function widget:Initialize()
if (not WG.Chili) then
widgetHandler:RemoveWidget(widget) --"widget" as extra argument because "handler=true"
return
end
WG.Docking_GetWindowSettings = Docking_GetWindowSettings
-- setup Chili
Chili = WG.Chili
Window = Chili.Window
screen0 = Chili.Screen0
end
-- returns snap orientation of box A compared to box B and distance of their edges - orientation = L/R/T/D and distance of snap
local function GetBoxRelation(boxa, boxb)
local mpah = 0 -- midposition a horizontal
local mpbh = 0
local mpav = 0
local mpbv = 0
local snaph, snapv
if not (boxa[2] > boxb[4] or boxa[4] < boxb[2]) then -- "vertical collision" they are either to left or to right
mpah = (boxa[3] + boxa[1])/2 -- gets midpos
mpbh = (boxb[3] + boxb[1])/2
snaph = true
end
if not (boxa[1] > boxb[3] or boxa[3] <boxb[1]) then -- "horizontal collision" they are above or below
mpav = (boxa[4] + boxa[2])/2 -- gets midpos
mpbv = (boxb[4] + boxb[2])/2
snapv = true
end
local axis = nil
local dist = 99999
if (snaph) then
if mpah < mpbh then
axis = 'R'
dist = boxb[1] - boxa[3]
else
axis = 'L'
dist = boxa[1] - boxb[3]
end
end
if (snapv) then
if mpav < mpbv then
local nd = boxb[2] - boxa[4]
if math.abs(nd) < math.abs(dist) then -- only snap this axis if its shorter "snap" distance
axis = 'D'
dist = nd
end
else
local nd = boxa[2] - boxb[4]
if math.abs(nd) < math.abs(dist) then
axis = 'T'
dist = nd
end
end
end
if axis ~= nil then
return axis, dist
else
return nil, nil
end
end
-- returns closest axis to snap to existing windows or screen edges - first parameter is axis (L/R/T/D) second is snap distance
local function GetClosestAxis(winPos, dockWindows, win)
local dockDist = options.dockThreshold.value
local minDist = dockDist + 1
local minAxis= 'L'
local function CheckAxis(dist, newAxis)
if dist < minDist and dist ~= 0 then
if newAxis == 'L' and (winPos[1] - dist < 0 or winPos[3] - dist > screen0.width) then return end
if newAxis == 'R' and (winPos[1] + dist < 0 or winPos[3] + dist > screen0.width) then return end
if newAxis == 'T' and (winPos[2] - dist < 0 or winPos[4] - dist > screen0.height) then return end
if newAxis == 'D' and (winPos[2] + dist < 0 or winPos[4] + dist > screen0.height) then return end
minDist = dist
minAxis = newAxis
end
end
CheckAxis(winPos[1], 'L')
CheckAxis(winPos[2], 'T')
CheckAxis(screen0.width - winPos[3], 'R')
CheckAxis(screen0.height - winPos[4], 'D')
if (minDist < dockDist and minDist ~= 0) then
return minAxis, minDist -- screen edges have priority ,dont check anything else
end
for w, dp in pairs(dockWindows) do
if win ~= w then
local a, d = GetBoxRelation(winPos, dp)
if a ~= nil then
CheckAxis(d, a)
end
end
end
if minDist < dockDist and minDist ~= 0 then
return minAxis, minDist
else
return nil, nil
end
end
-- snaps box data with axis and distance
local function SnapBox(wp, a,d)
if a == 'L' then
wp[1] = wp[1] - d
wp[3] = wp[3] - d
elseif a== 'R' then
wp[1] = wp[1] + d
wp[3] = wp[3] + d
elseif a== 'T' then
wp[2] = wp[2] - d
wp[4] = wp[4] - d
elseif a== 'D' then
wp[2] = wp[2] + d
wp[4] = wp[4] + d
end
end
local function GetButtonPos(win)
local size = 5 -- button thickness
local mindist = win.x*5000 + win.height
local mode = 'L'
local dist = win.y*5000 + win.width
if dist < mindist then
mindist = dist
mode = 'T'
end
dist = (screen0.width - win.x - win.width)*5000 + win.height
if dist < mindist then
mindist = dist
mode = 'R'
end
dist = (screen0.height - win.y - win.height)*5000 + win.width
if dist < mindist then
mindist = dist
mode = 'B'
end
if mode == 'L' then
return {x=win.x-3, y= win.y, width = size, height = win.height}
elseif mode =='T' then
return {x=win.x, y= win.y-3, width = win.width, height = size}
elseif mode =='R' then
return {x=win.x + win.width - size-3, y= win.y, width = size, height = win.height}
elseif mode=='B' then
return {x=win.x, y= win.y + win.height - size-3, width = win.width, height = size}
end
end
function widget:Update()
frameCounter = frameCounter +1
if (not screen0) or (frameCounter % 88 ~= 87 and #screen0.children == lastCount) then
return
end
lastCount = #screen0.children
local posChanged = false -- has position changed since last check
if (screen0.width ~= lastWidth or screen0.height ~= lastHeight) then
forceUpdate = true
lastWidth = screen0.width
lastHeight = screen0.height
end
local present = {}
local names = {}
for _, win in ipairs(screen0.children) do -- NEEDED FOR MINIMIZE BUTTONS: table.shallowcopy(
if (win.dockable) then
names[win.name] = win
present[win.name] = true
local lastWinPos = lastPos[win.name]
if lastWinPos == nil then -- new window appeared
posChanged = true
local settingsPos = settings[win.name]
if settingsPos ~= nil then -- and we have setings stored for new window, apply it
local w = settingsPos[3] - settingsPos[1]
local h = settingsPos[4] - settingsPos[2]
if win.fixedRatio then
local limit = 0
if (w > h) then limit = w else limit = h end
if (win.width > win.height) then
w = limit
h = limit*win.height/win.width
else
h = limit
w = limit*win.width/win.height
end
end
if win.resizable or win.tweakResizable then
win:Resize(w, h, false, false)
end
win:SetPos(settingsPos[1], settingsPos[2])
if not options.dockEnabled.value then
lastPos[win.name] = { win.x, win.y, win.x + win.width, win.y + win.height }
end
end
elseif lastWinPos[1] ~= win.x or lastWinPos[2] ~= win.y or lastWinPos[3] ~= win.x+win.width or lastWinPos[4] ~= win.y + win.height then -- window changed position
posChanged = true
settings[win.name] = { win.x, win.y, win.x + win.width, win.y + win.height } --save data immediately (useful when docking is not enabled)
end
end
end
for winName, _ in pairs(lastPos) do -- delete those not present atm (Redo/refresh docking when window un-minimized)
if not present[winName] then
lastPos[winName] = nil
end
end
-- BUTTONS to minimize stuff
-- FIXME HACK use object:IsDescendantOf(screen0) from chili to detect visibility, not this silly hack stuff with button.winVisible
for name, win in pairs(names) do
if win.minimizable and options.minimizeEnabled.value then
local button = buttons[name]
if not button then
button = Chili.Button:New{
x = win.x,
y = win.y,
width = 50,
height = 20,
caption = '',
dockable = false,
winName = win.name,
tooltip = 'Minimize ' .. win.name,
backgroundColor={0,1,0,1},
widgetName = win.parentWidgetName,
win = win,
OnClick = {
function(self)
if button.winVisible then
win.hidden = true -- todo this is needed for minimap to hide self, remove when windows can detect if its on the sreen or not
button.tooltip = 'Expand ' .. button.winName
button.backgroundColor={1,0,0,1}
if not win.selfImplementedMinimizable then
screen0:RemoveChild(win)
else
win.selfImplementedMinimizable(false)
end
else
win.hidden = false
button.tooltip = 'Minimize ' .. button.winName
button.backgroundColor={0,1,0,1}
if not win.selfImplementedMinimizable then
screen0:AddChild(win)
else
win.selfImplementedMinimizable(true)
end
end
button.winVisible = not button.winVisible
end
}
}
screen0:AddChild(button)
button:BringToFront()
buttons[name] = button
end
local pos = GetButtonPos(win)
button:SetPos(pos.x,pos.y, pos.width, pos.height)
if not button.winVisible then
button.winVisible = true
win.hidden = false
button.tooltip = 'Minimize ' .. button.winName
button.backgroundColor={0,1,0,1}
button:Invalidate()
end
else
local button = buttons[name]
if button then
screen0:RemoveChild(button)
buttons[name] = nil
end
end
end
for name, button in pairs(buttons) do
if not names[name] and button.winVisible then -- widget hid externally
button.winVisible = false
button.tooltip = 'Expand ' .. button.winName
button.backgroundColor={1,0,0,1}
button:Invalidate()
end
local widgetInfo = button.widgetName and widgetHandler.knownWidgets[button.widgetName]
if widgetInfo and not widgetInfo.active then --check if widget was removed
button:Dispose();
buttons[name] = nil
end
if button.win.parent and button.win.parent.name ~= screen0.name then
button:Dispose();
buttons[name] = nil
end
end
if forceUpdate or (posChanged and options.dockEnabled.value) then
forceUpdate = false
local dockWindows = {} -- make work array of windows
for _, win in ipairs(screen0.children) do
local dock = win.collide or win.dockable
if (dock) then
dockWindows[win] = {win.x, win.y, win.x + win.width, win.y + win.height}
end
end
-- dock windows
local mc = 2
repeat
for win, wp in pairs(dockWindows) do
local numTries = 5
repeat
--Spring.Echo("box "..wp[1].. " " ..wp[2] .. " " ..wp[3] .. " " .. wp[4])
local a,d = GetClosestAxis(wp,dockWindows, win)
if a~=nil then
SnapBox(wp,a,d)
--Spring.Echo("snap "..a .. " " ..d)
end
numTries = numTries - 1
until a == nil or numTries == 0
win:SetPos(wp[1], wp[2])
local winPos = { win.x, win.y, win.x + win.width, win.y + win.height }
lastPos[win.name] = winPos
settings[win.name] = winPos
end
mc = mc -1
until mc == 0
end
end
function widget:ViewResize(vsx, vsy)
scrW = vsx
scrH = vsy
end
function widget:SetConfigData(data)
settings = data
end
function widget:GetConfigData()
return settings
end | gpl-2.0 |
lewes6369/LAVG-GAME-ENGINE | src/LAVG/Lua/WinSetting.lua | 2 | 1214 | -- WinSetting
-- author by Liu Hao
-- 2017/06/18
local Lplus = require "Lplus"
local UserData = require "UserData"
local RenderManager = require "RenderManager"
local WinSetting = Lplus.Class("WinSetting")
local def = WinSetting.define
def.field("number").m_width = 0
def.field("number").m_height = 0
def.field("boolean").m_bFullScreen = false
def.field("number").m_scale = 0
local instance = nil
def.static("=>",WinSetting).Instance = function ()
if instance == nil then
instance = WinSetting()
end
return instance
end
def.method().Init = function(self)
self.m_width = UserData.Instance():GetSystemCfg("Width")
self.m_height = UserData.Instance():GetSystemCfg("Height")
self.m_scale = UserData.Instance():GetSystemCfg("Scale")
end
def.method("number","number","number").onSizeChanged = function(self,width,height,scale)
self.m_width = width
self.m_height = height
self.m_scale = scale
UserData.Instance():SetSystemCfg("Width",self.m_width)
UserData.Instance():SetSystemCfg("Height",self.m_height)
UserData.Instance():SetSystemCfg("Scale",self.m_scale)
RenderManager.Instance():OnWindowResize(scale)
end
WinSetting.Commit()
return WinSetting | mit |
evilexecutable/ResourceKeeper | install/Lua/lib/lua/oil/arch/corba/client.lua | 6 | 1097 | local pairs = pairs
local port = require "oil.port"
local component = require "oil.component"
local arch = require "oil.arch" --[[VERBOSE]] local verbose = require "oil.verbose"
module "oil.arch.corba.client"
OperationRequester = component.Template{
requests = port.Facet,
codec = port.Receptacle,
profiler = port.HashReceptacle,
channels = port.HashReceptacle,
}
function assemble(components)
arch.start(components)
-- GIOP MAPPINGS
local IOPClientChannels = { [0] = ClientChannels }
-- REQUESTER
OperationRequester.codec = CDREncoder.codec
OperationRequester.pcall = BasicSystem.pcall -- to catch marshal errors
-- COMMUNICATION
for tag, ClientChannels in pairs(IOPClientChannels) do
ClientChannels.sockets = BasicSystem.sockets
OperationRequester.channels[tag] = ClientChannels.channels
end
-- REFERENCES
ObjectReferrer.requester = OperationRequester.requests
for tag, IORProfiler in pairs(IORProfilers) do
OperationRequester.profiler[0] = IIOPProfiler
end
arch.finish(components)
end
| gpl-2.0 |
sami2448/a | plugins/admin.lua | 9 | 6057 | local function set_bot_photo(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/bot.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
set_profile_photo(file, ok_cb, false)
send_large_msg(receiver, 'Photo changed!', ok_cb, false)
redis:del("bot:photo")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function parsed_url(link)
local parsed_link = URL.parse(link)
local parsed_path = URL.parse_path(parsed_link.path)
return parsed_path[2]
end
local function get_contact_list_callback (cb_extra, success, result)
local text = " "
for k,v in pairs(result) do
if v.print_name and v.id and v.phone then
text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n"
end
end
local file = io.open("contact_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format
local file = io.open("contact_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format
end
local function user_info_callback(cb_extra, success, result)
result.access_hash = nil
result.flags = nil
result.phone = nil
if result.username then
result.username = '@'..result.username
end
result.print_name = result.print_name:gsub("_","")
local text = serpent.block(result, {comment=false})
text = text:gsub("[{}]", "")
text = text:gsub('"', "")
text = text:gsub(",","")
if cb_extra.msg.to.type == "chat" then
send_large_msg("chat#id"..cb_extra.msg.to.id, text)
else
send_large_msg("user#id"..cb_extra.msg.to.id, text)
end
end
local function get_dialog_list_callback(cb_extra, success, result)
local text = ""
for k,v in pairs(result) do
if v.peer then
if v.peer.type == "chat" then
text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")"
else
if v.peer.print_name and v.peer.id then
text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]"
end
if v.peer.username then
text = text.."("..v.peer.username..")"
end
if v.peer.phone then
text = text.."'"..v.peer.phone.."'"
end
end
end
if v.message then
text = text..'\nlast msg >\nmsg id = '..v.message.id
if v.message.text then
text = text .. "\n text = "..v.message.text
end
if v.message.action then
text = text.."\n"..serpent.block(v.message.action, {comment=false})
end
if v.message.from then
if v.message.from.print_name then
text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]"
end
if v.message.from.username then
text = text.."( "..v.message.from.username.." )"
end
if v.message.from.phone then
text = text.."' "..v.message.from.phone.." '"
end
end
end
text = text.."\n\n"
end
local file = io.open("dialog_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format
local file = io.open("dialog_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format
end
local function run(msg,matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local group = msg.to.id
if not is_admin(msg) then
return
end
if msg.media then
if msg.media.type == 'photo' and redis:get("bot:photo") then
if redis:get("bot:photo") == 'waiting' then
load_photo(msg.id, set_bot_photo, msg)
end
end
end
if matches[1] == "setbotphoto" then
redis:set("bot:photo", "waiting")
return 'Please send me bot photo now'
end
if matches[1] == "markread" then
if matches[2] == "on" then
redis:set("bot:markread", "on")
return "Mark read > on"
end
if matches[2] == "off" then
redis:del("bot:markread")
return "Mark read > off"
end
return
end
if matches[1] == "pm" then
send_large_msg("user#id"..matches[2],matches[3])
return "Msg sent"
end
if matches[1] == "block" then
if is_admin2(matches[2]) then
return "You can't block admins"
end
block_user("user#id"..matches[2],ok_cb,false)
return "User blocked"
end
if matches[1] == "unblock" then
unblock_user("user#id"..matches[2],ok_cb,false)
return "User unblocked"
end
if matches[1] == "import" then--join by group link
local hash = parsed_url(matches[2])
import_chat_link(hash,ok_cb,false)
end
if matches[1] == "contactlist" then
get_contact_list(get_contact_list_callback, {target = msg.from.id})
return "I've sent contact list with both json and text format to your private"
end
if matches[1] == "delcontact" then
del_contact("user#id"..matches[2],ok_cb,false)
return "User "..matches[2].." removed from contact list"
end
if matches[1] == "dialoglist" then
get_dialog_list(get_dialog_list_callback, {target = msg.from.id})
return "I've sent dialog list with both json and text format to your private"
end
if matches[1] == "whois" then
user_info("user#id"..matches[2],user_info_callback,{msg=msg})
end
return
end
return {
patterns = {
"^(pm) (%d+) (.*)$",
"^(import) (.*)$",
"^(unblock) (%d+)$",
"^(block) (%d+)$",
"^(markread) (on)$",
"^(markread) (off)$",
"^(setbotphoto)$",
"%[(photo)%]",
"^(contactlist)$",
"^(dialoglist)$",
"^(delcontact) (%d+)$",
"^(whois) (%d+)$"
},
run = run,
}
| gpl-2.0 |
geanux/darkstar | scripts/zones/Windurst_Walls/npcs/Raamimi.lua | 17 | 3005 | -----------------------------------
-- Area: Windurst Walls
-- Location: X:-81 Y:-9 Z:103
-- NPC: Raamimi
-- Working 100%
-- Involved in Quest: To Bee or Not to Bee?
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local ToBee = player:getQuestStatus(WINDURST,TO_BEE_OR_NOT_TO_BEE);
local ToBeeOrNotStatus = player:getVar("ToBeeOrNot_var");
if (ToBeeOrNotStatus == 10 and ToBee == QUEST_AVAILABLE) then
player:startEvent(0x0043); -- Quest Started - He gives you honey
elseif (ToBee == QUEST_ACCEPTED) then
player:startEvent(0x0044); -- After honey is given to player...... but before 5th hondy is given to Zayhi
elseif (ToBee == QUEST_COMPLETED and ToBeeOrNotStatus == 5) then
player:startEvent(0x0050); -- Quest Finish - Gives Mulsum
elseif (ToBee == QUEST_COMPLETED and ToBeeOrNotStatus == 0 and player:needToZone()) then
player:startEvent(0x004F); -- After Quest but before zoning "it's certainly gotten quiet around here..."
else
player:startEvent(0x0128);
end
end;
-- Event ID List for NPC
-- player:startEvent(0x0128); -- Standard Conversation
-- player:startEvent(0x0043); -- Quest is kicked off already, he gives you honey
-- player:startEvent(0x0044); -- After honey is given to player...... before given to Zayhi????
-- player:startEvent(0x0050); -- Quest Finish - Gives Mulsum
-- player:startEvent(0x004F); -- After Quest but before zoning: "it's certainly gotten quiet around here..."
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
printf("CSID: %u",csid);
printf("RESULT: %u",option);
if (csid == 0x0043) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4370); -- Cannot give Honey because player Inventory is full
else
player:addQuest(WINDURST,TO_BEE_OR_NOT_TO_BEE);
player:addItem(4370);
player:messageSpecial(ITEM_OBTAINED, 4370); -- Gives player Honey x1
end
elseif (csid == 0x0050) then -- After Honey#5: ToBee quest Finish (tooth hurts from all the Honey)
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4156); -- Cannot give Mulsum because player Inventory is full
else
player:setVar("ToBeeOrNot_var",0);
player:addItem(4156,3); -- Mulsum x3
player:messageSpecial(ITEMS_OBTAINED, 4156,3);
player:needToZone(true);
end
end
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/Meriphataud_Mountains/npcs/Donmo-Boronmo_WW.lua | 30 | 3082 | -----------------------------------
-- Area: Meriphataud Mountains
-- NPC: Donmo-Boronmo, W.W.
-- Type: Outpost Conquest Guards
-- @pos -294.470 15.806 420.117 119
-----------------------------------
package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Meriphataud_Mountains/TextIDs");
local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = ARAGONEU;
local csid = 0x7ff7;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
kaen/Zero-K | effects/gundam_heavybulletimpact.lua | 25 | 4293 | -- heavybulletimpact
return {
["heavybulletimpact"] = {
dirtg = {
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 0.7,
alwaysvisible = true,
colormap = [[0.1 0.1 0.1 1.0 0.5 0.4 0.3 1.0 0 0 0 0.0]],
directional = true,
emitrot = 90,
emitrotspread = 0,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 5,
particlelife = 10,
particlelifespread = 10,
particlesize = 2,
particlesizespread = 5,
particlespeed = 1,
particlespeedspread = 3,
pos = [[r-1 r1, 1, r-1 r1]],
sizegrowth = 1.2,
sizemod = 1.0,
texture = [[dirt]],
useairlos = true,
},
},
dirtw1 = {
class = [[CSimpleParticleSystem]],
count = 1,
water = true,
properties = {
airdrag = 0.9,
alwaysvisible = true,
colormap = [[0.9 0.9 0.9 1.0 0.5 0.5 0.9 0.0]],
directional = true,
emitrot = 90,
emitrotspread = 0,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.2, 0]],
numparticles = 8,
particlelife = 25,
particlelifespread = 7,
particlesize = 5,
particlesizespread = 5,
particlespeed = 1,
particlespeedspread = 7,
pos = [[r-1 r1, 1, r-1 r1]],
sizegrowth = 1.2,
sizemod = 1.0,
texture = [[randdots]],
useairlos = true,
},
},
dirtw2 = {
class = [[CSimpleParticleSystem]],
count = 1,
water = true,
properties = {
airdrag = 0.7,
alwaysvisible = true,
colormap = [[1.0 1.0 1.0 1.0 0.5 0.5 0.8 0.0]],
directional = true,
emitrot = 90,
emitrotspread = 0,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 5,
particlelife = 10,
particlelifespread = 10,
particlesize = 2,
particlesizespread = 5,
particlespeed = 1,
particlespeedspread = 7,
pos = [[r-1 r1, 1, r-1 r1]],
sizegrowth = 1.2,
sizemod = 1.0,
texture = [[dirt]],
useairlos = true,
},
},
poof01 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 0.8,
alwaysvisible = true,
colormap = [[0.0 0.55 0.5 0.01 0 0 0 0.01]],
directional = true,
emitrot = 45,
emitrotspread = 32,
emitvector = [[dir]],
gravity = [[0, 0, 0]],
numparticles = 8,
particlelife = 10,
particlelifespread = 5,
particlesize = 3,
particlesizespread = 0,
particlespeed = 2,
particlespeedspread = 5,
pos = [[0, 2, 0]],
sizegrowth = 1,
sizemod = 1.0,
texture = [[flashside1]],
useairlos = false,
},
},
whiteglow = {
air = true,
class = [[heatcloud]],
count = 1,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 10,
heatfalloff = 5,
maxheat = 15,
pos = [[0, 0, 0]],
size = 1,
sizegrowth = 20,
speed = [[0, 0, 0]],
texture = [[laserend]],
},
},
},
}
| gpl-2.0 |
geanux/darkstar | scripts/zones/Qufim_Island/npcs/Trodden_Snow.lua | 19 | 4780 | -----------------------------------
-- Area: Qufim Island
-- NPC: Trodden Snow
-- Mission: ASA - THAT_WHICH_CURDLES_BLOOD
-- Mission: ASA - SUGAR_COATED_DIRECTIVE
-- @zone 126
-- @pos -19 -17 104
-----------------------------------
package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil;
-------------------------------------
require("scripts/zones/Qufim_Island/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
-- Trade Enfeebling Kit
if (player:getCurrentMission(ASA) == THAT_WHICH_CURDLES_BLOOD) then
local item = 0;
local asaStatus = player:getVar("ASA_Status");
-- TODO: Other Enfeebling Kits
if (asaStatus == 0) then
item = 2779;
else
printf("Error: Unknown ASA Status Encountered <%u>", asaStatus);
end
if (trade:getItemCount() == 1 and trade:hasItemQty(item,1)) then
player:tradeComplete();
player:startEvent(0x002c);
end
end
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
--ASA 4 CS: Triggers With At Least 3 Counterseals.
if (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE) then
local completedSeals = 0;
if (player:hasKeyItem(AMBER_COUNTERSEAL)) then
completedSeals = completedSeals + 1;
end;
if (player:hasKeyItem(AZURE_COUNTERSEAL)) then
completedSeals = completedSeals + 1;
end;
if (player:hasKeyItem(CERULEAN_COUNTERSEAL)) then
completedSeals = completedSeals + 1;
end;
if (player:hasKeyItem(EMERALD_COUNTERSEAL)) then
completedSeals = completedSeals + 1;
end;
if (player:hasKeyItem(SCARLET_COUNTERSEAL)) then
completedSeals = completedSeals + 1;
end;
if (player:hasKeyItem(VIOLET_COUNTERSEAL)) then
completedSeals = completedSeals + 1;
end;
if (completedSeals >= 3) then
player:setVar("ASA_Status", completedSeals);
player:startEvent(0x002d);
end;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid==0x002c) then
player:addKeyItem(DOMINAS_SCARLET_SEAL);
player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_SCARLET_SEAL);
player:addKeyItem(DOMINAS_CERULEAN_SEAL);
player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_CERULEAN_SEAL);
player:addKeyItem(DOMINAS_EMERALD_SEAL);
player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_EMERALD_SEAL);
player:addKeyItem(DOMINAS_AMBER_SEAL);
player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_AMBER_SEAL);
player:addKeyItem(DOMINAS_VIOLET_SEAL);
player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_VIOLET_SEAL);
player:addKeyItem(DOMINAS_AZURE_SEAL);
player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_AZURE_SEAL);
player:completeMission(ASA,THAT_WHICH_CURDLES_BLOOD);
player:addMission(ASA,SUGAR_COATED_DIRECTIVE);
player:setVar("ASA_Status",0);
player:setVar("ASA4_Amber","0");
player:setVar("ASA4_Azure","0");
player:setVar("ASA4_Cerulean","0");
player:setVar("ASA4_Emerald","0");
player:setVar("ASA4_Scarlet","0");
player:setVar("ASA4_Violet","0");
elseif (csid==0x002d) then
local completedSeals = player:getVar("ASA_Status");
-- Calculate Reward
if (completedSeals == 3) then
player:addGil(GIL_RATE*3000);
elseif (completedSeals == 4) then
player:addGil(GIL_RATE*10000);
elseif (completedSeals == 5) then
player:addGil(GIL_RATE*30000);
elseif (completedSeals == 6) then
player:addGil(GIL_RATE*50000);
end
-- Clean Up Remaining Key Items
player:delKeyItem(DOMINAS_SCARLET_SEAL);
player:delKeyItem(DOMINAS_CERULEAN_SEAL);
player:delKeyItem(DOMINAS_EMERALD_SEAL);
player:delKeyItem(DOMINAS_AMBER_SEAL);
player:delKeyItem(DOMINAS_VIOLET_SEAL);
player:delKeyItem(DOMINAS_AZURE_SEAL);
player:delKeyItem(SCARLET_COUNTERSEAL);
player:delKeyItem(CERULEAN_COUNTERSEAL);
player:delKeyItem(EMERALD_COUNTERSEAL);
player:delKeyItem(AMBER_COUNTERSEAL);
player:delKeyItem(VIOLET_COUNTERSEAL);
player:delKeyItem(AZURE_COUNTERSEAL);
-- Advance Mission
player:completeMission(ASA,SUGAR_COATED_DIRECTIVE);
player:addMission(ASA,ENEMY_OF_THE_EMPIRE_I);
player:setVar("ASA_Status",0);
end
end; | gpl-3.0 |
girishramnani/Algorithm-Implementations | Caesar_Cipher/Lua/Yonaba/caesar_cipher_test.lua | 26 | 1202 | -- Tests for caesar_cipher.lua
local caesar = require 'caesar_cipher'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
run('Ciphering test', function()
assert(caesar.cipher('abcd',1) == 'bcde')
assert(caesar.cipher('WXYZ',2) == 'YZAB')
assert(caesar.cipher('abcdefghijklmnopqrstuvwxyz',3) == 'defghijklmnopqrstuvwxyzabc')
assert(caesar.cipher('ABCDEFGHIJKLMNOPQRSTUVWXYZ',4) == 'EFGHIJKLMNOPQRSTUVWXYZABCD')
end)
run('Deciphering test', function()
assert(caesar.decipher('bcde',1) == 'abcd')
assert(caesar.decipher('YZAB',2) == 'WXYZ')
assert(caesar.decipher('defghijklmnopqrstuvwxyzabc',3) == 'abcdefghijklmnopqrstuvwxyz')
assert(caesar.decipher('EFGHIJKLMNOPQRSTUVWXYZABCD',4) == 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
geanux/darkstar | scripts/zones/Port_Windurst/npcs/Mojo-Pojo.lua | 38 | 1037 | -----------------------------------
-- Area: Port Windurst
-- NPC: Mojo-Pojo
-- Type: Standard NPC
-- @zone: 240
-- @pos -108.041 -4.25 109.545
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00e5);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Yassi-Possi.lua | 38 | 1147 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Yassi-Possi
-- Type: Item Deliverer
-- @zone: 94
-- @pos 153.992 -0.001 -18.687
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Windurst_Waters_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, YASSI_POSSI_DIALOG);
player:openSendBox();
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
CandyKat/external_skia | tools/lua/bitmap_statistics.lua | 207 | 1862 | function string.startsWith(String,Start)
return string.sub(String,1,string.len(Start))==Start
end
function string.endsWith(String,End)
return End=='' or string.sub(String,-string.len(End))==End
end
local canvas = nil
local num_perspective_bitmaps = 0
local num_affine_bitmaps = 0
local num_scaled_bitmaps = 0
local num_translated_bitmaps = 0
local num_identity_bitmaps = 0
local num_scaled_up = 0
local num_scaled_down = 0
function sk_scrape_startcanvas(c, fileName)
canvas = c
end
function sk_scrape_endcanvas(c, fileName)
canvas = nil
end
function sk_scrape_accumulate(t)
-- dump the params in t, specifically showing the verb first, which we
-- then nil out so it doesn't appear in tostr()
if (string.startsWith(t.verb,"drawBitmap")) then
matrix = canvas:getTotalMatrix()
matrixType = matrix:getType()
if matrixType.perspective then
num_perspective_bitmaps = num_perspective_bitmaps + 1
elseif matrixType.affine then
num_affine_bitmaps = num_affine_bitmaps + 1
elseif matrixType.scale then
num_scaled_bitmaps = num_scaled_bitmaps + 1
if matrix:getScaleX() > 1 or matrix:getScaleY() > 1 then
num_scaled_up = num_scaled_up + 1
else
num_scaled_down = num_scaled_down + 1
end
elseif matrixType.translate then
num_translated_bitmaps = num_translated_bitmaps + 1
else
num_identity_bitmaps = num_identity_bitmaps + 1
end
end
end
function sk_scrape_summarize()
io.write( "identity = ", num_identity_bitmaps,
", translated = ", num_translated_bitmaps,
", scaled = ", num_scaled_bitmaps, " (up = ", num_scaled_up, "; down = ", num_scaled_down, ")",
", affine = ", num_affine_bitmaps,
", perspective = ", num_perspective_bitmaps,
"\n")
end
| bsd-3-clause |
evilexecutable/ResourceKeeper | install/Lua/lib/lua/oil/corba/idl.lua | 6 | 19865 | --------------------------------------------------------------------------------
------------------------------ ##### ## ------------------------------
------------------------------ ## ## # ## ------------------------------
------------------------------ ## ## ## ## ------------------------------
------------------------------ ## ## # ## ------------------------------
------------------------------ ##### ### ###### ------------------------------
-------------------------------- --------------------------------
----------------------- An Object Request Broker in Lua ------------------------
--------------------------------------------------------------------------------
-- Project: OiL - ORB in Lua: An Object Request Broker in Lua --
-- Release: 0.5 --
-- Title : Interface Definition Language (IDL) specifications in Lua --
-- Authors: Renato Maia <maia@inf.puc-rio.br> --
--------------------------------------------------------------------------------
-- Interface: --
-- istype(object) Checks whether object is an IDL type --
-- isspec(object) Checks whether object is an IDL specification --
-- --
-- null IDL null type --
-- void IDL void type --
-- short IDL integer type short --
-- long IDL integer type long --
-- ushort IDL integer type unsigned short --
-- ulong IDL integer type unsigned long --
-- float IDL floating-point numeric type --
-- double IDL double-precision floating-point numeric type --
-- boolean IDL boolean type --
-- char IDL character type --
-- octet IDL raw byte type --
-- any IDL generic type --
-- TypeCode IDL meta-type --
-- string IDL string type --
-- --
-- Object(definition) IDL Object type construtor --
-- struct(definition) IDL struct type construtor --
-- union(definition) IDL union type construtor --
-- enum(definition) IDL enumeration type construtor --
-- sequence(definition) IDL sequence type construtor --
-- array(definition) IDL array type construtor --
-- valuetype(definition) IDL value type construtor --
-- typedef(definition) IDL type definition construtor --
-- except(definition) IDL expection construtor --
-- --
-- attribute(definition) IDL attribute construtor --
-- operation(definition) IDL operation construtor --
-- module(definition) IDL module structure constructor --
-- interface(definition) IDL object interface structure constructor --
-- --
-- OctetSequence IDL type used in OiL implementation --
-- Version IDL type used in OiL implementation --
-- --
-- ScopeMemberList Class that defines behavior of interface member list-
--------------------------------------------------------------------------------
-- Notes: --
-- The syntax used for description of IDL specifications is strongly based --
-- on the work provided by Letícia Nogeira (i.e. LuaRep), which was mainly --
-- inteded to provide an user-friendly syntax. This approach may change to --
-- allow better fitting into CORBA model, since the use of LuaIDL parsing --
-- facilities already provides an user-friendly way to define IDL --
-- specifications. However backward compatibility may be provided whenever --
-- possible. --
--------------------------------------------------------------------------------
local type = type
local newproxy = newproxy
local pairs = pairs
local ipairs = ipairs
local rawset = rawset
local require = require
local rawget = rawget
-- backup of string package functions to avoid name crash with string IDL type
local match = require("string").match
local format = require("string").format
local table = require "table"
local OrderedSet = require "loop.collection.OrderedSet"
local UnorderedArraySet = require "loop.collection.UnorderedArraySet"
local oo = require "oil.oo"
local assert = require "oil.assert"
module "oil.corba.idl" --[[VERBOSE]] local verbose = require "oil.verbose"
--------------------------------------------------------------------------------
-- IDL element types -----------------------------------------------------------
BasicTypes = {
null = true,
void = true,
short = true,
long = true,
longlong = true,
ushort = true,
ulong = true,
ulonglong = true,
float = true,
double = true,
longdouble = true,
boolean = true,
char = true,
octet = true,
any = true,
TypeCode = true,
}
UserTypes = {
string = true,
Object = true,
struct = true,
union = true,
enum = true,
sequence = true,
array = true,
valuetype = true,
valuebox = true,
typedef = true,
except = true,
interface = true,
abstract_interface = true,
local_interface = true,
}
InterfaceElements = {
attribute = true,
operation = true,
module = true,
}
--------------------------------------------------------------------------------
-- Auxilary module functions ---------------------------------------------------
function istype(object)
return type(object) == "table" and (
BasicTypes[object._type] == object or
UserTypes[object._type]
)
end
function isspec(object)
return type(object) == "table" and (
BasicTypes[object._type] == object or
UserTypes[object._type] or
InterfaceElements[object._type]
)
end
assert.TypeCheckers["idl type"] = istype
assert.TypeCheckers["idl def."] = isspec
assert.TypeCheckers["^idl (%l+)$"] = function(value, name)
if istype(value)
then return (value._type == name), ("idl "..name.." type")
else return false, name
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function checkfield(field)
assert.type(field.name, "string", "field name")
assert.type(field.type, "idl type", "field type")
end
local function checkfields(fields)
for _, field in ipairs(fields) do checkfield(field) end
end
--------------------------------------------------------------------------------
-- Basic types -----------------------------------------------------------------
for name in pairs(BasicTypes) do
local basictype = {_type = name}
_M[name] = basictype
BasicTypes[name] = basictype
end
--------------------------------------------------------------------------------
-- Scoped definitions management -----------------------------------------------
function setnameof(contained, name)
contained.name = name
local container = contained.defined_in
if container then
local start, default = match(container.repID, "^(IDL:.*):(%d+%.%d+)$")
if not start then
assert.illegal(container.repID, "parent scope repository ID")
end
contained.repID = format("%s/%s:%s", start, contained.name,
contained.version or default)
else
contained.repID = format("IDL:%s:%s", contained.name,
contained.version or "1.0")
end
if contained.definitions then
for _, contained in ipairs(contained.definitions) do
setnameof(contained, contained.name)
end
end
end
--------------------------------------------------------------------------------
ContainerKey = newproxy()
Contents = oo.class()
function Contents:__newindex(name, contained)
if type(name) == "string" then
contained.defined_in = self[ContainerKey]
setnameof(contained, name)
return self:_add(contained)
end
rawset(self, name, contained)
end
function Contents:_add(contained)
UnorderedArraySet.add(self, contained)
rawset(self, contained.name, contained)
return contained
end
function Contents:_remove(contained)
contained = UnorderedArraySet.remove(self, contained)
if contained then
self[contained.name] = nil
return contained
end
end
function Contents:_removeat(index)
return self:remove(self[index])
end
Contents._removebyname = Contents._removeat
--------------------------------------------------------------------------------
function Container(self)
if not oo.instanceof(self.definitions, Contents) then
local contents = Contents{ [ContainerKey] = self }
if self.definitions then
for _, value in ipairs(self.definitions) do
assert.type(value.name, "string", "IDL definition name")
contents:__newindex(value.name, value)
end
for field, value in pairs(self.definitions) do
if type(field) == "string" then
contents:__newindex(field, value)
end
end
end
self.definitions = contents
end
return self
end
--------------------------------------------------------------------------------
function Contained(self)
assert.type(self, "table", "IDL definition")
if self.name == nil then self.name = "" end
if self.repID == nil then setnameof(self, self.name) end
assert.type(self.name, "string", "IDL definition name")
assert.type(self.repID, "string", "repository ID")
return self
end
--------------------------------------------------------------------------------
-- User-defined type constructors ----------------------------------------------
-- Note: internal structure is optimized for un/marshalling.
string = { _type = "string", maxlength = 0 }
function Object(self)
assert.type(self, "table", "Object type definition")
if self.name == nil then self.name = "" end
if self.repID == nil then setnameof(self, self.name) end
assert.type(self.name, "string", "Object type name")
assert.type(self.repID, "string", "Object type repository ID")
if self.repID == "IDL:omg.org/CORBA/Object:1.0"
then self = object
else self._type = "Object"
end
return self
end
function struct(self)
self = Container(Contained(self))
self._type = "struct"
if self.fields == nil then self.fields = self end
checkfields(self.fields)
return self
end
function union(self)
self = Container(Contained(self))
self._type = "union"
if self.options == nil then self.options = self end
if self.default == nil then self.default = -1 end -- indicates no default in CDR
assert.type(self.switch, "idl type", "union type discriminant")
assert.type(self.options, "table", "union options definition")
assert.type(self.default, "number", "union default option definition")
self.selector = {} -- maps field names to labels (option selector)
self.selection = {} -- maps labels (option selector) to options
for index, option in ipairs(self.options) do
checkfield(option)
if option.label == nil then assert.illegal(nil, "option label value") end
self.selector[option.name] = option.label
if index ~= self.default + 1 then
self.selection[option.label] = option
end
end
function self.__index(union, field)
if rawget(union, "_switch") == self.selector[field] then
return rawget(union, "_value")
end
end
function self.__newindex(union, field, value)
local label = self.selector[field]
if label then
rawset(union, "_switch", label)
rawset(union, "_value", value)
rawset(union, "_field", field)
end
end
return self
end
function enum(self)
self = Contained(self)
self._type = "enum"
if self.enumvalues == nil then self.enumvalues = self end
assert.type(self.enumvalues, "table", "enumeration values definition")
self.labelvalue = {}
for index, label in ipairs(self.enumvalues) do
assert.type(label, "string", "enumeration value label")
self.labelvalue[label] = index - 1
end
return self
end
function sequence(self)
self._type = "sequence"
if self.maxlength == nil then self.maxlength = 0 end
if self.elementtype == nil then self.elementtype = self[1] end
assert.type(self.maxlength, "number", "sequence type maximum length ")
assert.type(self.elementtype, "idl type", "sequence element type")
return self
end
function array(self)
self._type = "array"
assert.type(self.length, "number", "array type length")
if self.elementtype == nil then self.elementtype = self[1] end
assert.type(self.elementtype, "idl type", "array element type")
return self
end
ValueKind = {
none = 0,
custom = 1,
abstract = 2,
truncatable = 3,
}
ValueMemberAccess = {
private = 0,
public = 1,
}
for list in pairs{[ValueKind]=true, [ValueMemberAccess]=true} do
local values = {}
for _,value in pairs(list) do values[value] = true end
for value in pairs(values) do list[value] = value end
end
function valuemember(self)
self = Contained(self)
self._type = "valuemember"
checkfield(self)
local access = ValueMemberAccess[self.access]
if access == nil then
assert.illegal(self.access, "value member access")
end
self.access = access
return self
end
function valuetype(self)
self = Container(Contained(self))
self._type = "valuetype"
local kind = self.kind or (self.truncatable and ValueKind.truncatable)
or (self.abstract and ValueKind.abstract)
or ValueKind.none
kind = ValueKind[kind]
if kind == nil then
assert.illegal(self.kind, "value kind")
end
self.kind = kind
local base = self.base_value
if base == nil then
self.base_value = null
elseif base ~= null then
assert.type(base, "idl valuetype", "base in value definition")
end
if self.members == nil then self.members = self end
local members = self.members
local definitions = self.definitions
for index, member in ipairs(members) do
member = valuemember(member)
members[index] = member
definitions:__newindex(member.name, member)
end
return self
end
function valuebox(self)
self = Contained(self)
self._type = "valuebox"
if self.original_type == nil then self.original_type = self[1] end
local type = self.original_type
assert.type(type, "idl type", "type in typedef definition")
local kind = type._type
if kind == "valuetype" or kind == "valuebox" then
assert.illegal(type, "type of value box")
end
return self
end
function typedef(self)
self = Contained(self)
self._type = "typedef"
if self.original_type == nil then self.original_type = self[1] end
assert.type(self.original_type, "idl type", "type in typedef definition")
return self
end
function except(self)
self = Container(Contained(self))
self._type = "except"
if self.members == nil then self.members = self end
checkfields(self.members)
return self
end
--------------------------------------------------------------------------------
-- IDL interface definitions ---------------------------------------------------
-- Note: construtor syntax is optimized for use with Interface Repository
function attribute(self)
self = Contained(self)
self._type = "attribute"
if self.type == nil then self.type = self[1] end
assert.type(self.type, "idl type", "attribute type")
local mode = self.mode
if mode == "ATTR_READONLY" then
self.readonly = true
elseif mode ~= nil and mode ~= "ATTR_NORMAL" then
assert.illegal(self.mode, "attribute mode")
end
return self
end
function operation(self)
self = Contained(self)
self._type = "operation"
local mode = self.mode
if mode == "OP_ONEWAY" then
self.oneway = true
elseif mode ~= nil and mode ~= "OP_NORMAL" then
assert.illegal(self.mode, "operation mode")
end
self.inputs = {}
self.outputs = {}
if self.result and self.result ~= void then
self.outputs[#self.outputs+1] = self.result
end
if self.parameters then
for _, param in ipairs(self.parameters) do
checkfield(param)
if param.mode then
assert.type(param.mode, "string", "operation parameter mode")
if param.mode == "PARAM_IN" then
self.inputs[#self.inputs+1] = param.type
elseif param.mode == "PARAM_OUT" then
self.outputs[#self.outputs+1] = param.type
elseif param.mode == "PARAM_INOUT" then
self.inputs[#self.inputs+1] = param.type
self.outputs[#self.outputs+1] = param.type
else
assert.illegal(param.mode, "operation parameter mode")
end
else
self.inputs[#self.inputs+1] = param.type
end
end
end
if self.exceptions then
for _, except in ipairs(self.exceptions) do
assert.type(except, "idl except", "raised exception")
if self.exceptions[except.repID] ~= nil then
assert.illegal(except.repID,
"exception raise defintion, got duplicated repository ID")
end
self.exceptions[except.repID] = except
end
else
self.exceptions = {}
end
return self
end
function module(self)
self = Container(Contained(self))
self._type = "module"
return self
end
--------------------------------------------------------------------------------
local function ibases(queue, interface)
interface = queue[interface]
if interface then
for _, base in ipairs(interface.base_interfaces) do
queue:enqueue(base)
end
return interface
end
end
function basesof(self)
local queue = OrderedSet()
queue:enqueue(self)
return ibases, queue, OrderedSet.firstkey
end
function interface(self)
self = Container(Contained(self))
self._type = "interface"
if self.base_interfaces == nil then self.base_interfaces = self end
assert.type(self.base_interfaces, "table", "interface base list")
for _, base in ipairs(self.base_interfaces) do
if base._type ~= "abstract_interface" then
assert.type(base, "idl interface", "interface base")
end
end
self.hierarchy = basesof
return self
end
function abstract_interface(self)
self = interface(self)
for _, base in ipairs(self.base_interfaces) do
assert.type(base, "idl abstract_interface", "abstract interface base")
end
self._type = "abstract_interface"
return self
end
function local_interface(self)
self = interface(self)
for _, base in ipairs(self.base_interfaces) do
if base._type ~= "local_interface" then
assert.type(base, "idl interface", "local interface base")
end
end
self._type = "local_interface"
return self
end
--------------------------------------------------------------------------------
-- IDL types used in the implementation of OiL ---------------------------------
object = interface{
repID = "IDL:omg.org/CORBA/Object:1.0",
name = "Object",
}
ValueBase = valuetype{
repID = "IDL:omg.org/CORBA/ValueBase:1.0",
name = "ValueBase",
abstract = true,
}
OctetSeq = sequence{octet}
Version = struct{{ type = octet, name = "major" },
{ type = octet, name = "minor" }}
| gpl-2.0 |
ethantang95/DIGITS | examples/text-classification/text-classification-model.lua | 13 | 2920 | assert(pcall(function() require('dpnn') end), 'dpnn module required: luarocks install dpnn')
-- return function that returns network definition
return function(params)
-- get number of classes from external parameters (default to 14)
local nclasses = params.nclasses or 14
if pcall(function() require('cudnn') end) then
print('Using CuDNN backend')
backend = cudnn
convLayer = cudnn.SpatialConvolution
convLayerName = 'cudnn.SpatialConvolution'
else
print('Failed to load cudnn backend (is libcudnn.so in your library path?)')
if pcall(function() require('cunn') end) then
print('Falling back to legacy cunn backend')
else
print('Failed to load cunn backend (is CUDA installed?)')
print('Falling back to legacy nn backend')
end
backend = nn -- works with cunn or nn
convLayer = nn.SpatialConvolutionMM
convLayerName = 'nn.SpatialConvolutionMM'
end
local feature_len = 1
if params.inputShape then
assert(params.inputShape[1]==1, 'Network expects 1xHxW images')
params.inputShape:apply(function(x) feature_len=feature_len*x end)
end
local alphabet_len = 71 -- max index in input samples
local net = nn.Sequential()
-- feature_len x 1 x 1
net:add(nn.View(-1,feature_len))
-- feature_len
net:add(nn.OneHot(alphabet_len))
-- feature_len x alphabet_len
net:add(backend.TemporalConvolution(alphabet_len, 256, 7))
-- those shapes are assuming feature_len=1024
-- [1024-6=1018] x 256
net:add(nn.Threshold())
net:add(nn.TemporalMaxPooling(3, 3))
-- [(1018-3)/3+1=339] x 256
net:add(backend.TemporalConvolution(256, 256, 7))
-- [339-6=333] x 256
net:add(nn.Threshold())
net:add(nn.TemporalMaxPooling(3, 3))
-- [(333-3)/3+1=111] x 256
net:add(backend.TemporalConvolution(256, 256, 3))
-- [111-2=109] x 256
net:add(nn.Threshold())
net:add(backend.TemporalConvolution(256, 256, 3))
-- [109-2=107] x 256
net:add(nn.Threshold())
net:add(backend.TemporalConvolution(256, 256, 3))
-- [107-2=105] x 256
net:add(nn.Threshold())
net:add(backend.TemporalConvolution(256, 256, 3))
-- [105-2=103] x 256
net:add(nn.Threshold())
net:add(nn.TemporalMaxPooling(3, 3))
-- [(103-3)/3+1=34] x 256
net:add(nn.Reshape(8704))
-- 8704
net:add(nn.Linear(8704, 1024))
net:add(nn.Threshold())
net:add(nn.Dropout(0.5))
-- 1024
net:add(nn.Linear(1024, 1024))
net:add(nn.Threshold())
net:add(nn.Dropout(0.5))
-- 1024
net:add(nn.Linear(1024, nclasses))
net:add(backend.LogSoftMax())
-- weight initialization
local w,dw = net:getParameters()
w:normal():mul(5e-2)
return {
model = net,
loss = nn.ClassNLLCriterion(),
trainBatchSize = 128,
validationBatchSize = 128
}
end
| bsd-3-clause |
kaen/Zero-K | LuaRules/Gadgets/unit_overkill_prevention.lua | 3 | 11786 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if not gadgetHandler:IsSyncedCode() then
return
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Overkill Prevention",
desc = "Prevents some units from firing at units which are going to be killed by incoming missiles.",
author = "Google Frog, ivand",
date = "14 Jan 2015",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local spValidUnitID = Spring.ValidUnitID
local spSetUnitTarget = Spring.SetUnitTarget
local spGetUnitHealth = Spring.GetUnitHealth
local spGetGameFrame = Spring.GetGameFrame
local spFindUnitCmdDesc = Spring.FindUnitCmdDesc
local spEditUnitCmdDesc = Spring.EditUnitCmdDesc
local spInsertUnitCmdDesc = Spring.InsertUnitCmdDesc
local spGetUnitTeam = Spring.GetUnitTeam
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitRulesParam = Spring.GetUnitRulesParam
local spGetUnitCommands = Spring.GetUnitCommands
local spGiveOrderToUnit = Spring.GiveOrderToUnit
local pmap = VFS.Include("LuaRules/Utilities/pmap.lua")
local DECAY_FRAMES = 1200 -- time in frames it takes to decay 100% para to 0 (taken from unit_boolean_disable.lua)
local FAST_SPEED = 5.5*30 -- Speed which is considered fast.
local fastUnitDefs = {}
for i, ud in pairs(UnitDefs) do
if ud.speed > FAST_SPEED then
fastUnitDefs[i] = true
end
end
local canHandleUnit = {}
local units = {}
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local HandledUnitDefIDs = {
[UnitDefNames["corrl"].id] = true,
[UnitDefNames["armcir"].id] = true,
[UnitDefNames["nsaclash"].id] = true,
[UnitDefNames["missiletower"].id] = true,
[UnitDefNames["screamer"].id] = true,
[UnitDefNames["amphaa"].id] = true,
[UnitDefNames["puppy"].id] = true,
[UnitDefNames["fighter"].id] = true,
[UnitDefNames["hoveraa"].id] = true,
[UnitDefNames["spideraa"].id] = true,
[UnitDefNames["vehaa"].id] = true,
[UnitDefNames["gunshipaa"].id] = true,
[UnitDefNames["gunshipsupport"].id] = true,
[UnitDefNames["armsnipe"].id] = true,
[UnitDefNames["amphraider3"].id] = true,
[UnitDefNames["amphriot"].id] = true,
[UnitDefNames["subarty"].id] = true,
[UnitDefNames["subraider"].id] = true,
[UnitDefNames["corcrash"].id] = true,
[UnitDefNames["cormist"].id] = true,
[UnitDefNames["tawf114"].id] = true, --HT's banisher
[UnitDefNames["shieldarty"].id] = true, --Shields's racketeer
}
include("LuaRules/Configs/customcmds.h.lua")
local preventOverkillCmdDesc = {
id = CMD_PREVENT_OVERKILL,
type = CMDTYPE.ICON_MODE,
name = "Prevent Overkill.",
action = 'preventoverkill',
tooltip = 'Enable to prevent units shooting at units which are already going to die.',
params = {0, "Prevent Overkill", "Fire at anything"}
}
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local incomingDamage = {}
function GG.OverkillPrevention_IsDoomed(targetID)
if incomingDamage[targetID] then
local gameFrame = spGetGameFrame()
local lastFrame = incomingDamage[targetID].lastFrame or 0
return (gameFrame <= lastFrame and incomingDamage[targetID].doomed)
end
return false
end
function GG.OverkillPrevention_IsDisarmExpected(targetID)
if incomingDamage[targetID] then
local gameFrame = spGetGameFrame()
local lastFrame = incomingDamage[targetID].lastFrame or 0
return (gameFrame <= lastFrame and incomingDamage[targetID].disarmed)
end
return false
end
--[[
unitID, targetID - unit IDs. Self explainatory
fullDamage - regular damage of salvo
disarmDamage - disarming damage
disarmTimeout - for how long in frames unit projectile may cause unit disarm state (it's a cap for "disarmframe" unit param)
timeout -- percieved projectile travel time from unitID to targetID in frames
fastMult -- Multiplier to timeout if the target is fast
radarMult -- Multiplier to timeout if the taget is a radar dot
]]--
local function CheckBlockCommon(unitID, targetID, gameFrame, fullDamage, disarmDamage, disarmTimeout, timeout, fastMult, radarMult)
-- Modify timeout based on unit speed and fastMult
local unitDefID
if fastMult and fastMult ~= 1 then
unitDefID = Spring.GetUnitDefID(targetID)
if fastUnitDefs[unitDefID] then
timeout = timeout * (fastMult or 1)
end
end
-- Get unit health and status effects. An unseen unit is assumed to be fully healthy and armored.
local allyTeamID = Spring.GetUnitAllyTeam(unitID)
local targetVisiblityState = Spring.GetUnitLosState(targetID, allyTeamID, true)
local targetInLoS = (targetVisiblityState == 15)
local targetIdentified = (targetVisiblityState > 2)
local adjHealth, disarmFrame
if targetInLoS then
local armor = select(2,Spring.GetUnitArmored(targetID)) or 1
adjHealth = spGetUnitHealth(targetID)/armor -- adjusted health after incoming damage is dealt
disarmFrame = spGetUnitRulesParam(targetID, "disarmframe") or -1
if disarmFrame == -1 then
--no disarm damage on targetID yet(already)
disarmFrame = gameFrame
end
else
timeout = timeout * (radarMult or 1)
unitDefID = unitDefID or Spring.GetUnitDefID(targetID)
local ud = UnitDefs[unitDefID]
adjHealth = ud.health/ud.armoredMultiple
disarmFrame = -1
end
local incData = incomingDamage[targetID]
local targetFrame = gameFrame + timeout
local block = false
if incData then --seen this target
local startIndex, endIndex = incData.frames:GetIdxs()
for i = startIndex, endIndex do
local keyValue = incData.frames:GetKV(i)
local frame, data = keyValue[1], keyValue[2]
--Spring.Echo(frame)
if frame < gameFrame then
incData.frames:TrimFront() --frames should come in ascending order, so it's safe to trim front of array one by one
else
local disarmDamage = data.disarmDamage
local fullDamage = data.fullDamage
local disarmExtra = math.floor(disarmDamage/adjHealth*DECAY_FRAMES)
adjHealth = adjHealth - fullDamage
disarmFrame = disarmFrame + disarmExtra
if disarmFrame > frame + DECAY_FRAMES + disarmTimeout then
disarmFrame = frame + DECAY_FRAMES + disarmTimeout
end
end
end
else --new target
incomingDamage[targetID] = {frames = pmap()}
incData = incomingDamage[targetID]
end
local doomed = targetIdentified and (adjHealth < 0) and (fullDamage > 0) --for regular projectile
local disarmed = targetIdentified and (disarmFrame - gameFrame - timeout >= DECAY_FRAMES) and (disarmDamage > 0) --for disarming projectile
incomingDamage[targetID].doomed = doomed
incomingDamage[targetID].disarmed = disarmed
block = doomed or disarmed --assume function is not called with both regular and disarming damage types
if not block then
--Spring.Echo("^^^^SHOT^^^^")
local frameData = incData.frames:Get(targetFrame)
if frameData then
-- here we have a rare case when few different projectiles (from different attack units)
-- are arriving to the target at the same frame. Their powers must be accumulated/harmonized
frameData.fullDamage = frameData.fullDamage + fullDamage
frameData.disarmDamage = frameData.disarmDamage + disarmDamage
incData.frames:Upsert(targetFrame, frameData)
else --this case is much more common: such frame does not exist in incData.frames
incData.frames:Insert(targetFrame, {fullDamage = fullDamage, disarmDamage = disarmDamage})
end
incData.lastFrame = math.max(incData.lastFrame or 0, targetFrame)
else
local teamID = spGetUnitTeam(unitID)
-- Overkill prevention does not prevent firing at unidentified radar dots.
-- Although, it still remembers what has been fired at a radar dot. This is
if targetIdentified then
local queueSize = spGetUnitCommands(unitID, 0)
if queueSize == 1 then
local queue = spGetUnitCommands(unitID, 1)
local cmd = queue[1]
if (cmd.id == CMD.ATTACK) and (cmd.options.internal) and (#cmd.params == 1 and cmd.params[1] == targetID) then
--Spring.Echo("Removing auto-attack command")
spGiveOrderToUnit(unitID, CMD.REMOVE, {cmd.tag}, {} )
--Spring.GiveOrderToUnit(unitID, CMD.STOP, {}, {} )
end
else
spSetUnitTarget(unitID, 0)
end
return true
end
end
return false
end
function GG.OverkillPrevention_CheckBlockDisarm(unitID, targetID, damage, timeout, disarmTimer, fastMult, radarMult)
if not units[unitID] then
return false
end
if spValidUnitID(unitID) and spValidUnitID(targetID) then
local gameFrame = spGetGameFrame()
--CheckBlockCommon(unitID, targetID, gameFrame, fullDamage, disarmDamage, disarmTimeout, timeout)
return CheckBlockCommon(unitID, targetID, gameFrame, 0, damage, disarmTimer, timeout, fastMult, radarMult)
end
end
function GG.OverkillPrevention_CheckBlock(unitID, targetID, damage, timeout, fastMult, radarMult)
if not units[unitID] then
return false
end
if spValidUnitID(unitID) and spValidUnitID(targetID) then
local gameFrame = spGetGameFrame()
--CheckBlockCommon(unitID, targetID, gameFrame, fullDamage, disarmDamage, disarmTimeout, timeout)
return CheckBlockCommon(unitID, targetID, gameFrame, damage, 0, 0, timeout, fastMult, radarMult)
end
return false
end
function gadget:UnitDestroyed(unitID)
if incomingDamage[unitID] then
incomingDamage[unitID] = nil
end
end
--------------------------------------------------------------------------------
-- Command Handling
local function PreventOverkillToggleCommand(unitID, cmdParams, cmdOptions)
if canHandleUnit[unitID] then
local state = cmdParams[1]
local cmdDescID = spFindUnitCmdDesc(unitID, CMD_PREVENT_OVERKILL)
if (cmdDescID) then
preventOverkillCmdDesc.params[1] = state
spEditUnitCmdDesc(unitID, cmdDescID, {params = preventOverkillCmdDesc.params})
end
if state == 1 then
if not units[unitID] then
units[unitID] = true
end
else
if units[unitID] then
units[unitID] = nil
end
end
end
end
function gadget:AllowCommand_GetWantedCommand()
return {[CMD_PREVENT_OVERKILL] = true}
end
function gadget:AllowCommand_GetWantedUnitDefID()
return true
end
function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions)
if (cmdID ~= CMD_PREVENT_OVERKILL) then
return true -- command was not used
end
PreventOverkillToggleCommand(unitID, cmdParams, cmdOptions)
return false -- command was used
end
--------------------------------------------------------------------------------
-- Unit Handling
function gadget:UnitCreated(unitID, unitDefID, teamID)
if HandledUnitDefIDs[unitDefID] then
spInsertUnitCmdDesc(unitID, preventOverkillCmdDesc)
canHandleUnit[unitID] = true
PreventOverkillToggleCommand(unitID, {1})
end
end
function gadget:UnitDestroyed(unitID)
if canHandleUnit[unitID] then
if units[unitID] then
units[unitID] = nil
end
canHandleUnit[unitID] = nil
end
end
function gadget:Initialize()
-- register command
gadgetHandler:RegisterCMDID(CMD_PREVENT_OVERKILL)
-- load active units
for _, unitID in ipairs(Spring.GetAllUnits()) do
local unitDefID = Spring.GetUnitDefID(unitID)
local teamID = Spring.GetUnitTeam(unitID)
gadget:UnitCreated(unitID, unitDefID, teamID)
end
end | gpl-2.0 |
geanux/darkstar | scripts/zones/Misareaux_Coast/npcs/_0p8.lua | 17 | 1782 | -----------------------------------
-- Area: Misareaux Coast
-- NPC: Iron Gate
-- Entrance to Sacrarium
-----------------------------------
package.loaded["scripts/zones/Misareaux_Coast/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Misareaux_Coast/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local currentCoP = player:getCurrentMission(COP);
local PromathiaStatus = player:getVar("PromathiaStatus");
if (currentCoP == THE_SECRETS_OF_WORSHIP and PromathiaStatus == 1) then
player:startEvent(0x0009);
elseif (player:hasCompletedMission(COP,THE_LAST_VERSE) or (currentCoP == THE_SECRETS_OF_WORSHIP and PromathiaStatus >= 2)or(currentCoP > THE_SECRETS_OF_WORSHIP)) then
player:startEvent(0x01f6);
else
player:messageSpecial(DOOR_CLOSED);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0009 and option == 1) then
player:setVar("PromathiaStatus",2);
player:setPos(-220.075,-15.999,79.634,62,28); -- To Sacrarium {R}
elseif (csid == 0x01f6 and option == 1) then
player:setPos(-220.075,-15.999,79.634,62,28); -- To Sacrarium {R}
end
end; | gpl-3.0 |
legend18/dragonbone_cocos2dx-3.x | demos/cocos2d-x-3.x/DragonBonesCppDemos/cocos2d/cocos/scripting/lua-bindings/auto/api/PhysicsWorld.lua | 6 | 2737 |
--------------------------------
-- @module PhysicsWorld
-- @parent_module cc
--------------------------------
-- @function [parent=#PhysicsWorld] getGravity
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
-- @function [parent=#PhysicsWorld] getAllBodies
-- @param self
-- @return array_table#array_table ret (return value: array_table)
--------------------------------
-- @function [parent=#PhysicsWorld] setGravity
-- @param self
-- @param #vec2_table vec2
--------------------------------
-- @function [parent=#PhysicsWorld] getSpeed
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- @overload self, int
-- @overload self, cc.PhysicsBody
-- @function [parent=#PhysicsWorld] removeBody
-- @param self
-- @param #cc.PhysicsBody physicsbody
--------------------------------
-- @function [parent=#PhysicsWorld] removeJoint
-- @param self
-- @param #cc.PhysicsJoint physicsjoint
-- @param #bool bool
--------------------------------
-- @function [parent=#PhysicsWorld] getUpdateRate
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- @function [parent=#PhysicsWorld] setSpeed
-- @param self
-- @param #float float
--------------------------------
-- @function [parent=#PhysicsWorld] getShapes
-- @param self
-- @param #vec2_table vec2
-- @return array_table#array_table ret (return value: array_table)
--------------------------------
-- @function [parent=#PhysicsWorld] removeAllJoints
-- @param self
--------------------------------
-- @function [parent=#PhysicsWorld] getShape
-- @param self
-- @param #vec2_table vec2
-- @return PhysicsShape#PhysicsShape ret (return value: cc.PhysicsShape)
--------------------------------
-- @function [parent=#PhysicsWorld] removeAllBodies
-- @param self
--------------------------------
-- @function [parent=#PhysicsWorld] getDebugDrawMask
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- @function [parent=#PhysicsWorld] setDebugDrawMask
-- @param self
-- @param #int int
--------------------------------
-- @function [parent=#PhysicsWorld] getBody
-- @param self
-- @param #int int
-- @return PhysicsBody#PhysicsBody ret (return value: cc.PhysicsBody)
--------------------------------
-- @function [parent=#PhysicsWorld] setUpdateRate
-- @param self
-- @param #int int
--------------------------------
-- @function [parent=#PhysicsWorld] addJoint
-- @param self
-- @param #cc.PhysicsJoint physicsjoint
return nil
| mit |
geanux/darkstar | scripts/zones/King_Ranperres_Tomb/npcs/Strange_Apparatus.lua | 31 | 1146 | -----------------------------------
-- Area: King_Ranperre's Tomb
-- NPC: Strange Apparatus
-- @pos -260 7 -142 190
-----------------------------------
package.loaded["scripts/zones/King_Ranperres_Tomb/TextIDs"] = nil;
require("scripts/zones/King_Ranperres_Tomb/TextIDs");
require("scripts/globals/strangeapparatus");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
player:startEvent(0x000D, 0, 0, INFINITY_CORE, 0, 0, 0, 0, player:getZoneID());
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x000B, 0, 0, INFINITY_CORE, 0, 0, 0, 0, player:getZoneID());
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
Schwertspize/cuberite | Server/Plugins/APIDump/Hooks/OnChunkUnloading.lua | 28 | 1082 | return
{
HOOK_CHUNK_UNLOADING =
{
CalledWhen = " A chunk is about to be unloaded from the memory. Plugins may refuse the unload.",
DefaultFnName = "OnChunkUnloading", -- also used as pagename
Desc = [[
Cuberite calls this function when a chunk is about to be unloaded from the memory. A plugin may
force Cuberite to keep the chunk in memory by returning true.</p>
<p>
FIXME: The return value should be used only for event propagation stopping, not for the actual
decision whether to unload.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "The world from which the chunk is unloading" },
{ Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" },
{ Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" },
},
Returns = [[
If the function returns false or no value, the next plugin's callback is called and finally Cuberite
unloads the chunk. If the function returns true, no other callback is called for this event and the
chunk is left in the memory.
]],
}, -- HOOK_CHUNK_UNLOADING
}
| apache-2.0 |
aqasaeed/botw | plugins/inrealm.lua | 850 | 25085 | -- 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 |
tonylauCN/tutorials | lua/debugger/lualibs/lua_parser_loose.lua | 4 | 12914 | --[[
lua_parser_loose.lua.
Loose parsing of Lua code. See README.
(c) 2013 David Manura. MIT License.
--]]
local PARSE = {}
local unpack = table.unpack or unpack
local LEX = require 'lua_lexer_loose'
--[[
Loose parser.
lx - lexer stream of Lua tokens.
f(event...) - callback function to send events to.
Events generated:
'Var', name, lineinfo - variable declaration that immediately comes into scope.
'VarSelf', name, lineinfo - same as 'Var' but for implicit 'self' parameter
in method definitions. lineinfo is zero-width space after '('
'VarNext', name, lineinfo - variable definition that comes into scope
upon next statement.
'VarInside', name, lineinfo - variable definition that comes into scope
inside following block. Used for control variables in 'for' statements.
'Id', name, lineinfo - reference to variable.
'String', name - string or table field.
'Scope', opt - beginning of scope block.
'EndScope', nil, lineinfo - end of scope block.
'FunctionCall', name, lineinfo - function call (in addition to other events).
'Function', name, lineinfo - function definition.
--]]
function PARSE.parse_scope(lx, f, level)
local cprev = {tag='Eof'}
-- stack of scopes.
local scopes = {{}}
for l = 2, (level or 1) do scopes[l] = {} end
local function scope_begin(opt, lineinfo, nobreak)
scopes[#scopes+1] = {}
f('Scope', opt, lineinfo, nobreak)
end
local function scope_end(opt, lineinfo)
local scope = #scopes
if scope > 1 then table.remove(scopes) end
local inside_local = false
for scope = scope-1, 1, -1 do
if scopes[scope].inside_local then inside_local = true; break end
end
f('EndScope', opt, lineinfo, inside_local)
end
local function parse_function_list(has_self, name, pos)
local c = lx:next(); assert(c[1] == '(')
f('Statement', c[1], c.lineinfo, true) -- generate Statement for function definition
scope_begin(c[1], c.lineinfo, true)
local vars = {} -- accumulate vars (if any) to send after 'Function'
if has_self then
local lineinfo = c.lineinfo+1 -- zero size
table.insert(vars, {'VarSelf', 'self', lineinfo, true})
end
while true do
local n = lx:peek()
if not (n.tag == 'Id' or n.tag == 'Keyword' and n[1] == '...') then break end
local c = lx:next()
if c.tag == 'Id' then table.insert(vars, {'Var', c[1], c.lineinfo, true}) end
-- ignore '...' in this case
if lx:peek()[1] == ',' then lx:next() end
end
if lx:peek()[1] == ')' then
lx:next()
f('Function', name, pos or c.lineinfo, true)
end
for _, var in ipairs(vars) do f(unpack(var)) end
end
while true do
local c = lx:next()
-- Detect end of previous statement
if c.tag == 'Eof' -- trigger 'Statement' at the end of file
or c.tag == 'Keyword' and (
c[1] == 'break' or c[1] == 'goto' or c[1] == 'do' or c[1] == 'while' or
c[1] == 'repeat' or c[1] == 'if' or c[1] == 'for' or c[1] == 'function' and lx:peek().tag == 'Id' or
c[1] == 'local' or c[1] == ';' or c[1] == 'until' or c[1] == 'return' or c[1] == 'end') or
c.tag == 'Id' and
(cprev.tag == 'Id' or
cprev.tag == 'Keyword' and
(cprev[1] == ']' or cprev[1] == ')' or cprev[1] == '}' or
cprev[1] == '...' or cprev[1] == 'end' or
cprev[1] == 'true' or cprev[1] == 'false' or
cprev[1] == 'nil') or
cprev.tag == 'Number' or cprev.tag == 'String')
then
if scopes[#scopes].inside_until then scope_end(nil, c.lineinfo) end
local scope = #scopes
if not scopes[scope].inside_table then scopes[scope].inside_local = nil end
f('Statement', c[1], c.lineinfo,
scopes[scope].inside_local or c[1] == 'local' or c[1] == 'function' or c[1] == 'end')
end
if c.tag == 'Eof' then break end
-- Process token(s)
if c.tag == 'Keyword' then
if c[1] == 'local' and lx:peek().tag == 'Keyword' and lx:peek()[1] == 'function' then
-- local function
local c = lx:next(); assert(c[1] == 'function')
if lx:peek().tag == 'Id' then
c = lx:next()
f('Var', c[1], c.lineinfo, true)
if lx:peek()[1] == '(' then parse_function_list(nil, c[1], c.lineinfo) end
end
elseif c[1] == 'function' then
if lx:peek()[1] == '(' then -- inline function
parse_function_list()
elseif lx:peek().tag == 'Id' then -- function definition statement
c = lx:next(); assert(c.tag == 'Id')
local name = c[1]
local pos = c.lineinfo
f('Id', name, pos, true)
local has_self
while lx:peek()[1] ~= '(' and lx:peek().tag ~= 'Eof' do
c = lx:next()
name = name .. c[1]
if c.tag == 'Id' then
f('String', c[1], c.lineinfo, true)
elseif c.tag == 'Keyword' and c[1] == ':' then
has_self = true
end
end
if lx:peek()[1] == '(' then parse_function_list(has_self, name, pos) end
end
elseif c[1] == 'local' and lx:peek().tag == 'Id' then
scopes[#scopes].inside_local = true
c = lx:next()
f('VarNext', c[1], c.lineinfo, true)
while lx:peek().tag == 'Keyword' and lx:peek()[1] == ',' do
c = lx:next(); if lx:peek().tag ~= 'Id' then break end
c = lx:next()
f('VarNext', c[1], c.lineinfo, true)
end
elseif c[1] == 'for' and lx:peek().tag == 'Id' then
c = lx:next()
f('VarInside', c[1], c.lineinfo, true)
while lx:peek().tag == 'Keyword' and lx:peek()[1] == ',' do
c = lx:next(); if lx:peek().tag ~= 'Id' then break end
c = lx:next()
f('VarInside', c[1], c.lineinfo, true)
end
elseif c[1] == 'goto' and lx:peek().tag == 'Id' then
lx:next()
elseif c[1] == 'do' then
scope_begin('do', c.lineinfo)
-- note: do/while/for statement scopes all begin at 'do'.
elseif c[1] == 'repeat' or c[1] == 'then' then
scope_begin(c[1], c.lineinfo)
elseif c[1] == 'end' or c[1] == 'elseif' then
scope_end(c[1], c.lineinfo)
elseif c[1] == 'else' then
scope_end(nil, c.lineinfo)
scope_begin(c[1], c.lineinfo)
elseif c[1] == 'until' then
scopes[#scopes].inside_until = true
elseif c[1] == '{' then
scopes[#scopes].inside_table = (scopes[#scopes].inside_table or 0) + 1
elseif c[1] == '}' then
local newval = (scopes[#scopes].inside_table or 0) - 1
newval = newval >= 1 and newval or nil
scopes[#scopes].inside_table = newval
end
elseif c.tag == 'Id' then
local scope = #scopes
local inside_local = scopes[scope].inside_local ~= nil
local inside_table = scopes[scope].inside_table
local cnext = lx:peek()
if cnext.tag == 'Keyword' and (cnext[1] == '(' or cnext[1] == '{')
or cnext.tag == 'String' then
f('FunctionCall', c[1], c.lineinfo, inside_local)
end
-- either this is inside a table or it continues from a comma,
-- which may be a field assignment, so assume it's in a table
if (inside_table or cprev[1] == ',') and cnext.tag == 'Keyword' and cnext[1] == '=' then
-- table field; table fields are tricky to handle during incremental
-- processing as "a = 1" may be either an assignment (in which case
-- 'a' is Id) or a field initialization (in which case it's a String).
-- Since it's not possible to decide between two cases in isolation,
-- this is not a good place to insert a break; instead, the break is
-- inserted at the location of the previous keyword, which allows
-- to properly handle those cases. The desired location of
-- the restart point is returned as the `nobreak` value.
f('String', c[1], c.lineinfo,
inside_local or cprev and cprev.tag == 'Keyword' and cprev.lineinfo)
elseif cprev.tag == 'Keyword' and (cprev[1] == ':' or cprev[1] == '.') then
f('String', c[1], c.lineinfo, true)
else
f('Id', c[1], c.lineinfo, true)
-- this looks like the left side of (multi-variable) assignment
-- unless it's a part of `= var, field = value`, so skip if inside a table
if not inside_table and not (cprev and cprev.tag == 'Keyword' and cprev[1] == '=') then
while lx:peek().tag == 'Keyword' and lx:peek()[1] == ',' do
local c = lx:next(); if lx:peek().tag ~= 'Id' then break end
c = lx:next()
f('Id', c[1], c.lineinfo, true)
end
end
end
end
if c.tag ~= 'Comment' then cprev = c end
end
end
--[[
This is similar to parse_scope but determines if variables are local or global.
lx - lexer stream of Lua tokens.
f(event...) - callback function to send events to.
Events generated:
'Id', name, lineinfo, 'local'|'global'
(plus all events in parse_scope)
--]]
function PARSE.parse_scope_resolve(lx, f, vars)
local NEXT = {} -- unique key
local INSIDE = {} -- unique key
local function newscope(vars, opt, lineinfo)
local newvars = opt=='do' and vars[INSIDE] or {}
if newvars == vars[INSIDE] then vars[INSIDE] = false end
newvars[INSIDE]=false
newvars[NEXT]=false
local level = (vars[0] or 0) + 1
newvars[0] = level -- keep the current level
newvars[-1] = lineinfo -- keep the start of the scope
newvars[level] = newvars -- reference the current vars table
return setmetatable(newvars, {__index=vars})
end
vars = vars or newscope({[0] = 0}, nil, 1)
vars[NEXT] = false -- vars that come into scope upon next statement
vars[INSIDE] = false -- vars that come into scope upon entering block
PARSE.parse_scope(lx, function(op, name, lineinfo, nobreak)
-- in some (rare) cases VarNext can follow Statement event (which copies
-- vars[NEXT]). This may cause vars[0] to be `nil`, so default to 1.
local var = op:find("^Var") and
{fpos = lineinfo, at = (vars[0] or 1) + (op == 'VarInside' and 1 or 0),
masked = vars[name], self = (op == 'VarSelf') or nil } or nil
if op == 'Var' or op == 'VarSelf' then
vars[name] = var
elseif op == 'VarNext' then
vars[NEXT] = vars[NEXT] or {}
vars[NEXT][name] = var
elseif op == 'VarInside' then
vars[INSIDE] = vars[INSIDE] or {}
vars[INSIDE][name] = var
elseif op == 'Scope' then
vars = newscope(vars, name, lineinfo)
elseif op == 'EndScope' then
local mt = getmetatable(vars)
if mt ~= nil then vars = mt.__index end
elseif op == 'Id'
or op == 'String' or op == 'FunctionCall' or op == 'Function' then
-- Just make callback
elseif op == 'Statement' then -- beginning of statement
-- Apply vars that come into scope upon beginning of statement.
if vars[NEXT] then
for k,v in pairs(vars[NEXT]) do
vars[k] = v; vars[NEXT][k] = nil
end
end
else
assert(false)
end
f(op, name, lineinfo, vars, nobreak)
end, vars[0])
end
function PARSE.extract_vars(code, f)
local lx = LEX.lexc(code)
local char0 = 1 -- next char offset to write
local function gen(char1, nextchar0)
char0 = nextchar0
end
PARSE.parse_scope_resolve(lx, function(op, name, lineinfo, other)
if op == 'Id' then
f('Id', name, other, lineinfo)
elseif op == 'Var' or op == 'VarNext' or op == 'VarInside' then
gen(lineinfo, lineinfo+#name)
f('Var', name, "local", lineinfo)
end -- ignore 'VarSelf' and others
end)
gen(#code+1, nil)
end
--[[
Converts 5.2 code to 5.1 style code with explicit _ENV variables.
Example: "function f(_ENV, x) print(x, y)" -->
"function _ENV.f(_ENV, x) _ENV.print(x, _ENV.y) end"
code - string of Lua code. Assumed to be valid Lua (FIX: 5.1 or 5.2?)
f(s) - call back function to send chunks of Lua code output to. Example: io.stdout.
--]]
function PARSE.replace_env(code, f)
if not f then return PARSE.accumulate(PARSE.replace_env, code) end
PARSE.extract_vars(code, function(op, name, other)
if op == 'Id' then
f(other == 'global' and '_ENV.' .. name or name)
elseif op == 'Var' or op == 'Other' then
f(name)
end
end)
end
-- helper function. Can be passed as argument `f` to functions
-- like `replace_env` above to accumulate fragments into a single string.
function PARSE.accumulator()
local ts = {}
local mt = {}
mt.__index = mt
function mt:__call(s) ts[#ts+1] = s end
function mt:result() return table.concat(ts) end
return setmetatable({}, mt)
end
-- helper function
function PARSE.accumulate(g, code)
local accum = PARSE.accumulator()
g(code, accum)
return accum:result()
end
return PARSE
| apache-2.0 |
geanux/darkstar | scripts/zones/Port_Windurst/npcs/Newlyn.lua | 38 | 1034 | -----------------------------------
-- Area: Port Windurst
-- NPC: Newlyn
-- Type: Standard NPC
-- @zone: 240
-- @pos 200.673 -6.601 108.665
--
-- Auto-Script: Requires Verification (Verfied By Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00be);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/Dynamis-Tavnazia/mobs/Nightmare_Makara.lua | 13 | 1506 | -----------------------------------
-- Area: Dynamis Tavnazia
-- NPC: Nightmare_Makara
-----------------------------------
package.loaded["scripts/zones/Dynamis-Tavnazia/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Tavnazia/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
local X = mob:getXPos();
local Y = mob:getYPos();
local Z = mob:getZPos();
local spawnList = TavnaziaCloneList;
if (mob:getStatPoppedMobs() == false) then
mob:setStatPoppedMobs(true);
for nb = 1, table.getn(spawnList), 2 do
if (mob:getID() == spawnList[nb]) then
for nbi = 1, table.getn(spawnList[nb + 1]), 1 do
if ((nbi % 2) == 0) then X=X+2; Z=Z+2; else X=X-2; Z=Z-2; end
local mobNBR = spawnList[nb + 1][nbi];
if (mobNBR ~= nil) then
-- Spawn Mob
SpawnMob(mobNBR):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(mobNBR):setPos(X,Y,Z);
GetMobByID(mobNBR):setSpawn(X,Y,Z);
end
end
end
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
end; | gpl-3.0 |
LiangMa/skynet | service/launcher.lua | 51 | 3199 | local skynet = require "skynet"
local core = require "skynet.core"
require "skynet.manager" -- import manager apis
local string = string
local services = {}
local command = {}
local instance = {} -- for confirm (function command.LAUNCH / command.ERROR / command.LAUNCHOK)
local function handle_to_address(handle)
return tonumber("0x" .. string.sub(handle , 2))
end
local NORET = {}
function command.LIST()
local list = {}
for k,v in pairs(services) do
list[skynet.address(k)] = v
end
return list
end
function command.STAT()
local list = {}
for k,v in pairs(services) do
local stat = skynet.call(k,"debug","STAT")
list[skynet.address(k)] = stat
end
return list
end
function command.KILL(_, handle)
handle = handle_to_address(handle)
skynet.kill(handle)
local ret = { [skynet.address(handle)] = tostring(services[handle]) }
services[handle] = nil
return ret
end
function command.MEM()
local list = {}
for k,v in pairs(services) do
local kb, bytes = skynet.call(k,"debug","MEM")
list[skynet.address(k)] = string.format("%.2f Kb (%s)",kb,v)
end
return list
end
function command.GC()
for k,v in pairs(services) do
skynet.send(k,"debug","GC")
end
return command.MEM()
end
function command.REMOVE(_, handle, kill)
services[handle] = nil
local response = instance[handle]
if response then
-- instance is dead
response(not kill) -- return nil to caller of newservice, when kill == false
instance[handle] = nil
end
-- don't return (skynet.ret) because the handle may exit
return NORET
end
local function launch_service(service, ...)
local param = table.concat({...}, " ")
local inst = skynet.launch(service, param)
local response = skynet.response()
if inst then
services[inst] = service .. " " .. param
instance[inst] = response
else
response(false)
return
end
return inst
end
function command.LAUNCH(_, service, ...)
launch_service(service, ...)
return NORET
end
function command.LOGLAUNCH(_, service, ...)
local inst = launch_service(service, ...)
if inst then
core.command("LOGON", skynet.address(inst))
end
return NORET
end
function command.ERROR(address)
-- see serivce-src/service_lua.c
-- init failed
local response = instance[address]
if response then
response(false)
instance[address] = nil
end
services[address] = nil
return NORET
end
function command.LAUNCHOK(address)
-- init notice
local response = instance[address]
if response then
response(true, address)
instance[address] = nil
end
return NORET
end
-- for historical reasons, launcher support text command (for C service)
skynet.register_protocol {
name = "text",
id = skynet.PTYPE_TEXT,
unpack = skynet.tostring,
dispatch = function(session, address , cmd)
if cmd == "" then
command.LAUNCHOK(address)
elseif cmd == "ERROR" then
command.ERROR(address)
else
error ("Invalid text command " .. cmd)
end
end,
}
skynet.dispatch("lua", function(session, address, cmd , ...)
cmd = string.upper(cmd)
local f = command[cmd]
if f then
local ret = f(address, ...)
if ret ~= NORET then
skynet.ret(skynet.pack(ret))
end
else
skynet.ret(skynet.pack {"Unknown command"} )
end
end)
skynet.start(function() end)
| mit |
forward619/luci | applications/luci-app-multiwan/luasrc/controller/multiwan.lua | 62 | 1929 | module("luci.controller.multiwan", package.seeall)
function index()
local fs = require "nixio.fs"
if not fs.access("/etc/config/multiwan") then
return
end
local page
page = entry({"admin", "network", "multiwan"}, cbi("multiwan/multiwan"), _("Multi-WAN"))
page.dependent = true
entry({"admin", "network", "multiwan", "status"}, call("multiwan_status"))
page = entry({"mini", "network", "multiwan"}, cbi("multiwan/multiwanmini", {autoapply=true}), _("Multi-WAN"))
page.dependent = true
end
function multiwan_status()
local nfs = require "nixio.fs"
local cachefile = "/tmp/.mwan/cache"
local rv = { }
cachefile = nfs.readfile(cachefile)
if cachefile then
local ntm = require "luci.model.network".init()
_, _, wan_if_map = string.find(cachefile, "wan_if_map=\"([^\"]*)\"")
_, _, wan_fail_map = string.find(cachefile, "wan_fail_map=\"([^\"]*)\"")
_, _, wan_recovery_map = string.find(cachefile, "wan_recovery_map=\"([^\"]*)\"")
rv.wans = { }
wansid = {}
for wanname, wanifname in string.gfind(wan_if_map, "([^%[]+)%[([^%]]+)%]") do
local wanlink = ntm:get_interface(wanifname)
wanlink = wanlink and wanlink:get_network()
wanlink = wanlink and wanlink:adminlink() or "#"
wansid[wanname] = #rv.wans + 1
rv.wans[wansid[wanname]] = { name = wanname, link = wanlink, ifname = wanifname, status = "ok", count = 0 }
end
for wanname, failcount in string.gfind(wan_fail_map, "([^%[]+)%[([^%]]+)%]") do
if failcount == "x" then
rv.wans[wansid[wanname]].status = "ko"
else
rv.wans[wansid[wanname]].status = "failing"
rv.wans[wansid[wanname]].count = failcount
end
end
for wanname, recoverycount in string.gfind(wan_recovery_map, "([^%[]+)%[([^%]]+)%]") do
rv.wans[wansid[wanname]].status = "recovering"
rv.wans[wansid[wanname]].count = recoverycount
end
end
luci.http.prepare_content("application/json")
luci.http.write_json(rv)
end
| apache-2.0 |
geanux/darkstar | scripts/globals/items/rarab_meatball.lua | 35 | 1731 | -----------------------------------------
-- ID: 4507
-- Item: rarab_meatball
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Health 10
-- Strength 2
-- Vitality 2
-- Intelligence -1
-- Attack % 30
-- Attack Cap 20
-- Ranged ATT % 30
-- Ranged ATT Cap 20
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4507);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 10);
target:addMod(MOD_STR, 2);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_INT, -1);
target:addMod(MOD_FOOD_ATTP, 30);
target:addMod(MOD_FOOD_ATT_CAP, 20);
target:addMod(MOD_FOOD_RATTP, 30);
target:addMod(MOD_FOOD_RATT_CAP, 20);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 10);
target:delMod(MOD_STR, 2);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_INT, -1);
target:delMod(MOD_FOOD_ATTP, 30);
target:delMod(MOD_FOOD_ATT_CAP, 20);
target:delMod(MOD_FOOD_RATTP, 30);
target:delMod(MOD_FOOD_RATT_CAP, 20);
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/The_Garden_of_RuHmet/mobs/Jailer_of_Fortitude.lua | 17 | 2477 | -----------------------------------
-- Area: The Garden of Ru'Hmet
-- NPC: Jailer_of_Fortitude
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
-- Give it two hour
mob:setMobMod(MOBMOD_MAIN_2HOUR, 1);
mob:setMobMod(MOBMOD_2HOUR_MULTI, 1);
-- Change animation to humanoid w/ prismatic core
mob:AnimationSub(1);
mob:setModelId(1169);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob)
local delay = mob:getLocalVar("delay");
local LastCast = mob:getLocalVar("LAST_CAST");
local spell = mob:getLocalVar("COPY_SPELL");
if (mob:getBattleTime() - LastCast > 30) then
mob:setLocalVar("COPY_SPELL", 0);
mob:setLocalVar("delay", 0);
end;
if (IsMobDead(16921016)==false or IsMobDead(16921017)==false) then -- check for kf'ghrah
if (spell > 0 and mob:hasStatusEffect(EFFECT_SILENCE) == false) then
if (delay >= 3) then
mob:castSpell(spell);
mob:setLocalVar("COPY_SPELL", 0);
mob:setLocalVar("delay", 0);
else
mob:setLocalVar("delay", delay+1);
end;
end;
end;
end;
-----------------------------------
-- onMagicHit Action
-----------------------------------
function onMagicHit(caster,target,spell)
if (spell:tookEffect() and (caster:isPC() or caster:isPet()) and spell:getSpellGroup() ~= SPELLGROUP_BLUE ) then
-- Handle mimicked spells
target:setLocalVar("COPY_SPELL", spell:getID());
target:setLocalVar("LAST_CAST", target:getBattleTime());
target:setLocalVar("reflectTime", target:getBattleTime());
target:AnimationSub(1);
end;
return 1;
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer, npc)
-- Despawn the pets if alive
DespawnMob(Kf_Ghrah_WHM);
DespawnMob(Kf_Ghrah_BLM);
-- Set 15 mins respawn
local qm1 = GetNPCByID(Jailer_of_Fortitude_QM);
qm1:hideNPC(900);
-- Move it to a random location
local qm1position = math.random(1,5);
qm1:setPos(Jailer_of_Fortitude_QM_POS[qm1position][1], Jailer_of_Fortitude_QM_POS[qm1position][2], Jailer_of_Fortitude_QM_POS[qm1position][3]);
end;
| gpl-3.0 |
ModusCreateOrg/libOpenMPT-ios | libopenmpt-0.2.6401/build/premake/premake.lua | 1 | 13979 |
-- premake gets a tiny bit confused if the same project appears in multiple
-- solutions in a single run. premake adds a bogus $projectname path to the
-- intermediate objects directory in that case. work-around using multiple
-- invocations of premake and a custom option to distinguish them.
MPT_PREMAKE_VERSION = ""
MPT_WITH_SHARED = true
if _PREMAKE_VERSION == "5.0.0-alpha8" then
MPT_PREMAKE_VERSION = "5.0"
else
print "Premake 5.0.0-alpha8 required"
os.exit(1)
end
newoption {
trigger = "group",
value = "PROJECTS",
description = "OpenMPT project group",
allowed = {
{ "libopenmpt-all", "libopenmpt-all" },
{ "libopenmpt_test", "libopenmpt_test" },
{ "libopenmpt", "libopenmpt" },
{ "libopenmpt-small", "libopenmpt-small" },
{ "foo_openmpt", "foo_openmpt" },
{ "in_openmpt", "in_openmpt" },
{ "xmp-openmpt", "xmp-openmpt" },
{ "openmpt123", "openmpt123" },
{ "PluginBridge", "PluginBridge" },
{ "OpenMPT-VSTi", "OpenMPT-VSTi" },
{ "OpenMPT", "OpenMPT" },
{ "all-externals", "all-externals" }
}
}
function replace_in_file (filename, from, to)
local text
local infile
local outfile
local oldtext
local newtext
infile = io.open(filename, "r")
text = infile:read("*all")
infile:close()
oldtext = text
newtext = string.gsub(oldtext, from, to)
text = newtext
if newtext == oldtext then
print("Failed to postprocess '" .. filename .. "': " .. from .. " -> " .. to)
os.exit(1)
end
outfile = io.open(filename, "w")
outfile:write(text)
outfile:close()
end
-- related to issue https://github.com/premake/premake-core/issues/68
function postprocess_vs2008_main (filename)
replace_in_file(filename, "\t\t\t\tEntryPointSymbol=\"mainCRTStartup\"\n", "")
end
function postprocess_vs2008_nonxcompat (filename)
replace_in_file(filename, "\t\t\t<Tool\n\t\t\t\tName=\"VCLinkerTool\"\n", "\t\t\t<Tool\n\t\t\t\tName=\"VCLinkerTool\"\n\t\t\t\t\DataExecutionPrevention=\"1\"\n")
end
-- related to issue https://github.com/premake/premake-core/issues/68
function postprocess_vs2010_main (filename)
replace_in_file(filename, "<EntryPointSymbol>mainCRTStartup</EntryPointSymbol>", "")
end
function postprocess_vs2010_nonxcompat (filename)
replace_in_file(filename, " </Link>\n", " <DataExecutionPrevention>false</DataExecutionPrevention>\n </Link>\n")
end
function postprocess_vs2010_disabledpiaware (filename)
replace_in_file(filename, "%%%(AdditionalManifestFiles%)</AdditionalManifestFiles>\n", "%%%(AdditionalManifestFiles%)</AdditionalManifestFiles>\n <EnableDPIAwareness>false</EnableDPIAwareness>\n")
end
newaction {
trigger = "postprocess",
description = "OpenMPT postprocess the project files to mitigate premake problems",
execute = function ()
postprocess_vs2008_main("build/vs2008/libopenmpt_test.vcproj")
postprocess_vs2008_main("build/vs2008/openmpt123.vcproj")
postprocess_vs2008_main("build/vs2008/libopenmpt_example_c.vcproj")
postprocess_vs2008_main("build/vs2008/libopenmpt_example_c_mem.vcproj")
postprocess_vs2008_main("build/vs2008/libopenmpt_example_c_unsafe.vcproj")
postprocess_vs2008_nonxcompat("build/vs2008/OpenMPT.vcproj")
postprocess_vs2008_nonxcompat("build/vs2008/PluginBridge.vcproj")
postprocess_vs2010_main("build/vs2010/libopenmpt_test.vcxproj")
postprocess_vs2010_main("build/vs2010/openmpt123.vcxproj")
postprocess_vs2010_main("build/vs2010/libopenmpt_example_c.vcxproj")
postprocess_vs2010_main("build/vs2010/libopenmpt_example_c_mem.vcxproj")
postprocess_vs2010_main("build/vs2010/libopenmpt_example_c_unsafe.vcxproj")
postprocess_vs2010_main("build/vs2010/libopenmpt_example_cxx.vcxproj")
postprocess_vs2010_nonxcompat("build/vs2010/OpenMPT.vcxproj")
postprocess_vs2010_disabledpiaware("build/vs2010/OpenMPT.vcxproj")
postprocess_vs2010_nonxcompat("build/vs2010/PluginBridge.vcxproj")
postprocess_vs2010_disabledpiaware("build/vs2010/PluginBridge.vcxproj")
postprocess_vs2010_main("build/vs2012/libopenmpt_test.vcxproj")
postprocess_vs2010_main("build/vs2012/openmpt123.vcxproj")
postprocess_vs2010_main("build/vs2012/libopenmpt_example_c.vcxproj")
postprocess_vs2010_main("build/vs2012/libopenmpt_example_c_mem.vcxproj")
postprocess_vs2010_main("build/vs2012/libopenmpt_example_c_unsafe.vcxproj")
postprocess_vs2010_main("build/vs2012/libopenmpt_example_cxx.vcxproj")
postprocess_vs2010_nonxcompat("build/vs2012/OpenMPT.vcxproj")
postprocess_vs2010_disabledpiaware("build/vs2012/OpenMPT.vcxproj")
postprocess_vs2010_nonxcompat("build/vs2012/PluginBridge.vcxproj")
postprocess_vs2010_disabledpiaware("build/vs2012/PluginBridge.vcxproj")
postprocess_vs2010_main("build/vs2013/libopenmpt_test.vcxproj")
postprocess_vs2010_main("build/vs2013/openmpt123.vcxproj")
postprocess_vs2010_main("build/vs2013/libopenmpt_example_c.vcxproj")
postprocess_vs2010_main("build/vs2013/libopenmpt_example_c_mem.vcxproj")
postprocess_vs2010_main("build/vs2013/libopenmpt_example_c_unsafe.vcxproj")
postprocess_vs2010_main("build/vs2013/libopenmpt_example_cxx.vcxproj")
postprocess_vs2010_nonxcompat("build/vs2013/OpenMPT.vcxproj")
postprocess_vs2010_disabledpiaware("build/vs2013/OpenMPT.vcxproj")
postprocess_vs2010_nonxcompat("build/vs2013/PluginBridge.vcxproj")
postprocess_vs2010_disabledpiaware("build/vs2013/PluginBridge.vcxproj")
postprocess_vs2010_main("build/vs2015/libopenmpt_test.vcxproj")
postprocess_vs2010_main("build/vs2015/openmpt123.vcxproj")
postprocess_vs2010_main("build/vs2015/libopenmpt_example_c.vcxproj")
postprocess_vs2010_main("build/vs2015/libopenmpt_example_c_mem.vcxproj")
postprocess_vs2010_main("build/vs2015/libopenmpt_example_c_unsafe.vcxproj")
postprocess_vs2010_main("build/vs2015/libopenmpt_example_cxx.vcxproj")
postprocess_vs2010_nonxcompat("build/vs2015/OpenMPT.vcxproj")
postprocess_vs2010_disabledpiaware("build/vs2015/OpenMPT.vcxproj")
postprocess_vs2010_nonxcompat("build/vs2015/PluginBridge.vcxproj")
postprocess_vs2010_disabledpiaware("build/vs2015/PluginBridge.vcxproj")
end
}
if _OPTIONS["group"] == "libopenmpt-all" then
solution "libopenmpt-all"
location ( "../../build/" .. _ACTION )
configurations { "Debug", "Release" }
platforms { "x86", "x86_64" }
dofile "../../build/premake/mpt-libopenmpt_test.lua"
dofile "../../build/premake/mpt-libopenmpt.lua"
dofile "../../build/premake/mpt-libopenmpt_examples.lua"
dofile "../../build/premake/mpt-libopenmpt-small.lua"
dofile "../../build/premake/mpt-libopenmpt_modplug.lua"
dofile "../../build/premake/mpt-foo_openmpt.lua"
dofile "../../build/premake/mpt-in_openmpt.lua"
dofile "../../build/premake/mpt-xmp-openmpt.lua"
dofile "../../build/premake/mpt-openmpt123.lua"
dofile "../../build/premake/ext-flac.lua"
dofile "../../build/premake/ext-miniz.lua"
dofile "../../build/premake/ext-ogg.lua"
dofile "../../build/premake/ext-portaudio.lua"
dofile "../../build/premake/ext-portaudiocpp.lua"
dofile "../../build/premake/ext-vorbis.lua"
dofile "../../build/premake/ext-zlib.lua"
end
if _OPTIONS["group"] == "libopenmpt_test" then
solution "libopenmpt_test"
location ( "../../build/" .. _ACTION )
configurations { "Debug", "Release" }
platforms { "x86", "x86_64" }
dofile "../../build/premake/mpt-libopenmpt_test.lua"
dofile "../../build/premake/ext-ogg.lua"
dofile "../../build/premake/ext-vorbis.lua"
dofile "../../build/premake/ext-zlib.lua"
end
if _OPTIONS["group"] == "foo_openmpt" then
solution "foo_openmpt"
location ( "../../build/" .. _ACTION )
configurations { "Debug", "Release" }
platforms { "x86" }
dofile "../../build/premake/mpt-foo_openmpt.lua"
dofile "../../build/premake/mpt-libopenmpt.lua"
dofile "../../build/premake/ext-ogg.lua"
dofile "../../build/premake/ext-vorbis.lua"
dofile "../../build/premake/ext-zlib.lua"
end
if _OPTIONS["group"] == "in_openmpt" then
solution "in_openmpt"
location ( "../../build/" .. _ACTION )
configurations { "Debug", "Release" }
platforms { "x86" }
dofile "../../build/premake/mpt-in_openmpt.lua"
dofile "../../build/premake/mpt-libopenmpt.lua"
dofile "../../build/premake/ext-ogg.lua"
dofile "../../build/premake/ext-vorbis.lua"
dofile "../../build/premake/ext-zlib.lua"
end
if _OPTIONS["group"] == "xmp-openmpt" then
solution "xmp-openmpt"
location ( "../../build/" .. _ACTION )
configurations { "Debug", "Release" }
platforms { "x86" }
dofile "../../build/premake/mpt-xmp-openmpt.lua"
dofile "../../build/premake/mpt-libopenmpt.lua"
dofile "../../build/premake/ext-ogg.lua"
dofile "../../build/premake/ext-pugixml.lua"
dofile "../../build/premake/ext-vorbis.lua"
dofile "../../build/premake/ext-zlib.lua"
end
if _OPTIONS["group"] == "libopenmpt-small" then
solution "libopenmpt-small"
location ( "../../build/" .. _ACTION )
if MPT_WITH_SHARED then
configurations { "Debug", "Release", "DebugShared", "ReleaseShared" }
else
configurations { "Debug", "Release" }
end
platforms { "x86", "x86_64" }
dofile "../../build/premake/mpt-libopenmpt-small.lua"
dofile "../../build/premake/ext-miniz.lua"
dofile "../../build/premake/ext-stb_vorbis.lua"
end
-- should stay the last libopenmpt solution in order to overwrite the libopenmpt base project with all possible configurations
if _OPTIONS["group"] == "libopenmpt" then
solution "libopenmpt"
location ( "../../build/" .. _ACTION )
if MPT_WITH_SHARED then
configurations { "Debug", "Release", "DebugShared", "ReleaseShared" }
else
configurations { "Debug", "Release" }
end
platforms { "x86", "x86_64" }
dofile "../../build/premake/mpt-libopenmpt.lua"
dofile "../../build/premake/mpt-libopenmpt_examples.lua"
dofile "../../build/premake/mpt-libopenmpt_modplug.lua"
dofile "../../build/premake/ext-ogg.lua"
dofile "../../build/premake/ext-portaudio.lua"
dofile "../../build/premake/ext-portaudiocpp.lua"
dofile "../../build/premake/ext-vorbis.lua"
dofile "../../build/premake/ext-zlib.lua"
end
if _OPTIONS["group"] == "openmpt123" then
solution "openmpt123"
location ( "../../build/" .. _ACTION )
if MPT_WITH_SHARED then
configurations { "Debug", "Release", "DebugShared", "ReleaseShared" }
else
configurations { "Debug", "Release" }
end
platforms { "x86", "x86_64" }
dofile "../../build/premake/mpt-openmpt123.lua"
dofile "../../build/premake/mpt-libopenmpt.lua"
dofile "../../build/premake/ext-flac.lua"
dofile "../../build/premake/ext-ogg.lua"
dofile "../../build/premake/ext-portaudio.lua"
dofile "../../build/premake/ext-vorbis.lua"
dofile "../../build/premake/ext-zlib.lua"
end
if _OPTIONS["group"] == "PluginBridge" then
solution "PluginBridge"
location ( "../../build/" .. _ACTION )
configurations { "Debug", "Release", "DebugMDd", "ReleaseLTCG" }
platforms { "x86", "x86_64" }
dofile "../../build/premake/mpt-PluginBridge.lua"
end
if 1 == 0 then
-- disabled
if _OPTIONS["group"] == "OpenMPT-VSTi" then
solution "OpenMPT-VSTi"
location ( "../../build/" .. _ACTION )
configurations { "Debug", "Release" }
platforms { "x86", "x86_64" }
dofile "../../build/premake/mpt-OpenMPT-VSTi.lua"
dofile "../../build/premake/ext-flac.lua"
dofile "../../build/premake/ext-lhasa.lua"
dofile "../../build/premake/ext-minizip.lua"
dofile "../../build/premake/ext-ogg.lua"
dofile "../../build/premake/ext-opus.lua"
dofile "../../build/premake/ext-opusfile.lua"
dofile "../../build/premake/ext-portaudio.lua"
dofile "../../build/premake/ext-portmidi.lua"
dofile "../../build/premake/ext-r8brain.lua"
dofile "../../build/premake/ext-smbPitchShift.lua"
dofile "../../build/premake/ext-soundtouch.lua"
dofile "../../build/premake/ext-UnRAR.lua"
dofile "../../build/premake/ext-vorbis.lua"
dofile "../../build/premake/ext-zlib.lua"
end
end
if _OPTIONS["group"] == "OpenMPT" then
solution "OpenMPT"
location ( "../../build/" .. _ACTION )
if MPT_WITH_SHARED then
configurations { "Debug", "Release", "DebugMDd", "ReleaseLTCG", "DebugShared", "ReleaseShared" }
else
configurations { "Debug", "Release", "DebugMDd", "ReleaseLTCG" }
end
platforms { "x86", "x86_64" }
dofile "../../build/premake/mpt-OpenMPT.lua"
dofile "../../build/premake/mpt-PluginBridge.lua"
dofile "../../build/premake/ext-flac.lua"
dofile "../../build/premake/ext-lhasa.lua"
dofile "../../build/premake/ext-minizip.lua"
dofile "../../build/premake/ext-ogg.lua"
dofile "../../build/premake/ext-opus.lua"
dofile "../../build/premake/ext-opusfile.lua"
dofile "../../build/premake/ext-portaudio.lua"
dofile "../../build/premake/ext-portmidi.lua"
dofile "../../build/premake/ext-r8brain.lua"
dofile "../../build/premake/ext-smbPitchShift.lua"
dofile "../../build/premake/ext-soundtouch.lua"
dofile "../../build/premake/ext-UnRAR.lua"
dofile "../../build/premake/ext-vorbis.lua"
dofile "../../build/premake/ext-zlib.lua"
end
-- overwrite all external projects once again with the full matrix of possible build config combinations
if _OPTIONS["group"] == "all-externals" then
solution "all-externals"
location ( "../../build/" .. _ACTION .. "-ext" )
if MPT_WITH_SHARED then
configurations { "Debug", "Release", "DebugMDd", "ReleaseLTCG", "DebugShared", "ReleaseShared" }
else
configurations { "Debug", "Release", "DebugMDd", "ReleaseLTCG" }
end
platforms { "x86", "x86_64" }
dofile "../../build/premake/ext-flac.lua"
dofile "../../build/premake/ext-lhasa.lua"
dofile "../../build/premake/ext-miniz.lua"
dofile "../../build/premake/ext-minizip.lua"
dofile "../../build/premake/ext-ogg.lua"
dofile "../../build/premake/ext-opus.lua"
dofile "../../build/premake/ext-opusfile.lua"
dofile "../../build/premake/ext-portaudio.lua"
dofile "../../build/premake/ext-portmidi.lua"
dofile "../../build/premake/ext-pugixml.lua"
dofile "../../build/premake/ext-r8brain.lua"
dofile "../../build/premake/ext-smbPitchShift.lua"
dofile "../../build/premake/ext-soundtouch.lua"
dofile "../../build/premake/ext-stb_vorbis.lua"
dofile "../../build/premake/ext-UnRAR.lua"
dofile "../../build/premake/ext-vorbis.lua"
dofile "../../build/premake/ext-zlib.lua"
end
| bsd-3-clause |
geanux/darkstar | scripts/zones/Selbina/npcs/Porter_Moogle.lua | 41 | 1520 | -----------------------------------
-- Area: Selbina
-- NPC: Porter Moogle
-- Type: Storage Moogle
-- @zone 248
-- @pos TODO
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/porter_moogle_util");
local e =
{
TALK_EVENT_ID = 1137,
STORE_EVENT_ID = 1138,
RETRIEVE_EVENT_ID = 1139,
ALREADY_STORED_ID = 1140,
MAGIAN_TRIAL_ID = 1141
};
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
porterMoogleTrade(player, trade, e);
end
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- No idea what the params are, other than event ID and gil.
player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8);
end
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED);
end
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
porterEventFinish(player, csid, option, e.TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL);
end | gpl-3.0 |
geanux/darkstar | scripts/zones/Inner_Horutoto_Ruins/npcs/_5cg.lua | 34 | 1075 | -----------------------------------
-- Area: Inner Horutoto Ruins
-- NPC: _5cg (Gate of Fire)
-- @pos -332 0 99 192
-----------------------------------
package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Inner_Horutoto_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(DOOR_FIRMLY_CLOSED);
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
geanux/darkstar | scripts/globals/mobskills/Sickle_Slash.lua | 12 | 1266 | ---------------------------------------------------
-- Sickle Slash
-- Deals critical damage. Chance of critical hit varies with TP.
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
---------------------------------------------------
-- onMobSkillCheck
-- Check for Grah Family id 122,123,124
-- if not in Spider form, then ignore.
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
if ((mob:getFamily() == 122 or mob:getFamily() == 123 or mob:getFamily() == 124) and mob:AnimationSub() ~= 2) then
return 1;
else
return 0;
end
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = math.random(2,5) + math.random();
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_CRIT_VARIES,1,1.5,2);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded);
-- cap off damage around 600
if (dmg > 600) then
dmg = dmg * 0.7;
end
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
geanux/darkstar | scripts/globals/spells/lightning_carol.lua | 18 | 1517 | -----------------------------------------
-- Spell: Lightning Carol
-- Increases lightning resistance for party members within the area of effect.
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
local power = 20;
if (sLvl+iLvl > 200) then
power = power + math.floor((sLvl+iLvl-200) / 10);
end
if (power >= 40) then
power = 40;
end
local iBoost = caster:getMod(MOD_CAROL_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
power = power + iBoost*5;
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_CAROL,power,0,duration,caster:getID(), ELE_LIGHTNING, 1)) then
spell:setMsg(75);
end
return EFFECT_CAROL;
end; | gpl-3.0 |
geanux/darkstar | scripts/zones/Chateau_dOraguille/npcs/Halver.lua | 18 | 8554 | -----------------------------------
-- Area: Chateau d'Oraguille
-- NPC: Halver
-- Involved in Mission 2-3, 3-3, 5-1, 5-2, 8-1
-- Involved in Quest: Lure of the Wildcat (San d'Oria)
-- @pos 2 0.1 0.1 233
-----------------------------------
package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/zones/Chateau_dOraguille/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--print(player:getVar("MissionStatus"));
local pNation = player:getNation();
local currentMission = player:getCurrentMission(pNation);
local WildcatSandy = player:getVar("WildcatSandy");
local MissionStatus = player:getVar("MissionStatus");
-- Lure of the Wildcat San d'Oria
if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,16) == false) then
player:startEvent(0x022e);
-- Blackmail quest
elseif (player:getQuestStatus(SANDORIA, BLACKMAIL) == QUEST_ACCEPTED and player:hasKeyItem(SUSPICIOUS_ENVELOPE)) then
player:startEvent(0x0225);
player:setVar("BlackMailQuest",1);
player:delKeyItem(SUSPICIOUS_ENVELOPE);
-- San D'Oria Flag check
elseif (player:getVar("Flagsando") == 1) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,181);
else
player:setVar("Flagsando",0);
player:addItem(181);
player:messageSpecial(ITEM_OBTAINED,181);
end
elseif (player:getCurrentMission(TOAU) == CONFESSIONS_OF_ROYALTY) then
if (player:hasKeyItem(RAILLEFALS_LETTER)) then
player:startEvent(0x0234);
end
elseif (player:getCurrentMission(TOAU) == EASTERLY_WINDS and player:getVar("TOAUM6") == 0) then
player:startEvent(0x0235);
elseif (pNation == SANDORIA) then
-- Mission San D'Oria 9-2 The Heir to the Light
if (player:hasCompletedMission(SANDORIA,THE_HEIR_TO_THE_LIGHT)) then
player:startEvent(0x001f);
elseif (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus == 7) then
player:startEvent(0x0009);
elseif (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus == 6) then
player:startEvent(0x001e);
elseif (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus >= 2 and MissionStatus <=5) then
player:startEvent(0x001d);
-- Mission San d'Oria 8-1 Coming of Age --
elseif (currentMission == COMING_OF_AGE and MissionStatus == 3 and player:hasKeyItem(DROPS_OF_AMNIO)) then
player:startEvent(0x0066);
elseif (currentMission == COMING_OF_AGE and MissionStatus == 1) then
player:startEvent(0x003A);
-- Mission San D'Oria 6-1 Leaute's last wishes
elseif (currentMission == LEAUTE_S_LAST_WISHES and MissionStatus == 3) then
player:startEvent(0x0016);
elseif (currentMission == LEAUTE_S_LAST_WISHES and MissionStatus == 2) then
player:startEvent(0x0018);
elseif (currentMission == LEAUTE_S_LAST_WISHES and MissionStatus == 1) then
player:startEvent(0x0017);
elseif (currentMission == LEAUTE_S_LAST_WISHES and MissionStatus == 0) then
player:startEvent(0x0019);
-- Mission San D'Oria 5-2 The Shadow Lord
elseif (player:hasCompletedMission(SANDORIA,THE_SHADOW_LORD) and currentMission == 255) then
player:showText(npc,HALVER_OFFSET+500);
elseif (currentMission == THE_SHADOW_LORD and MissionStatus == 5) then
player:showText(npc,HALVER_OFFSET+471);
elseif (currentMission == THE_SHADOW_LORD and MissionStatus == 4 and player:hasKeyItem(SHADOW_FRAGMENT)) then
player:startEvent(0x0224);
elseif (currentMission == THE_SHADOW_LORD and MissionStatus == 0) then
player:startEvent(0x0222);
-- Mission San D'Oria 5-1 The Ruins of Fei'Yin
elseif (currentMission == THE_RUINS_OF_FEI_YIN and MissionStatus == 12 and player:hasKeyItem(BURNT_SEAL)) then
player:startEvent(0x0216);
elseif (currentMission == THE_RUINS_OF_FEI_YIN and MissionStatus == 10) then
player:showText(npc,HALVER_OFFSET+334);
elseif (currentMission == THE_RUINS_OF_FEI_YIN and MissionStatus == 9) then
player:startEvent(0x0215);
-- Mission San D'Oria 3-3 Appointment to Jeuno
elseif (currentMission == APPOINTMENT_TO_JEUNO and MissionStatus == 0) then
player:startEvent(0x01fc);
-- Mission San D'Oria 2-3 Journey Abroad
elseif (currentMission == JOURNEY_ABROAD and MissionStatus == 11) then
player:startEvent(0x01fb);
elseif (currentMission == JOURNEY_ABROAD and MissionStatus == 0) then
player:startEvent(0x01f9);
elseif (currentMission == JOURNEY_ABROAD) then
player:startEvent(0x0214);
end
elseif (pNation == BASTOK) then
--Bastok 2-3 San -> Win
if (currentMission == THE_EMISSARY) then
if (MissionStatus == 3) then
player:startEvent(0x01f5);
end
--Bastok 2-3 San -> Win, report to consulate
elseif (currentMission == THE_EMISSARY_SANDORIA) then
player:showText(npc,HALVER_OFFSET+279);
--Bastok 2-3 Win -> San
elseif (currentMission == THE_EMISSARY_SANDORIA2) then
if (MissionStatus == 8) then
player:startEvent(0x01f7);
elseif (MissionStatus <= 10) then
player:showText(npc,HALVER_OFFSET+279);
end
else
player:showText(npc,HALVER_OFFSET+1092);
end
elseif (pNation == WINDURST) then
--Windurst 2-3
if (currentMission == THE_THREE_KINGDOMS and MissionStatus < 3) then
player:startEvent(0x0214);
elseif (currentMission == THE_THREE_KINGDOMS_SANDORIA or currentMission == THE_THREE_KINGDOMS_SANDORIA2) then
if (MissionStatus == 3) then
player:startEvent(0x01F6);
elseif (MissionStatus == 8) then
player:startEvent(0x01F8);
else
player:showText(npc,HALVER_OFFSET+279);
end
end
else
player:showText(npc,HALVER_OFFSET+1092);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x01f5) then
player:addMission(BASTOK,THE_EMISSARY_SANDORIA);
player:setVar("MissionStatus",4);
elseif (csid == 0x01f7) then
player:setVar("MissionStatus",9);
elseif (csid == 0x01fc) then
player:setVar("MissionStatus",2);
elseif (csid == 0x01f9) then
player:setVar("MissionStatus",2);
player:addKeyItem(LETTER_TO_THE_CONSULS_SANDORIA);
player:messageSpecial(KEYITEM_OBTAINED,LETTER_TO_THE_CONSULS_SANDORIA);
elseif (csid == 0x01F6) then
player:setVar("MissionStatus",4);
elseif (csid == 0x022e) then
player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",16,true);
elseif (csid == 0x01F8) then
player:setVar("MissionStatus",9);
elseif (csid == 0x0222) then
player:setVar("MissionStatus",1);
elseif (csid == 0x01fb or csid == 0x0224 or csid == 0x0215 or csid == 0x0216) then
finishMissionTimeline(player,3,csid,option);
elseif (csid == 0x0019) then
player:setVar("MissionStatus",1);
elseif (csid == 0x0016) then
player:setVar("MissionStatus",4);
elseif (csid == 0x0009) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,181);
player:setVar("Flagsando",1);
else player:addItem(181);
player:messageSpecial(ITEM_OBTAINED,181);
end
player:setVar("MissionStatus",0);
player:completeMission(SANDORIA,THE_HEIR_TO_THE_LIGHT);
player:setRank(10);
player:addGil(100000);
player:messageSpecial(GIL_OBTAINED,100000);
player:setTitle(295);
player:setVar("SandoEpilogue",1);
elseif (csid == 0x003A) then
player:setVar("MissionStatus",2);
elseif (csid == 0x0066) then
finishMissionTimeline(player,3,csid,option);
player:setVar("Wait1DayM8-1_date", os.date("%j"));
elseif (csid == 0x0234 and option == 1) then
player:completeMission(TOAU,CONFESSIONS_OF_ROYALTY);
player:addMission(TOAU,EASTERLY_WINDS);
player:delKeyItem(RAILLEFALS_LETTER);
end
end;
| gpl-3.0 |
semyon422/lua-mania | src/lmfw/loveio/input/navigation.lua | 1 | 2657 | local init = function(input, loveio)
--------------------------------
local navigation = {}
navigation.buttons = {
["up"] = "up",
["down"] = "down",
["left"] = "left",
["right"] = "right",
["activate"] = "return"
}
navigation.currentPosition = {1, 1}
navigation.oldPosition = {0, 0}
navigation.map = {{}}
navigation.move = function(direction)
local curPos = navigation.currentPosition
local map = navigation.map
if map[curPos[1]] and map[curPos[1]][curPos[2]] and objects[map[curPos[1]][curPos[2]]] then
if direction == "activate" then
objects[map[curPos[1]][curPos[2]]].update("activate")
return
end
end
if direction == "up" then
if map[curPos[1] + 1] and map[curPos[1] + 1][curPos[2]] and objects[map[curPos[1] + 1][curPos[2]]] then
curPos[1] = curPos[1] + 1
end
elseif direction == "down" then
if map[curPos[1] - 1] and map[curPos[1] - 1][curPos[2]] and objects[map[curPos[1] - 1][curPos[2]]] then
curPos[1] = curPos[1] - 1
end
elseif direction == "left" then
if map[curPos[1]] and map[curPos[1]][curPos[2] - 1] and objects[map[curPos[1]][curPos[2] - 1]] then
curPos[2] = curPos[2] - 1
end
elseif direction == "right" then
if map[curPos[1]] and map[curPos[1]][curPos[2] + 1] and objects[map[curPos[1]][curPos[2] + 1]] then
curPos[2] = curPos[2] + 1
end
end
if not map[curPos[1]] and not map[curPos[1]][curPos[1]] and curPos[1] ~= 1 and curPos[2] ~= 1 then
curPos[1] = 1
curPos[1] = 1
end
end
navigation.loaded = false
navigation.object = {}
navigation.object.update = function(command)
local curPos = navigation.currentPosition
local oldPos = navigation.oldPosition
local map = navigation.map
local curObj = objects[map[curPos[1]][curPos[2]]]
if curObj then
if curPos[1] ~= oldPos[1] or curPos[2] ~= oldPos[2] then
loveio.output.objects.selectionObject = {
class = "rectangle",
x = curObj.x or 0, y = curObj.y or 0,
w = curObj.w or 0, h = curObj.h or 0,
mode = "line"
}
oldPos[1] = curPos[1]
oldPos[2] = curPos[2]
end
else
loveio.output.objects.selectionObject = nil
end
if not navigation.loaded then
loveio.input.callbacks.navigation = {
keypressed = function(key)
if key == navigation.buttons.up then
navigation.move("up")
elseif key == navigation.buttons.down then
navigation.move("down")
elseif key == navigation.buttons.left then
navigation.move("left")
elseif key == navigation.buttons.right then
navigation.move("right")
elseif key == navigation.buttons.activate then
navigation.move("activate")
end
end
}
end
end
return navigation
--------------------------------
end
return init | gpl-3.0 |
geanux/darkstar | scripts/globals/abilities/gallants_roll.lua | 8 | 2243 | -----------------------------------
-- Ability: Gallant's Roll
-- Reduces physical damage taken by party members within area of effect
-- Optimal Job: Paladin
-- Lucky Number: 3
-- Unlucky Number: 7
-- Level: 55
--
-- Die Roll |No PLD |With PLD
-- -------- ------- -----------
-- 1 |4% |14%
-- 2 |5% |15%
-- 3 |15% |25%
-- 4 |6% |16%
-- 5 |7% |17%
-- 6 |8% |18%
-- 7 |3% |13%
-- 8 |9% |19%
-- 9 |10% |20%
-- 10 |12% |22%
-- 11 |20% |30%
-- Bust |-10% |-10%
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
local effectID = getCorsairRollEffect(ability:getID());
ability:setRange(ability:getRange() + player:getMod(MOD_ROLL_RANGE));
if (player:hasStatusEffect(effectID) or player:hasBustEffect(effectID)) then
return MSGBASIC_ROLL_ALREADY_ACTIVE,0;
else
return 0,0;
end
end;
-----------------------------------
-- onUseAbilityRoll
-----------------------------------
function onUseAbilityRoll(caster,target,ability,total)
local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK)
local effectpowers = {4, 5, 15, 6, 7, 8, 3, 9, 10, 12, 20, 10}
local effectpower = effectpowers[total]
if (total < 12 and caster:hasPartyJob(JOB_PLD) ) then
effectpower = effectpower + 10;
end
if (caster:getMainJob() == JOB_COR and caster:getMainLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl());
elseif (caster:getSubJob() == JOB_COR and caster:getSubLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl());
end
if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_GALLANTS_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_DMG) == false) then
ability:setMsg(423);
end
end; | gpl-3.0 |
vvtam/vlc | share/lua/modules/common.lua | 54 | 4986 | --[[ This code is public domain (since it really isn't very interesting) ]]--
module("common",package.seeall)
-- Iterate over a table in the keys' alphabetical order
function pairs_sorted(t)
local s = {}
for k,_ in pairs(t) do table.insert(s,k) end
table.sort(s)
local i = 0
return function () i = i + 1; return s[i], t[s[i]] end
end
-- Return a function such as skip(foo)(a,b,c) = foo(b,c)
function skip(foo)
return function(discard,...) return foo(...) end
end
-- Return a function such as setarg(foo,a)(b,c) = foo(a,b,c)
function setarg(foo,a)
return function(...) return foo(a,...) end
end
-- Trigger a hotkey
function hotkey(arg)
local id = vlc.misc.action_id( arg )
if id ~= nil then
vlc.var.set( vlc.object.libvlc(), "key-action", id )
return true
else
return false
end
end
-- Take a video snapshot
function snapshot()
local vout = vlc.object.vout()
if not vout then return end
vlc.var.set(vout,"video-snapshot",nil)
end
-- Naive (non recursive) table copy
function table_copy(t)
c = {}
for i,v in pairs(t) do c[i]=v end
return c
end
-- tonumber() for decimals number, using a dot as decimal separator
-- regardless of the system locale
function us_tonumber(str)
local s, i, d = string.match(str, "^([+-]?)(%d*)%.?(%d*)$")
if not s or not i or not d then
return nil
end
if s == "-" then
s = -1
else
s = 1
end
if i == "" then
i = "0"
end
if d == nil or d == "" then
d = "0"
end
return s * (tonumber(i) + tonumber(d)/(10^string.len(d)))
end
-- tostring() for decimals number, using a dot as decimal separator
-- regardless of the system locale
function us_tostring(n)
s = tostring(n):gsub(",", ".", 1)
return s
end
-- strip leading and trailing spaces
function strip(str)
return string.gsub(str, "^%s*(.-)%s*$", "%1")
end
-- print a table (recursively)
function table_print(t,prefix)
local prefix = prefix or ""
if not t then
print(prefix.."/!\\ nil")
return
end
for a,b in pairs_sorted(t) do
print(prefix..tostring(a),b)
if type(b)==type({}) then
table_print(b,prefix.."\t")
end
end
end
-- print the list of callbacks registered in lua
-- useful for debug purposes
function print_callbacks()
print "callbacks:"
table_print(vlc.callbacks)
end
-- convert a duration (in seconds) to a string
function durationtostring(duration)
return string.format("%02d:%02d:%02d",
math.floor(duration/3600),
math.floor(duration/60)%60,
math.floor(duration%60))
end
-- realpath
function realpath(path)
return string.gsub(string.gsub(string.gsub(string.gsub(path,"/%.%./[^/]+","/"),"/[^/]+/%.%./","/"),"/%./","/"),"//","/")
end
-- parse the time from a string and return the seconds
-- time format: [+ or -][<int><H or h>:][<int><M or m or '>:][<int><nothing or S or s or ">]
function parsetime(timestring)
local seconds = 0
local hourspattern = "(%d+)[hH]"
local minutespattern = "(%d+)[mM']"
local secondspattern = "(%d+)[sS\"]?$"
local _, _, hoursmatch = string.find(timestring, hourspattern)
if hoursmatch ~= nil then
seconds = seconds + tonumber(hoursmatch) * 3600
end
local _, _, minutesmatch = string.find(timestring, minutespattern)
if minutesmatch ~= nil then
seconds = seconds + tonumber(minutesmatch) * 60
end
local _, _, secondsmatch = string.find(timestring, secondspattern)
if secondsmatch ~= nil then
seconds = seconds + tonumber(secondsmatch)
end
if string.sub(timestring,1,1) == "-" then
seconds = seconds * -1
end
return seconds
end
-- seek
function seek(value)
local input = vlc.object.input()
if input ~= nil and value ~= nil then
if string.sub(value,-1) == "%" then
local number = us_tonumber(string.sub(value,1,-2))
if number ~= nil then
local posPercent = number/100
if string.sub(value,1,1) == "+" or string.sub(value,1,1) == "-" then
vlc.var.set(input,"position",vlc.var.get(input,"position") + posPercent)
else
vlc.var.set(input,"position",posPercent)
end
end
else
local posTime = parsetime(value)
if string.sub(value,1,1) == "+" or string.sub(value,1,1) == "-" then
vlc.var.set(input,"time",vlc.var.get(input,"time") + (posTime * 1000000))
else
vlc.var.set(input,"time",posTime * 1000000)
end
end
end
end
function volume(value)
if type(value)=="string" and string.sub(value,1,1) == "+" or string.sub(value,1,1) == "-" then
vlc.volume.set(vlc.volume.get()+tonumber(value))
else
vlc.volume.set(tostring(value))
end
end
| gpl-2.0 |
ArchiveTeam/wget-lua | lua-example/table_show.lua | 1 | 3227 | --[[
Author: Julio Manuel Fernandez-Diaz
Date: January 12, 2007
(For Lua 5.1)
Modified slightly by RiciLake to avoid the unnecessary table traversal in tablecount()
Formats tables with cycles recursively to any depth.
The output is returned as a string.
References to other tables are shown as values.
Self references are indicated.
The string returned is "Lua code", which can be procesed
(in the case in which indent is composed by spaces or "--").
Userdata and function keys and values are shown as strings,
which logically are exactly not equivalent to the original code.
This routine can serve for pretty formating tables with
proper indentations, apart from printing them:
print(table.show(t, "t")) -- a typical use
Heavily based on "Saving tables with cycles", PIL2, p. 113.
Arguments:
t is the table.
name is the name of the table (optional)
indent is a first indentation (optional).
--]]
function table.show(t, name, indent)
local cart -- a container
local autoref -- for self references
--[[ counts the number of elements in a table
local function tablecount(t)
local n = 0
for _, _ in pairs(t) do n = n+1 end
return n
end
]]
-- (RiciLake) returns true if the table is empty
local function isemptytable(t) return next(t) == nil end
local function basicSerialize (o)
local so = tostring(o)
if type(o) == "function" then
local info = debug.getinfo(o, "S")
-- info.name is nil because o is not a calling level
if info.what == "C" then
return string.format("%q", so .. ", C function")
else
-- the information is defined through lines
return string.format("%q", so .. ", defined in (" ..
info.linedefined .. "-" .. info.lastlinedefined ..
")" .. info.source)
end
elseif type(o) == "number" or type(o) == "boolean" then
return so
else
return string.format("%q", so)
end
end
local function addtocart (value, name, indent, saved, field)
indent = indent or ""
saved = saved or {}
field = field or name
cart = cart .. indent .. field
if type(value) ~= "table" then
cart = cart .. " = " .. basicSerialize(value) .. ";\n"
else
if saved[value] then
cart = cart .. " = {}; -- " .. saved[value]
.. " (self reference)\n"
autoref = autoref .. name .. " = " .. saved[value] .. ";\n"
else
saved[value] = name
--if tablecount(value) == 0 then
if isemptytable(value) then
cart = cart .. " = {};\n"
else
cart = cart .. " = {\n"
for k, v in pairs(value) do
k = basicSerialize(k)
local fname = string.format("%s[%s]", name, k)
field = string.format("[%s]", k)
-- three spaces between levels
addtocart(v, fname, indent .. " ", saved, field)
end
cart = cart .. indent .. "};\n"
end
end
end
end
name = name or "__unnamed__"
if type(t) ~= "table" then
return name .. " = " .. basicSerialize(t)
end
cart, autoref = "", ""
addtocart(t, name, indent)
return cart .. autoref
end
| gpl-3.0 |
Schwertspize/cuberite | Server/Plugins/HookNotify/HookNotify.lua | 22 | 2130 |
-- HookNotify.lua
--[[
Implements the entire plugin
NOTE: This plugin is not meant for production servers. It is used mainly by developers to verify that things
are working properly when implementing Cuberite features. Do not enable this plugin on production servers!
This plugin logs a notification for each hook that is being called by the server.
The TICK and WORLD_TICK hooks are disabled because they produce too much output.
--]]
function Initialize(a_Plugin)
-- Notify the admin that HookNotify is installed, this is not meant for production servers
LOGINFO("HookNotify plugin is installed, beware, the log output may be quite large!");
LOGINFO("You want this plugin enabled only when developing another plugin, not for regular gameplay.");
-- These hooks will not be notified:
local hooksToIgnore =
{
["HOOK_TICK"] = true, -- Too much spam
["HOOK_WORLD_TICK"] = true, -- Too much spam
["HOOK_TAKE_DAMAGE"] = true, -- Has a separate handler with more info logged
["HOOK_MAX"] = true, -- No such hook, placeholder only
["HOOK_NUM_HOOKS"] = true, -- No such hook, placeholder only
}
-- Add all hooks:
for n, v in pairs(cPluginManager) do
if (n:match("HOOK_.*")) then
if not(hooksToIgnore[n]) then
LOG("Adding notification for hook " .. n .. " (" .. v .. ").")
cPluginManager.AddHook(v,
function (...)
LOG(n .. "(")
for i, param in ipairs(arg) do
LOG(" " .. i .. ": " .. tolua.type(param) .. ": " .. tostring(param))
end
LOG(")");
end -- hook handler
) -- AddHook
end -- not (ignore)
end -- n matches "HOOK"
end -- for cPluginManager{}
-- OnTakeDamage has a special handler listing the details of the damage dealt:
cPluginManager.AddHook(cPluginManager.HOOK_TAKE_DAMAGE,
function (a_Receiver, a_TDI)
-- a_Receiver is cPawn
-- a_TDI is TakeDamageInfo
LOG("OnTakeDamage(): " .. a_Receiver:GetClass() .. " was dealt RawDamage " .. a_TDI.RawDamage .. ", FinalDamage " .. a_TDI.FinalDamage .. " (that is, " .. (a_TDI.RawDamage - a_TDI.FinalDamage) .. " HPs covered by armor)");
end
)
return true
end
| apache-2.0 |
geanux/darkstar | scripts/zones/Port_Bastok/npcs/Zoby_Quhyo.lua | 36 | 1693 | -----------------------------------
-- Area: Port Bastok
-- NPC: Zoby Quhyo
-- Only sells when Bastok controlls Elshimo Lowlands
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(ELSHIMOLOWLANDS);
if (RegionOwner ~= BASTOK) then
player:showText(npc,ZOBYQUHYO_CLOSED_DIALOG);
else
player:showText(npc,ZOBYQUHYO_OPEN_DIALOG);
stock = {
0x0272, 234, --Black Pepper
0x0264, 55, --Kazham Peppers
0x1150, 55, --Kazham Pineapple
0x0278, 110, --Kukuru Bean
0x1126, 36, --Mithran Tomato
0x0276, 88, --Ogre Pumpkin
0x0583, 1656 --Phalaenopsis
}
showShop(player,BASTOK,stock);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/Bastok_Mines/npcs/Conrad.lua | 17 | 1874 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Conrad
-- Outpost Teleporter NPC
-- @pos 94.457 -0.375 -66.161 234
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Bastok_Mines/TextIDs");
guardnation = BASTOK;
csid = 0x0245;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (guardnation == player:getNation()) then
player:startEvent(csid,0,0,0,0,0,0,player:getMainLvl(),1073741823 - player:getNationTeleport(guardnation));
else
player:startEvent(csid,0,0,0,0,0,256,0,0);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
loca = option - 1073741829;
player:updateEvent(player:getGil(),OP_TeleFee(player,loca),player:getCP(),OP_TeleFee(player,loca),player:getCP());
end;
-----------------------------------
--onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (option >= 5 and option <= 23) then
if (player:delGil(OP_TeleFee(player,option-5))) then
toOutpost(player,option);
end
elseif (option >= 1029 and option <= 1047) then
local cpCost = OP_TeleFee(player,option-1029);
--printf("CP Cost: %u",cpCost);
if (player:getCP()>=cpCost) then
player:delCP(cpCost);
toOutpost(player,option-1024);
end
end
end; | gpl-3.0 |
yurenyong123/nodemcu-firmware | lua_modules/ds3231/ds3231-web.lua | 84 | 1338 | require('ds3231')
port = 80
-- ESP-01 GPIO Mapping
gpio0, gpio2 = 3, 4
days = {
[1] = "Sunday",
[2] = "Monday",
[3] = "Tuesday",
[4] = "Wednesday",
[5] = "Thursday",
[6] = "Friday",
[7] = "Saturday"
}
months = {
[1] = "January",
[2] = "Febuary",
[3] = "March",
[4] = "April",
[5] = "May",
[6] = "June",
[7] = "July",
[8] = "August",
[9] = "September",
[10] = "October",
[11] = "November",
[12] = "December"
}
ds3231.init(gpio0, gpio2)
srv=net.createServer(net.TCP)
srv:listen(port,
function(conn)
second, minute, hour, day, date, month, year = ds3231.getTime()
prettyTime = string.format("%s, %s %s %s %s:%s:%s", days[day], date, months[month], year, hour, minute, second)
conn:send("HTTP/1.1 200 OK\nContent-Type: text/html\nRefresh: 5\n\n" ..
"<!DOCTYPE HTML>" ..
"<html><body>" ..
"<b>ESP8266</b></br>" ..
"Time and Date: " .. prettyTime .. "<br>" ..
"Node ChipID : " .. node.chipid() .. "<br>" ..
"Node MAC : " .. wifi.sta.getmac() .. "<br>" ..
"Node Heap : " .. node.heap() .. "<br>" ..
"Timer Ticks : " .. tmr.now() .. "<br>" ..
"</html></body>")
conn:on("sent",function(conn) conn:close() end)
end
) | mit |
famellad/oldschool-scroller | main-deps.lua | 1 | 4791 | -- TODO WHAT THE FUCK IS THIS FILE??????
-- Load libs
require("libs.AnAL") -- Library for animations (is there another one?)
-- Base classes
require("game") -- Basic game handling
require("static") -- Static functions and variables
require("console") -- Game console TODO
require("debug-print") -- Debug output functions
require("entity") -- Generic entity that may appear in the game area
-- Load Controller classes
require("lua-ctl.controller") -- General controller class
require("lua-ctl.controller-keyboard") -- Keyboard compatibility
require("lua-ctl.controller-xbox") -- Xbox gamepad compat
-- States and scenes
require("game-state") -- Class holding the game state (everything after starting new game)
require("lua-scenes.scene") -- Base scene class
require("lua-scenes.scene-menu") -- Parent scene for screens that are handled as menus
require("lua-scenes.scene-gamearea") -- Parent scene for screens that are handled as playable
require("lua-scenes.lua-menus.scene-title") -- Scene for the titles and the "press start"
require("lua-scenes.lua-menus.scene-mainmenu") -- Main menu scene (new, cont, opts etc)
-- Direction and staging
require("lua-staging.director") -- The director that controls the waves :)
require("lua-staging.challenge") -- Challenges for stages
require("lua-staging.wave")
require("challenge-deps")
require("waves-deps") -- Waves for challenges
-- Load Player
require("lua-player.player") -- Player class
require("lua-player.player-weapons") -- Player weapons system
require("lua-player.player-movement") -- Player movement
-- Load Entities
require("lua-actors.enemy") -- Generic enemy
require("lua-actors.enemies.enemy-asteroid") -- Medium Asteroid
require("lua-actors.enemies.enemy-asteroid-small") -- Small Asteroid
require("lua-actors.enemies.enemy-medium") -- Medium shooty enemy
require("lua-actors.enemies.enemy-simu-med") -- Medium simu shooty enemy
require("lua-actors.enemies.enemy-mine") -- Mine enemy
require("lua-actors.powerup") -- Generic powerup that may be picked up
require("lua-actors.powerups.powerup-hp") -- Health powerup
require("lua-actors.powerups.powerup-hp-full") -- Full Health powerup
require("lua-actors.powerups.powerup-sp") -- Shield powerup
require("lua-actors.powerups.powerup-sp-full") -- Full Shield powerup
require("lua-actors.powerups.powerup-pp") -- Energy powerup
require("lua-actors.powerups.powerup-pp-full") -- Full Energy powerup
-- Load Ships
require("lua-actors.ship") -- Prototype ship class
require("lua-actors.ships.arrow") -- The main ship in the game
require("lua-actors.ships.dart") -- PIECES OF UTTER
require("lua-actors.ships.javelin") -- MEGA USELESSNESS
-- Load Particle Systems
require("lua-part.bullet-system") -- Bullet system class, for all your bullet needs
require("lua-part.bullet") -- A single individual bullet (Prototype)
require("lua-part.bullets.bullet-hammer") -- Hammer bullets
require("lua-part.explosion") -- Prototype explosion
require("lua-part.explosions.explosion-hit") -- Bullet hit
require("lua-part.explosions.explosion-med") -- Medium sized explosion
require("lua-part.emitter") -- Particle emitter
require("lua-part.particle") -- A single particle (prototype)
-- Load Emitters
require("lua-part.emitters.emitter-exhaust") -- Fire-like emitter
require("lua-part.emitters.emitter-explosion") -- Hot red debris flying off in every direction
-- Load Particles
require("lua-part.particles.particle-small-fire") -- A small particle that goes from bright orange to dim red
-- Aditional Visual Elements
require("lua-bg.background") -- The backdrop (prototype)
require("lua-bg.back-space-proto") -- Prototypical backdrop for space scenes
require("lua-bg.back-nebula") -- Green nebula backdrop
require("lua-bg.back-eagle") -- Red nebula backdrop
require("lua-bg.back-simu") -- Simulation backdrop
require("lua-gui.gui") -- The GUI-HUD thing
require("lua-gui.gui-fonts") -- All them fonts
--require("shader")
-- Weapons
require("lua-we.weapon") -- Prototype weapon
require("lua-we.weapon-hammer") -- Hammer weapon
-- Load sounds
require("lua-snd.TEsound") -- Class for controlling once-sounds
--require("lua-snd.msm")
require("lua-snd.music") -- Class for musics
require("lua-snd.sound") -- I don't know what this does TODO
-- Class system and post processing
Class = require "libs.hump.class" -- I don't think these do anything
shine = require "libs.shine"
--require("libs.shine.init")
| gpl-2.0 |
geanux/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Churacoco.lua | 38 | 1049 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Churacoco
-- Type: Standard NPC
-- @zone: 94
-- @pos -76.139 -4.499 20.986
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01b2);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
evilexecutable/ResourceKeeper | install/Lua/share/zerobranestudio/src/editor/keymap.lua | 1 | 3165 | local ide = ide
--[[
Accelerator general syntax is any combination of "CTRL", "ALT" and "SHIFT"
strings (case doesn't matter) separated by either '-' or '+' characters and
followed by the accelerator itself. The accelerator may be any alphanumeric
character, any function key (from F1 to F12) or one of the special characters
listed below (again, case doesn't matter):
DEL/DELETE Delete key
INS/INSERT Insert key
ENTER/RETURN Enter key
PGUP PageUp key
PGDN PageDown key
LEFT Left cursor arrow key
RIGHT Right cursor arrow key
UP Up cursor arrow key
DOWN Down cursor arrow key
HOME Home key
END End key
SPACE Space
TAB Tab key
ESC/ESCAPE Escape key (Windows only)
--]]
ide.config.keymap = {
-- File menu
[ID_NEW] = "Ctrl-N",
[ID_OPEN] = "Ctrl-O",
[ID_CLOSE] = "Ctrl-W",
[ID_SAVE] = "Ctrl-S",
[ID_SAVEAS] = "Alt-Shift-S",
[ID_SAVEALL] = "",
[ID_RECENTFILES] = "",
[ID_EXIT] = "Ctrl-Q",
-- Edit menu
[ID_CUT] = "Ctrl-X",
[ID_COPY] = "Ctrl-C",
[ID_PASTE] = "Ctrl-V",
[ID_SELECTALL] = "Ctrl-A",
[ID_UNDO] = "Ctrl-Z",
[ID_REDO] = "Ctrl-Y",
[ID_SHOWTOOLTIP] = "Ctrl-T",
[ID_AUTOCOMPLETE] = "Ctrl-K",
[ID_AUTOCOMPLETEENABLE] = "",
[ID_COMMENT] = "Ctrl-U",
[ID_FOLD] = "F12",
[ID_CLEARDYNAMICWORDS] = "",
-- Search menu
[ID_FIND] = "Ctrl-F",
[ID_FINDNEXT] = "F3",
[ID_FINDPREV] = "Shift-F3",
[ID_REPLACE] = "Ctrl-R",
[ID_FINDINFILES] = "Ctrl-Shift-F",
[ID_REPLACEINFILES] = "Ctrl-Shift-R",
[ID_GOTOLINE] = "Ctrl-G",
[ID_SORT] = "",
-- View menu
[ID_VIEWFILETREE] = "Ctrl-Shift-P",
[ID_VIEWOUTPUT] = "Ctrl-Shift-O",
[ID_VIEWWATCHWINDOW] = "Ctrl-Shift-W",
[ID_VIEWCALLSTACK] = "Ctrl-Shift-S",
[ID_VIEWDEFAULTLAYOUT] = "",
[ID_VIEWFULLSCREEN] = "Ctrl-Shift-A",
-- Project menu
[ID_RUN] = "F6",
[ID_RUNNOW] = "Ctrl-F6",
[ID_COMPILE] = "F7",
[ID_ANALYZE] = "Shift-F7",
[ID_STARTDEBUG] = "F5",
[ID_ATTACHDEBUG] = "",
[ID_STOPDEBUG] = "Shift-F5",
[ID_STEP] = "F10",
[ID_STEPOVER] = "Shift-F10",
[ID_STEPOUT] = "Ctrl-F10",
[ID_TRACE] = "",
[ID_BREAK] = "Shift-F9",
[ID_TOGGLEBREAKPOINT] = "F9",
[ID_CLEAROUTPUT] = "",
[ID_INTERPRETER] = "",
[ID_PROJECTDIR] = "",
-- Help menu
[ID_ABOUT] = "F1",
-- Watch window menu items
[ID_ADDWATCH] = "Ins",
[ID_EDITWATCH] = "F2",
[ID_REMOVEWATCH] = "Del",
[ID_EVALUATEWATCH] = "",
-- Editor popup menu items
[ID_QUICKADDWATCH] = "",
[ID_QUICKEVAL] = "",
}
function KSC(id, default)
-- this is only for the rare case of someone assigning a complete list
-- to ide.config.keymap.
local keymap = ide.config.keymap
return keymap[id] and "\t"..keymap[id] or default or ""
end
| gpl-2.0 |
kling-igor/particle-designer | loveframes/objects/form.lua | 14 | 7892 | --[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2012-2014 Kenny Shields --
--]]------------------------------------------------
-- get the current require path
local path = string.sub(..., 1, string.len(...) - string.len(".objects.form"))
local loveframes = require(path .. ".libraries.common")
-- form object
local newobject = loveframes.NewObject("form", "loveframes_object_form", true)
--[[---------------------------------------------------------
- func: initialize()
- desc: initializes the object
--]]---------------------------------------------------------
function newobject:initialize()
self.type = "form"
self.name = "Form"
self.layout = "vertical"
self.width = 200
self.height = 50
self.padding = 5
self.spacing = 5
self.topmargin = 12
self.internal = false
self.children = {}
end
--[[---------------------------------------------------------
- func: update(deltatime)
- desc: updates the element
--]]---------------------------------------------------------
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 children = self.children
local parent = self.parent
local base = loveframes.base
local update = self.Update
-- move to parent if there is a parent
if parent ~= base and parent.type ~= "list" then
self.x = self.parent.x + self.staticx
self.y = self.parent.y + self.staticy
end
self:CheckHover()
for k, v in ipairs(children) do
v:update(dt)
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 children = self.children
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.DrawForm or skins[defaultskin].DrawForm
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
-- loop through the object's children and draw them
for k, v in ipairs(children) do
v:draw()
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 children = self.children
local hover = self.hover
if hover and button == "l" then
local baseparent = self:GetBaseParent()
if baseparent and baseparent.type == "frame" then
baseparent:MakeTop()
end
end
for k, v in ipairs(children) do
v:mousepressed(x, y, button)
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
local children = self.children
if not visible then
return
end
for k, v in ipairs(children) do
v:mousereleased(x, y, button)
end
end
--[[---------------------------------------------------------
- func: AddItem(object)
- desc: adds an item to the object
--]]---------------------------------------------------------
function newobject:AddItem(object)
local objtype = object.type
if objtype == "frame" then
return
end
local children = self.children
local state = self.state
object:Remove()
object.parent = self
object:SetState(state)
table.insert(children, object)
self:LayoutObjects()
return self
end
--[[---------------------------------------------------------
- func: RemoveItem(object or number)
- desc: removes an item from the object
--]]---------------------------------------------------------
function newobject:RemoveItem(data)
local dtype = type(data)
if dtype == "number" then
local children = self.children
local item = children[data]
if item then
item:Remove()
end
else
data:Remove()
end
self:LayoutObjects()
return self
end
--[[---------------------------------------------------------
- func: LayoutObjects()
- desc: positions the object's children and calculates
a new size for the object
--]]---------------------------------------------------------
function newobject:LayoutObjects()
local layout = self.layout
local padding = self.padding
local spacing = self.spacing
local topmargin = self.topmargin
local children = self.children
local width = padding * 2
local height = padding * 2 + topmargin
local x = padding
local y = padding + topmargin
if layout == "vertical" then
local largest_width = 0
for k, v in ipairs(children) do
v.staticx = x
v.staticy = y
y = y + v.height + spacing
height = height + v.height + spacing
if v.width > largest_width then
largest_width = v.width
end
end
height = height - spacing
self.width = width + largest_width
self.height = height
elseif layout == "horizontal" then
local largest_height = 0
for k, v in ipairs(children) do
v.staticx = x
v.staticy = y
x = x + v.width + spacing
width = width + v.width + spacing
if v.height > largest_height then
largest_height = v.height
end
end
width = width - spacing
self.width = width
self.height = height + largest_height
end
return self
end
--[[---------------------------------------------------------
- func: SetLayoutType(ltype)
- desc: sets the object's layout type
--]]---------------------------------------------------------
function newobject:SetLayoutType(ltype)
self.layout = ltype
return self
end
--[[---------------------------------------------------------
- func: GetLayoutType()
- desc: gets the object's layout type
--]]---------------------------------------------------------
function newobject:GetLayoutType()
return self.layout
end
--[[---------------------------------------------------------
- func: SetTopMargin(margin)
- desc: sets the margin between the top of the object
and its children
--]]---------------------------------------------------------
function newobject:SetTopMargin(margin)
self.topmargin = margin
return self
end
--[[---------------------------------------------------------
- func: GetTopMargin()
- desc: gets the margin between the top of the object
and its children
--]]---------------------------------------------------------
function newobject:GetTopMargin()
return self.topmargin
end
--[[---------------------------------------------------------
- func: SetName(name)
- desc: sets the object's name
--]]---------------------------------------------------------
function newobject:SetName(name)
self.name = name
return self
end
--[[---------------------------------------------------------
- func: GetName()
- desc: gets the object's name
--]]---------------------------------------------------------
function newobject:GetName()
return self.name
end
| mit |
forward619/luci | applications/luci-app-asterisk/luasrc/model/cbi/asterisk-mod-res-feature.lua | 46 | 3988 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
cbimap = Map("asterisk", "asterisk", "")
featuremap = cbimap:section(TypedSection, "featuremap", "Feature Key maps", "")
featuremap.anonymous = true
featuremap.addremove = true
atxfer = featuremap:option(Value, "atxfer", "Attended transfer key", "")
atxfer.rmempty = true
blindxfer = featuremap:option(Value, "blindxfer", "Blind transfer key", "")
blindxfer.rmempty = true
disconnect = featuremap:option(Value, "disconnect", "Key to Disconnect call", "")
disconnect.rmempty = true
parkcall = featuremap:option(Value, "parkcall", "Key to Park call", "")
parkcall.rmempty = true
featurepark = cbimap:section(TypedSection, "featurepark", "Parking Feature", "")
featurepark.anonymous = true
parkenabled = featurepark:option(Flag, "parkenabled", "Enable Parking", "")
adsipark = featurepark:option(Flag, "adsipark", "ADSI Park", "")
adsipark.rmempty = true
adsipark:depends({ parkenabled = "1" })
atxfernoanswertimeout = featurepark:option(Value, "atxfernoanswertimeout", "Attended transfer timeout (sec)", "")
atxfernoanswertimeout.rmempty = true
atxfernoanswertimeout:depends({ parkenabled = "1" })
automon = featurepark:option(Value, "automon", "One touch record key", "")
automon.rmempty = true
automon:depends({ parkenabled = "1" })
context = featurepark:option(Value, "context", "Name of call context for parking", "")
context.rmempty = true
context:depends({ parkenabled = "1" })
courtesytone = featurepark:option(Value, "courtesytone", "Sound file to play to parked caller", "")
courtesytone.rmempty = true
courtesytone:depends({ parkenabled = "1" })
featuredigittimeout = featurepark:option(Value, "featuredigittimeout", "Max time (ms) between digits for feature activation", "")
featuredigittimeout.rmempty = true
featuredigittimeout:depends({ parkenabled = "1" })
findslot = featurepark:option(ListValue, "findslot", "Method to Find Parking slot", "")
findslot:value("first", "First available slot")
findslot:value("next", "Next free parking space")
findslot.rmempty = true
findslot:depends({ parkenabled = "1" })
parkedmusicclass = featurepark:option(ListValue, "parkedmusicclass", "Music on Hold class for the parked channel", "")
parkedmusicclass.titleref = luci.dispatcher.build_url( "admin", "services", "asterisk" )
parkedmusicclass:depends({ parkenabled = "1" })
cbimap.uci:foreach( "asterisk", "moh", function(s) parkedmusicclass:value(s['.name']) end )
parkedplay = featurepark:option(ListValue, "parkedplay", "Play courtesy tone to", "")
parkedplay:value("caller", "Caller")
parkedplay:value("parked", "Parked user")
parkedplay:value("both", "Both")
parkedplay.rmempty = true
parkedplay:depends({ parkenabled = "1" })
parkext = featurepark:option(Value, "parkext", "Extension to dial to park", "")
parkext.rmempty = true
parkext:depends({ parkenabled = "1" })
parkingtime = featurepark:option(Value, "parkingtime", "Parking time (secs)", "")
parkingtime.rmempty = true
parkingtime:depends({ parkenabled = "1" })
parkpos = featurepark:option(Value, "parkpos", "Range of extensions for call parking", "")
parkpos.rmempty = true
parkpos:depends({ parkenabled = "1" })
pickupexten = featurepark:option(Value, "pickupexten", "Pickup extension", "")
pickupexten.rmempty = true
pickupexten:depends({ parkenabled = "1" })
transferdigittimeout = featurepark:option(Value, "transferdigittimeout", "Seconds to wait bewteen digits when transferring", "")
transferdigittimeout.rmempty = true
transferdigittimeout:depends({ parkenabled = "1" })
xferfailsound = featurepark:option(Value, "xferfailsound", "sound when attended transfer is complete", "")
xferfailsound.rmempty = true
xferfailsound:depends({ parkenabled = "1" })
xfersound = featurepark:option(Value, "xfersound", "Sound when attended transfer fails", "")
xfersound.rmempty = true
xfersound:depends({ parkenabled = "1" })
return cbimap
| apache-2.0 |
sroccaserra/object-lua | lib/objectlua/Traits/Trait.lua | 2 | 2333 | --
-- The Trait Extension
--
local TraitComponent = require 'objectlua.Traits.TraitComponent'
local TraitComposition = require 'objectlua.Traits.TraitComposition'
local Class = require 'objectlua.Class'
module(..., package.seeall)
--
-- If traits must resolve conflicts, it's easier if they are not modified after being used
-- Traits must bestored in a Set, or their functions in a table with key = function name, value = function.
--
local function uses(self, ...)
rawset(self, '__traits__', self.__traits__ or TraitComposition:new())
local traits = self.__traits__
local mt = debug.getmetatable(self.__prototype__) or debug.getmetatable(self)
if 'table' == type(mt.__index) then
local newMt = setmetatable({}, mt)
rawset(newMt, '__index', function(t, key)
local method = traits:methodFor(key)
if nil ~= method then
return method
end
return mt[key]
end)
debug.setmetatable(self.__prototype__, newMt)
end
traits:add(...)
end
local function doesUse(self, trait)
return self.__traits__:doesUse(trait)
end
----
-- Extend all classes
Class.uses = uses
Class.doesUse = doesUse
----
--
local function traitNewIndex(t, k, v)
assert(not t:isUsed())
assert('function' == type(v))
t._methods[k] = v
end
local function setAsTrait(trait)
trait.__prototype__.__newindex = traitNewIndex
end
----
-- The Trait class
Trait = TraitComponent:subclass()
setAsTrait(Trait)
Trait.uses = uses
Trait.doesUse = doesUse
function Trait:initialize(name)
rawset(self, '_name', name)
rawset(self, '_methods', {})
end
function Trait.class:named(name)
local env = getfenv(0)
env[name] = self:new(name)
end
function Trait:markAsUsed()
rawset(self, '__isUsed__', true)
end
function Trait:isUsed()
return rawget(self, '__isUsed__')
end
function Trait:alias(aliases)
error("Todo")
end
function Trait:methods()
return self._methods
end
function Trait:methodFor(key)
return self._methods[key]
end
function Trait:name()
return self._name
end
function Trait:requirement()
error("Error: Required method is missing.")
end
return Trait
| mit |
PhearNet/scanner | bin/nmap-openshift/nselib/stdnse.lua | 3 | 45011 | ---
-- Standard Nmap Scripting Engine functions. This module contains various handy
-- functions that are too small to justify modules of their own.
--
-- @copyright Same as Nmap--See https://nmap.org/book/man-legal.html
-- @class module
-- @name stdnse
local _G = require "_G"
local coroutine = require "coroutine"
local math = require "math"
local nmap = require "nmap"
local os = require "os"
local string = require "string"
local table = require "table"
local assert = assert;
local error = error;
local getmetatable = getmetatable;
local ipairs = ipairs
local pairs = pairs
local next = next
local rawset = rawset
local require = require;
local select = select
local setmetatable = setmetatable;
local tonumber = tonumber;
local tostring = tostring;
local print = print;
local type = type
local ceil = math.ceil
local floor = math.floor
local fmod = math.fmod
local max = math.max
local random = math.random
local format = string.format;
local rep = string.rep
local match = string.match
local find = string.find
local sub = string.sub
local gsub = string.gsub
local char = string.char
local byte = string.byte
local concat = table.concat;
local insert = table.insert;
local remove = table.remove;
local pack = table.pack;
local unpack = table.unpack;
local difftime = os.difftime;
local time = os.time;
local date = os.date;
local EMPTY = {}; -- Empty constant table
_ENV = require "strict" {};
--- Sleeps for a given amount of time.
--
-- This causes the program to yield control and not regain it until the time
-- period has elapsed. The time may have a fractional part. Internally, the
-- timer provides millisecond resolution.
-- @name sleep
-- @class function
-- @param t Time to sleep, in seconds.
-- @usage stdnse.sleep(1.5)
_ENV.sleep = nmap.socket.sleep;
-- These stub functions get overwritten by the script run loop in nse_main.lua
-- These empty stubs will be used if a library calls stdnse.debug while loading
_ENV.getid = function () return end
_ENV.getinfo = function () return end
_ENV.gethostport = function () return end
local function debug (level, ...)
if type(level) ~= "number" then
return debug(1, level, ...)
end
local current = nmap.debugging()
if level <= current then
local host, port = gethostport()
local prefix = ( (current >= 2 and getinfo or getid)() or "")
.. (host and " "..host.ip .. (port and ":"..port.number or "") or "")
if prefix ~= "" then
nmap.log_write("stdout", "[" .. prefix .. "] " .. format(...))
else
nmap.log_write("stdout", format(...))
end
end
end
---
-- Prints a formatted debug message if the current debugging level is greater
-- than or equal to a given level.
--
-- This is a convenience wrapper around <code>nmap.log_write</code>. The first
-- optional numeric argument, <code>level</code>, is used as the debugging level
-- necessary to print the message (it defaults to 1 if omitted). All remaining
-- arguments are processed with Lua's <code>string.format</code> function.
--
-- If known, the output includes some context based information: the script
-- identifier and the target ip/port (if there is one). If the debug level is
-- at least 2, it also prints the base thread identifier and whether it is a
-- worker thread or the master thread.
--
-- @class function
-- @name debug
-- @param level Optional debugging level.
-- @param fmt Format string.
-- @param ... Arguments to format.
_ENV.debug = debug
--Aliases for particular debug levels
function debug1 (...) return debug(1, ...) end
function debug2 (...) return debug(2, ...) end
function debug3 (...) return debug(3, ...) end
function debug4 (...) return debug(4, ...) end
function debug5 (...) return debug(5, ...) end
---
-- Deprecated version of debug(), kept for now to prevent the script id from being
-- printed twice. Scripts should use debug() and not pass SCRIPT_NAME
print_debug = function(level, fmt, ...)
local l, d = tonumber(level), nmap.debugging();
if l and l <= d then
nmap.log_write("stdout", format(fmt, ...));
elseif not l and 1 <= d then
nmap.log_write("stdout", format(level, fmt, ...));
end
end
local function verbose (level, ...)
if type(level) ~= "number" then
return verbose(1, level, ...)
end
local current = nmap.verbosity()
if level <= current then
local prefix
if current >= 2 then
local host, port = gethostport()
prefix = (getid() or "")
.. (host and " "..host.ip .. (port and ":"..port.number or "") or "")
else
prefix = getid() or ""
end
if prefix ~= "" then
nmap.log_write("stdout", "[" .. prefix .. "] " .. format(...))
else
nmap.log_write("stdout", format(...))
end
end
end
---
-- Prints a formatted verbosity message if the current verbosity level is greater
-- than or equal to a given level.
--
-- This is a convenience wrapper around <code>nmap.log_write</code>. The first
-- optional numeric argument, <code>level</code>, is used as the verbosity level
-- necessary to print the message (it defaults to 1 if omitted). All remaining
-- arguments are processed with Lua's <code>string.format</code> function.
--
-- If known, the output includes some context based information: the script
-- identifier. If the verbosity level is at least 2, it also prints the target
-- ip/port (if there is one)
--
-- @class function
-- @name verbose
-- @param level Optional verbosity level.
-- @param fmt Format string.
-- @param ... Arguments to format.
_ENV.verbose = verbose
--Aliases for particular verbosity levels
function verbose1 (...) return verbose(1, ...) end
function verbose2 (...) return verbose(2, ...) end
function verbose3 (...) return verbose(3, ...) end
function verbose4 (...) return verbose(4, ...) end
function verbose5 (...) return verbose(5, ...) end
---
-- Deprecated version of verbose(), kept for now to prevent the script id from being
-- printed twice. Scripts should use verbose() and not pass SCRIPT_NAME
print_verbose = function(level, fmt, ...)
local l, d = tonumber(level), nmap.verbosity();
if l and l <= d then
nmap.log_write("stdout", format(fmt, ...));
elseif not l and 1 <= d then
nmap.log_write("stdout", format(level, fmt, ...));
end
end
--- Join a list of strings with a separator string.
--
-- This is Lua's <code>table.concat</code> function with the parameters
-- swapped for coherence.
-- @usage
-- stdnse.strjoin(", ", {"Anna", "Bob", "Charlie", "Dolores"})
-- --> "Anna, Bob, Charlie, Dolores"
-- @param delimiter String to delimit each element of the list.
-- @param list Array of strings to concatenate.
-- @return Concatenated string.
function strjoin(delimiter, list)
assert(type(delimiter) == "string" or type(delimiter) == nil, "delimiter is of the wrong type! (did you get the parameters backward?)")
return concat(list, delimiter);
end
--- Split a string at a given delimiter, which may be a pattern.
-- @usage
-- stdnse.strsplit(",%s*", "Anna, Bob, Charlie, Dolores")
-- --> { "Anna", "Bob", "Charlie", "Dolores" }
-- @param pattern Pattern that separates the desired strings.
-- @param text String to split.
-- @return Array of substrings without the separating pattern.
function strsplit(pattern, text)
local list, pos = {}, 1;
assert(pattern ~= "", "delimiter matches empty string!");
while true do
local first, last, match = text:find(pattern, pos);
if first then -- found?
list[#list+1] = text:sub(pos, first-1);
pos = last+1;
else
list[#list+1] = text:sub(pos);
break;
end
end
return list;
end
--- Generate a random string.
--
-- You can either provide your own charset or the function will use
-- a default one which is [A-Z].
-- @param len Length of the string we want to generate.
-- @param charset Charset that will be used to generate the string. String or table
-- @return A random string of length <code>len</code> consisting of
-- characters from <code>charset</code> if one was provided, otherwise
-- <code>charset</code> defaults to [A-Z] letters.
function generate_random_string(len, charset)
local t = {}
local ascii_A = 65
local ascii_Z = 90
if charset then
if type(charset) == "string" then
for i=1,len do
local r = random(#charset)
t[i] = sub(charset, r, r)
end
else
for i=1,len do
t[i]=charset[random(#charset)]
end
end
else
for i=1,len do
t[i]=char(random(ascii_A,ascii_Z))
end
end
return concat(t)
end
--- Return a wrapper closure around a socket that buffers socket reads into
-- chunks separated by a pattern.
--
-- This function operates on a socket attempting to read data. It separates the
-- data by <code>sep</code> and, for each invocation, returns a piece of the
-- separated data. Typically this is used to iterate over the lines of data
-- received from a socket (<code>sep = "\r?\n"</code>). The returned string
-- does not include the separator. It will return the final data even if it is
-- not followed by the separator. Once an error or EOF is reached, it returns
-- <code>nil, msg</code>. <code>msg</code> is what is returned by
-- <code>nmap.receive_lines</code>.
-- @param socket Socket for the buffer.
-- @param sep Separator for the buffered reads.
-- @return Data from socket reads or <code>nil</code> on EOF or error.
-- @return Error message, as with <code>receive_lines</code>.
function make_buffer(socket, sep)
local point, left, buffer, done, msg = 1, "";
local function self()
if done then
return nil, msg; -- must be nil for stdnse.lines (below)
elseif not buffer then
local status, str = socket:receive();
if not status then
if #left > 0 then
done, msg = not status, str;
return left;
else
return status, str;
end
else
buffer = left..str;
return self();
end
else
local i, j = buffer:find(sep, point);
if i then
local ret = buffer:sub(point, i-1);
point = j + 1;
return ret;
else
point, left, buffer = 1, buffer:sub(point), nil;
return self();
end
end
end
return self;
end
--[[ This function may be usable in Lua 5.2
function lines(socket)
return make_buffer(socket, "\r?\n"), nil, nil;
end --]]
do
local t = {
["0"] = "0000",
["1"] = "0001",
["2"] = "0010",
["3"] = "0011",
["4"] = "0100",
["5"] = "0101",
["6"] = "0110",
["7"] = "0111",
["8"] = "1000",
["9"] = "1001",
a = "1010",
b = "1011",
c = "1100",
d = "1101",
e = "1110",
f = "1111"
};
--- Converts the given number, n, to a string in a binary number format (12
-- becomes "1100").
-- @param n Number to convert.
-- @return String in binary format.
function tobinary(n)
assert(tonumber(n), "number expected");
return (("%x"):format(n):gsub("%w", t):gsub("^0*", ""));
end
end
--- Converts the given number, n, to a string in an octal number format (12
-- becomes "14").
-- @param n Number to convert.
-- @return String in octal format.
function tooctal(n)
assert(tonumber(n), "number expected");
return ("%o"):format(n)
end
--- Encode a string or number in hexadecimal (12 becomes "c", "AB" becomes
-- "4142").
--
-- An optional second argument is a table with formatting options. The possible
-- fields in this table are
-- * <code>separator</code>: A string to use to separate groups of digits.
-- * <code>group</code>: The size of each group of digits between separators. Defaults to 2, but has no effect if <code>separator</code> is not also given.
-- @usage
-- stdnse.tohex("abc") --> "616263"
-- stdnse.tohex("abc", {separator = ":"}) --> "61:62:63"
-- stdnse.tohex("abc", {separator = ":", group = 4}) --> "61:6263"
-- stdnse.tohex(123456) --> "1e240"
-- stdnse.tohex(123456, {separator = ":"}) --> "1:e2:40"
-- stdnse.tohex(123456, {separator = ":", group = 4}) --> "1:e240"
-- @param s String or number to be encoded.
-- @param options Table specifying formatting options.
-- @return String in hexadecimal format.
function tohex( s, options )
options = options or EMPTY
local separator = options.separator
local hex
if type( s ) == "number" then
hex = ("%x"):format(s)
elseif type( s ) == 'string' then
hex = ("%02x"):rep(#s):format(s:byte(1,#s))
else
error( "Type not supported in tohex(): " .. type(s), 2 )
end
-- format hex if we got a separator
if separator then
local group = options.group or 2
local fmt_table = {}
-- split hex in group-size chunks
for i=#hex,1,-group do
-- table index must be consecutive otherwise table.concat won't work
fmt_table[ceil(i/group)] = hex:sub(max(i-group+1,1),i)
end
hex = concat( fmt_table, separator )
end
return hex
end
---Format a MAC address as colon-separated hex bytes.
--@param mac The MAC address in binary, such as <code>host.mac_addr</code>
--@return The MAC address in XX:XX:XX:XX:XX:XX format
function format_mac(mac)
return tohex(mac, {separator=":"})
end
---Either return the string itself, or return "<blank>" (or the value of the second parameter) if the string
-- was blank or nil.
--
--@param string The base string.
--@param blank The string to return if <code>string</code> was blank
--@return Either <code>string</code> or, if it was blank, <code>blank</code>
function string_or_blank(string, blank)
if(string == nil or string == "") then
if(blank == nil) then
return "<blank>"
else
return blank
end
else
return string
end
end
---
-- Parses a time duration specification, which is a number followed by a
-- unit, and returns a number of seconds.
--
-- The unit is optional and defaults to seconds. The possible units
-- (case-insensitive) are
-- * <code>ms</code>: milliseconds,
-- * <code>s</code>: seconds,
-- * <code>m</code>: minutes,
-- * <code>h</code>: hours.
-- In case of a parsing error, the function returns <code>nil</code>
-- followed by an error message.
--
-- @usage
-- parse_timespec("10") --> 10
-- parse_timespec("10ms") --> 0.01
-- parse_timespec("10s") --> 10
-- parse_timespec("10m") --> 600
-- parse_timespec("10h") --> 36000
-- parse_timespec("10z") --> nil, "Can't parse time specification \"10z\" (bad unit \"z\")"
--
-- @param timespec A time specification string.
-- @return A number of seconds, or <code>nil</code> followed by an error
-- message.
function parse_timespec(timespec)
if timespec == nil then return nil, "Can't parse nil timespec" end
local n, unit, t, m
local multipliers = {[""] = 1, s = 1, m = 60, h = 60 * 60, ms = 0.001}
n, unit = match(timespec, "^([%d.]+)(.*)$")
if not n then
return nil, format("Can't parse time specification \"%s\"", timespec)
end
t = tonumber(n)
if not t then
return nil, format("Can't parse time specification \"%s\" (bad number \"%s\")", timespec, n)
end
m = multipliers[unit]
if not m then
return nil, format("Can't parse time specification \"%s\" (bad unit \"%s\")", timespec, unit)
end
return t * m
end
-- Find the offset in seconds between local time and UTC. That is, if we
-- interpret a UTC date table as a local date table by passing it to os.time,
-- how much must be added to the resulting integer timestamp to make it
-- correct?
local function utc_offset(t)
-- What does the calendar say locally?
local localtime = date("*t", t)
-- What does the calendar say in UTC?
local gmtime = date("!*t", t)
-- Interpret both as local calendar dates and find the difference.
return difftime(time(localtime), time(gmtime))
end
--- Convert a date table into an integer timestamp.
--
-- Unlike os.time, this does not assume that the date table represents a local
-- time. Rather, it takes an optional offset number of seconds representing the
-- time zone, and returns the timestamp that would result using that time zone
-- as local time. If the offset is omitted or 0, the date table is interpreted
-- as a UTC date. For example, 4:00 UTC is the same as 5:00 UTC+1:
-- <code>
-- date_to_timestamp({year=1970,month=1,day=1,hour=4,min=0,sec=0}) --> 14400
-- date_to_timestamp({year=1970,month=1,day=1,hour=4,min=0,sec=0}, 0) --> 14400
-- date_to_timestamp({year=1970,month=1,day=1,hour=5,min=0,sec=0}, 1*60*60) --> 14400
-- </code>
-- And 4:00 UTC+1 is an earlier time:
-- <code>
-- date_to_timestamp({year=1970,month=1,day=1,hour=4,min=0,sec=0}, 1*60*60) --> 10800
-- </code>
function date_to_timestamp(date, offset)
offset = offset or 0
return time(date) + utc_offset(time(date)) - offset
end
local function format_tz(offset)
local sign, hh, mm
if not offset then
return ""
end
if offset < 0 then
sign = "-"
offset = -offset
else
sign = "+"
end
-- Truncate to minutes.
offset = floor(offset / 60)
hh = floor(offset / 60)
mm = floor(fmod(offset, 60))
return format("%s%02d:%02d", sign, hh, mm)
end
--- Format a date and time (and optional time zone) for structured output.
--
-- Formatting is done according to RFC 3339 (a profile of ISO 8601), except
-- that a time zone may be omitted to signify an unspecified local time zone.
-- Time zones are given as an integer number of seconds from UTC. Use
-- <code>0</code> to mark UTC itself. Formatted strings with a time zone look
-- like this:
-- <code>
-- format_timestamp(os.time(), 0) --> "2012-09-07T23:37:42+00:00"
-- format_timestamp(os.time(), 2*60*60) --> "2012-09-07T23:37:42+02:00"
-- </code>
-- Without a time zone they look like this:
-- <code>
-- format_timestamp(os.time()) --> "2012-09-07T23:37:42"
-- </code>
--
-- This function should be used for all dates emitted as part of NSE structured
-- output.
function format_timestamp(t, offset)
if type(t) == "table" then
return format(
"%d-%02d-%02dT%02d:%02d:%02d",
t.year, t.month, t.day, t.hour, t.min, t.sec
)
else
local tz_string = format_tz(offset)
offset = offset or 0
return date("!%Y-%m-%dT%H:%M:%S", t + offset) .. tz_string
end
end
--- Format a time interval into a string
--
-- String is in the same format as format_difftime
-- @param interval A time interval
-- @param unit The time unit division as a number. If <code>interval</code> is
-- in milliseconds, this is 1000 for instance. Default: 1 (seconds)
-- @return The time interval in string format
function format_time(interval, unit)
unit = unit or 1
local precision = floor(math.log(unit, 10))
local sec = (interval % (60 * unit)) / unit
interval = floor(interval / (60 * unit))
local min = interval % 60
interval = floor(interval / 60)
local hr = interval % 24
interval = floor(interval / 24)
local s = format("%dd%02dh%02dm%02.".. precision .."fs",
interval, hr, min, sec)
-- trim off leading 0 and "empty" units
return match(s, "([1-9].*)") or format("%0.".. precision .."fs", 0)
end
--- Format the difference between times <code>t2</code> and <code>t1</code>
-- into a string
--
-- String is in one of the forms (signs may vary):
-- * 0s
-- * -4s
-- * +2m38s
-- * -9h12m34s
-- * +5d17h05m06s
-- * -2y177d10h13m20s
-- The string shows <code>t2</code> relative to <code>t1</code>; i.e., the
-- calculation is <code>t2</code> minus <code>t1</code>.
function format_difftime(t2, t1)
local d, s, sign, yeardiff
d = difftime(time(t2), time(t1))
if d > 0 then
sign = "+"
elseif d < 0 then
sign = "-"
t2, t1 = t1, t2
d = -d
else
sign = ""
end
-- t2 is always later than or equal to t1 here.
-- The year is a tricky case because it's not a fixed number of days
-- the way a day is a fixed number of hours or an hour is a fixed
-- number of minutes. For example, the difference between 2008-02-10
-- and 2009-02-10 is 366 days because 2008 was a leap year, but it
-- should be printed as 1y0d0h0m0s, not 1y1d0h0m0s. We advance t1 to be
-- the latest year such that it is still before t2, which means that its
-- year will be equal to or one less than t2's. The number of years
-- skipped is stored in yeardiff.
if t2.year > t1.year then
local tmpyear = t1.year
-- Put t1 in the same year as t2.
t1.year = t2.year
d = difftime(time(t2), time(t1))
if d < 0 then
-- Too far. Back off one year.
t1.year = t2.year - 1
d = difftime(time(t2), time(t1))
end
yeardiff = t1.year - tmpyear
t1.year = tmpyear
else
yeardiff = 0
end
local s = format_time(d)
if yeardiff == 0 then return sign .. s end
-- Years.
s = format("%dy", yeardiff) .. s
return sign .. s
end
--- Returns the current time in milliseconds since the epoch
-- @return The current time in milliseconds since the epoch
function clock_ms()
return nmap.clock() * 1000
end
--- Returns the current time in microseconds since the epoch
-- @return The current time in microseconds since the epoch
function clock_us()
return nmap.clock() * 1000000
end
---Get the indentation symbols at a given level.
local function format_get_indent(indent)
return rep(" ", #indent)
end
local function splitlines(s)
local result = {}
local i = 0
while i <= #s do
local b, e
b, e = find(s, "\r?\n", i)
if not b then
break
end
result[#result + 1] = sub(s, i, b - 1)
i = e + 1
end
if i <= #s then
result[#result + 1] = sub(s, i)
end
return result
end
-- A helper for format_output (see below).
local function format_output_sub(status, data, indent)
if (#data == 0) then
return ""
end
-- Used to put 'ERROR: ' in front of all lines on error messages
local prefix = ""
-- Initialize the output string to blank (or, if we're at the top, add a newline)
local output = {}
if(not(indent)) then
insert(output, '\n')
end
if(not(status)) then
if(nmap.debugging() < 1) then
return nil
end
prefix = "ERROR: "
end
-- If a string was passed, turn it into a table
if(type(data) == 'string') then
data = {data}
end
-- Make sure we have an indent value
indent = indent or {}
if(data['name']) then
if(data['warning'] and nmap.debugging() > 0) then
insert(output, format("%s%s%s (WARNING: %s)\n",
format_get_indent(indent), prefix,
data['name'], data['warning']))
else
insert(output, format("%s%s%s\n",
format_get_indent(indent), prefix,
data['name']))
end
elseif(data['warning'] and nmap.debugging() > 0) then
insert(output, format("%s%s(WARNING: %s)\n",
format_get_indent(indent), prefix,
data['warning']))
end
for i, value in ipairs(data) do
if(type(value) == 'table') then
-- Do a shallow copy of indent
local new_indent = {}
for _, v in ipairs(indent) do
insert(new_indent, v)
end
if(i ~= #data) then
insert(new_indent, false)
else
insert(new_indent, true)
end
insert(output, format_output_sub(status, value, new_indent))
elseif(type(value) == 'string') then
local lines = splitlines(value)
for j, line in ipairs(lines) do
insert(output, format("%s %s%s\n",
format_get_indent(indent),
prefix, line))
end
end
end
return concat(output)
end
---Takes a table of output on the commandline and formats it for display to the
-- user.
--
-- This is basically done by converting an array of nested tables into a
-- string. In addition to numbered array elements, each table can have a 'name'
-- and a 'warning' value. The 'name' will be displayed above the table, and
-- 'warning' will be displayed, with a 'WARNING' tag, if and only if debugging
-- is enabled.
--
-- Here's an example of a table:
-- <code>
-- local domains = {}
-- domains['name'] = "DOMAINS"
-- table.insert(domains, 'Domain 1')
-- table.insert(domains, 'Domain 2')
--
-- local names = {}
-- names['name'] = "NAMES"
-- names['warning'] = "Not all names could be determined!"
-- table.insert(names, "Name 1")
--
-- local response = {}
-- table.insert(response, "Apple pie")
-- table.insert(response, domains)
-- table.insert(response, names)
--
-- return stdnse.format_output(true, response)
-- </code>
--
-- With debugging enabled, this is the output:
-- <code>
-- Host script results:
-- | smb-enum-domains:
-- | Apple pie
-- | DOMAINS
-- | Domain 1
-- | Domain 2
-- | NAMES (WARNING: Not all names could be determined!)
-- |_ Name 1
-- </code>
--
--@param status A boolean value dictating whether or not the script succeeded.
-- If status is false, and debugging is enabled, 'ERROR' is prepended
-- to every line. If status is false and debugging is disabled, no output
-- occurs.
--@param data The table of output.
--@param indent Used for indentation on recursive calls; should generally be set to
-- nil when calling from a script.
-- @return <code>nil</code>, if <code>data</code> is empty, otherwise a
-- multiline string.
function format_output(status, data, indent)
-- If data is nil, die with an error (I keep doing that by accident)
assert(data, "No data was passed to format_output()")
-- Don't bother if we don't have any data
if (#data == 0) then
return nil
end
local result = format_output_sub(status, data, indent)
-- Check for an empty result
if(result == nil or #result == "" or result == "\n" or result == "\n") then
return nil
end
return result
end
-- Get the value of a script argument, or nil if the script argument was not
-- given. This works also for arguments given as top-level array values, like
-- --script-args=unsafe; for these it returns the value 1.
local function arg_value(argname)
if nmap.registry.args[argname] then
return nmap.registry.args[argname]
else
-- if scriptname.arg is not there, check "arg"
local argument_frags = strsplit("%.", argname)
if #argument_frags > 0 then
if nmap.registry.args[argument_frags[2]] then
return nmap.registry.args[argument_frags[2]]
end
end
end
for _, v in ipairs(nmap.registry.args) do
if v == argname then
return 1
end
end
end
--- Parses the script arguments passed to the --script-args option.
--
-- @usage
-- --script-args 'script.arg1=value,script.arg3,script-x.arg=value'
-- local arg1, arg2, arg3 = get_script_args('script.arg1','script.arg2','script.arg3')
-- => arg1 = value
-- => arg2 = nil
-- => arg3 = 1
--
-- --script-args 'displayall,unsafe,script-x.arg=value,script-y.arg=value'
-- local displayall, unsafe = get_script_args('displayall','unsafe')
-- => displayall = 1
-- => unsafe = 1
--
-- --script-args 'dns-cache-snoop.mode=timed,dns-cache-snoop.domains={host1,host2}'
-- local mode, domains = get_script_args('dns-cache-snoop.mode',
-- 'dns-cache-snoop.domains')
-- => mode = 'timed'
-- => domains = {host1,host2}
--
-- @param Arguments Script arguments to check.
-- @return Arguments values.
function get_script_args (...)
local args = {}
for i, set in ipairs({...}) do
if type(set) == "string" then
set = {set}
end
for _, test in ipairs(set) do
local v = arg_value(test)
if v then
args[i] = v
break
end
end
end
return unpack(args, 1, select("#", ...))
end
---Get the best possible hostname for the given host. This can be the target as given on
-- the commandline, the reverse dns name, or simply the ip address.
--@param host The host table (or a string that'll simply be returned).
--@return The best possible hostname, as a string.
function get_hostname(host)
if type(host) == "table" then
return host.targetname or ( host.name ~= '' and host.name ) or host.ip
else
return host
end
end
---Retrieve an item from the registry, checking if each sub-key exists. If any key doesn't
-- exist, return nil.
function registry_get(subkeys)
local registry = nmap.registry
local i = 1
while(subkeys[i]) do
if(not(registry[subkeys[i]])) then
return nil
end
registry = registry[subkeys[i]]
i = i + 1
end
return registry
end
--Check if the given element exists in the registry. If 'key' is nil, it isn't checked.
function registry_exists(subkeys, key, value)
local subkey = registry_get(subkeys)
if(not(subkey)) then
return false
end
for k, v in pairs(subkey) do
if((key == nil or key == k) and (v == value)) then -- TODO: if 'value' is a table, this fails
return true
end
end
return false
end
---Add an item to an array in the registry, creating all sub-keys if necessary.
--
-- For example, calling:
-- <code>registry_add_array({'192.168.1.100', 'www', '80', 'pages'}, 'index.html')</code>
-- Will create nmap.registry['192.168.1.100'] as a table, if necessary, then add a table
-- under the 'www' key, and so on. 'pages', finally, is treated as an array and the value
-- given is added to the end.
function registry_add_array(subkeys, value, allow_duplicates)
local registry = nmap.registry
local i = 1
-- Unless the user wants duplicates, make sure there aren't any
if(allow_duplicates ~= true) then
if(registry_exists(subkeys, nil, value)) then
return
end
end
while(subkeys[i]) do
if(not(registry[subkeys[i]])) then
registry[subkeys[i]] = {}
end
registry = registry[subkeys[i]]
i = i + 1
end
-- Make sure the value isn't already in the table
for _, v in pairs(registry) do
if(v == value) then
return
end
end
insert(registry, value)
end
---Similar to <code>registry_add_array</code>, except instead of adding a value to the
-- end of an array, it adds a key:value pair to the table.
function registry_add_table(subkeys, key, value, allow_duplicates)
local registry = nmap.registry
local i = 1
-- Unless the user wants duplicates, make sure there aren't any
if(allow_duplicates ~= true) then
if(registry_exists(subkeys, key, value)) then
return
end
end
while(subkeys[i]) do
if(not(registry[subkeys[i]])) then
registry[subkeys[i]] = {}
end
registry = registry[subkeys[i]]
i = i + 1
end
registry[key] = value
end
--- This function allows you to create worker threads that may perform
-- network tasks in parallel with your script thread.
--
-- Any network task (e.g. <code>socket:connect(...)</code>) will cause the
-- running thread to yield to NSE. This allows network tasks to appear to be
-- blocking while being able to run multiple network tasks at once.
-- While this is useful for running multiple separate scripts, it is
-- unfortunately difficult for a script itself to perform network tasks in
-- parallel. In order to allow scripts to also have network tasks running in
-- parallel, we provide this function, <code>stdnse.new_thread</code>, to
-- create a new thread that can perform its own network related tasks
-- in parallel with the script.
--
-- The script launches the worker thread by calling the <code>new_thread</code>
-- function with the parameters:
-- * The main Lua function for the script to execute, similar to the script action function.
-- * The variable number of arguments to be passed to the worker's main function.
--
-- The <code>stdnse.new_thread</code> function will return two results:
-- * The worker thread's base (main) coroutine (useful for tracking status).
-- * A status query function (described below).
--
-- The status query function shall return two values:
-- * The result of coroutine.status using the worker thread base coroutine.
-- * The error object thrown that ended the worker thread or <code>nil</code> if no error was thrown. This is typically a string, like most Lua errors.
--
-- Note that NSE discards all return values of the worker's main function. You
-- must use function parameters, upvalues or environments to communicate
-- results.
--
-- You should use the condition variable (<code>nmap.condvar</code>)
-- and mutex (<code>nmap.mutex</code>) facilities to coordinate with your
-- worker threads. Keep in mind that Nmap is single threaded so there are
-- no (memory) issues in synchronization to worry about; however, there
-- is resource contention. Your resources are usually network
-- bandwidth, network sockets, etc. Condition variables are also useful if the
-- work for any single thread is dynamic. For example, a web server spider
-- script with a pool of workers will initially have a single root html
-- document. Following the retrieval of the root document, the set of
-- resources to be retrieved (the worker's work) will become very large
-- (an html document adds many new hyperlinks (resources) to fetch).
--@name new_thread
--@class function
--@param main The main function of the worker thread.
--@param ... The arguments passed to the main worker thread.
--@return co The base coroutine of the worker thread.
--@return info A query function used to obtain status information of the worker.
--@usage
--local requests = {"/", "/index.html", --[[ long list of objects ]]}
--
--function thread_main (host, port, responses, ...)
-- local condvar = nmap.condvar(responses);
-- local what = {n = select("#", ...), ...};
-- local allReqs = nil;
-- for i = 1, what.n do
-- allReqs = http.pGet(host, port, what[i], nil, nil, allReqs);
-- end
-- local p = assert(http.pipeline(host, port, allReqs));
-- for i, response in ipairs(p) do responses[#responses+1] = response end
-- condvar "signal";
--end
--
--function many_requests (host, port)
-- local threads = {};
-- local responses = {};
-- local condvar = nmap.condvar(responses);
-- local i = 1;
-- repeat
-- local j = math.min(i+10, #requests);
-- local co = stdnse.new_thread(thread_main, host, port, responses,
-- table.unpack(requests, i, j));
-- threads[co] = true;
-- i = j+1;
-- until i > #requests;
-- repeat
-- condvar "wait";
-- for thread in pairs(threads) do
-- if coroutine.status(thread) == "dead" then threads[thread] = nil end
-- end
-- until next(threads) == nil;
-- return responses;
--end
do end -- no function here, see nse_main.lua
--- Returns the base coroutine of the running script.
--
-- A script may be resuming multiple coroutines to facilitate its own
-- collaborative multithreading design. Because there is a "root" or "base"
-- coroutine that lets us determine whether the script is still active
-- (that is, the script did not end, possibly due to an error), we provide
-- this <code>stdnse.base</code> function that will retrieve the base
-- coroutine of the script. This base coroutine is the coroutine that runs
-- the action function.
--
-- The base coroutine is useful for many reasons but here are some common
-- uses:
-- * We want to attribute the ownership of an object (perhaps a network socket) to a script.
-- * We want to identify if the script is still alive.
--@name base
--@class function
--@return coroutine Returns the base coroutine of the running script.
do end -- no function here, see nse_main.lua
--- The Lua Require Function with errors silenced.
--
-- See the Lua manual for description of the require function. This modified
-- version allows the script to quietly fail at loading if a required
-- library does not exist.
--
--@name silent_require
--@class function
--@usage stdnse.silent_require "openssl"
do end -- no function here, see nse_main.lua
---Checks if the port is in the port range
--
-- For example, calling:
-- <code>in_port_range({number=31337,protocol="udp"},"T:15,50-75,U:31334-31339")</code>
-- would result in a true value
--@param port a port structure containing keys port number(number) and protocol(string)
--@param port_range a port range string in Nmap standard format (ex. "T:80,1-30,U:31337,21-25")
--@returns boolean indicating whether the port is in the port range
function in_port_range(port,port_range)
assert(port and type(port.number)=="number" and type(port.protocol)=="string" and
(port.protocol=="udp" or port.protocol=="tcp"),"Port structure missing or invalid: port={ number=<port_number>, protocol=<port_protocol> }")
assert((type(port_range)=="string" or type(port_range)=="number") and port_range~="","Incorrect port range specification.")
-- Proto - true for TCP, false for UDP
local proto
if(port.protocol=="tcp") then proto = true else proto = false end
--TCP flag for iteration - true for TCP, false for UDP, if not specified we presume TCP
local tcp_flag = true
-- in case the port_range is a single number
if type(port_range)=="number" then
if proto and port_range==port.number then return true
else return false
end
end
--clean the string a bit
port_range=port_range:gsub("%s+","")
-- single_pr - single port range
for i, single_pr in ipairs(strsplit(",",port_range)) do
if single_pr:match("T:") then
tcp_flag = true
single_pr = single_pr:gsub("T:","")
else
if single_pr:match("U:") then
tcp_flag = false
single_pr = single_pr:gsub("U:","")
end
end
-- compare ports only when the port's protocol is the same as
-- the current single port range
if tcp_flag == proto then
local pone = single_pr:match("^(%d+)$")
if pone then
pone = tonumber(pone)
assert(pone>-1 and pone<65536, "Port range number out of range (0-65535).")
if pone == port.number then
return true
end
else
local pstart, pend = single_pr:match("^(%d+)%-(%d+)$")
pstart, pend = tonumber(pstart), tonumber(pend)
assert(pstart,"Incorrect port range specification.")
assert(pstart<=pend,"Incorrect port range specification, the starting port should have a smaller value than the ending port.")
assert(pstart>-1 and pstart<65536 and pend>-1 and pend<65536, "Port range number out of range (0-65535).")
if port.number >=pstart and port.number <= pend then
return true
end
end
end
end
-- if no match is found then the port doesn't belong to the port_range
return false
end
--- Module function that mimics some behavior of Lua 5.1 module function.
--
-- This convenience function returns a module environment to set the _ENV
-- upvalue. The _NAME, _PACKAGE, and _M fields are set as in the Lua 5.1
-- version of this function. Each option function (e.g. stdnse.seeall)
-- passed is run with the new environment, in order.
--
-- @see stdnse.seeall
-- @see strict
-- @usage
-- _ENV = stdnse.module(name, stdnse.seeall, require "strict");
-- @param name The module name.
-- @param ... Option functions which modify the environment of the module.
function module (name, ...)
local env = {};
env._NAME = name;
env._PACKAGE = name:match("(.+)%.[^.]+$");
env._M = env;
local mods = pack(...);
for i = 1, mods.n do
mods[i](env);
end
return env;
end
--- Change environment to load global variables.
--
-- Option function for use with stdnse.module. It is the same
-- as package.seeall from Lua 5.1.
--
-- @see stdnse.module
-- @usage
-- _ENV = stdnse.module(name, stdnse.seeall);
-- @param env Environment to change.
function seeall (env)
local m = getmetatable(env) or {};
m.__index = _G;
setmetatable(env, m);
end
--- Return a table that keeps elements in order of insertion.
--
-- The pairs function, called on a table returned by this function, will yield
-- elements in the order they were inserted. This function is meant to be used
-- to construct output tables returned by scripts.
--
-- Reinserting a key that is already in the table does not change its position
-- in the order. However, removing a key by assigning to <code>nil</code> and
-- then doing another assignment will move the key to the end of the order.
--
-- @return An ordered table.
function output_table ()
local t = {}
local order = {}
local function iterator ()
for i, key in ipairs(order) do
coroutine.yield(key, t[key])
end
end
local mt = {
__newindex = function (_, k, v)
if t[k] == nil and v ~= nil then
-- New key?
insert(order, k)
elseif v == nil then
-- Deleting an existing key?
for i, key in ipairs(order) do
if key == k then
remove(order, i)
break
end
end
end
rawset(t, k, v)
end,
__index = function (_, k)
return t[k]
end,
__pairs = function (_)
return coroutine.wrap(iterator)
end,
__call = function (_) -- hack to mean "not_empty?"
return not not next(order)
end,
__len = function (_)
return #order
end
}
return setmetatable({}, mt)
end
--- A pretty printer for Lua objects.
--
-- Takes an object (usually a table) and prints it using the
-- printer function. The printer function takes a sole string
-- argument and will be called repeatedly.
--
-- @param obj The object to pretty print.
-- @param printer The printer function.
function pretty_printer (obj, printer)
if printer == nil then printer = print end
local function aux (obj, spacing)
local t = type(obj)
if t == "table" then
printer "{\n"
for k, v in pairs(obj) do
local spacing = spacing.."\t"
printer(spacing)
printer "["
aux(k, spacing)
printer "] = "
aux(v, spacing)
printer ",\n"
end
printer(spacing.."}")
elseif t == "string" then
printer(format("%q", obj))
else
printer(tostring(obj))
end
end
return aux(obj, "")
end
-- This pattern must match the percent sign '%' since it is used in
-- escaping.
local FILESYSTEM_UNSAFE = "[^a-zA-Z0-9._-]"
---
-- Escape a string to remove bytes and strings that may have meaning to
-- a filesystem, such as slashes.
--
-- All bytes are escaped, except for:
-- * alphabetic <code>a</code>-<code>z</code> and <code>A</code>-<code>Z</code>
-- * digits 0-9
-- * <code>.</code> <code>_</code> <code>-</code>
-- In addition, the strings <code>"."</code> and <code>".."</code> have
-- their characters escaped.
--
-- Bytes are escaped by a percent sign followed by the two-digit
-- hexadecimal representation of the byte value.
-- * <code>filename_escape("filename.ext") --> "filename.ext"</code>
-- * <code>filename_escape("input/output") --> "input%2foutput"</code>
-- * <code>filename_escape(".") --> "%2e"</code>
-- * <code>filename_escape("..") --> "%2e%2e"</code>
-- This escaping is somewhat like that of JavaScript
-- <code>encodeURIComponent</code>, except that fewer bytes are
-- whitelisted, and it works on bytes, not Unicode characters or UTF-16
-- code points.
function filename_escape(s)
if s == "." then
return "%2e"
elseif s == ".." then
return "%2e%2e"
else
return (gsub(s, FILESYSTEM_UNSAFE, function (c)
return format("%%%02x", byte(c))
end))
end
end
--- Check for the presence of a value in a table
--@param tab the table to search into
--@param item the searched value
--@return Boolean true if the item was found, false if not
--@return The index or key where the value was found, or nil
function contains(tab, item)
for k, val in pairs(tab) do
if val == item then
return true, k
end
end
return false, nil
end
--- Returns a conservative timeout for a host
--
-- If the host parameter is a NSE host table with a <code>times.timeout</code>
-- attribute, then the return value is the host timeout scaled according to the
-- max_timeout. The scaling factor is defined by a linear formula such that
-- (max_timeout=8000, scale=2) and (max_timeout=1000, scale=1)
--
-- @param host The host object to base the timeout on. If this is anything but
-- a host table, the max_timeout is returned.
-- @param max_timeout The maximum timeout in milliseconds. This is the default
-- timeout used if there is no host.times.timeout. Default: 8000
-- @param min_timeout The minimum timeout in milliseconds that will be
-- returned. Default: 1000
-- @return The timeout in milliseconds, suitable for passing to set_timeout
-- @usage
-- assert(host.times.timeout == 1.3)
-- assert(get_timeout() == 8000)
-- assert(get_timeout(nil, 5000) == 5000)
-- assert(get_timeout(host) == 2600)
-- assert(get_timeout(host, 10000, 3000) == 3000)
function get_timeout(host, max_timeout, min_timeout)
max_timeout = max_timeout or 8000
local t = type(host) == "table" and host.times and host.times.timeout
if not t then
return max_timeout
end
t = t * (max_timeout + 6000) / 7
min_timeout = min_timeout or 1000
if t < min_timeout then
return min_timeout
elseif t > max_timeout then
return max_timeout
end
return t
end
--- Returns the keys of a table as an array
-- @param t The table
-- @return A table of keys
function keys(t)
local ret = {}
local k, v = next(t)
while k do
ret[#ret+1] = k
k, v = next(t, k)
end
return ret
end
return _ENV;
| mit |
girishramnani/Algorithm-Implementations | Lempel_Ziv_Welch/Lua/Yonaba/lzw.lua | 24 | 1387 | -- Lempel-Ziv Welch compression data algorithm implementation
-- See : http://en.wikipedia.org/wiki/LZW
local function lzw_encode(str)
local w = ''
local result = {}
local dict_size = 256
-- Builds the dictionnary
local dict = {}
for i = 0, dict_size-1 do
dict[string.char(i)] = i
end
local i = dict_size
for char in str:gmatch('.') do
-- Finds the longest string matching the input
local wc = w .. char
if dict[wc] then
-- Save the current match index
w = wc
else
-- Add the match to the dictionary
table.insert(result, dict[w])
dict[wc] = i
i = i + 1
w = char
end
end
if w~='' then
table.insert(result, dict[w])
end
return result
end
local function lzw_decode(str)
local dict_size = 256
-- Builds the dictionary
local dict = {}
for i = 0, dict_size-1 do
dict[i] = string.char(i)
end
local w = string.char(str[1])
local result = w
for i = 2, #str do
local k = str[i]
local entry = ''
if dict[k] then
entry = dict[k]
elseif k == dict_size then
entry = w .. w:sub(1,1)
else
return nil -- No match found, decoding error
end
result = result .. entry
dict[dict_size] = w .. entry:sub(1,1)
dict_size = dict_size + 1
w = entry
end
return result
end
return {
encode = lzw_encode,
decode = lzw_decode,
}
| mit |
geanux/darkstar | scripts/globals/items/shining_trout.lua | 18 | 1323 | -----------------------------------------
-- ID: 5791
-- Item: shining_trout
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 2
-- Mind -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5791);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_MND, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_MND, -4);
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/Yughott_Grotto/Zone.lua | 28 | 1638 | -----------------------------------
--
-- Zone: Yughott_Grotto (142)
--
-----------------------------------
package.loaded["scripts/zones/Yughott_Grotto/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Yughott_Grotto/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
UpdateTreasureSpawnPoint(17359048);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(439.814,-42.481,169.755,118);
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
girishramnani/Algorithm-Implementations | Binary_Search/Lua/Yonaba/binary_search_test.lua | 53 | 1896 | -- Tests for binary_search.lua
local binary_search = require 'binary_search'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
run('Performs a binary search', function()
local t = {1, 2, 3, 4, 5}
assert(binary_search(t, 1) == 1)
assert(binary_search(t, 2) == 2)
assert(binary_search(t, 3) == 3)
assert(binary_search(t, 4) == 4)
assert(binary_search(t, 5) == 5)
end)
run('Array values do not have to be consecutive',function()
local t = {1, 3, 5, 10, 13}
assert(binary_search(t, 1) == 1)
assert(binary_search(t, 3) == 2)
assert(binary_search(t, 5) == 3)
assert(binary_search(t, 10) == 4)
assert(binary_search(t, 13) == 5)
end)
run('But the array needs to be sorted',function()
local t = {1, 15, 12, 14, 13}
assert(binary_search(t, 13) == nil)
assert(binary_search(t, 15) == nil)
end)
run('In case the value exists more than once, it returns any of them',function()
local t = {1, 12, 12, 13, 15, 15, 16}
assert(binary_search(t, 15) == 6)
assert(binary_search(t, 12) == 2)
end)
run('Accepts comparison functions for reversed arrays',function()
local t = {50, 33, 18, 12, 5, 1, 0}
local comp = function(a, b) return a > b end
assert(binary_search(t, 50, comp) == 1)
assert(binary_search(t, 33, comp) == 2)
assert(binary_search(t, 18, comp) == 3)
assert(binary_search(t, 12, comp) == 4)
assert(binary_search(t, 5, comp) == 5)
assert(binary_search(t, 1, comp) == 6)
assert(binary_search(t, 0, comp) == 7)
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
geanux/darkstar | scripts/globals/spells/yurin_ichi.lua | 18 | 1597 | -----------------------------------------
-- Spell: Yurin: Ichi
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local effect = EFFECT_INHIBIT_TP;
-- Base Stats
local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT));
--Duration Calculation
local resist = applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0);
--Base power is 10 and is not affected by resistaces.
local power = 10;
--Calculates Resist Chance
if (resist >= 0.125) then
local duration = 180 * resist;
if (duration >= 50) then
-- Erases a weaker inhibit tp and applies the stronger one
local inhibit_tp = target:getStatusEffect(effect);
if (inhibit_tp ~= nil) then
if (inhibit_tp:getPower() < power) then
target:delStatusEffect(effect);
target:addStatusEffect(effect,power,0,duration);
spell:setMsg(237);
else
-- no effect
spell:setMsg(75);
end
else
target:addStatusEffect(effect,power,0,duration);
spell:setMsg(237);
end
else
spell:setMsg(85);
end
else
spell:setMsg(284);
end
return effect;
end; | gpl-3.0 |
geanux/darkstar | scripts/zones/Windurst_Woods/npcs/Mushuhi-Metahi.lua | 59 | 1052 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Mushuhi-Metahi
-- Type: Weather Reporter
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x82718,0,0,0,0,0,0,0,VanadielTime());
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
geanux/darkstar | scripts/zones/Southern_San_dOria/npcs/Legata.lua | 17 | 1999 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Legata
-- Starts and Finishes Quest: Starting a Flame (R)
-- @zone 230
-- @pos 82 0 116
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,STARTING_A_FLAME) ~= QUEST_AVAILABLE) then
if (trade:hasItemQty(768,4) and trade:getItemCount() == 4) then
player:startEvent(0x0024);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(SANDORIA,STARTING_A_FLAME) == QUEST_AVAILABLE) then
player:startEvent(0x0025);
else
player:startEvent(0x0023);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0025 and option == 1) then
player:addQuest(SANDORIA,STARTING_A_FLAME);
elseif (csid == 0x0024) then
player:tradeComplete();
player:addGil(GIL_RATE*100);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*100);
if (player:getQuestStatus(SANDORIA,STARTING_A_FLAME) == QUEST_ACCEPTED) then
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,STARTING_A_FLAME);
else
player:addFame(SANDORIA,SAN_FAME*5);
end
end
end; | gpl-3.0 |
famellad/oldschool-scroller | libs/shine/colorgradesimple.lua | 8 | 1750 | --[[
The MIT License (MIT)
Copyright (c) 2015 Matthias Richter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]--
return {
description = "Simple linear color grading of red, green and blue channel",
new = function(self)
self.canvas = love.graphics.newCanvas()
self.shader = love.graphics.newShader[[
extern vec3 grade;
vec4 effect(vec4 color, Image texture, vec2 tc, vec2 _)
{
return vec4(grade, 1.0f) * Texel(texture, tc) * color;
}
]]
self.shader:send("grade",{1.0,1.0,1.0})
end,
draw = function(self, func, ...)
self:_apply_shader_to_scene(self.shader, self.canvas, func, ...)
end,
set = function(self, key, value)
if key == "grade" then
self.shader:send(key, value)
else
error("Unknown property: " .. tostring(key))
end
return self
end
}
| gpl-2.0 |
kaen/Zero-K | units/armbanth.lua | 2 | 10085 | unitDef = {
unitname = [[armbanth]],
name = [[Bantha]],
description = [[Ranged Support Strider]],
acceleration = 0.1047,
brakeRate = 0.2212,
buildCostEnergy = 10500,
buildCostMetal = 10500,
builder = false,
buildPic = [[ARMBANTH.png]],
buildTime = 10500,
canAttack = true,
canGuard = true,
canManualFire = true,
canMove = true,
canPatrol = true,
canstop = [[1]],
category = [[LAND]],
collisionVolumeOffsets = [[0 0 -2]],
collisionVolumeScales = [[55 80 35]],
collisionVolumeTest = 1,
collisionVolumeType = [[box]],
corpse = [[DEAD]],
customParams = {
extradrawrange = 465,
description_fr = [[Mechwarrior d'Assaut Lourd]],
description_de = [[Schwerer Kampfstreicher]],
description_pl = [[Ciezki robot bojowy]],
helptext = [[The Bantha is an even heavier solution to a particularly uncrackable defense line, with a tachyon projector and EMP missiles for stand-off engagements, lightning hand cannons for general purpose combat, and a good deal of armor. Beware though, for it is defenseless against air and cannot be used effectively on its own.]],
helptext_de = [[Der Bantha ist die Lösung für eine besonders schwierig zu knackende Verteidigungslinie. Dazu besitzt er einen Tachyonen Beschleuniger und Marschflugkörper für Pattsituationen, blitzschnelle Handfeuerwaffen für den normalen Kampf und haufenweise Munition. Dennoch gib Acht darauf, dass er gegen Luftangriffe fast schutzlos ist.]],
helptext_fr = [[Le Bantha est aussi cher et lent qu'il est inarretable. Il dispose de canons EMP, d'un canon accelerateur tachyon et de missiles. Courez.]],
helptext_pl = [[Bantha to ciezki robot bojowy, ktory jest uzbrojony po zeby i bardzo wytrzymaly. Posiada rakiety EMP dalekiego zasiegu, ciezki laser oraz dzialka EMP. Nie ma jednak zadnej obrony przeciwlotniczej i slabo radzi sobie bez wsparcia mniejszych jednostek.]],
aimposoffset = [[0 -8 0]],
midposoffset = [[0 -8 0]],
modelradius = [[17]],
},
explodeAs = [[ATOMIC_BLAST]],
footprintX = 4,
footprintZ = 4,
iconType = [[t3generic]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
losEmitHeight = 60,
mass = 1387,
maxDamage = 36000,
maxSlope = 36,
maxVelocity = 1.72,
maxWaterDepth = 22,
minCloakDistance = 75,
movementClass = [[KBOT4]],
noAutoFire = false,
noChaseCategory = [[FIXEDWING SATELLITE SUB]],
objectName = [[Bantha.s3o]],
seismicSignature = 4,
selfDestructAs = [[ATOMIC_BLAST]],
script = [[armbanth.lua]],
sfxtypes = {
explosiongenerators = {
[[custom:zeusmuzzle]],
[[custom:zeusgroundflash]],
[[custom:opticblast_charge]]
},
},
side = [[ARM]],
sightDistance = 720,
smoothAnim = true,
trackOffset = 0,
trackStrength = 8,
trackStretch = 0.5,
trackType = [[ComTrack]],
trackWidth = 42,
turnRate = 1056,
upright = true,
workerTime = 0,
weapons = {
{
def = [[ATA]],
badTargetCategory = [[GUNSHIP]],
onlyTargetCategory = [[SWIM LAND SHIP SINK TURRET FLOAT GUNSHIP HOVER]],
},
{
def = [[LIGHTNING]],
badTargetCategory = [[FIXEDWING]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
{
def = [[EMP_MISSILE]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
},
weaponDefs = {
ATA = {
name = [[Tachyon Accelerator]],
areaOfEffect = 20,
beamTime = 1,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
customParams = {
statsprojectiles = 1,
statsdamage = 3000,
},
damage = {
default = 600.1,
planes = 600.1,
subs = 30,
},
explosionGenerator = [[custom:ataalaser]],
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
largeBeamLaser = true,
laserFlareSize = 16.94,
minIntensity = 1,
noSelfDamage = true,
projectiles = 5,
range = 950,
reloadtime = 10,
rgbColor = [[0.25 0 1]],
soundStart = [[weapon/laser/heavy_laser6]],
soundStartVolume = 3,
texture1 = [[largelaserdark]],
texture2 = [[flaredark]],
texture3 = [[flaredark]],
texture4 = [[smallflaredark]],
thickness = 16.9,
tolerance = 10000,
turret = true,
weaponType = [[BeamLaser]],
weaponVelocity = 1500,
},
EMP_MISSILE = {
name = [[EMP Missiles]],
areaOfEffect = 128,
accuracy = 512,
avoidFeature = false,
avoidFriendly = false,
burst = 10,
burstrate = 0.2,
cegTag = [[emptrail]],
commandFire = true,
craterBoost = 0,
craterMult = 0,
damage = {
default = 1500,
empresistant75 = 375,
empresistant99 = 15,
planes = 1500,
},
dance = 20,
edgeEffectiveness = 0.5,
explosionGenerator = [[custom:YELLOW_LIGHTNINGPLOSION]],
fireStarter = 100,
fixedlauncher = true,
flightTime = 12,
impulseBoost = 0,
impulseFactor = 0,
interceptedByShieldType = 2,
model = [[banthamissile.s3o]],
noSelfDamage = true,
paralyzer = true,
paralyzeTime = 20,
range = 1200,
reloadtime = 30,
smokeTrail = false,
soundHit = [[weapon/missile/vlaunch_emp_hit]],
soundStart = [[weapon/missile/missile_launch_high]],
soundStartVolume = 5,
startVelocity = 100,
tracks = true,
trajectoryHeight = 1,
tolerance = 512,
turnRate = 8000,
turret = true,
weaponAcceleration = 100,
weaponTimer = 6,
weaponType = [[MissileLauncher]],
weaponVelocity = 250,
wobble = 18000,
},
LIGHTNING = {
name = [[Lightning Cannon]],
areaOfEffect = 8,
craterBoost = 0,
craterMult = 0,
customParams = {
extra_damage = [[320]],
},
damage = {
default = 960,
empresistant75 = 240,
empresistant99 = 9.6,
},
duration = 10,
explosionGenerator = [[custom:LIGHTNINGPLOSION]],
fireStarter = 50,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
intensity = 12,
interceptedByShieldType = 1,
paralyzer = true,
paralyzeTime = 1.5,
range = 465,
reloadtime = 1,
rgbColor = [[0.5 0.5 1]],
soundStart = [[weapon/LightningBolt]],
soundStartVolume = 2,
soundTrigger = true,
sprayAngle = 1000,
startsmoke = [[1]],
texture1 = [[lightning]],
thickness = 10,
turret = true,
weaponType = [[LightningCannon]],
weaponVelocity = 400,
},
},
featureDefs = {
DEAD = {
description = [[Wreckage - Bantha]],
blocking = true,
category = [[corpses]],
damage = 36000,
energy = 0,
featureDead = [[HEAP]],
featurereclamate = [[SMUDGE01]],
footprintX = 4,
footprintZ = 4,
height = [[20]],
hitdensity = [[100]],
metal = 4200,
object = [[bantha_wreck.s3o]],
reclaimable = true,
reclaimTime = 4200,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
HEAP = {
description = [[Debris - Bantha]],
blocking = false,
category = [[heaps]],
damage = 36000,
energy = 0,
featurereclamate = [[SMUDGE01]],
footprintX = 4,
footprintZ = 4,
height = [[4]],
hitdensity = [[100]],
metal = 2100,
object = [[debris4x4b.s3o]],
reclaimable = true,
reclaimTime = 2100,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
},
}
return lowerkeys({ armbanth = unitDef })
| gpl-2.0 |
ModusCreateOrg/libOpenMPT-ios | libopenmpt-0.2.6401/build/premake/mpt-OpenMPT.lua | 1 | 2879 |
project "OpenMPT"
uuid "37FC32A4-8DDC-4A9C-A30C-62989DD8ACE9"
language "C++"
location ( "../../build/" .. _ACTION )
objdir "../../build/obj/OpenMPT"
dofile "../../build/premake/premake-defaults-EXEGUI.lua"
dofile "../../build/premake/premake-defaults.lua"
filter { "configurations:*Shared" }
targetname "OpenMPT"
filter { "not configurations:*Shared" }
targetname "mptrack"
filter {}
includedirs {
"../../common",
"../../soundlib",
"../../include",
"../../include/msinttypes/inttypes",
"../../include/vstsdk2.4",
"../../include/ASIOSDK2/common",
"../../include/flac/include",
"../../include/lhasa/lib/public",
"../../include/ogg/include",
"../../include/opus/include",
"../../include/opusfile/include",
"../../include/portaudio/include",
"../../include/vorbis/include",
"../../include/zlib",
"$(IntDir)/svn_version",
"../../build/svn_version",
}
files {
"../../mptrack/res/OpenMPT.manifest",
}
files {
"../../common/*.cpp",
"../../common/*.h",
"../../soundlib/*.cpp",
"../../soundlib/*.h",
"../../soundlib/plugins/*.cpp",
"../../soundlib/plugins/*.h",
"../../soundlib/plugins/dmo/*.cpp",
"../../soundlib/plugins/dmo/*.h",
"../../sounddsp/*.cpp",
"../../sounddsp/*.h",
"../../sounddev/*.cpp",
"../../sounddev/*.h",
"../../unarchiver/*.cpp",
"../../unarchiver/*.h",
"../../mptrack/*.cpp",
"../../mptrack/*.h",
"../../test/*.cpp",
"../../test/*.h",
"../../pluginBridge/BridgeCommon.h",
"../../pluginBridge/BridgeWrapper.cpp",
"../../pluginBridge/BridgeWrapper.h",
"../../plugins/MidiInOut/*.cpp",
"../../plugins/MidiInOut/*.h",
}
files {
"../../mptrack/mptrack.rc",
"../../mptrack/res/*.*", -- resource data files
}
excludes {
"../../mptrack/res/rt_manif.bin", -- the old build system manifest
}
pchheader "stdafx.h"
pchsource "../../common/stdafx.cpp"
defines { "MODPLUG_TRACKER" }
exceptionhandling "SEH"
defines { "MPT_EXCEPTIONS_SEH" }
largeaddressaware ( true )
characterset "MBCS"
flags { "MFC", "ExtraWarnings", "WinMain" }
links {
"UnRAR",
"zlib",
"minizip",
"smbPitchShift",
"lhasa",
"flac",
"ogg",
"opus",
"opusfile",
"portaudio",
"portmidi",
"r8brain",
"soundtouch",
"vorbis",
}
linkoptions {
"/DELAYLOAD:uxtheme.dll",
}
filter { "configurations:*Shared" }
filter { "not configurations:*Shared" }
linkoptions {
"/DELAYLOAD:OpenMPT_SoundTouch_f32.dll",
}
targetname "mptrack"
filter {}
filter { "not action:vs2008" }
linkoptions {
"/DELAYLOAD:mf.dll",
"/DELAYLOAD:mfplat.dll",
"/DELAYLOAD:mfreadwrite.dll",
-- "/DELAYLOAD:mfuuid.dll", -- static library
"/DELAYLOAD:propsys.dll",
}
filter {}
prebuildcommands { "..\\..\\build\\svn_version\\update_svn_version_vs_premake.cmd $(IntDir)" }
| bsd-3-clause |
geanux/darkstar | scripts/globals/mobskills/Necropurge.lua | 43 | 1080 | ---------------------------------------------
-- Necropurge
--
---------------------------------------------
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 == 1839) then
return 0;
else
return 1;
end
end
if(mob:getFamily() == 91) then
local mobSkin = mob:getModelId();
if (mobSkin == 1840) then
return 0;
else
return 1;
end
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 10;
local dmgmod = 2;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded);
MobStatusEffectMove(mob, target, EFFECT_CURSE_I, 1, 0, 60);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
geanux/darkstar | scripts/zones/Sauromugue_Champaign/npcs/Cavernous_Maw.lua | 16 | 2985 | -----------------------------------
-- Area: Sauromugue Champaign
-- NPC: Cavernous Maw
-- Teleports Players to Sauromugue_Champaign_S
-- @pos 369 8 -227 120
-----------------------------------
package.loaded["scripts/zones/Sauromugue_Champaign/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/teleports");
require("scripts/globals/missions");
require("scripts/globals/campaign");
require("scripts/zones/Sauromugue_Champaign/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (ENABLE_WOTG == 1 and player:hasKeyItem(PURE_WHITE_FEATHER) == false) then
player:startEvent(500,2);
elseif (ENABLE_WOTG == 1 and hasMawActivated(player,2)) then
if (player:getCurrentMission(WOTG) == BACK_TO_THE_BEGINNING and
(player:getQuestStatus(CRYSTAL_WAR, CLAWS_OF_THE_GRIFFON) == QUEST_COMPLETED or
player:getQuestStatus(CRYSTAL_WAR, THE_TIGRESS_STRIKES) == QUEST_COMPLETED or
player:getQuestStatus(CRYSTAL_WAR, FIRES_OF_DISCONTENT) == QUEST_COMPLETED)) then
player:startEvent(501);
else
player:startEvent(904);
end
else
player:messageSpecial(NOTHING_HAPPENS);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID:",csid);
-- printf("RESULT:",option);
if (csid == 500) then
local r = math.random(1,3);
player:addKeyItem(PURE_WHITE_FEATHER);
player:messageSpecial(KEYITEM_OBTAINED,PURE_WHITE_FEATHER);
player:completeMission(WOTG,CAVERNOUS_MAWS);
player:addMission(WOTG,BACK_TO_THE_BEGINNING);
if (r == 1) then
player:addNationTeleport(MAW,1);
toMaw(player,1); -- go to Batallia_Downs[S]
elseif (r == 2) then
player:addNationTeleport(MAW,2);
toMaw(player,3); -- go to Rolanberry_Fields_[S]
elseif (r == 3) then
player:addNationTeleport(MAW,4);
toMaw(player,5); -- go to Sauromugue_Champaign_[S]
end;
elseif (csid == 904 and option == 1) then
toMaw(player,5); -- go to Sauromugue_Champaign_[S]
elseif (csid == 501) then
player:completeMission(WOTG, BACK_TO_THE_BEGINNING);
player:addMission(WOTG, CAIT_SITH);
player:addTitle(CAIT_SITHS_ASSISTANT);
toMaw(player,5);
end;
end; | gpl-3.0 |
evilexecutable/ResourceKeeper | install/Lua/share/lua/5.1/socket/http.lua | 45 | 12330 | -----------------------------------------------------------------------------
-- HTTP/1.1 client support for the Lua language.
-- LuaSocket toolkit.
-- Author: Diego Nehab
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-------------------------------------------------------------------------------
local socket = require("socket")
local url = require("socket.url")
local ltn12 = require("ltn12")
local mime = require("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 | gpl-2.0 |
knyghtmare/The_Legend_Begins | lua/gui.lua | 1 | 1818 | --#textdomain wesnoth-The_Legend_Begins
_ = wesnoth.textdomain "wesnoth-The_Legend_Begins"
wlib = wesnoth.textdomain "wesnoth-lib"
helper = wesnoth.require "lua/helper.lua"
T = helper.set_wml_tag_metatable {}
function wesnoth.wml_actions.character_descriptions_prompt(cfg)
local main_window = {
maximum_height = 400,
maximum_width = 500,
T.helptip { id="tooltip_large" }, -- mandatory field
T.tooltip { id="tooltip_large" }, -- mandatory field
T.grid {
T.row {
T.column {
horizontal_alignment = "left",
grow_factor = 1,
border = "all",
border_size = 5,
T.label {
definition = "title",
label = _"Character Descriptions"
}
}
},
T.row {
T.column {
horizontal_alignment = "left",
border = "all",
border_size = 5,
T.scroll_label {
label = _"Do you wish to see brief descriptions of the characters when you select them on the map for the first time?"
}
}
},
T.row {
T.column {
T.spacer { height = 10 }
}
},
T.row {
grow_factor = 1,
T.column {
horizontal_alignment = "right",
T.grid {
T.row {
T.column {
border = "all",
border_size = 5,
horizontal_alignment = "right",
T.button {
id = "yes_button",
return_value = 1,
label = wlib "Yes"
}
},
T.column {
border = "all",
border_size = 5,
horizontal_alignment = "right",
T.button {
id = "no_button",
return_value = 2,
label = wlib "No"
}
}
}
}
}
}
}
}
-- 1 on Yes, -1 on [Enter], 2 on No, -2 on [Escape].
local result = math.abs(wesnoth.show_dialog(main_window))
wesnoth.set_variable("character_1st_time_help", (result == 1))
end
| gpl-2.0 |
geanux/darkstar | scripts/globals/spells/jubaku_ichi.lua | 18 | 1730 | -----------------------------------------
-- Spell: Jubaku: Ichi
-- Spell accuracy is most highly affected by Enfeebling Magic Skill, Magic Accuracy, and INT.
-- taken from paralyze
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local effect = EFFECT_PARALYSIS;
-- Base Stats
local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT));
--Duration Calculation
local duration = 180 * applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0);
--Paralyze base power is 20 and is not affected by resistaces.
local power = 20;
--Calculates resist chanve from Reist Blind
if (math.random(0,100) >= target:getMod(MOD_PARALYZERES)) then
if (duration >= 80) then
-- Erases a weaker blind and applies the stronger one
local paralysis = target:getStatusEffect(effect);
if (paralysis ~= nil) then
if (paralysis:getPower() < power) then
target:delStatusEffect(effect);
target:addStatusEffect(effect,power,0,duration);
spell:setMsg(237);
else
-- no effect
spell:setMsg(75);
end
else
target:addStatusEffect(effect,power,0,duration);
spell:setMsg(237);
end
else
spell:setMsg(85);
end
else
spell:setMsg(284);
end
return effect;
end; | gpl-3.0 |
mohammad43/MOHAMMAD | plugins/all.lua | 264 | 4202 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'chat stats! \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
if not data[tostring(target)] then
return 'Group is not added.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group \n \n"
local settings = show_group_settings(target)
text = text.."Group settings \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\n"..modlist
local link = get_link(target)
text = text.."\n\n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] and msg.to.id ~= our_id then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
return
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end | gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.