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 |
|---|---|---|---|---|---|
romanchyla/nodemcu-firmware | lua_examples/ucglib/GT_text.lua | 30 | 1039 | local M, module = {}, ...
_G[module] = M
function M.run()
-- make this a volatile module:
package.loaded[module] = nil
print("Running component text...")
local x, y, w, h, i
local m
disp:setColor(0, 80, 40, 0)
disp:setColor(1, 60, 0, 40)
disp:setColor(2, 20, 0, 20)
disp:setColor(3, 60, 0, 0)
disp:drawGradientBox(0, 0, disp:getWidth(), disp:getHeight())
disp:setColor(255, 255, 255)
disp:setPrintPos(2,18)
disp:setPrintDir(0)
disp:print("Text")
m = millis() + T
i = 0
while millis() < m do
disp:setColor(bit.band(lcg_rnd(), 31), bit.band(lcg_rnd(), 127) + 127, bit.band(lcg_rnd(), 127) + 64)
w = 40
h = 22
x = bit.rshift(lcg_rnd() * (disp:getWidth() - w), 8)
y = bit.rshift(lcg_rnd() * (disp:getHeight() - h), 8)
disp:setPrintPos(x, y+h)
disp:setPrintDir(bit.band(bit.rshift(i, 2), 3))
i = i + 1
disp:print("Ucglib")
end
disp:setPrintDir(0)
print("...done")
end
return M
| mit |
cyanskies/OpenRA | mods/ra/maps/fort-lonestar/fort-lonestar.lua | 6 | 7406 |
SovietEntryPoints = { Entry1, Entry2, Entry3, Entry4, Entry5, Entry6, Entry7, Entry8 }
PatrolWaypoints = { Entry2, Entry4, Entry6, Entry8 }
ParadropWaypoints = { Paradrop1, Paradrop2, Paradrop3, Paradrop4 }
SpawnPoints = { Spawn1, Spawn2, Spawn3, Spawn4 }
Snipers = { Sniper1, Sniper2, Sniper3, Sniper4, Sniper5, Sniper6, Sniper7, Sniper8, Sniper9, Sniper10, Sniper11, Sniper12 }
Walls =
{
{ WallTopRight1, WallTopRight2, WallTopRight3, WallTopRight4, WallTopRight5, WallTopRight6, WallTopRight7, WallTopRight8, WallTopRight9 },
{ WallTopLeft1, WallTopLeft2, WallTopLeft3, WallTopLeft4, WallTopLeft5, WallTopLeft6, WallTopLeft7, WallTopLeft8, WallTopLeft9 },
{ WallBottomLeft1, WallBottomLeft2, WallBottomLeft3, WallBottomLeft4, WallBottomLeft5, WallBottomLeft6, WallBottomLeft7, WallBottomLeft8, WallBottomLeft9 },
{ WallBottomRight1, WallBottomRight2, WallBottomRight3, WallBottomRight4, WallBottomRight5, WallBottomRight6, WallBottomRight7, WallBottomRight8, WallBottomRight9 }
}
if Map.LobbyOption("difficulty") == "veryeasy" then
ParaChance = 20
Patrol = { "e1", "e2", "e1" }
Infantry = { "e4", "e1", "e1", "e2", "e2" }
Vehicles = { "apc" }
Tank = { "3tnk" }
LongRange = { "arty" }
Boss = { "v2rl" }
Swarm = { "shok", "shok", "shok" }
elseif Map.LobbyOption("difficulty") == "easy" then
ParaChance = 25
Patrol = { "e1", "e2", "e1" }
Infantry = { "e4", "e1", "e1", "e2", "e1", "e2", "e1" }
Vehicles = { "ftrk", "apc", "arty" }
Tank = { "3tnk" }
LongRange = { "v2rl" }
Boss = { "4tnk" }
Swarm = { "shok", "shok", "shok", "shok", "ttnk" }
elseif Map.LobbyOption("difficulty") == "normal" then
ParaChance = 30
Patrol = { "e1", "e2", "e1", "e1" }
Infantry = { "e4", "e1", "e1", "e2", "e1", "e2", "e1" }
Vehicles = { "ftrk", "ftrk", "apc", "arty" }
Tank = { "3tnk" }
LongRange = { "v2rl" }
Boss = { "4tnk" }
Swarm = { "shok", "shok", "shok", "shok", "ttnk", "ttnk", "ttnk" }
elseif Map.LobbyOption("difficulty") == "hard" then
ParaChance = 35
Patrol = { "e1", "e2", "e1", "e1", "e4" }
Infantry = { "e4", "e1", "e1", "e2", "e1", "e2", "e1" }
Vehicles = { "arty", "ftrk", "ftrk", "apc", "apc" }
Tank = { "3tnk" }
LongRange = { "v2rl" }
Boss = { "4tnk" }
Swarm = { "shok", "shok", "shok", "shok", "shok", "ttnk", "ttnk", "ttnk", "ttnk" }
else
ParaChance = 40
Patrol = { "e1", "e2", "e1", "e1", "e4", "e4" }
Infantry = { "e4", "e1", "e1", "e2", "e1", "e2", "e1", "e1" }
Vehicles = { "arty", "arty", "ftrk", "apc", "apc" }
Tank = { "ftrk", "3tnk" }
LongRange = { "v2rl" }
Boss = { "4tnk" }
Swarm = { "shok", "shok", "shok", "shok", "shok", "shok", "ttnk", "ttnk", "ttnk", "ttnk", "ttnk" }
end
Wave = 0
Waves =
{
{ delay = 500, units = { Infantry } },
{ delay = 500, units = { Patrol, Patrol } },
{ delay = 700, units = { Infantry, Infantry, Vehicles }, },
{ delay = 1500, units = { Infantry, Infantry, Infantry, Infantry } },
{ delay = 1500, units = { Infantry, Infantry, Patrol, Vehicles } },
{ delay = 1500, units = { Infantry, Infantry, Patrol, Infantry, Tank, Vehicles } },
{ delay = 1500, units = { Infantry, Infantry, Patrol, Infantry, Tank, Tank, Swarm } },
{ delay = 1500, units = { Infantry, Infantry, Patrol, Infantry, Infantry, Infantry, LongRange } },
{ delay = 1500, units = { Infantry, Infantry, Patrol, Infantry, Infantry, Infantry, Infantry, LongRange, Tank, LongRange } },
{ delay = 1500, units = { Infantry, Infantry, Patrol, Infantry, Infantry, Infantry, Infantry, Infantry, LongRange, LongRange, Tank, Tank, Vehicles } },
{ delay = 1500, units = { Infantry, Infantry, Patrol, Infantry, Infantry, Infantry, Infantry, Infantry, Infantry, Boss, Swarm } }
}
-- Now do some adjustments to the waves
if Map.LobbyOption("difficulty") == "tough" or Map.LobbyOption("difficulty") == "endless" then
Waves[8] = { delay = 1500, units = { Infantry, Infantry, Patrol, Infantry, Infantry, Infantry }, ironUnits = { LongRange } }
Waves[9] = { delay = 1500, units = { Infantry, Infantry, Patrol, Infantry, Infantry, Infantry, Infantry, Infantry, LongRange, LongRange, Vehicles, Tank }, ironUnits = { Tank } }
Waves[11] = { delay = 1500, units = { Vehicles, Infantry, Patrol, Patrol, Patrol, Infantry, LongRange, Tank, Boss, Infantry, Infantry, Patrol } }
end
SendUnits = function(entryCell, unitTypes, targetCell, extraData)
Reinforcements.Reinforce(soviets, unitTypes, { entryCell }, 40, function(a)
if not a.HasProperty("AttackMove") then
Trigger.OnIdle(a, function(a)
a.Move(targetCell)
end)
return
end
a.AttackMove(targetCell)
Trigger.OnIdle(a, function(a)
a.Hunt()
end)
if extraData == "IronCurtain" then
a.GrantTimedUpgrade("invulnerability", DateTime.Seconds(25))
end
end)
end
SendWave = function()
Wave = Wave + 1
local wave = Waves[Wave]
Trigger.AfterDelay(wave.delay, function()
Utils.Do(wave.units, function(units)
local entry = Utils.Random(SovietEntryPoints).Location
local target = Utils.Random(SpawnPoints).Location
SendUnits(entry, units, target)
end)
if wave.ironUnits then
Utils.Do(wave.ironUnits, function(units)
local entry = Utils.Random(SovietEntryPoints).Location
local target = Utils.Random(SpawnPoints).Location
SendUnits(entry, units, target, "IronCurtain")
end)
end
Utils.Do(players, function(player)
Media.PlaySpeechNotification(player, "EnemyUnitsApproaching")
end)
if (Wave < #Waves) then
if Utils.RandomInteger(1, 100) < ParaChance then
local units = ParaProxy.SendParatroopers(Utils.Random(ParadropWaypoints).CenterPosition)
Utils.Do(units, function(unit)
Trigger.OnIdle(unit, function(a)
if a.IsInWorld then
a.Hunt()
end
end)
end)
local delay = Utils.RandomInteger(DateTime.Seconds(20), DateTime.Seconds(45))
Trigger.AfterDelay(delay, SendWave)
else
SendWave()
end
else
if Map.LobbyOption("difficulty") == "endless" then
Wave = 0
IncreaseDifficulty()
SendWave()
return
end
Trigger.AfterDelay(DateTime.Minutes(1), SovietsRetreating)
Media.DisplayMessage("You almost survived the onslaught! No more waves incoming.")
end
end)
end
SovietsRetreating = function()
Utils.Do(Snipers, function(a)
if not a.IsDead and a.Owner == soviets then
a.Destroy()
end
end)
end
IncreaseDifficulty = function()
local additions = { Infantry, Patrol, Vehicles, Tank, LongRange, Boss, Swarm }
Utils.Do(Waves, function(wave)
wave.units[#wave.units + 1] = Utils.Random(additions)
end)
end
Tick = function()
if (Utils.RandomInteger(1, 200) == 10) then
local delay = Utils.RandomInteger(1, 10)
Lighting.Flash("LightningStrike", delay)
Trigger.AfterDelay(delay, function()
Media.PlaySound("thunder" .. Utils.RandomInteger(1,6) .. ".aud")
end)
end
if (Utils.RandomInteger(1, 200) == 10) then
Media.PlaySound("thunder-ambient.aud")
end
end
SetupWallOwners = function()
Utils.Do(players, function(player)
Utils.Do(Walls[player.Spawn], function(wall)
wall.Owner = player
end)
end)
end
WorldLoaded = function()
soviets = Player.GetPlayer("Soviets")
players = { }
for i = 0, 4 do
local player = Player.GetPlayer("Multi" ..i)
players[i] = player
if players[i] and players[i].IsBot then
ActivateAI(players[i], i)
end
end
Media.DisplayMessage("Defend Fort Lonestar at all costs!")
SetupWallOwners()
ParaProxy = Actor.Create("powerproxy.paratroopers", false, { Owner = soviets })
SendWave()
end
| gpl-3.0 |
skigs/EFCoreExtend | src/EFCoreExtend.Test/Datas/Lua/Global/PersonGlobalEx.lua | 1 | 1041 |
cfg.table("PersonEx", function(tb)
tb.layout = "TestExLayout"; --设置布局页(分部页),就是会继承TestLayout下的配置(包括策略配置),如果相同配置的会覆盖布局页配置的
tb.spolis.Add1 = {};
tb.spolis.Add1.clear = {
isUse = false, --不使用缓存清理策略
};
tb.sqls.Get = function ()
return "select * from Person where name=@name";
end
tb.sqls.Count = function ()
return "select count(*) from Person where name=@name";
end
tb.sqls.Add = function ()
--insname在全局文件中配置了
return insname .. " Person(name, birthday, addrid) values(@name, @birthday, @addrid)";
end
tb.sqls.Add1 = function ()
--insname在全局文件中配置了
return insname .. " Person(name, birthday, addrid) values(@name, @birthday, @addrid)";
end
tb.sqls.Update = function ()
return "update Person set addrid=@addrid where name=@name"
end
tb.sqls.Delete = function ()
--delname在全局文件中配置了
return delname .. " Person where name=@name"
end
end);
| apache-2.0 |
meirfaraj/tiproject | finance/src/std/str.lua | 1 | 5469 | --------------------------------------------------------------------------
-- String utils --
--------------------------------------------------------------------------
function utf8(n)
return string.uchar(n)
end
function Utf8to32(utf8str)
assert(type(utf8str) == "string")
local res, seq, val = {}, 0, nil
for i = 1, #utf8str do
local c = string.byte(utf8str, i)
if seq == 0 then
table.insert(res, val)
seq = c < 0x80 and 1 or c < 0xE0 and 2 or c < 0xF0 and 3 or
c < 0xF8 and 4 or c < 0xFC and 5 or c < 0xFE and 6 or
error("invalid UTF-8 character sequence")
val = bit.band(c, 2^(8-seq) - 1)
else
val = bit.bor(bit.lshift(val, 6), bit.band(c, 0x3F))
end
seq = seq - 1
end
table.insert(res, val)
table.insert(res, 0)
return res
end
SubNumbers={185, 178, 179, 8308, 8309, 8310, 8311, 8312, 8313}
function numberToSub(w,n)
return w..utf8(SubNumbers[tonumber(n)])
end
function string.fromhex(str)
return (str:gsub('..', function (cc)
return string.char(tonumber(cc, 16))
end))
end
function string.bintohex(str)
return (str:gsub('.', function (c)
return string.format('%02X', string.byte(c))
end))
end
function string.tohex(num)
return string.format('%02X', num)
end
function string.simplify(str)
local simplified = str
if simplified:match ("\".*\"") then
simplified=simplified:sub(2,simplified:len()-1)
print("["..str.."] simplified has ["..simplified.."]")
end
return simplified
end
-- ABNF from RFC 3629
--
-- UTF8-octets = *( UTF8-char )
-- UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
-- UTF8-1 = %x00-7F
-- UTF8-2 = %xC2-DF UTF8-tail
-- UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
-- %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
-- UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
-- %xF4 %x80-8F 2( UTF8-tail )
-- UTF8-tail = %x80-BF
--
-- returns the number of bytes used by the UTF-8 character at byte i in s
-- also doubles as a UTF-8 character validator
local UTF8 = {}
function UTF8.charbytes (s, i)
-- argument defaults
i = i or 1
local c = string.byte(s, i)
-- determine bytes needed for character, based on RFC 3629
if c > 0 and c <= 127 then
-- UTF8-1
return 1
elseif c >= 194 and c <= 223 then
-- UTF8-2
local c2 = string.byte(s, i + 1)
return 2
elseif c >= 224 and c <= 239 then
-- UTF8-3
local c2 = s:byte(i + 1)
local c3 = s:byte(i + 2)
return 3
elseif c >= 240 and c <= 244 then
-- UTF8-4
local c2 = s:byte(i + 1)
local c3 = s:byte(i + 2)
local c4 = s:byte(i + 3)
return 4
end
end
-- returns the number of characters in a UTF-8 string
function UTF8.len (s)
local pos = 1
local bytes = string.len(s)
local len = 0
while pos <= bytes and len ~= chars do
local c = string.byte(s,pos)
len = len + 1
pos = pos + UTF8.charbytes(s, pos)
end
if chars ~= nil then
return pos - 1
end
return len
end
-- pretty printed square root characters from MathBoxes take two 'special' characters in returned expression string
-- cursor position in expression returned by getExpression() then does not match cursor position in string after the square root
function ulen(str)
local n = string.len(str)
local i = 1
local j = 1
local c
while(j<=n) do
c = string.len(string.usub(str,i,i))
j = j+c
i = i+1
end
return i-1
end
-- functions identically to string.sub except that i and j are UTF-8 characters
-- instead of bytes
function UTF8.sub (s, i, j)
j = j or -1
if i == nil then
return ""
end
local pos = 1
local bytes = string.len(s)
local len = 0
-- only set l if i or j is negative
local l = (i >= 0 and j >= 0) or UTF8.len(s)
local startChar = (i >= 0) and i or l + i + 1
local endChar = (j >= 0) and j or l + j + 1
-- can't have start before end!
if startChar > endChar then
return ""
end
-- byte offsets to pass to string.sub
local startByte, endByte = 1, bytes
while pos <= bytes do
len = len + 1
if len == startChar then
startByte = pos
end
pos = pos + UTF8.charbytes(s, pos)
if len == endChar then
endByte = pos - 1
break
end
end
return string.sub(s, startByte, endByte)
end
function string.isempty(s)
return s == nil or s == ''
end
-- replace UTF-8 characters based match
function UTF8.replaceAll (s, charToReplace,byChar)
local pos = 1
local bytes = string.len(s)
local charbytes
local newstr = ""
while pos <= bytes do
charbytes = UTF8.charbytes(s, pos)
local c = string.sub(s, pos, pos + charbytes - 1)
if charToReplace==c then
newstr = newstr .. byChar
else
newstr = newstr .. c
end
pos = pos + charbytes
end
return newstr
end
-- replace UTF-8 characters based on a mapping table
function UTF8.replace (s, mapping)
local pos = 1
local bytes = string.len(s)
local charbytes
local newstr = ""
while pos <= bytes do
charbytes = UTF8.charbytes(s, pos)
local c = string.sub(s, pos, pos + charbytes - 1)
newstr = newstr .. (mapping[c] or c)
pos = pos + charbytes
end
return newstr
end
| apache-2.0 |
sloong/sloongnet | src/modules/middleLayer/lua/scripts/ex.lua | 1 | 1061 | local Ex_Req = {};
Ex_Req.GetFileData = function( u, req, res )
local md5 = req['MD5'] or nil;
local h = tonumber(req['height']) or nil
local w = tonumber(req['width']) or nil
local q = tonumber(req['quality']) or 5
if not md5 or not h or not w then
return -1,'param error';
end
local cmd = "SELECT `Path` FROM `Walls_FileList` WHERE `MD5`='" .. md5 .. "'"
showLog("run sql cmd:" .. cmd);
local res = querySql(cmd);
showLog(res);
local thumbpath = Sloongnet_GetThumbImage(res,w,h,q)
local errno,errmsg=Sloongnet_SendFile(thumbpath);
if errno == -1 then
return errno,errmsg;
else
return 0,thumbpath,errno;
end
end
Ex_Req.SetUInfo = function( u, req, res )
local key = req['key'];
local value = req['value'];
u:setdata(key,value);
return 0, 'set ' .. key .. ' to ' .. value;
end
Ex_Req.GetUInfo = function( u, req, res )
local key = req['key']
return 0,u:getdata(key) or 'nil';
end
g_ex_function =
{
['GetFile'] = Ex_Req.GetFileData,
['SetUInfo'] = Ex_Req.SetUInfo,
['GetUInfo'] = Ex_Req.GetUInfo,
}
AddModule(g_ex_function);
| mit |
vipteam1/VIP_TEAM_EN11 | plugins/rebot.lua | 4 | 1251 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Team name : ( 🌐 VIP_TEAM 🌐 )▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ File name : ( الرد التلقائي ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Guenat team: ( @VIP_TEAM1 ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄
—]]
do
local function run(msg, matches)
if ( msg.text ) then
if ( msg.to.type == "user" ) then
return [[
اهلا بكم في سورس 🔹VIP🔺TEAM🔹
🎗للتحدث مع المطورين راسل احدهم🎗
🎗 1. @XxX_TEAM_XxX
🎗2. @i_d_b
🎗3. @lIlDevlIl
🎗4. @A_6_Q
🎗5. @mustafa_dev
▫️➖▫️➖▫️➖▫️➖▫️➖▫️
تابع قناة السورس لتطوير بوتك @VIP_TEAm1
]]
end
end
end
return {
patterns = {
"(.*)$"
},
run = run
}
end | gpl-2.0 |
Shell64/LuaWebserver2 | Bin/Windows_x64/socket/socket/http.lua | 121 | 12193 | -----------------------------------------------------------------------------
-- HTTP/1.1 client support for the Lua language.
-- LuaSocket toolkit.
-- Author: Diego Nehab
-- RCS ID: $Id: http.lua,v 1.71 2007/10/13 23:55:20 diego Exp $
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- 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 base = _G
local table = require("table")
module("socket.http")
-----------------------------------------------------------------------------
-- Program constants
-----------------------------------------------------------------------------
-- connection timeout in seconds
TIMEOUT = 60
-- default port for document retrieval
PORT = 80
-- user agent field sent in request
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 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(TIMEOUT))
h.try(c:connect(host, port or 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(headers)
local h = "\r\n"
for i, v in base.pairs(headers) do
h = i .. ": " .. 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"] = 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 = 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) 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
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
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 = 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
request = socket.protect(function(reqt, body)
if base.type(reqt) == "string" then return srequest(reqt, body)
else return trequest(reqt) end
end)
| lgpl-2.1 |
romanchyla/nodemcu-firmware | app/cjson/lua/cjson/util.lua | 170 | 6837 | local json = require "cjson"
-- Various common routines used by the Lua CJSON package
--
-- Mark Pulford <mark@kyne.com.au>
-- Determine with a Lua table can be treated as an array.
-- Explicitly returns "not an array" for very sparse arrays.
-- Returns:
-- -1 Not an array
-- 0 Empty table
-- >0 Highest index in the array
local function is_array(table)
local max = 0
local count = 0
for k, v in pairs(table) do
if type(k) == "number" then
if k > max then max = k end
count = count + 1
else
return -1
end
end
if max > count * 2 then
return -1
end
return max
end
local serialise_value
local function serialise_table(value, indent, depth)
local spacing, spacing2, indent2
if indent then
spacing = "\n" .. indent
spacing2 = spacing .. " "
indent2 = indent .. " "
else
spacing, spacing2, indent2 = " ", " ", false
end
depth = depth + 1
if depth > 50 then
return "Cannot serialise any further: too many nested tables"
end
local max = is_array(value)
local comma = false
local fragment = { "{" .. spacing2 }
if max > 0 then
-- Serialise array
for i = 1, max do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment, serialise_value(value[i], indent2, depth))
comma = true
end
elseif max < 0 then
-- Serialise table
for k, v in pairs(value) do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment,
("[%s] = %s"):format(serialise_value(k, indent2, depth),
serialise_value(v, indent2, depth)))
comma = true
end
end
table.insert(fragment, spacing .. "}")
return table.concat(fragment)
end
function serialise_value(value, indent, depth)
if indent == nil then indent = "" end
if depth == nil then depth = 0 end
if value == json.null then
return "json.null"
elseif type(value) == "string" then
return ("%q"):format(value)
elseif type(value) == "nil" or type(value) == "number" or
type(value) == "boolean" then
return tostring(value)
elseif type(value) == "table" then
return serialise_table(value, indent, depth)
else
return "\"<" .. type(value) .. ">\""
end
end
local function file_load(filename)
local file
if filename == nil then
file = io.stdin
else
local err
file, err = io.open(filename, "rb")
if file == nil then
error(("Unable to read '%s': %s"):format(filename, err))
end
end
local data = file:read("*a")
if filename ~= nil then
file:close()
end
if data == nil then
error("Failed to read " .. filename)
end
return data
end
local function file_save(filename, data)
local file
if filename == nil then
file = io.stdout
else
local err
file, err = io.open(filename, "wb")
if file == nil then
error(("Unable to write '%s': %s"):format(filename, err))
end
end
file:write(data)
if filename ~= nil then
file:close()
end
end
local function compare_values(val1, val2)
local type1 = type(val1)
local type2 = type(val2)
if type1 ~= type2 then
return false
end
-- Check for NaN
if type1 == "number" and val1 ~= val1 and val2 ~= val2 then
return true
end
if type1 ~= "table" then
return val1 == val2
end
-- check_keys stores all the keys that must be checked in val2
local check_keys = {}
for k, _ in pairs(val1) do
check_keys[k] = true
end
for k, v in pairs(val2) do
if not check_keys[k] then
return false
end
if not compare_values(val1[k], val2[k]) then
return false
end
check_keys[k] = nil
end
for k, _ in pairs(check_keys) do
-- Not the same if any keys from val1 were not found in val2
return false
end
return true
end
local test_count_pass = 0
local test_count_total = 0
local function run_test_summary()
return test_count_pass, test_count_total
end
local function run_test(testname, func, input, should_work, output)
local function status_line(name, status, value)
local statusmap = { [true] = ":success", [false] = ":error" }
if status ~= nil then
name = name .. statusmap[status]
end
print(("[%s] %s"):format(name, serialise_value(value, false)))
end
local result = { pcall(func, unpack(input)) }
local success = table.remove(result, 1)
local correct = false
if success == should_work and compare_values(result, output) then
correct = true
test_count_pass = test_count_pass + 1
end
test_count_total = test_count_total + 1
local teststatus = { [true] = "PASS", [false] = "FAIL" }
print(("==> Test [%d] %s: %s"):format(test_count_total, testname,
teststatus[correct]))
status_line("Input", nil, input)
if not correct then
status_line("Expected", should_work, output)
end
status_line("Received", success, result)
print()
return correct, result
end
local function run_test_group(tests)
local function run_helper(name, func, input)
if type(name) == "string" and #name > 0 then
print("==> " .. name)
end
-- Not a protected call, these functions should never generate errors.
func(unpack(input or {}))
print()
end
for _, v in ipairs(tests) do
-- Run the helper if "should_work" is missing
if v[4] == nil then
run_helper(unpack(v))
else
run_test(unpack(v))
end
end
end
-- Run a Lua script in a separate environment
local function run_script(script, env)
local env = env or {}
local func
-- Use setfenv() if it exists, otherwise assume Lua 5.2 load() exists
if _G.setfenv then
func = loadstring(script)
if func then
setfenv(func, env)
end
else
func = load(script, nil, nil, env)
end
if func == nil then
error("Invalid syntax.")
end
func()
return env
end
-- Export functions
return {
serialise_value = serialise_value,
file_load = file_load,
file_save = file_save,
compare_values = compare_values,
run_test_summary = run_test_summary,
run_test = run_test,
run_test_group = run_test_group,
run_script = run_script
}
-- vi:ai et sw=4 ts=4:
| mit |
tinydanbo/Impoverished-Starfighter | lib/hump/signal.lua | 24 | 2729 | --[[
Copyright (c) 2012-2013 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.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
local Registry = {}
Registry.__index = function(self, key)
return Registry[key] or (function()
local t = {}
rawset(self, key, t)
return t
end)()
end
function Registry:register(s, f)
self[s][f] = f
return f
end
function Registry:emit(s, ...)
for f in pairs(self[s]) do
f(...)
end
end
function Registry:remove(s, ...)
local f = {...}
for i = 1,select('#', ...) do
self[s][f[i]] = nil
end
end
function Registry:clear(...)
local s = {...}
for i = 1,select('#', ...) do
self[s[i]] = {}
end
end
function Registry:emit_pattern(p, ...)
for s in pairs(self) do
if s:match(p) then self:emit(s, ...) end
end
end
function Registry:remove_pattern(p, ...)
for s in pairs(self) do
if s:match(p) then self:remove(s, ...) end
end
end
function Registry:clear_pattern(p)
for s in pairs(self) do
if s:match(p) then self[s] = {} end
end
end
local function new()
return setmetatable({}, Registry)
end
local default = new()
return setmetatable({
new = new,
register = function(...) default:register(...) end,
emit = function(...) default:emit(...) end,
remove = function(...) default:remove(...) end,
clear = function(...) default:clear(...) end,
emit_pattern = function(...) default:emit_pattern(...) end,
remove_pattern = function(...) default:remove_pattern(...) end,
clear_pattern = function(...) default:clear_pattern(...) end,
}, {__call = new})
| mit |
romanchyla/nodemcu-firmware | lua_examples/irsend.lua | 88 | 1803 | ------------------------------------------------------------------------------
-- IR send module
--
-- LICENCE: http://opensource.org/licenses/MIT
-- Vladimir Dronnikov <dronnikov@gmail.com>
--
-- Example:
-- dofile("irsend.lua").nec(4, 0x00ff00ff)
------------------------------------------------------------------------------
local M
do
-- const
local NEC_PULSE_US = 1000000 / 38000
local NEC_HDR_MARK = 9000
local NEC_HDR_SPACE = 4500
local NEC_BIT_MARK = 560
local NEC_ONE_SPACE = 1600
local NEC_ZERO_SPACE = 560
local NEC_RPT_SPACE = 2250
-- cache
local gpio, bit = gpio, bit
local mode, write = gpio.mode, gpio.write
local waitus = tmr.delay
local isset = bit.isset
-- NB: poorman 38kHz PWM with 1/3 duty. Touch with care! )
local carrier = function(pin, c)
c = c / NEC_PULSE_US
while c > 0 do
write(pin, 1)
write(pin, 0)
c = c + 0
c = c + 0
c = c + 0
c = c + 0
c = c + 0
c = c + 0
c = c * 1
c = c * 1
c = c * 1
c = c - 1
end
end
-- tsop signal simulator
local pull = function(pin, c)
write(pin, 0)
waitus(c)
write(pin, 1)
end
-- NB: tsop mode allows to directly connect pin
-- inplace of TSOP input
local nec = function(pin, code, tsop)
local pulse = tsop and pull or carrier
-- setup transmitter
mode(pin, 1)
write(pin, tsop and 1 or 0)
-- header
pulse(pin, NEC_HDR_MARK)
waitus(NEC_HDR_SPACE)
-- sequence, lsb first
for i = 31, 0, -1 do
pulse(pin, NEC_BIT_MARK)
waitus(isset(code, i) and NEC_ONE_SPACE or NEC_ZERO_SPACE)
end
-- trailer
pulse(pin, NEC_BIT_MARK)
-- done transmitter
--mode(pin, 0, tsop and 1 or 0)
end
-- expose
M = {
nec = nec,
}
end
return M
| mit |
luanorlandi/Swift-Space-Battle | src/interface/game/lives.lua | 2 | 1128 | local lifeIconSize = Vector:new(30 * window.scale, 30 * window.scale)
local lifeIcon = MOAIGfxQuad2D.new()
lifeIcon:setTexture("texture/ship/ship5life.png")
lifeIcon:setRect(-lifeIconSize.x, -lifeIconSize.y, lifeIconSize.x, lifeIconSize.y)
Lives = {}
Lives.__index = Lives
function Lives:new(qty)
local L = {}
setmetatable(L, Lives)
L.max = qty
L.qty = qty
L.icon = {}
for i = 1, qty, 1 do
local sprite = MOAIProp2D.new()
changePriority(sprite, "interface")
sprite:setDeck(lifeIcon)
sprite:setLoc(iconLifePos(i))
window.layer:insertProp(sprite)
table.insert(L.icon, sprite)
end
return L
end
function Lives:decrease()
if #self.icon > 0 then
window.layer:removeProp(self.icon[#self.icon])
table.remove(self.icon, #self.icon)
self.qty = self.qty - 1
end
end
function iconLifePos(n)
-- fin position 'n' that the icon will stay
local d = (window.width / 2) / 5 -- distance between icons
return (window.width / 2) - (n * d), -(window.height / 2) + d
end
function Lives:clear()
for i = 1, #self.icon, 1 do
window.layer:removeProp(self.icon[1])
table.remove(self.icon, 1)
end
end | gpl-3.0 |
Zefiros-Software/ZPM | test/src/common/testEnv.lua | 1 | 2120 | --[[ @cond ___LICENSE___
-- Copyright (c) 2017 Zefiros Software.
--
-- 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.
--
-- @endcond
--]]
function Test:testEnv_scriptPath()
u.assertNotNil(zpm.env.getScriptPath())
u.assertStrContains(zpm.env.getScriptPath(), "src")
end
function Test:testEnv_getCacheDirectory()
local dir = zpm.env.getCacheDirectory()
u.assertNotNil(dir)
u.assertStrContains(dir, "zpm")
end
function Test:testEnv_getCacheDirectory_SetENV()
local mock = os.getenv
os.getenv = function() return "foo" end
local dir = zpm.env.getCacheDirectory()
u.assertNotNil(dir)
u.assertEquals(dir, "foo")
os.getenv = mock
end
function Test:testEnv_getDataDirectory()
local dir = zpm.env.getDataDirectory()
u.assertNotNil(dir)
u.assertStrContains(dir, "zpm")
end
function Test:testEnv_getDataDirectory_SetENV()
local mock = os.getenv
os.getenv = function() return "foo2" end
local dir = zpm.env.getDataDirectory()
u.assertNotNil(dir)
u.assertEquals(dir, "foo2")
os.getenv = mock
end | mit |
dan-f/Soundpipe | modules/data/rpt.lua | 1 | 1954 | sptbl["rpt"] = {
files = {
module = "rpt.c",
header = "rpt.h",
example = "ex_rpt.c",
},
func = {
create = "sp_rpt_create",
destroy = "sp_rpt_destroy",
init = "sp_rpt_init",
compute = "sp_rpt_compute",
},
params = {
mandatory = {
{
name = "maxdur",
type = "SPFLOAT",
description = "Maximum delay duration in seconds. This will set the buffer size.",
default = "0.7"
}
},
optional = {
{
name = "bpm",
type = "SPFLOAT",
description = "Beats per minute.",
default = 130
},
{
name = "div",
type = "int",
description = "Division amount of the beat. 1 = quarter, 2 = eight, 4 = sixteenth, 8 = thirty-second, etc. Any whole number integer is acceptable.",
default = 8
},
{
name = "rep",
type = "int",
description = "Number of times to repeat.",
default = 4
},
}
},
modtype = "module",
description = [[Trigger based beat-repeat stuttering effect
When the input is a non-zero value, rpt will load up the buffer and loop a certain number of times. Speed and repeat amounts can be set with the sp_rpt_set function.]],
ninputs = 2,
noutputs = 1,
inputs = {
{
name = "trig",
description = "When this value is non-zero, it will start the repeater."
},
{
name = "input",
description = "The signal to be repeated."
},
},
outputs = {
{
name = "out",
description = "Signal out. This is passive unless explicity triggered in the input."
},
}
}
| mit |
nstockton/mushclient-mume | lua/ee5_base64.lua | 1 | 22398 | --[[**************************************************************************]]
-- base64.lua
-- Copyright 2014 Ernest R. Ewert
--
-- https://github.com/ErnieE5/ee5_base64
-- This Lua module contains the implementation of a Lua base64 encode
-- and decode library.
--
-- The library exposes these methods.
--
-- Method Args
-- ----------- ----------------------------------------------
-- encode String in / out
-- decode String in / out
--
-- encode String, function(value) predicate
-- decode String, function(value) predicate
--
-- encode file, function(value) predicate
-- deocde file, function(value) predicate
--
-- encode file, file
-- deocde file, file
--
-- alpha alphabet, term char
--
--------------------------------------------------------------------------------
-- known_base64_alphabets
--
--
local known_base64_alphabets=
{
base64= -- RFC 2045 (Ignores max line length restrictions)
{
_alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
_strip="[^%a%d%+%/%=]",
_term="="
},
base64noterm= -- RFC 2045 (Ignores max line length restrictions)
{
_alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
_strip="[^%a%d%+%/]",
_term=""
},
base64url= -- RFC 4648 'base64url'
{
_alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
_strip="[^%a%d%+%-%_=]",
_term=""
},
}
local c_alpha=known_base64_alphabets.base64
local pattern_strip
--[[**************************************************************************]]
--[[****************************** Encoding **********************************]]
--[[**************************************************************************]]
-- Precomputed tables (compromise using more memory for speed)
local b64e -- 6 bit patterns to ANSI 'char' values
local b64e_a -- ready to use
local b64e_a2 -- byte addend
local b64e_b1 -- byte addend
local b64e_b2 -- byte addend
local b64e_c1 -- byte addend
local b64e_c -- ready to use
-- Tail padding values
local tail_padd64=
{
"==", -- two bytes modulo
"=" -- one byte modulo
}
--------------------------------------------------------------------------------
-- e64
--
-- Helper function to convert three eight bit values into four encoded
-- 6 (significant) bit values.
--
-- 7 0 7 0 7 0
-- e64(a a a a a a a a,b b b b b b b b,c c c c c c c c)
-- | | | |
-- return [ a a a a a a]| | |
-- [ a a b b b b]| |
-- [ b b b b c c]|
-- [ c c c c c c]
--
local function e64( a, b, c )
-- Return pre-calculated values for encoded value 1 and 4
-- Get the pre-calculated extractions for value 2 and 3, look them
-- up and return the proper value.
--
return b64e_a[a],
b64e[ b64e_a2[a]+b64e_b1[b] ],
b64e[ b64e_b2[b]+b64e_c1[c] ],
b64e_c[c]
end
--------------------------------------------------------------------------------
-- encode_tail64
--
-- Send a tail pad value to the output predicate provided.
--
local function encode_tail64( out, x, y )
-- If we have a number of input bytes that isn't exactly divisible
-- by 3 then we need to pad the tail
if x ~= nil then
local a,b,r = x,0,1
if y ~= nil then
r = 2
b = y
end
-- Encode three bytes of info, with the tail byte as zeros and
-- ignore any fourth encoded ASCII value. (We should NOT have a
-- forth byte at this point.)
local b1, b2, b3 = e64( a, b, 0 )
-- always add the first 2 six bit values to the res table
-- 1 remainder input byte needs 8 output bits
local tail_value = string.char( b1, b2 )
-- two remainder input bytes will need 18 output bits (2 as pad)
if r == 2 then
tail_value=tail_value..string.char( b3 )
end
-- send the last 4 byte sequence with appropriate tail padding
out( tail_value .. tail_padd64[r] )
end
end
--------------------------------------------------------------------------------
-- encode64_io_iterator
--
-- Create an io input iterator to read an input file and split values for
-- proper encoding.
--
local function encode64_io_iterator(file)
assert( io.type(file) == "file", "argument must be readable file handle" )
assert( file.read ~= nil, "argument must be readable file handle" )
local ii = { } -- Table for the input iterator
setmetatable(ii,{ __tostring=function() return "base64.io_iterator" end})
-- Begin returns an input read iterator
--
function ii.begin()
local sb = string.byte
-- The iterator returns three bytes from the file for encoding or nil
-- when the end of the file has been reached.
--
return function()
s = file:read(3)
if s ~= nil and #s == 3 then
return sb(s,1,3)
end
return nil
end
end
-- The tail method on the iterator allows the routines to run faster
-- because each sequence of bytes doesn't have to test for EOF.
--
function ii.tail()
-- If one or two "overflow" bytes exist, return those.
--
if s ~= nil then return s:byte(1,2) end
end
return ii
end
--------------------------------------------------------------------------------
-- encode64_with_ii
--
-- Convert the value provided by an encode iterator that provides a begin
-- method, a tail method, and an iterator that returns three bytes for
-- each call until at the end. The tail method should return either 1 or 2
-- tail bytes (for source values that are not evenly divisible by three).
--
local function encode64_with_ii( ii, out )
local sc=string.char
for a, b, c in ii.begin() do
out( sc( e64( a, b, c ) ) )
end
encode_tail64( out, ii.tail() )
end
--------------------------------------------------------------------------------
-- encode64_with_predicate
--
-- Implements the basic raw data --> base64 conversion. Each three byte
-- sequence in the input string is converted to the encoded string and
-- given to the predicate provided in 4 output byte chunks. This method
-- is slightly faster for traversing existing strings in memory.
--
local function encode64_with_predicate( raw, out )
local rem=#raw%3 -- remainder
local len=#raw-rem -- 3 byte input adjusted
local sb=string.byte -- Mostly notational (slight performance)
local sc=string.char -- Mostly notational (slight performance)
-- Main encode loop converts three input bytes to 4 base64 encoded
-- ACSII values and calls the predicate with the value.
for i=1,len,3 do
-- This really isn't intended as obfuscation. It is more about
-- loop optimization and removing temporaries.
--
out( sc( e64( sb( raw ,i , i+3 ) ) ) )
-- | | |
-- | | byte i to i + 3
-- | |
-- | returns 4 encoded values
-- |
-- creates a string with the 4 returned values
end
-- If we have a number of input bytes that isn't exactly divisible
-- by 3 then we need to pad the tail
if rem > 0 then
local x, y = sb( raw, len+1 )
if rem > 1 then
y = sb( raw, len+2 )
end
encode_tail64( out, x, y )
end
end
--------------------------------------------------------------------------------
-- encode64_tostring
--
-- Convenience method that accepts a string value and returns the
-- encoded version of that string.
--
local function encode64_tostring(raw)
local sb={} -- table to build string
local function collection_predicate(v)
sb[#sb+1]=v
end
-- Test with an 818K string in memory. Result is 1.1M of data.
--
-- lua_base64 base64 (gnu 8.21)
-- 202ms 54ms
-- 203ms 48ms
-- 204ms 50ms
-- 203ms 42ms
-- 205ms 46ms
--
encode64_with_predicate( raw, collection_predicate )
return table.concat(sb)
end
--[[**************************************************************************]]
--[[****************************** Decoding **********************************]]
--[[**************************************************************************]]
-- Precomputed tables (compromise using more memory for speed)
local b64d -- ANSI 'char' to right shifted bit pattern
local b64d_a1 -- byte addend
local b64d_a2 -- byte addend
local b64d_b1 -- byte addend
local b64d_b2 -- byte addend
local b64d_c1 -- byte addend
local b64d_z -- zero
--------------------------------------------------------------------------------
-- d64
--
-- Helper function to convert four six bit values into three full eight
-- bit values. Input values are the integer expression of the six bit value
-- encoded in the original base64 encoded string.
--
-- d64( _ _1 1 1 1 1 1,
-- | _ _ 2 2 2 2 2 2,
-- | | _ _ 3 3 3 3 3 3,
-- | | | _ _ 4 4 4 4 4 4)
-- | | | |
-- return ', [1 1 1 1 1 1 2 2] | |
-- ', [2 2 2 2 3 3 3 3] |
-- ' [3 3 4 4 4 4 4 4]
--
local function d64( b1, b2, b3, b4 )
-- We can get away with addition instead of anding the values together
-- because there are no overlapping bit patterns.
--
return
b64d_a1[b1] + b64d_a2[b2],
b64d_b1[b2] + b64d_b2[b3],
b64d_c1[b3] + b64d[b4]
end
--------------------------------------------------------------------------------
-- decode_tail64
--
-- Send the end of stream bytes that didn't get decoded via the main loop.
--
local function decode_tail64( out, e1, e2 ,e3, e4 )
if tail_padd64[2] == "" or e4 == tail_padd64[2]:byte() then
local n3 = b64d_z
if e3 ~= nil and e3 ~= tail_padd64[2]:byte() then
n3 = e3
end
-- Unpack the six bit values into the 8 bit values
local b1, b2 = d64( e1, e2, n3, b64d_z )
-- And add them to the res table
if e3 ~= nil and e3 ~= tail_padd64[2]:byte() then
out( string.char( b1, b2 ) )
else
out( string.char( b1 ) )
end
end
end
--------------------------------------------------------------------------------
-- decode64_io_iterator
--
-- Create an io input iterator to read an input file and split values for
-- proper decoding.
--
local function decode64_io_iterator( file )
local ii = { }
-- An enumeration coroutine that handles the reading of an input file
-- to break data into proper pieces for building the original string.
--
local function enummerate( file )
local sc=string.char
local sb=string.byte
local ll="" -- last line storage
local len
local yield = coroutine.yield
-- Read a "reasonable amount" of data into the line buffer. Line by
-- line is not used so that a file with no line breaks doesn't
-- cause an inordinate amount of memory usage.
--
for cl in file:lines(2048) do
-- Reset the current line to contain valid chars and any previous
-- "leftover" bytes from the previous read
--
cl = ll .. cl:gsub(pattern_strip,"")
-- | |
-- | Remove "Invalid" chars (white space etc)
-- |
-- Left over from last line
--
len = (#cl-4)-(#cl%4)
-- see the comments in decode64_with_predicate for a rundown of
-- the results of this loop (sans the coroutine)
for i=1,len,4 do
yield( sc( d64( sb( cl, i, i+4 ) ) ) )
end
ll = cl:sub( len +1, #cl )
end
local l = #ll
if l >= 4 and ll:sub(-1) ~= tail_padd64[2] then
yield( sc( d64( sb( ll, 1, 4 ) ) ) )
l=l-4
end
if l > 0 then
local e1,e2,e3,e4 = ll:byte( 0 - l, -1 )
if e1 ~= nil then
decode_tail64( function(s) yield( s ) end, e1, e2, e3, e4 )
end
end
end
-- Returns an input iterator that is implemented as a coroutine. Each
-- yield of the co-routine sends reconstructed bytes to the loop handling
-- the iteration.
--
function ii.begin()
local co = coroutine.create( function() enummerate(file) end )
return function()
local code,res = coroutine.resume(co)
assert(code == true)
return res
end
end
return ii
end
--------------------------------------------------------------------------------
-- decode64_with_ii
--
-- Convert the value provided by a decode iterator that provides a begin
-- method, a tail method, and an iterator that returns four (usable!) bytes
-- for each call until at the end.
--
local function decode64_with_ii( ii, out )
-- Uses the iterator to pull values. Each reconstructed string
-- is sent to the output predicate.
--
for l in ii.begin() do out( l ) end
end
--------------------------------------------------------------------------------
-- decode64_with_predicate
--
-- Decode an entire base64 encoded string in memory using the predicate for
-- output.
--
local function decode64_with_predicate( raw, out )
-- Sanitize the input to strip characters that are not in the alphabet.
--
-- Note: This is a deviation from strict implementations where "bad data"
-- in the input stream is unsupported.
--
local san = raw:gsub(pattern_strip,"")
local len = #san-#san%4
local rem = #san-len
local sc = string.char
local sb = string.byte
if san:sub(-1,-1) == tail_padd64[2] then
rem = rem + 4
len = len - 4
end
for i=1,len,4 do
out( sc( d64( sb( san, i, i+4 ) ) ) )
end
if rem > 0 then
decode_tail64( out, sb( san, 0-rem, -1 ) )
end
end
--------------------------------------------------------------------------------
-- decode64_tostring
--
-- Takes a string that is encoded in base64 and returns the decoded value in
-- a new string.
--
local function decode64_tostring( raw )
local sb={} -- table to build string
local function collection_predicate(v)
sb[#sb+1]=v
end
decode64_with_predicate( raw, collection_predicate )
return table.concat(sb)
end
--------------------------------------------------------------------------------
-- set_and_get_alphabet
--
-- Sets and returns the encode / decode alphabet.
--
--
local function set_and_get_alphabet(alpha,term)
if alpha ~= nil then
local magic=
{
-- ["%"]="%%",
[" "]="% ",
["^"]="%^",
["$"]="%$",
["("]="%(",
[")"]="%)",
["."]="%.",
["["]="%[",
["]"]="%]",
["*"]="%*",
["+"]="%+",
["-"]="%-",
["?"]="%?",
}
c_alpha=known_base64_alphabets[alpha]
if c_alpha == nil then
c_alpha={ _alpha=alpha, _term=term }
end
assert( #c_alpha._alpha == 64, "The alphabet ~must~ be 64 unique values." )
assert( #c_alpha._term <= 1, "Specify zero or one termination character.")
b64d={} -- Decode table alpha -> right shifted int values
b64e={} -- Encode table 0-63 (6 bits) -> char table
local s=""
for i = 1,64 do
local byte = c_alpha._alpha:byte(i)
local str = string.char(byte)
b64e[i-1]=byte
assert( b64d[byte] == nil, "Duplicate value '"..str.."'" )
b64d[byte]=i-1
s=s..str
end
local ext --Alias for extraction routine that avoids extra table lookups
if bit32 then
ext = bit32.extract -- slight speed, vast visual (IMO)
elseif bit then
local band = bit.band
local rshift = bit.rshift
ext =
function(n, field, width)
width = width or 1
return band(rshift(n, field), 2^width-1)
end
else
error("Neither Lua 5.2 bit32 nor LuaJit bit library found!")
end
-- preload encode lookup tables
b64e_a = {}
b64e_a2 = {}
b64e_b1 = {}
b64e_b2 = {}
b64e_c1 = {}
b64e_c = {}
for f = 0,255 do
b64e_a [f]=b64e[ext(f,2,6)]
b64e_a2 [f]=ext(f,0,2)*16
b64e_b1 [f]=ext(f,4,4)
b64e_b2 [f]=ext(f,0,4)*4
b64e_c1 [f]=ext(f,6,2)
b64e_c [f]=b64e[ext(f,0,6)]
end
-- preload decode lookup tables
b64d_a1 = {}
b64d_a2 = {}
b64d_b1 = {}
b64d_b2 = {}
b64d_c1 = {}
b64d_z = b64e[0]
for k,v in pairs(b64d) do
-- Each comment shows the rough C expression that would be used to
-- generate the returned triple.
--
b64d_a1 [k] = v*4 -- ([b1] ) << 2
b64d_a2 [k] = math.floor( v / 16 ) -- ([b2] & 0x30) >> 4
b64d_b1 [k] = ext( v, 0, 4 ) * 16 -- ([b2] & 0x0F) << 4
b64d_b2 [k] = math.floor( v / 4 ) -- ([b3] & 0x3c) >> 2
b64d_c1 [k] = ext( v, 0, 2 ) * 64 -- ([b3] & 0x03) << 6
end
if c_alpha._term ~= "" then
tail_padd64[1]=string.char(c_alpha._term:byte(),c_alpha._term:byte())
tail_padd64[2]=string.char(c_alpha._term:byte())
else
tail_padd64[1]=""
tail_padd64[2]=""
end
local esc_term
if magic[c_alpha._term] ~= nil then
esc_term=c_alpha._term:gsub(magic[c_alpha._term],function (s) return magic[s] end)
elseif c_alpha._term == "%" then
esc_term = "%%"
else
esc_term=c_alpha._term
end
if not c_alpha._strip then
local p=s:gsub("%%",function (s) return "__unique__" end)
for k,v in pairs(magic)
do
p=p:gsub(v,function (s) return magic[s] end )
end
local mr=p:gsub("__unique__",function() return "%%" end)
c_alpha._strip = string.format("[^%s%s]",mr,esc_term)
end
assert( c_alpha._strip )
pattern_strip = c_alpha._strip
local c =0 for i in pairs(b64d) do c=c+1 end
assert( c_alpha._alpha == s, "Integrity error." )
assert( c == 64, "The alphabet must be 64 unique values." )
if esc_term ~= "" then
assert( not c_alpha._alpha:find(esc_term), "Tail characters must not exist in alphabet." )
end
if known_base64_alphabets[alpha] == nil then
known_base64_alphabets[alpha]=c_alpha
end
end
return c_alpha._alpha,c_alpha._term
end
--------------------------------------------------------------------------------
-- encode64
--
-- Entry point mode selector.
--
--
local function encode64(i,o)
local method
if o ~= nil and io.type(o) == "file" then
local file_out = o
o = function(s) file_out:write(s) end
end
if type(i) == "string" then
if type(o) == "function" then
method = encode64_with_predicate
else
assert( o == nil, "unsupported request")
method = encode64_tostring
end
elseif io.type(i) == "file" then
assert( type(o) == "function", "file source requires output predicate")
i = encode64_io_iterator(i)
method = encode64_with_ii
else
assert( false, "unsupported mode" )
end
return method(i,o)
end
--------------------------------------------------------------------------------
-- decode64
--
-- Entry point mode selector.
--
--
local function decode64(i,o)
local method
if o ~= nil and io.type(o) == "file" then
local file_out = o
o = function(s) file_out:write(s) end
end
if type(i) == "string" then
if type(o) == "function" then
method = decode64_with_predicate
else
assert( o == nil, "unsupported request")
method = decode64_tostring
end
elseif io.type(i) == "file" then
assert( type(o) == "function", "file source requires output predicate")
i = decode64_io_iterator(i)
method = decode64_with_ii
else
assert( false, "unsupported mode" )
end
return method(i,o)
end
set_and_get_alphabet("base64")
--[[**************************************************************************]]
--[[****************************** Module **********************************]]
--[[**************************************************************************]]
return
{
encode = encode64,
decode = decode64,
alpha = set_and_get_alphabet,
}
| mpl-2.0 |
dan-f/Soundpipe | modules/data/count.lua | 4 | 1324 | sptbl["count"] = {
files = {
module = "count.c",
header = "count.h",
example = "ex_count.c",
},
func = {
create = "sp_count_create",
destroy = "sp_count_destroy",
init = "sp_count_init",
compute = "sp_count_compute",
},
params = {
optional = {
{
name = "count",
type = "SPFLOAT",
description = "Number to count up to (count - 1). Decimal points will be truncated.",
default = 4
},
{
name = "mode",
type = "SPFLOAT",
description = "Counting mode. 0 = wrap-around, 1 = count up to N -1, then stop and spit out -1",
default = 0
},
},
},
modtype = "module",
description = [[Trigger-based fixed counter
The signal output will count from 0 to [N-1], and then
repeat itself. Count will start when it has been triggered, otherwise it will be -1.]],
ninputs = 1,
noutputs = 1,
inputs = {
{
name = "trig",
description = "When non-zero, this value will increment."
},
},
outputs = {
{
name = "out",
description = "Signal output."
},
}
}
| mit |
lizh06/premake-core | src/base/workspace.lua | 9 | 4118 | ---
-- workspace.lua
-- Work with the list of workspaces loaded from the script.
-- Copyright (c) 2002-2015 Jason Perkins and the Premake project
---
local p = premake
p.workspace = p.api.container("workspace", p.global)
local workspace = p.workspace
---
-- Switch this container's name from "solution" to "workspace"
--
-- We changed these names on 30 Jul 2015. While it might be nice to leave
-- `solution()` around for Visual Studio folks and everyone still used to the
-- old system, it would be good to eventually deprecate and remove all of
-- the other, more internal uses of "solution" and "sln". Probably including
-- all uses of container class aliases, since we probably aren't going to
-- need those again (right?).
---
p.solution = workspace
workspace.alias = "solution"
p.alias(_G, "workspace", "solution")
p.alias(_G, "externalworkspace", "externalsolution")
---
-- Create a new workspace container instance.
---
function workspace.new(name)
local wks = p.container.new(workspace, name)
return wks
end
--
-- Iterate over the configurations of a workspace.
--
-- @return
-- A configuration iteration function.
--
function workspace.eachconfig(self)
self = p.oven.bakeWorkspace(self)
local i = 0
return function()
i = i + 1
if i > #self.configs then
return nil
else
return self.configs[i]
end
end
end
--
-- Iterate over the projects of a workspace.
--
-- @return
-- An iterator function, returning project configurations.
--
function workspace.eachproject(self)
local i = 0
return function ()
i = i + 1
if i <= #self.projects then
return p.workspace.getproject(self, i)
end
end
end
--
-- Locate a project by name, case insensitive.
--
-- @param name
-- The name of the projec to find.
-- @return
-- The project object, or nil if a matching project could not be found.
--
function workspace.findproject(self, name)
name = name:lower()
for _, prj in ipairs(self.projects) do
if name == prj.name:lower() then
return prj
end
end
return nil
end
--
-- Retrieve the tree of project groups.
--
-- @return
-- The tree of project groups defined for the workspace.
--
function workspace.grouptree(self)
-- check for a previously cached tree
if self.grouptree then
return self.grouptree
end
-- build the tree of groups
local tr = p.tree.new()
for prj in workspace.eachproject(self) do
local prjpath = path.join(prj.group, prj.name)
local node = p.tree.add(tr, prjpath)
node.project = prj
end
-- assign UUIDs to each node in the tree
p.tree.traverse(tr, {
onbranch = function(node)
node.uuid = os.uuid("group:" .. node.path)
end
})
self.grouptree = tr
return tr
end
--
-- Retrieve the project configuration at a particular index.
--
-- @param idx
-- An index into the array of projects.
-- @return
-- The project configuration at the given index.
--
function workspace.getproject(self, idx)
self = p.oven.bakeWorkspace(self)
return self.projects[idx]
end
---
-- Determines if the workspace contains a project that meets certain criteria.
--
-- @param func
-- A test function. Receives a project as its only argument and returns a
-- boolean indicating whether it meets to matching criteria.
-- @return
-- True if the test function returned true.
---
function workspace.hasProject(self, func)
return p.container.hasChild(self, p.project, func)
end
--
-- Return the relative path from the solution to the specified file.
--
-- @param self
-- The workspace object to query.
-- @param filename
-- The file path, or an array of file paths, to convert.
-- @return
-- The relative path, or array of paths, from the workspace to the file.
--
function workspace.getrelative(self, filename)
if type(filename) == "table" then
local result = {}
for i, name in ipairs(filename) do
if name and #name > 0 then
table.insert(result, workspace.getrelative(self, name))
end
end
return result
else
if filename then
return path.getrelative(self.location, filename)
end
end
end
| bsd-3-clause |
uonline/debut | src/day2/act6/scaffold.room.lua | 1 | 56821 | -- Состояния
-- 1. Герой приходит в себя и осматривается
-- 2. Обратный отсчёт действий до казни (первая концовка)
-- 3. Обратный отсчёт действий до спасения (вторая концовка)
-- Переменные локации
_scaffold_position = 1; -- текущее состояние локации
_scaffold_the_end_counter = 3; -- количество действий до концовки
-- Функции локации
-- Функция подъёма на эшфот
go_to_scaffold = function()
scaffold_birds:enable();
scaffold_propagandist_and_singer:disable();
scaffold_propagandist_and_singer_second:disable();
scaffold_propagandist:enable();
scaffold_singer:enable();
scaffold_priest:enable();
end;
-- Функция для обратного отсчёта до одной из концовок на эшафоте
-- Вызывается при взаимодействиях с разными объектами локации, и генерирует разные события,
-- зависящие от счётчика наступления концовки
scaffold_action = function(act_text)
local signer_execution_text = [[
Кончив чистить меч, богоизбранный вопрошающе глядит на городского
глашатая. Тот пару раз кашляет в кулак и машет рукой. Латник
подходит к барду и стальной хваткой стискивает пухлое плечо.
Подведя менестреля к плахе, он делает жест объявлять приговор.
^
-- Сегодня мы станем свидетелями справедливого наказания для...
-- начинает свою речь глашатай.
^
-- Всем и так прекрасно известно кто я, -- перебивает его менестрель
самым наглым образом. Оробевший глашатай только разводит руками под
требовательным взглядом богоизбранного.
^
-- Известно-известно, -- слышится из толпы, -- распутник он и прохиндей.
^
Палач-богоизбранный было снова кладёт латную перчатку на плечо барда, но
из толпы раздаются всё новые крики:
^
-- Да пусть говорит!
^
-- Устали мы слушать ваши приговоры! Пусть говорит уже!
^
-- Последнее слово! -- требовательно зазвучало над толпой.
^
-- Последняя песня! -- пискнул девичий голосок, сменившийся смешками.
^
Мрачный богоизбранный отпускает менестреля и отступает назад.
^
-- Спасибо люди! -- благодарит бард выпятив грудь, -- теперь уж моя песенка спета!
Не радовать мне вас больше своим пением. Посему вот моё последнее слово!
Сегодня казнят тех, кто отстаивал вашу свободу: контрабандистов и
рецидивистов.
^
В толпе послышался смех.
^
-- Но это дело прошлое, -- зычно продолжает бородач, -- да и кому
может быть интересна казнь всякого отребья! Другое дело, то что
вы можете прозевать. То что прямо сейчас творится у городских ворот!
^
Речь менестреля резко обрывается, когда воздух разрезает
металлический блеск. Какое-то время бард с удивлением смотрит на
метательный нож, торчащий из его глазницы, но затем падает замертво.
^
По людскому морю волной прокатывается тяжёлый вздох. Внутри неё вспыхивает
дёрганное движение. Под многочисленные крики толпа выплёвывает стройную фигуру.
Одетая в плащ и капюшон, она устремляется к ближайшему проулку.
Несколько стражников бросается в погоню, пробиваясь через скопление народа.
^
Богоизбранный хладнокровно поднимает тело и кидает его на плаху.
Размахнувшись, он срубает изуродованную голову менестреля, и гомон
мгновенно стихает.
^
-- Возмездие неотвратимо, -- спокойно завявляет богоизбранный,
-- унесите его.
^
Лязгая железом, латник поднимает тряпицу и принимается оттирать кровь с меча.
^
Глядя на голову менестреля в корзине, тебе же остаётся лишь догадываться,
видел ли он перед смертью огонь лиловых глаз.
]];
local propagandist_execution_text = [[
Дождавшись, когда стражники спустили тело с эшафота, богоизбранный швырнул
тряпку обратно на доски. Взяв бритоголового под локоть, он подводит его
к плахе.
^
-- Продолжим, -- ворчливо сказал латник, сделав знак глашатаю, -- и в этот
раз обойдёмся без последнего слова.
^
-- Сегодня, -- прочистив горло, начинает глашатай,
-- мы станем свидетелями справедливого наказания для Гезэля Зинера.
^
На этот раз народ безмолствует, хотя ты уверен, что рожа бритоголового и его
выпученные глаза тоже хорошо известны в городе.
^
-- Сий уроженец Мистического архипелага, бывший житель вольного города Сэльвеста,
обвиняется в совершении тяжких преступлений против человечества и Режима Ремана.
А именно в шпионаже и сотрудничестве с бандой контрабандистов. Кроме того, был
уличён в хуле против Блага и попрании церкви Тантикула, а так же входил в
запрещённую секту "Кара Благих", называя себя глашатаем Благих.
^
Глашатай делает многозначительную паузу, но люди по прежнему молчат.
^
-- Решением суда наместника Гезэль Зинер приговариавается
к смерти через обезглавливание! Привести приговор в исполнение!
^
Не говоря ни слова, палач-богоизбранный ставит приговорённого на колени.
Бритоголовый сам кладёт голову на плаху.
^
Свист меча, и стражники поднимаются на эшафот за новым трупом. Латник
принимается снова водить тряпкой по клинку.
]];
local prison_guard_execution_text = [[
Внезапно бывший тюремщик рядом с тобой издаёт жуткий вой
и бросается к краю эшафота. Сиганув вниз он расталкивает замешкавшихся
стражников и врезается в толпу.
^
Городской глашатай едва не выпускает из рук свои свитки, но богоизбранный
сохраняет невозмутимость. Он молча наблюдает, как приговорённый тщетно
пытается пробиться к свободе.
^
-- Куда полез! -- доносится шипение из толпы, -- держи эту крысу режимную!
^
-- На плаху его! -- весело кричит кто-то.
^
Двое стражников хватают бывшего солдата и затаскивают обратно на эшафот.
Удерживая извивающееся как угорь тело перед плахой, они вопросительно
смотрят на богоизбранного-палача. Тот кивает глашатаю, начинать объявлять
приговор.
^
-- Сегодня мы станем свидетелями справедливого наказания для...
^
-- Не хочу! -- как умалишённый орёт бывший тюремщик, перебивая глашатая.
^
-- Отпустите его, -- тихо приказывает латник, поудобней перехватывая
свой двуручник.
^
Едва стражники разжимают руки, как приговорённый снова пускается в бегство.
Но на этот раз богоизбранный оказывается быстрее. Сверкает меч, и жуткий вопль
застывает над площадью. Ты отворачиваешься, чтобы не видеть как латник волочит
за шкирку скулящего тюремщика. Сталь гудит второй раз, и вот уже стражники
спускают изуродованное тело с эшафота.
^
Богоизбранный сплёвывает на пропитавшиеся кровью доски и берётся отчищать
меч тряпицей.
]];
local hero_execution_start_text = [[
Когда тело бритоголового спускают с эшафота, до тебя доходит, что твоя
казнь будет следующей.
^
Богоизбранный выпускает из рук выпачканную кровью тряпку и подходит к
тебе. Ты чувствуешь хват холодной стали у себя на загривке и сам начинаешь
идти к плахе.
^
Глашатай с неохотой принимается зачитывать твой приговор:
^
-- Сегодня мы станем свидетелями долгожданного возмездия для дезертира, столько лет
скрывавшегося от правосудия. Естественно за это время он успел совершить ещё
немало преступлений. Например, буквально несколько часов назад он проник
в покои бывшего военачальника и вечного защитника города
советника Конроя и хладнокровно убил его...
^
На этих словах толпа взрывается. Лица людей искажённые ненавистью и гневом
становятся неотличимы друг на друга. В тебя летят грязь, камни и тухлые овощи,
видимо заготовленные специально на этого случая.
^
]];
local hero_execution_text = hero_execution_start_text .. [[
Почему-то ты воспринимаешь это как должное.
^
Богоизбранный отходит от тебя, прикрывая голову рукой. Когда пара камней
скрежещет об его доспех, он внезапно заслоняет тебя собой. Толпа ревёт
ещё сильней. Через брань и проклятия до тебя едва доносится голос глашатая.
^
-- Решением суда наместника..., -- толпа проглатывает твоё имя, -- приговариавается
к смерти через обезглавливание! Привести приговор в исполнение!
^
-- На дыбу его, -- выделяется из общего гомона, -- четвертовать! Сжечь!
^
-- Приговор привести в исполнение! -- орёт глашатай богоизбранному, перекрикивая
толпу.
^
Но старый вояка всё так же стоит перед тобой. Только когда народ на площади
умеряет свой пыл, он отступает тебе за спину.
^
Ноги твои подкашиваются, шея ложится на плаху. Перед глазами оказывается
корзина, из которой на тебя смотрят стелянными глазами глашатай и менестрель.
]];
local orc_band_attack_text = hero_execution_start_text .. [[
Неожиданно к крикам ненависти примешиваются испуганные возгласы.
Как лучик света в бесконечной тьме до тебя доносится глухой стон:
^
-- Пожар!
^
Его подхватывает всё больше голосов, пока ненависть окончательно
не выпускает людей из своих цепких лап, уступая место страху.
Ты видишь, как головы отворачиваются от эшфота, чтобы обратить лица
на запад. Там на догорающем небе поднимается ввысь несколько чёрных столбов
дыма. Толпа стихает окончально, напряжённо вслушиваясь в наступающую ночь.
И ночь не заставляет ждать. Она отзывается нарастающими криками ужаса и боли.
^
-- Орки! -- вопит кто-то из горожан.
^
И орки действительно появляются. С рёвом они выбегают на площадь сразу с нескольких
улиц и переулков.
^
-- К оружию, -- одаёт приказ богоизбранный. Его неожиданно охрипший голос, тонет
в ревё десятков орочьих голоток.
^
Вокруг эшафота разверзается хаос. Люди бросаются кто куда,
начинается давка. Урук-хай врываются в эту массу тел, рубя направо и налево.
За считанные мгновения орки добираются до городской стражи.
Завязывается беспорядочный бой, и к воплям присоединяется скрежет стали.
^
Городской глашатай вскрикивает и тут же исчёзает, стянутый с помоста чёрной
лапой. Ты видишь как сразу дюжина орочьих рук впивается в эшафот с разных сторон.
Богоизбранный одним махом разрубает ближайшую пару кистей, и кидается к другому
краю. Один за другим на скрипящие доски забираются вояки урук-хай. Твои
мордовороты-стражники уже бьются со здоровенным орком, орудующим парой топоров.
^
Во всей этой суматохе ты не успеваешь заметить куда пропал тот странный
проповедник. Перед тобой как из под земли вырастает урук с кривым ножом.
Но чудовищный меч палача нехотя сносит ему голову, чтобы тут же вернуться
к своему хозяину, который сражается с двумя вояками. Ты оборачиваешься
и видишь как ещё один орк в рогатом шлеме бежит богоизбранному за спину.
Не раздумывая, ты бросаешься ему под ноги, и он кубарем скатывается вниз.
^
Поднявшись на четвереньки, ты видишь лежащих у лестницы стражников.
Над их телами возвышается знакомый тебе татуированный урук из Харгфхейма.
К своему ужасу ты узнаёшь в нём того самого главаря орочьей банды, который
едва не убил тебя вчера. У тебя нет времени гадать, как он оказался в подполье
сегодня и почему ты не опознаел его раньше.
^
С другой стороны эшафота богоизбранный привычными движениями протирает
меч от чёрной крови. Сплюнув, он подходит к тебе и пинком сбырасывает с эшафота.
^
]];
act_text = act_text .. "^";
-- Если герой попал на эшафот по первой концовке, то включаем обратный отсчёт первой концовки
if _scaffold_position == 2 then
_scaffold_the_end_counter = _scaffold_the_end_counter - 1;
-- Описание произошедшего действия
-- Казнь менестреля
if _scaffold_the_end_counter == 2 then
event "signer execution"
return act_text .. signer_execution_text;
end;
-- Казнь глашатая
if _scaffold_the_end_counter == 1 then
event "propagandist execution"
return act_text .. propagandist_execution_text;
end;
-- Казнь главного героя
if _scaffold_the_end_counter <= 0 then
walk 'the_end_in_scaffold';
return act_text .. hero_execution_text;
end;
end;
-- Если герой попал на эшафот по второй концовке, то включаем обратный отсчёт для второй концовки
if _scaffold_position == 3 then
_scaffold_the_end_counter = _scaffold_the_end_counter - 1;
-- Описание произошедшего действия
-- Казнь менестреля
if _scaffold_the_end_counter == 3 then
event "signer execution"
return act_text .. signer_execution_text;
end;
-- Казнь глашатая
if _scaffold_the_end_counter == 2 then
event "propagandist execution"
return act_text .. propagandist_execution_text;
end;
-- Казнь тюремщика
if _scaffold_the_end_counter == 1 then
event "prison guard execution"
return act_text .. prison_guard_execution_text;
end;
-- Казнь главного героя и нападение орков
if _scaffold_the_end_counter <= 0 then
walk 'under_scaffold';
return act_text .. orc_band_attack_text;
end;
end;
return act_text;
end;
-- Локация
scaffold = room {
nam = function()
local text = {
[1] = 'Площадь Режима';
[2] = 'Эшафот';
[3] = 'Эшафот';
};
return text[_scaffold_position];
end;
dsc = function()
local scaffold_dsc_text = [[
Ты стоишь на пружинящих досках эшафота. Глаза жжёт пылающее зарево заката.
Сверху видно всю площадь Режима, наполненную алым светом.
Сам воздух словно пропитался кровью. Жгучие порывы ветра вздымают к небу столбы
душной пыли. Наверху стремительно темнеет. Восток обложен тучами. Единым фронтом
чернота движется вслед солнцу. На ещё светлой полосе неба видно как от туч отделяется
сомн силуэтов: стаи птиц кружат над городом.
]];
local text = {
[1] = [[
Ты обнаруживаешь себя в окружении городской стражи. Руки
занемели от тугих верёвок на запястьях.
Среди стражников ты находишь других приговорённых.
У них понурые лица со следами недваних побоев.
Некоторые тебе знакомы.
^
Поверх голов тебе удаётся рассмотреть контуры уже виденных тобой сегодня
зданий и горделиво возвышающееся каменное древо. Ты узнаёшь площадь Режима.
^
За спинами стражников тебя ожидает свежесколоченный эшафот.
Рядом стоит здоровенная телега, в которой уже навалено с десяток окровавленных тел.
Повозчик телеги в чёрном балахоне с капюшоном здорово смахивает на смерть.
]];
[2] = scaffold_dsc_text;
[3] = scaffold_dsc_text;
};
return text[_scaffold_position];
end;
obj = {
'scaffold_guards';
'scaffold_crown';
'scaffold_propagandist_and_singer';
'scaffold_propagandist_and_singer_second';
'scaffold_singer';
'scaffold_propagandist';
'scaffold_prison_guard';
'scaffold_priest';
'scaffold_godchosen';
'scaffold_birds';
};
entered = function()
-- Clear inventory, add whitelisted items
inv():zap();
return [[
Ты приходишь в себя, лёжа лицом в дорожной пыли. Пара сильных рук
поднимает тебя и ставит на ноги. Но ноги предательски подкашиваются,
и ты падаешь на четвереньки. Тогда по твом рёбрам пару раз тычат
сапогом. Крехтя, ты встаёшь и протираешь глаза от пыли,
чтобы осмотреться.
]];
end;
}
-- Объёкты локации
-- Стражники
scaffold_guards = obj {
nam = 'Стражники';
dsc = function()
local scaffold_dsc_text = [[
{Стражники} стоят плечом к плечу, окружив эшафот.
]];
local text = {
[1] = [[
{Стражники} стоят плечом к плечу и хмуро озираются по сторонам,
бросая косые взгляды то на зевак, то на заключённых.
]];
[2] = scaffold_dsc_text;
[3] = scaffold_dsc_text;
};
return text[_scaffold_position];
end;
act = function()
local scaffold_act_text = [[
Ты ещё раз пробегаешь взглядом по шеренге стражников, лелея в душе
непонятную надежду. Время от времени кто-то из них нет нет и оборачивается.
Бледность и глубокие тени под глазами делают его лицо похожим
на обтянутый кожей оскал черепа мертвеца.
Неожиданно для самого себя ты представляешь,
как эта маленькая армия мертвецов извлекает мечи из ножен
и с глухим стоном принимается рубить, собравшихся
на площади. Покрутив головой ты отгоняешь наваждение прочь.
]];
local text = {
[1] = [[
Ты присматриваешься к стражникам. Некоторые нервно поглаживают эфесы мечей.
Другие переглядываются между собой, словно договариваясь о чём-то.
Похоже, стражники предпочли бы оказаться в другом месте.
]];
[2] = scaffold_act_text;
[3] = scaffold_act_text;
};
return scaffold_action(text[_scaffold_position]);
end;
}
-- Толпа
scaffold_crown = obj {
nam = 'Толпа';
dsc = function()
local scaffold_dsc_text = [[
За их спинами плещется беспокойное {море горожан}.
]];
local text = {
[1] = [[
Из-за плотного кольца стражи тебе сложно оценить размер собравшейся
на площади {толпы}. Но судя по гулу, эшафот окружила половина города.
]];
[2] = scaffold_dsc_text;
[3] = scaffold_dsc_text;
};
return text[_scaffold_position];
end;
act = function()
scaffold_act_text = [[
Ты окидываешь взглядом собравшихся людей, вглядываясь в их лица.
Находятся среди них выражающие сочувствие. Таких куда больше, чем осуждающих.
Многие с опаской переглядываются и качают головами.
Кто-то перешёптывается.
И все же над толпой парит волнующее ожидание чего-то.
Ты догадываешься чего, и поэтому не ждешь от горожан помощи.
Объявив себя невиновным, ты лишь попытаешься оправдаться.
А твоему предупреждению никто не поверит.
Да и дадут ли они тебе что-то сказать?
]];
local text = {
[1] = [[
Ты прислушиваешься к гомону толпы. Среди общего шума можно
различить отдельные гневные выкрики, но чаще слышатся
удивлённые возгласы мужчин, вздохи и причитания женщин.
^
Горожане встревожены.
]];
[2] = scaffold_act_text;
[3] = scaffold_act_text;
};
return scaffold_action(text[_scaffold_position]);
end;
}
-- Глашатай и менестрель
scaffold_propagandist_and_singer = obj {
nam = 'Глашатай Благих и менестрель';
dsc = [[
Через шум до тебя доносятся обрывки перешёптываний двух приговорённых.
Ты узнаёшь {менестреля и глашатая Благих}.
]];
act_text = function()
return [[
Озираясь на стражников, ты подходишь к своим утренним приятелям.
^
-- Гляди-ка какая метаморфоза, -- менестрель тычет в тебя толстым пальцем,
-- на рассвете солдат Режима, на закате приговорённый к плахе.
^
-- А вы всё продолжаете выступать, как я посмотрю, -- отзываешься ты, кивая
на эшафот, -- скоро на сцену, зрители ждут?
^
-- Тебя они ждут не меньше, дезертир, -- в ответ на твой вопросительный взгляд,
бард являет тебе наглую улыбку в рамке жиденькой бороды, -- да-да, не нужно удивляться,
разнюхивать -- наша работа. Нам стало интересно, кто так ловко провёл нас утром.
И мы разузнали, что за фрукт сбежал из штаба Режима, едва туда угодив.
^
-- Теперь-то все фрукты лежат в одной корзине, -- ты киваешь в сторону эшафота,
наблюдая как мрачнеет бородатая физиономия менестреля.
^
-- Проклятый капитан всё таки устроил облаву на подполье, -- со злостью в голосе
пробасил бард, -- не меньше сотни человек угодили в застенки. Половину привезли сюда.
^
Он покосился на телегу с трупами.
^
-- Всё-таки? Так вы знали, что облава случится? -- удивляешься ты.
^
-- Рано или поздно это должно было случиться, -- вступает в разговор
бритоголовый глашатай. Он уже не выпучивает глаза как на проповеди утром
и кажется более разумным человеком, -- Режим не допускает восстаний.
Но капитан разыграл эту карту в свою пользу.
^
-- Что это значит? -- спрашиваешь ты, хотя ответ тебе уже известен.
^
-- Вся эта казнь лишь для отвлечения внимания. Посмотри вокруг, ты
не найдёшь ни одного солдата Режима. Потому что сейчас почти все они слоняются по
городу в поисках сообщников подполья. А в это время режимники преданные капитану
вырезают городскую стражу у ворот, чтобы впустить сюда орочью банду.
^
-- Они хотят впустить орков в город? -- переспрашиваешь ты как заколдованный.
В голове у тебя всплывают письма капитана лордам Приграничья.
В них говорилось только о подкупе банды для осады.
^
-- Орки устроят в городе мясорубку, -- потрясённо говоришь ты, -- зачем это капитану?
^
-- Это известно только ему одному, -- хмуро отвечает глашатай Благих, -- когда он
буквально развалил гарнизон Режима в городе, мы подумали, что он на нашей стороне.
Но потом, он начал стравливать горожан, тех, кто поддерживает режимников и тех,
кто Режим недолюбливает. Распускал разные гнусные слухи. А когда капитан
стал вербовать членов подполья, стало совершенно ясно, что он ведёт свою игру.
^
Ты долго переводишь взгляд с менестреля на глашатая Благих. Внезапно тебя
осеняет догадка.
^
-- Так он и вас завербовал?
^
Менестрель скривил рот, а глашатай нахмурился ещё больше.
^
-- Капитан давно знал о подполье. Он был в курсе агентов среди режимников.
Раскрыл связных. Он мог прихлопнуть подполье в любой момент.
Но предпочёл использовать его...
^
-- Капитан сделал нам предолжение, от которого нельзя отказаться,
-- яростно шепчет бард, -- он посвятил нас в свои планы.
Рассказал, что этому городу суждено сгореть, и никто не сможет этому
помешать ни подполье, ни Режим. Он обещал нам спасение, если мы согласимся
работать на него.
^
-- Выходит, вы предали не только подполье. Вы предали свой город.
Вы знали, что его ждёт, но ничего не сделали, чтобы это предотвратить.
^
-- Ты хочешь воззвать к моей совести?! -- бородач подавляет булькающий смех,
-- да этот городишко лицедеев заслужил быть сожённым. Они целовали режимникам ноги,
когда те прогнали орков. Но едва Режим начал наводить свои порядки,
они начали изображать недовольных. Думаешь, они поддержали подполье?
Бандиты и проходимцы, вот что говорили про нас. Им и сейчас плевать на нас.
Люди собрались здесь, чтобы посмотреть на казнь убийцы советника Конроя.
^
Раздаётся очередной свист меча палача. У тебя внутри всё холодеет.
^
С эшафота гремя доспехами, спускается тот самый лысый вояка. На громоздком наплечнике
покоится окровавленный двуручник.
^
-- Богоизбранный? -- обращается к латнику один из стражников. Взгляд вояки пробегает
по заключённым, чтобы остановиться на тебе.
^
-- Давайте теперь этих, -- названный богоизбранный кивает в твою сторону.
^
Стражники хватают менестреля, бритоголового и тебя под руки и выводят на эшафот.
Вслед за тобой толкают ещё двоих заключённых.
]];
end;
act = function()
-- Выключаем обратный отсчёт действий на эшафоте
-- Переходим на второе состояние эщафота
event 'go to scaffold';
return scaffold_propagandist_and_singer:act_text();
end;
}
-- Глашатай и менестрель для второй концовки
scaffold_propagandist_and_singer_second = obj {
nam = scaffold_propagandist_and_singer.nam;
dsc = scaffold_propagandist_and_singer.dsc;
act = function()
event 'go to scaffold for escape';
return scaffold_propagandist_and_singer:act_text();
end;
};
scaffold_propagandist_and_singer_second:disable()
-- Менестрель
scaffold_singer = obj {
nam = 'Менестрель';
dsc = [[
{Менестрель} словно лихой рыбак, закидывает в это море, то улыбки, то поклоны,
то неприличные жесты. По толпе прокатываются волны перешёптываний: "Этот-то что,
там делает?".
]];
act = function()
local text = [[
Ты обращаешь на себя внимание менестреля, чтобы быстро прошептать:
^
-- У нас еще есть шанс. Если вот-вот появятся орки,
нам всего лишь нужно как-то потянуть время -- ты киваешь на толпу,
-- давай, развлеки их как ты умеешь. Спой им песню на прощание!
^
Бородач в ответ подмигивает тебе с улыбкой обречённого.
]];
return scaffold_action(text);
end;
}
scaffold_singer:disable();
-- Глашатай Благих
scaffold_propagandist = obj {
nam = 'Глашатай Благих';
dsc = [[
Угрюмый {глашатай Благих} тихо шепчет молитву, сцепив пальцы.
]];
act = function()
local text = [[
Ты обращаешь на себя внимание бритоголового, чтобы прошептать ему на ухо:
^
-- У нас еще есть шанс. Если вот-вот появятся орки,
нам всего лишь нужно как-то потянуть время -- ты киваешь на толпу,
-- давай, подурачь их как ты умеешь. Отпусти грехи или наоброт прокляни.
^
Глашатай Благих смотрит на тебя как на умалишённого.
^
-- Я предпочитаю определённость, -- спокойно говорит он,
-- умереть здесь и сейчас от удара меча несравненно лучше,
чем попасть в хаос мясорубки. Ты хочешь броситься в пекло и гадать,
когда какой-нибудь орк переломает тебе все кости,
выдернет руки с корнем или сожжёт заживо? Я не хочу.
^
-- Тогда к чему твои молитвы, как не для спасения?
-- ты чувствуешь как внутри зашевелилась непонятная злоба.
-- ^
-- Люди молятся во спасение души, что куда важней чем
мирской исход, -- чувственно поправляет тебя бритоголовый,
и глаза его округляются как утром.
^
-- Поздновато ты задумался о душе, -- язвительно замечаешь ты,
чтобы поймать себя на мысли, что о своей ты сам никогда
не задумывался.
]];
return scaffold_action(text);
end;
}
scaffold_propagandist:disable();
--- Стражник из тюрьмы штаба Режима
scaffold_prison_guard = obj {
nam = 'Тюремщик';
dsc = function()
local text = {
[1] = [[
За ними стоит ещё пара твоих знакомцев, но ты никак не можешь вспомнить,
где ты их видел.
]];
[2] = [[
Позади тебя трясётся ссутулившийся {человек}, в котором ты с трудом распознаёшь
своего бывшего тюремщика из застенков в штабе Режима.
]];
[3] = [[
Следующим в очереди на плаху оказывается ссутулившийся {человек},
в котором ты с трудом распознаёшь своего тюремщика из застенков
в штабе Режима.
]];
};
return text[_scaffold_position];
end;
act = function()
local text = [[
Ты с удивлением смотришь на бывшего солдата Режима.
^
-- А его-то за что? -- вопрошаешь ты неизвестно кого.
]];
-- Проверяем не казнили ли ещё глашатая Благих
if not scaffold_propagandist:disabled() then
text = text .. [[
^
Услышавший это глашатай Благих подавил усмешку.
^
-- Так это же он упустил тебя из штаба, -- тихо проговорил
бритоголовый, -- его нашли валявшимся с подозрительным мешочком в руках.
Весь день пытались привести в чувства. Думали уже, что не очнётся.
Потом он нёс какой-то бред про говорящую крысу, которая стащила
у него ключи. Хотя всем и так было всё понятно. Употребление,
да ещё и на службе, тяжкое преступление.
^
Тебе остаётся только согласиться.
]];
end;
return scaffold_action(text);
end;
}
-- Проповедник
scaffold_priest = obj {
nam = 'Проповедник';
dsc = function()
local text = {
[1] = '';
[2] = [[
Его поддерживает за локоть худощавая личность так же тебе известная.
Это {проповедник}, которого ты видел в лагере подполья, сидящим
на куче книг.
]];
[3] = [[
Позади тебя странно улыбается худощавая {личность} в тёмной рясе.
Ты вспоминаешь, что видел этого типа в подполье, молящимся на куче книг.
]];
};
return text[_scaffold_position];
end;
act = function()
local text = {
[1] = '';
[2] = [[
Ты раздумываешь, стоит ли заговаривать с этим сумасшедшим проповедником.
Тогда он обращается к тебе сам.
^
-- Эту заблудшую душу я уже встречал раньше. Я вижу ты отвернулся от лже-Блага?
-- он кивает на твою грудь, которую когда-то закрывал нагрудник солдата Режима,
-- возможно теперь ты готов услышать об истинной религии?
^
-- Не думаю, что сейчас время для проповедей, -- ты с опаской косишься на
богоизбранного и стражников.
^
-- О, любое время хорошо для почитания божественного, -- слышишь ты наставление,
-- а перед смертью самое время принять истинную веру.
^
-- Это точно плохая идея, -- возражаешь ты.
^
-- Об этом я и хочу тебе рассказать, -- улыбается человек, -- об идеях -- настоящих богах
смертного мира. Об этих симбионтах сознания, невозможных без своих носителей -- людей и
им подобных. Но и люди немыслимы без них.
^
Его улыбка становится ещё шире, обнажая два ряда ровных зубов.
^
-- Вижу ты не понимаешь, к чему я всё это тебе рассказываю, но терпение.
Сейчас ты всё поймешь. Идеи способны бесконечно перерождаться, сквозь века и эпохи
они живут сменяя носителей и распыляя почитателей, как грибы -- споры.
Их мессии-проводники: люди искусства, философы, ученые, политики.
Их почитатели это народы и нации. Люди их плоть и кровь, идеи сражаются между
собой за них. Многие идеи тщетны и не имеют будущего, так же как и многие люди
его недостойны. Одна идея может оказывается настолько сильной, что победит все
прочие, став <b>навязчивой</b>. Но горе, если она тоже окажется тщетной!
^
Он многозначительно смотрит на тебя.
^
-- Да, теперь я говорю о тебе и твоей одержимости спасением.
Ты так упивался этой идеей, но куда она тебя привела? На эшафот!
Чтож, эта идея оказалась тщетной для тебя.
^
Человек заканчивает свою проповедь со странным торжеством на лице,
оставляя тебя наедине со своей навязчивой идеей.
]];
[3] = [[
Ты раздумываешь, стоит ли заговаривать с этим сумасшедшим проповедником.
Тогда он обращается к тебе сам.
^
-- Вот мы и встретились снова, заблудшая душа. В месте где судьбы подходят в концу,
-- его улыбка становится ещё более странной, -- удалось ли тебе осуществить задуманное?
^
Видя недоумение на твоём лице, человек усмехается.
^
-- Да ты ничего и не задумывал! Насколько же ты охвачен течением?
Что за сила тобой движет и куда ведёт? Увидев тебя в первый раз,
я уже понял как легко тебя использовать. Как думаешь, ты ещё можешь быть полезен
хоть <b>чему-то</b>? Сейчас над тобой навис рок. Сумеешь ли ты отвести его?
Совсем скоро узнаем.
^
Закончив свою речь, довольный собой проповедник и не думает прекращать улыбаться.
У тебя возникает ощущение, что перед тобой стоит староста из твоей
разорённой деревни.
]];
};
return scaffold_action(text[_scaffold_position]);
end;
};
scaffold_priest:disable();
-- Кевраза
scaffold_godchosen = obj {
nam = 'Богоизбранный Кевраза';
dsc = function()
local scaffold_dsc_text = [[
За вами присматривает пара мордоворотов-стражников.
^
В центре эшафота рядом с плахой вышагивает {богоизбранный} и буднично протирает
меч тряпицей. У края городской глашатай готовится зачитывать очередной
приговор.
]];
local text = {
[1] = [[
Одного из них всё время пробивает дрожь, едва с эшафота гремит очередной приговор,
сменяющийся скрежетом и воем стали.
]];
[2] = scaffold_dsc_text;
[3] = scaffold_dsc_text;
};
return text[_scaffold_position];
end;
act = function()
local text = '';
if _scaffold_the_end_counter == 4 then
text = [[
Ты смотришь на разгуливающего латника, трущего сталь меча грязной тряпкой.
Мимо него стражники проносят к лестнице очередное обезглавленное тело.
Занятие богоизбранного прерывает ворчание городского глашатая.
^
-- Вот ведь черти! И кто это написал? -- негодует тот, изучая
свиток с приговорами, -- послушайте только! "Должно вершить возмездие
как над предателем не только земли своей, но и всего человечества."
И это только концовка! Как вам это нравится?! Почему просто нельзя
объявить: "обвиняются в госизмене и приговаривается к казне", и вздёрнуть
из всех разом? Нет же, эшафот соорудили, плаху. Торчим тут уже битый час.
Скоро стемнеет, да того и гляди, дождь ливанёт.
^
-- Так распорядился наместник, -- нехотя отозывается латник.
^
-- Странные у него распоряжения, у этого вашего наместника, -- замечает глашатай,
-- где же это виданно, чтобы богоизбранный головы рубил на плахе?
^
-- Таков приказ. Я здесь, чтобы изъявлять его волю
и вершить правосудие от лица Режима Ремана. Это большая честь.
^
-- Оно и понятно, сам-то наместник не пожелал присутсвовать.
Всё сидит в своей резиденции и носу не кажет. Хотя кого ему теперь бояться?
^
-- Довольно этого трёпа! За дело! -- обрубает латник.
]];
end;
if _scaffold_the_end_counter == 3 then
text = [[
Ты смотришь на сурового латника с жутким мечом в руках. Таким двуручником
можно за раз срубить все пять ваших голов. Тебе странно наблюдать богоизбранного
в качестве палача, да и ему самому эта роль, похоже, не в радость. Он чистит
клинок с некоторой брезгливостью.
]];
end;
if _scaffold_the_end_counter == 2 then
text = [[
Ты смотришь на латника. Его пугающий двуручный меч притягивает твой взгляд
как магнит. Сегодня утром ты видел точно такой же: в арсенале штаба Режима
старый солдат счищал с него ржавчину. Заодно он поведал тебе, что меч некогда
принадлежал отцу теперешнего лорда местных земель. Соврал солдат или нет,
остаётся загадкой, но то что сейчас именно этот двуручник вершит правосудие
сомневаться не приходится, потому что на поясе богоизбранного в ножнах
покоится ещё один клинок.
]];
end;
if _scaffold_the_end_counter == 1 then
text = [[
Ты смотришь на латника. Тот ловит твой взгляд, и пару мгновений
вы изучаете друг на друга. Когда ты увидел его в первый раз в башне,
то даже не оценил его возраст. Глубокие морщины тогда смешались
со шрамами, и ты не смог разглядеть в грозном воителе древнего старика.
Впрочем, это меньшее, что удивляет в богоизбранном. Его старческие
выцветшие глаза с металлическим блеском будто бы вовсе непохожи
на глаза человека. Из них на тебя словно смотрит нечто холодное
и далёкое. Но взор латника приковывает к себе, и чем дольше ты
смотришь ему в глаза, тем ближе это холодное нечто становится.
^
Ты поспешно отводишь взгляд.
]];
end;
return scaffold_action(text);
end;
}
-- Птицы
scaffold_birds = obj {
nam = 'Птицы';
dsc = [[
^
Множество {воронов} устроилось на крышах домов и внимательно
наблюдает за происходящим на площади.
]];
act = function()
local text = {
[1] = '';
[2] = [[
Ты с опаской глядишь на воронов. Пока они хранят терпеливое молчание,
но их желание поживиться чувствуется как нечто осязаемое. Холодным и влажным зверем
оно трётся тебе о спину, оставляя на ней тяжёлые капли пота.
]];
[3] = [[
Ты с опаской глядишь на воронов. Одна сразу птица привлекает твоё внимание.
Она изучающе смотрит прямо на тебя, повернув голову на бок.
Не выдержав, ты отворачиваешься, а в голову к тебе закрадываются странные мысли:
не та ли эта птица, которую ты освободил в башне?
]];
};
return scaffold_action(text[_scaffold_position]);
end;
}
scaffold_birds:disable()
-- События локации
-- ?
on_event('caught in action', function()
walk 'scaffold';
end)
-- Переходим на локацию эшафота для второй концовки
on_event('leave from black room', function()
scaffold_propagandist_and_singer:disable();
scaffold_propagandist_and_singer_second:enable();
walk 'scaffold';
end)
-- Поднимаемся на эшафот для первой концовки
on_event('go to scaffold', function()
_scaffold_position = 2;
_scaffold_the_end_counter = 3;
go_to_scaffold();
end)
-- Поднимаемся на эшафот для второй концовки
on_event('go to scaffold for escape', function()
_scaffold_position = 3;
_scaffold_the_end_counter = 4;
go_to_scaffold();
end)
-- Казнь менестреля
on_event('signer execution', function()
scaffold_singer:disable();
end)
-- Казнь глашатая
on_event('propagandist execution', function()
scaffold_propagandist:disable();
end)
-- Казнь стража тюрьмы штаба Режима
on_event('prison guard execution', function()
scaffold_prison_guard:disable();
end)
-- Концовка на эшафоте
on_event('the end in scaffold', function()
walk 'the_end_in_scaffold';
end)
-- Спасение с эшафота
on_event('the escape from scaffold', function()
walk 'under_scaffold';
end)
| gpl-3.0 |
robbie-cao/mooncake | stat.lua | 1 | 1609 | local sys_stat = require "posix.sys.stat"
local bit = require("bit")
if #arg < 1 then
print(string.format("Usage: %s path", arg[0]))
return
end
local path = arg[1]
function stmode(mode)
if bit.band(mode, sys_stat.S_IFBLK) ~= 0 then return "block device" end
if bit.band(mode, sys_stat.S_IFCHR) ~= 0 then return "character device" end
if bit.band(mode, sys_stat.S_IFDIR) ~= 0 then return "directory" end
if bit.band(mode, sys_stat.S_IFIFO) ~= 0 then return "FIFO/pipe" end
--[[
if bit.band(mode, sys_stat.S_IFLNK) ~= 0 then return "symlink" end
--]]
if bit.band(mode, sys_stat.S_IFREG) ~= 0 then return "regular file" end
if bit.band(mode, sys_stat.S_IFSOCK) ~= 0 then return "socket" end
return "unknown?"
end
sb = sys_stat.stat(path)
print(string.format("File type : %s", stmode(sb.st_mode)))
print(string.format("I-node number : %d", sb.st_ino))
print(string.format("Mode : %o (octal)", sb.st_mode))
print(string.format("Link count : %d", sb.st_nlink))
print(string.format("Ownership : UID=%d GID=%d", sb.st_uid, sb.st_gid))
print(string.format("Preferred I/O block size: %d bytes", sb.st_blksize))
print(string.format("File size : %d bytes", sb.st_size))
print(string.format("Blocks allocated : %d", sb.st_blocks))
print(string.format("Last status change : %s", sb.st_ctime))
print(string.format("Last file access : %s", sb.st_atime))
print(string.format("Last file modification : %s", sb.st_mtime))
| mit |
JarnoVgr/Mr.Green-MTA-Resources | resources/[gameplay]/mapstop100/mapstop100.lua | 1 | 10559 | handlerConnect = nil
canScriptWork = true
addEventHandler('onResourceStart', getResourceRootElement(),
function()
handlerConnect = dbConnect( 'mysql', 'host=' .. get"*gcshop.host" .. ';dbname=' .. get"*gcshop.dbname" .. ';charset=utf8mb4', get("*gcshop.user"), get("*gcshop.pass"))
if handlerConnect then
dbExec( handlerConnect, "CREATE TABLE IF NOT EXISTS `mapstop100` ( `id` int(11) NOT NULL AUTO_INCREMENT, `mapresourcename` VARCHAR(70) BINARY NOT NULL, `mapname` VARCHAR(70) BINARY NOT NULL, `author` VARCHAR(70) BINARY NOT NULL, `gamemode` VARCHAR(70) BINARY NOT NULL, `rank` INTEGER, `votes` INTEGER, `balance` INTEGER, PRIMARY KEY (`id`) )" )
dbExec( handlerConnect, "CREATE TABLE IF NOT EXISTS `votestop100` ( `id` int(11) NOT NULL AUTO_INCREMENT, `forumid` int(10) unsigned NOT NULL, `choice1` VARCHAR(70) BINARY NOT NULL, `choice2` VARCHAR(70) BINARY NOT NULL, `choice3` VARCHAR(70) BINARY NOT NULL, `choice4` VARCHAR(70) BINARY NOT NULL, `choice5` VARCHAR(70) BINARY NOT NULL, PRIMARY KEY (`id`) )" )
else
outputDebugString('Maps top 100 error: could not connect to the mysql db')
canScriptWork = false
return
end
end
)
function maps100_fetchMaps(player)
refreshResources()
local mapList = {}
-- Get race and uploaded maps
local raceMps = exports.mapmanager:getMapsCompatibleWithGamemode(getResourceFromName("race"))
if not raceMps then return false end
for _,map in ipairs(raceMps) do
local name = getResourceInfo(map,"name")
local author = getResourceInfo(map,"author")
local resname = getResourceName(map)
if not name then name = resname end
if not author then author = "N/A" end
local gamemode
local t = {name = name, author = author, resname = resname, gamemode = "Race"}
table.insert(mapList,t)
end
table.sort(mapList,function(a,b) return tostring(a.name) < tostring(b.name) end)
local map100 = {}
local qh = dbQuery(handlerConnect, "SELECT * FROM `mapstop100`")
local map100_sql = dbPoll(qh,-1)
if not map100_sql then return false end
for _,row in ipairs(map100_sql) do
local name = tostring(row.mapname)
local author = tostring(row.author)
local resname = tostring(row.mapresourcename)
local gamemode = tostring(row.gamemode)
local t = {name = name, author = author, resname = resname, gamemode = gamemode}
table.insert(map100,t)
end
table.sort(map100,function(a,b) return tostring(a.name) < tostring(b.name) end)
triggerClientEvent(player,"maps100_receiveMapLists",resourceRoot,mapList,map100)
end
function maps100_command(p)
maps100_fetchMaps(p)
triggerClientEvent(p,"maps100_openCloseGUI",resourceRoot)
end
addCommandHandler("maps100", maps100_command, true, true)
function maps100_addMap(p, name, author, gamemode, resname)
local qh = dbQuery(handlerConnect, "SELECT * FROM `mapstop100` WHERE `mapresourcename`=?", tostring(resname))
local resCheck = dbPoll(qh,-1)
if resCheck[1] then
if tostring(resCheck[1].mapresourcename) == tostring(resname) then
outputChatBox("Map already added", p)
return
end
end
local qh = dbQuery(handlerConnect, "INSERT INTO `mapstop100` (`mapresourcename`, `mapname`, `author`, `gamemode`, `rank`, `votes`) VALUES (?,?,?,?,?,?)", resname, name, author, gamemode, "0", "0" )
if dbFree( qh ) then
outputChatBox("Map added succesfully", p)
end
maps100_fetchMaps(p)
end
addEvent("maps100_addMap", true)
addEventHandler("maps100_addMap", resourceRoot, maps100_addMap)
function maps100_delMap(p, name, author, gamemode, resname)
local qh = dbQuery(handlerConnect, "DELETE FROM `mapstop100` WHERE `mapresourcename`=?", resname)
if dbFree( qh ) then
outputChatBox("Map deleted succesfully", p)
end
maps100_fetchMaps(p)
end
addEvent("maps100_delMap", true)
addEventHandler("maps100_delMap", resourceRoot, maps100_delMap)
function maps100_fetchInsight(p)
local voterList = {}
local qh = dbQuery(handlerConnect, "SELECT * FROM `votestop100`")
local map100_sql = dbPoll(qh,-1)
if not map100_sql then return false end
for _,row in ipairs(map100_sql) do
local id = tostring(row.id)
local forumid = tostring(row.forumid)
local choice1 = tostring(row.choice1)
local choice2 = tostring(row.choice2)
local choice3 = tostring(row.choice3)
local choice4 = tostring(row.choice4)
local choice5 = tostring(row.choice5)
local t = {id = id, forumid = forumid, choice1 = choice1, choice2 = choice2, choice3 = choice3, choice4 = choice4, choice5 = choice5}
table.insert(voterList,t)
end
table.sort(voterList,function(a,b) return tostring(a.id) < tostring(b.id) end)
local mapsList = {}
local qh = dbQuery(handlerConnect, "SELECT * FROM `mapstop100` ORDER BY `rank` DESC")
local map100_sql = dbPoll(qh,-1)
if not map100_sql then return false end
for _,row in ipairs(map100_sql) do
local id = tostring(row.id)
local mapresourcename = tostring(row.mapresourcename)
local rank = tostring(row.rank)
local votes = tostring(row.votes)
local balance = tostring(row.balance)
local mapname = tostring(row.mapname)
local author = tostring(row.author)
local gamemode = tostring(row.gamemode)
local t = {id = id, mapresourcename = mapresourcename, rank = rank, votes = votes, balance = balance, mapname = mapname, author = author, gamemode = gamemode}
table.insert(mapsList,t)
end
--table.sort(mapsList,function(a,b) return tostring(a.rank) < tostring(b.rank) end)
triggerClientEvent(p,"maps100_receiveInsight",resourceRoot,voterList,mapsList)
end
addEvent("maps100_fetchInsight", true)
addEventHandler("maps100_fetchInsight", resourceRoot, maps100_fetchInsight)
function maps100_removeVote(p, forumid, option)
local qh = dbQuery(handlerConnect, "SELECT * FROM `votestop100` WHERE `forumid`=?", forumid)
local votesList_sql = dbPoll(qh,-1)
if not votesList_sql then return false end
if votesList_sql[1] then
local empty = ""
if option == "all" then
local qh = dbQuery(handlerConnect, "DELETE FROM `votestop100` WHERE `forumid`=?", forumid)
if dbFree( qh ) then
outputChatBox("Voter removed succesfully", p)
end
elseif option == "choice1" then
local qh = dbQuery(handlerConnect, "UPDATE `votestop100` SET `choice1`=? WHERE `forumid`=?", empty, forumid)
if dbFree( qh ) then
outputChatBox("Vote ".. option .. " removed succesfully", p)
end
elseif option == "choice2" then
local qh = dbQuery(handlerConnect, "UPDATE `votestop100` SET `choice2`=? WHERE `forumid`=?", empty, forumid)
if dbFree( qh ) then
outputChatBox("Vote ".. option .. " removed succesfully", p)
end
elseif option == "choice3" then
local qh = dbQuery(handlerConnect, "UPDATE `votestop100` SET `choice3`=? WHERE `forumid`=?", empty, forumid)
if dbFree( qh ) then
outputChatBox("Vote ".. option .. " removed succesfully", p)
end
elseif option == "choice4" then
local qh = dbQuery(handlerConnect, "UPDATE `votestop100` SET `choice4`=? WHERE `forumid`=?", empty, forumid)
if dbFree( qh ) then
outputChatBox("Vote ".. option .. " removed succesfully", p)
end
elseif option == "choice5" then
local qh = dbQuery(handlerConnect, "UPDATE `votestop100` SET `choice5`=? WHERE `forumid`=?", empty, forumid)
if dbFree( qh ) then
outputChatBox("Vote ".. option .. " removed succesfully", p)
end
else
outputChatBox("No option selected", p)
end
maps100_fetchInsight(p)
else
outputChatBox("Player not in database", p)
end
end
addEvent("maps100_removeVote", true)
addEventHandler("maps100_removeVote", resourceRoot, maps100_removeVote)
function maps100_countVotes(p)
local qh = dbQuery(handlerConnect, "SELECT * FROM `mapstop100`")
local maps_sql = dbPoll(qh,-1)
if not maps_sql then
outputDebugString("Could not fetch maps_sql")
return false
end
local mapRatings = exports.mapratings:getTableOfRatedMaps()
if not mapRatings then
outputDebugString("Could not fetch mapRatings")
return false
end
local qh = dbQuery(handlerConnect, "SELECT * FROM `votestop100`")
local votes_sql = dbPoll(qh,-1)
if not votes_sql then
outputDebugString("Could not fetch votes_sql")
return false
end
for _,row in ipairs(maps_sql) do
local resname = tostring(maps_sql[_].mapresourcename)
local votes = 0
for i,rij in ipairs(votes_sql) do
if tostring(votes_sql[i].choice1) == resname then votes = votes + 1 end
if tostring(votes_sql[i].choice2) == resname then votes = votes + 1 end
if tostring(votes_sql[i].choice3) == resname then votes = votes + 1 end
if tostring(votes_sql[i].choice4) == resname then votes = votes + 1 end
if tostring(votes_sql[i].choice5) == resname then votes = votes + 1 end
end
local rating = mapRatings[resname]
local balance = 0
if rating then
likes = rating.likes
dislikes = rating.dislikes
if tonumber(likes) and tonumber(dislikes) then
balance = tonumber(likes) - tonumber(dislikes)
end
end
local qh = dbQuery(handlerConnect, "UPDATE `mapstop100` SET `votes`=?, `balance`=? WHERE `mapresourcename`=?", votes, balance, resname)
if dbFree( qh ) then
else
outputChatBox("Could not set ".. votes .. " votes for " .. resname, p)
end
end
local qh = dbQuery(handlerConnect, "SELECT * FROM `mapstop100` ORDER BY `votes` DESC, `balance` DESC")
local maps_sql = dbPoll(qh,-1)
if not maps_sql then return false end
for _,row in ipairs(maps_sql) do
local resname = tostring(maps_sql[_].mapresourcename)
local qh = dbQuery(handlerConnect, "UPDATE `mapstop100` SET `rank`=? WHERE `mapresourcename`=?", _, resname)
if dbFree( qh ) then
else
outputChatBox("Could not set ".. _ .. " rank for " .. resname, p)
end
end
maps100_fetchInsight(p)
end
addEvent("maps100_countVotes", true)
addEventHandler("maps100_countVotes", resourceRoot, maps100_countVotes)
function mapstop100_insertTrigger(p, rank)
local qh = dbQuery(handlerConnect, "SELECT * FROM `mapstop100` WHERE `rank`<=? ORDER BY `rank` DESC", rank)
local map100_sql = dbPoll(qh,-1)
if not map100_sql then return false end
exports.gcshop:mapstop100_insert(p, map100_sql)
end
addEvent("mapstop100_insertTrigger", true)
addEventHandler("mapstop100_insertTrigger", resourceRoot, mapstop100_insertTrigger)
function mapstop100_removeTrigger(p)
exports.gcshop:mapstop100_remove(p)
end
addEvent("mapstop100_removeTrigger", true)
addEventHandler("mapstop100_removeTrigger", resourceRoot, mapstop100_removeTrigger) | mit |
aminaleahmad/merbots | plugins/banhammer.lua | 2 | 18022 | -- data saved to moderation.json
do
-- make sure to set with value that not higher than stats.lua
local NUM_MSG_MAX = 4 -- Max number of messages per TIME_CHECK seconds
local TIME_CHECK = 4
local function kick_user(user_id, chat_id)
if user_id == tostring(our_id) then
send_large_msg('chat#id'..chat_id, 'I won\'t kick myself!')
else
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
local function ban_user(user_id, chat_id)
-- Save to redis
redis:set('banned:'..chat_id..':'..user_id, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
local function superban_user(user_id, chat_id)
redis:set('superbanned:'..user_id, true)
kick_user(user_id, chat_id)
end
local function unban_user(user_id, chat_id)
redis:del('banned:'..chat_id..':'..user_id)
end
local function superunban_user(user_id, chat_id)
redis:del('superbanned:'..user_id)
return 'User '..user_id..' unbanned'
end
local function action_by_id(extra, success, result)
if success == 1 then
local matches = extra.matches
local chat_id = result.id
local receiver = 'chat#id'..chat_id
local group_member = false
for k,v in pairs(result.members) do
if matches[2] == tostring(v.id) then
group_member = true
local full_name = (v.first_name or '')..' '..(v.last_name or '')
if matches[1] == 'ban' then
ban_user(matches[2], chat_id)
send_large_msg(receiver, full_name..' ['..matches[2]..'] banned')
elseif matches[1] == 'superban' then
superban_user(matches[2], chat_id)
send_large_msg(receiver, full_name..' ['..matches[2]..'] globally banned!')
elseif matches[1] == 'kick' then
kick_user(matches[2], chat_id)
end
end
end
if matches[1] == 'unban' then
if is_banned(matches[2], chat_id) then
unban_user(matches[2], chat_id)
send_large_msg(receiver, 'User with ID ['..matches[2]..'] is unbanned.')
else
send_large_msg(receiver, 'No user with ID '..matches[2]..' in (super)ban list.')
end
elseif matches[1] == 'superunban' then
if is_super_banned(matches[2]) then
superunban_user(matches[2], chat_id)
send_large_msg(receiver, 'User with ID ['..matches[2]..'] is globally unbanned.')
else
send_large_msg(receiver, 'No user with ID '..matches[2]..' in (super)ban list.')
end
end
if not group_member then
send_large_msg(receiver, 'No user with ID '..matches[2]..' in this group.')
end
end
end
local function action_by_reply(extra, success, result)
local chat_id = result.to.id
local user_id = result.from.id
local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '')
if is_chat_msg(result) and not is_sudo(result) then
if extra.match == 'kick' then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, false)
elseif extra.match == 'ban' then
ban_user(user_id, chat_id)
send_large_msg('chat#id'..chat_id, 'User '..user_id..' banned')
elseif extra.match == 'superban' then
superban_user(user_id, chat_id)
send_large_msg('chat#id'..chat_id, full_name..' ['..user_id..'] globally banned!')
elseif extra.match == 'unban' then
unban_user(user_id, chat_id)
send_large_msg('chat#id'..chat_id, 'User '..user_id..' unbanned')
elseif extra.match == 'superunban' then
superunban_user(user_id, chat_id)
send_large_msg('chat#id'..chat_id, full_name..' ['..user_id..'] globally unbanned!')
elseif extra.match == 'whitelist' then
redis:set('whitelist:user#id'..user_id, true)
send_large_msg('chat#id'..chat_id, full_name..' ['..user_id..'] whitelisted')
elseif extra.match == 'unwhitelist' then
redis:del('whitelist:user#id'..user_id)
send_large_msg('chat#id'..chat_id, full_name..' ['..user_id..'] removed from whitelist')
end
else
return 'Use This in Your Groups'
end
end
local function resolve_username(extra, success, result)
vardump(extra)
vardump(result)
local chat_id = extra.msg.to.id
if result ~= false then
local user_id = result.id
local username = result.username
if is_chat_msg(extra.msg) then
-- check if sudo users
local is_sudoers = false
for v,sudoer in pairs(_config.sudo_users) do
if sudoer == user_id then
is_sudoers = true
end
end
if not is_sudoers then
if extra.match == 'kick' then
chat_del_user('chat#id'..chat_id, 'user#id'..result.id, ok_cb, false)
elseif extra.match == 'ban' then
ban_user(user_id, chat_id)
send_large_msg('chat#id'..chat_id, 'User @'..username..' banned')
elseif extra.match == 'superban' then
superban_user(user_id, chat_id)
send_large_msg('chat#id'..chat_id, 'User @'..username..' ['..user_id..'] globally banned!')
elseif extra.match == 'unban' then
unban_user(user_id, chat_id)
send_large_msg('chat#id'..chat_id, 'User @'..username..' unbanned', ok_cb, true)
elseif extra.match == 'superunban' then
superunban_user(user_id, chat_id)
send_large_msg('chat#id'..chat_id, 'User @'..username..' ['..user_id..'] globally unbanned!')
end
end
else
return 'Use This in Your Groups.'
end
else
send_large_msg('chat#id'..chat_id, 'No user '..string.gsub(extra.msg.text, '^.- ', '')..' in this group.')
end
end
local function trigger_anti_splooder(user_id, chat_id, splooder)
local data = load_data(_config.moderation.data)
local anti_spam_stat = data[tostring(chat_id)]['settings']['anti_flood']
if not redis:get('kicked:'..chat_id..':'..user_id) or false then
if anti_spam_stat == 'kick' then
kick_user(user_id, chat_id)
send_large_msg('chat#id'..chat_id, 'User '..user_id..' is '..splooder)
elseif anti_spam_stat == 'ban' then
ban_user(user_id, chat_id)
send_large_msg('chat#id'..chat_id, 'User '..user_id..' is '..splooder..'. Banned')
end
-- hackish way to avoid mulptiple kicking
redis:setex('kicked:'..chat_id..':'..user_id, 2, 'true')
end
msg = nil
end
local function pre_process(msg)
local user_id = msg.from.id
local chat_id = msg.to.id
-- ANTI SPAM
if msg.from.type == 'user' and msg.text and not is_mod(msg) then
local _nl, ctrl_chars = string.gsub(msg.text, '%c', '')
-- if string length more than 2048 or control characters is more than 50
if string.len(msg.text) > 2048 or ctrl_chars > 50 then
local _c, chars = string.gsub(msg.text, '%a', '')
local _nc, non_chars = string.gsub(msg.text, '%A', '')
-- if non characters is bigger than characters
if non_chars > chars then
local splooder = 'spamming'
trigger_anti_splooder(user_id, chat_id, splooder)
end
end
end
-- ANTI FLOOD
local post_count = 'floodc:'..user_id..':'..chat_id
redis:incr(post_count)
if msg.from.type == 'user' and not is_mod(msg) then
local post_count = 'user:'..user_id..':floodc'
local msgs = tonumber(redis:get(post_count) or 0)
if msgs > NUM_MSG_MAX then
local splooder = 'flooding'
trigger_anti_splooder(user_id, chat_id, splooder)
end
redis:setex(post_count, TIME_CHECK, msgs+1)
end
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat
if action == 'chat_add_user' or action == 'chat_add_user_link' then
if msg.action.link_issuer then
user_id = msg.from.id
else
user_id = msg.action.user.id
end
print('>>> banhammer : Checking invited user '..user_id)
if is_super_banned(user_id) or is_banned(user_id, chat_id) then
print('>>> banhammer : '..user_id..' is (super)banned from '..chat_id)
kick_user(user_id, chat_id)
end
end
-- No further checks
return msg
end
-- BANNED USER TALKING
if is_chat_msg(msg) then
if is_super_banned(user_id) then
print('>>> banhammer : SuperBanned user talking!')
superban_user(user_id, chat_id)
msg.text = ''
elseif is_banned(user_id, chat_id) then
print('>>> banhammer : Banned user talking!')
ban_user(user_id, chat_id)
msg.text = ''
end
end
-- WHITELIST
-- Allow all sudo users even if whitelist is allowed
if redis:get('whitelist:enabled') and not is_sudo(msg) then
print('>>> banhammer : Whitelist enabled and not sudo')
-- Check if user or chat is whitelisted
local allowed = redis:get('whitelist:user#id'..user_id) or false
if not allowed then
print('>>> banhammer : User '..user_id..' not whitelisted')
if is_chat_msg(msg) then
allowed = redis:get('whitelist:chat#id'..chat_id) or false
if not allowed then
print ('Chat '..chat_id..' not whitelisted')
else
print ('Chat '..chat_id..' whitelisted :)')
end
end
else
print('>>> banhammer : User '..user_id..' allowed :)')
end
if not allowed then
msg.text = ''
end
else
print('>>> banhammer : Whitelist not enabled or is sudo')
end
return msg
end
local function run(msg, matches)
local receiver = get_receiver(msg)
local user = 'user#id'..(matches[2] or '')
if is_chat_msg(msg) then
if matches[1] == 'kickme' then
if is_sudo(msg) or is_admin(msg) then
return 'I won\'t kick an admin!'
elseif is_mod(msg) then
return 'I won\'t kick a moderator!'
else
kick_user(msg.from.id, msg.to.id)
end
end
if is_mod(msg) then
if matches[1] == 'kick' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]})
elseif string.match(matches[2], '^%d+$') then
chat_info(receiver, action_by_id, {msg=msg, matches=matches})
elseif string.match(matches[2], '^@.+$') then
msgr = res_user(string.gsub(matches[2], '@', ''), resolve_username, {msg=msg, match=matches[1]})
end
elseif matches[1] == 'ban' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]})
elseif string.match(matches[2], '^%d+$') then
chat_info(receiver, action_by_id, {msg=msg, matches=matches})
elseif string.match(matches[2], '^@.+$') then
msgr = res_user(string.gsub(matches[2], '@', ''), resolve_username, {msg=msg, match=matches[1]})
end
elseif matches[1] == 'banlist' then
local text = 'Ban list for '..msg.to.title..' ['..msg.to.id..']:\n\n'
for k,v in pairs(redis:keys('banned:'..msg.to.id..':*')) do
text = text..k..'. '..v..'\n'
end
return string.gsub(text, 'banned:'..msg.to.id..':', '')
elseif matches[1] == 'unban' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]})
elseif string.match(matches[2], '^%d+$') then
chat_info(receiver, action_by_id, {msg=msg, matches=matches})
elseif string.match(matches[2], '^@.+$') then
msgr = res_user(string.gsub(matches[2], '@', ''), resolve_username, {msg=msg, match=matches[1]})
end
end
if matches[1] == 'antispam' then
local data = load_data(_config.moderation.data)
local settings = data[tostring(msg.to.id)]['settings']
if matches[2] == 'kick' then
if settings.anti_flood ~= 'kick' then
settings.anti_flood = 'kick'
save_data(_config.moderation.data, data)
end
return 'Anti flood and spam protection already enabled.\nOffender will be kicked.'
end
if matches[2] == 'ban' then
if settings.anti_flood ~= 'ban' then
settings.anti_flood = 'ban'
save_data(_config.moderation.data, data)
end
return 'Anti flood and spam protection already enabled.\nOffender will be banned.'
end
if matches[2] == 'disable' then
if settings.anti_flood == 'no' then
return 'Anti flood and spam protection is not enabled.'
else
settings.anti_flood = 'no'
save_data(_config.moderation.data, data)
return 'Anti flood and spam protection has been disabled.'
end
end
end
if matches[1] == 'whitelist' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]})
end
if matches[2] == 'enable' then
redis:set('whitelist:enabled', true)
return 'Enabled whitelist'
elseif matches[2] == 'disable' then
redis:del('whitelist:enabled')
return 'Disabled whitelist'
elseif matches[2] == 'user' then
redis:set('whitelist:user#id'..matches[3], true)
return 'User '..matches[3]..' whitelisted'
elseif matches[2] == 'delete' and matches[3] == 'user' then
redis:del('whitelist:user#id'..matches[4])
return 'User '..matches[4]..' removed from whitelist'
elseif matches[2] == 'chat' then
redis:set('whitelist:chat#id'..msg.to.id, true)
return 'Chat '..msg.to.id..' whitelisted'
elseif matches[2] == 'delete' and matches[3] == 'chat' then
redis:del('whitelist:chat#id'..msg.to.id)
return 'Chat '..msg.to.id..' removed from whitelist'
end
elseif matches[1] == 'unwhitelist' and msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]})
end
end
if is_admin(msg) then
if matches[1] == 'superban' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]})
elseif string.match(matches[2], '^%d+$') then
chat_info(receiver, action_by_id, {msg=msg, matches=matches})
elseif string.match(matches[2], '^@.+$') then
msgr = res_user(string.gsub(matches[2], '@', ''), resolve_username, {msg=msg, match=matches[1]})
end
elseif matches[1] == 'superunban' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]})
elseif string.match(matches[2], '^%d+$') then
chat_info(receiver, action_by_id, {msg=msg, matches=matches})
elseif string.match(matches[2], '^@.+$') then
msgr = res_user(string.gsub(matches[2], '@', ''), resolve_username, {msg=msg, match=matches[1]})
end
end
end
else
print '>>> This is not a chat group.'
end
end
return {
description = 'Plugin to manage bans, kicks and white/black lists.',
usage = {
user = {
'!kickme : Kick yourself out of this group.'
},
admin = {
'!superban : If type in reply, will ban user globally.',
'!superban <user_id>/@<username> : Kick user_id/username from all chat and kicks it if joins again',
'!superunban : If type in reply, will unban user globally.',
'!superunban <user_id>/@<username> : Unban user_id/username globally.'
},
moderator = {
'!antispam kick : Enable flood and spam protection. Offender will be kicked.',
'!antispam ban : Enable flood and spam protection. Offender will be banned.',
'!antispam disable : Disable flood and spam protection',
'!ban : If type in reply, will ban user from chat group.',
'!ban <user_id>/<@username>: Kick user from chat and kicks it if joins chat again',
'!banlist : List users banned from chat group.',
'!unban : If type in reply, will unban user from chat group.',
'!unban <user_id>/<@username>: Unban user',
'!kick : If type in reply, will kick user from chat group.',
'!kick <user_id>/<@username>: Kick user from chat group',
'!whitelist : If type in reply, allow user to use the bot when whitelist mode is enabled',
'!whitelist chat: Allow everybody on current chat to use the bot when whitelist mode is enabled',
'!whitelist delete chat: Remove chat from whitelist',
'!whitelist delete user <user_id>: Remove user from whitelist',
'!whitelist <enable>/<disable>: Enable or disable whitelist mode',
'!whitelist user <user_id>: Allow user to use the bot when whitelist mode is enabled',
'!unwhitelist : If type in reply, remove user from whitelist'
},
},
patterns = {
'^!(antispam) (.*)$',
'^!(ban) (.*)$',
'^!(ban)$',
'^!(banlist)$',
'^!(unban) (.*)$',
'^!(unban)$',
'^!(kick) (.+)$',
'^!(kick)$',
'^!(kickme)$',
'^!!tgservice (.+)$',
'^!(whitelist)$',
'^!(whitelist) (chat)$',
'^!(whitelist) (delete) (chat)$',
'^!(whitelist) (delete) (user) (%d+)$',
'^!(whitelist) (disable)$',
'^!(whitelist) (enable)$',
'^!(whitelist) (user) (%d+)$',
'^!(unwhitelist)$',
'^!(superban)$',
'^!(superban) (.*)$',
'^!(superunban)$',
'^!(superunban) (.*)$'
},
run = run,
pre_process = pre_process
}
end
| gpl-2.0 |
1lann/Convorse | luaclient/client.lua | 1 | 17862 | local debugLog = {}
local function log(...)
local receive = {...}
for k,v in pairs(receive) do
if type(v) == "table" then
receive[k] = textutils.serialize(v)
end
end
local insert = table.concat(receive, ", ")
for line in insert:gmatch("[^\n]+") do
table.insert(debugLog, line)
end
end
local args = {...}
local username = "1lann"
local password = "awdaw"
local activeConversations = {
{
name = "2lann",
id = "awdu892qe",
lastUpdate = 123123,
unread = true,
selected = false,
inTabBar = true,
x = 0,
y = 0,
width = 0,
},
{
name = "gravityscore",
id = "awdawddw",
lastUpdate = 123122,
unread = false,
selected = true,
inTabBar = true,
x = 0,
y = 0,
width = 0,
}
}
local cachedMessages = {
["awdu892qe"] = {
lastUpdate = 123, -- In os.clock() time
{
origin = "2lann",
message = "Hello! This is a reasonably long message to test out text wrapping!",
humanTime = "4 hours ago",
timestamp = 129,
},
{
origin = "2lann",
message = "aHello! This is a reasonably long message to test out text wrapping!",
humanTime = "4 hours ago",
timestamp = 128,
},
{
origin = "2lann",
message = "bHello! This is a reasonably long message to test out text wrapping!",
humanTime = "4 hours ago",
timestamp = 127,
},
{
origin = "2lann",
message = "fHello! This is a reasonably long message to test out text wrapping!",
humanTime = "4 hours ago",
timestamp = 126,
},
{
origin = "2lann",
message = "Hgello! This is a reasonably long message to test out text wrapping!",
humanTime = "4 hours ago",
timestamp = 125,
},
{
origin = "1lann",
message = "hih",
humanTime = "5 hours ago",
timestamp = 124,
},
}
}
local messagePostTracker = {}
---
--- User interface tools
---
local theme = {
background = colors.white,
accent = colors.blue,
text = colors.black,
header = colors.white,
input = colors.white,
inputText = colors.gray,
placeholder = colors.lightGray,
err = colors.red,
subtle = colors.lightGray,
selected = colors.blue,
unfocusedText = colors.lightBlue,
selfOrigin = colors.lightBlue,
externalOrigin = colors.blue,
new = colors.red,
timestamp = colors.lightGray,
message = colors.gray,
}
-- if not term.isColor() then
-- theme = {
-- background = colors.white,
-- accent = colors.black,
-- text = colors.black,
-- header = colors.white,
-- input = colors.white,
-- inputText = colors.black,
-- placeholder = colors.black,
-- err = colors.black,
-- subtle = colors.white,
-- selected = colors.white,
-- selectedText = colors.black,
-- newIndicator = colors.red
-- }
-- end
local t = {
bg = term.setBackgroundColor,
tc = term.setTextColor,
p = term.setCursorPos,
gp = term.getCursorPos,
c = term.clear,
cl = term.clearLine,
w = function(text)
local x, y = term.getCursorPos()
term.write(text)
return {x = x, y = y, width = #text}
end,
nl = function(num)
if not num then num = 1 end
local x, y = term.getCursorPos()
term.setCursorPos(1, y + num)
end,
up = function()
local x, y = term.getCursorPos()
term.setCursorPos(1, y - 1)
end,
o = function() term.setCursorPos(1, 1) end,
db = function(height)
local x, y = term.getCursorPos()
for i = 1, height do
term.setCursorPos(1, y + i - 1)
term.clearLine()
end
term.setCursorPos(x, y)
end
}
local w, h = term.getSize()
local isPocket = false
if w < 40 then
isPocket = true
end
local center = function(text, shift)
if not shift then shift = 0 end
local x, y = t.gp()
t.p(math.ceil(w / 2 - text:len() / 2) + 1 + shift, y)
t.w(text)
t.p(1, y + 1)
return {math.ceil(w / 2 - text:len() / 2) + 1 + shift, y}
end
local right = function(text)
local x, y = t.gp()
t.p(w - #text + 1, y)
t.w(text)
t.p(1, y + 1)
return {x = w - #text, y = y, width = #text - 1}
end
---
--- HTTP API and Fetching
---
local lastUpdateUnix = 0
local updatedConversationEvent = "convorse_conversation_update"
local messagePostResponseEvent = "convorse_message_post"
local generalErrorEvent = "convorse_general_error"
local databaseErrorEvent = "convorse_database_error"
local authErrorEvent = "convorse_auth_error"
local apiURL = "http://convorse.tk/api/"
local patternURL = "http://convorse%.tk/api/"
local pollTimer
local pollStart = -40
local pollURL = apiURL .. "poll"
local function parseServerResponse(text)
end
local function getConversation(id)
http.request(apiURL .. "conversation", {
username = username,
password = password,
conversation = id
})
end
local function getUnread()
http.request(apiURL .. "unread", {
username = username,
password = password
})
end
local function postMessage(conversation, message, callbackInfo)
http.request(apiURL .. "post", {
username = username,
password = password,
conversation = conversation,
message = message,
callback = callbackInfo,
})
end
local function getConversationByUsername(user)
http.request(apiURL .. "user-conversation", {
username = username,
password = password,
user = user
})
end
local function markAsRead(conversation)
http.request(apiURL .. "mark-as-read", {
username = username,
password = password,
user = user
})
end
local function poll(force)
if (os.clock() > pollStart + 10) or force then
http.request(pollURL, {
username = username,
password = password,
lastUpdate = lastUpdateUnix,
})
pollTimer = os.startTimer(35)
pollStart = os.clock()
end
end
local successHandlers = {
["conversation"] = function(resp)
local result = resp.readAll()
if not result then
os.queueEvent(generalErrorEvent, {"Empty response while", "fetching conv. data"})
else
local parseResult = parseServerResponse(result)
if parseResult == "success" then
os.queueEvent(updatedConversationEvent)
elseif parseResult == "database" then
os.queueEvent(databaseErrorEvent)
elseif parseResult == "server-error" then
os.queueEvent(generalErrorEvent, {"Server Error", "on conversation"})
elseif parseResult == "auth-error" then
os.queueEvent(authErrorEvent)
else
os.queueEvent(generalErrorEvent, {"Parse Error", "on conversation"})
end
end
end,
["user-conversation"] = function(resp)
local result = resp.readAll()
if not result then
os.queueEvent(generalErrorEvent, {"Empty response while", "fetching user conv. data"})
else
local parseResult = parseServerResponse(result)
if parseResult == "success" then
os.queueEvent(updatedConversationEvent)
elseif parseResult == "database" then
os.queueEvent(databaseErrorEvent)
elseif parseResult == "server-error" then
os.queueEvent(generalErrorEvent, {"Server Error", "on user conversation"})
elseif parseResult == "auth-error" then
os.queueEvent(authErrorEvent)
else
os.queueEvent(generalErrorEvent, {"Parse Error", "on user conversation"})
end
end
end,
["unread"] = function(resp)
local result = resp.readAll()
if not result then
os.queueEvent(generalErrorEvent, {"Empty response while", "fetching unread data"})
else
local parseResult = parseServerResponse(result)
if parseResult == "success" then
os.queueEvent(updatedConversationEvent)
elseif parseResult == "database" then
os.queueEvent(databaseErrorEvent)
elseif parseResult == "server-error" then
os.queueEvent(generalErrorEvent, {"Server Error", "on unread"})
elseif parseResult == "auth-error" then
os.queueEvent(authErrorEvent)
else
os.queueEvent(generalErrorEvent, {"Parse Error", "on unread"})
end
end
end,
["post"] = function(resp)
local result = resp.readAll()
if not result then
os.queueEvent(messagePostResponseEvent, "failure")
else
local parseResult, callbackInfo = parseServerResponse(result)
if parseResult == "success" then
os.queueEvent(messagePostResponseEvent, "success", callbackInfo)
elseif parseResult == "database" then
os.queueEvent(databaseErrorEvent)
elseif parseResult == "server-error" then
os.queueEvent(generalErrorEvent, {"Server Error", "on message post"})
elseif parseResult == "auth-error" then
os.queueEvent(authErrorEvent)
else
os.queueEvent(generalErrorEvent, {"Parse Error", "on message post"})
end
end
end,
["poll"] = function(resp)
local result = resp.readAll()
if not result then
-- Retry
poll(true)
else
local parseResult = parseServerResponse(result)
if parseResult == "success" then
os.queueEvent(updatedConversationEvent, "poll")
poll(true)
elseif parseResult == "poll-timeout" then
poll(true)
elseif parseResult == "database" then
os.queueEvent(databaseErrorEvent)
elseif parseResult == "server-error" then
os.queueEvent(generalErrorEvent, {"Server Error", "on polling"})
elseif parseResult == "auth-error" then
os.queueEvent(authErrorEvent)
else
os.queueEvent(generalErrorEvent, {"Parse Error", "on polling"})
end
end
end,
["mark-as-read"] = function()
local result = resp.readAll()
if result then
local parseResult = parseServerResponse(result)
if parseResult == "success" then
elseif parseResult == "database" then
os.queueEvent(databaseErrorEvent)
elseif parseResult == "server-error" then
os.queueEvent(generalErrorEvent, {"Server Error", "on reading message"})
elseif parseResult == "auth-error" then
os.queueEvent(authErrorEvent)
end
end
end
}
local failureHandlers = {
["conversation"] = function()
os.queueEvent(generalErrorEvent, {"HTTP error while", "fetching conv. data"})
end,
["user-conversation"] = function()
os.queueEvent(generalErrorEvent, {"HTTP error while", "fetching user-conv. data"})
end,
["unread"] = function()
os.queueEvent(generalErrorEvent, {"HTTP error while", "fetching unread data"})
end,
["post"] = function()
os.queueEvent(messagePostResponseEvent, "failure")
end,
["poll"] = function()
poll()
end,
}
local function fetchManager()
while true do
local event, url, resp = os.pullEvent()
if event == "http_success" then
if successHandlers[url:gsub(patternURL, "")] then
successHandlers[url:gsub(patternURL, "")]()
end
elseif event == "http_failure" then
if failureHandlers[url:gsub(patternURL, "")] then
failureHandlers[url:gsub(patternURL, "")]()
end
elseif event == "timer" then
if url == pollTimer then
poll()
end
end
end
end
---
--- Processing help
---
local function processConversation(conversationID)
local conversationMessages = cachedMessages[conversationID]
if not conversationMessages then return nil end
local displaySim = {}
table.sort(conversationMessages, function(a, b)
return a.timestamp < b.timestamp
end)
for k,v in pairs(conversationMessages) do
if type(v) == "table" then
local selfOrigin = false
if v.origin == username then
selfOrigin = true
end
-- if not (k - 1 > 0 and conversationMessages[k - 1].origin == v.origin) then
local displayName = ""
if isPocket then
if #v.origin > 12 then
displayName = "<" .. v.origin:sub(1, 12) .. ">"
else
displayName = "<" .. v.origin .. ">"
end
else
if #v.origin > 22 then
displayName = "<" .. v.origin:sub(1, 22) .. ">"
else
displayName = "<" .. v.origin .. ">"
end
end
-- table.insert(displaySim, {spacer = true})
table.insert(displaySim, {block = true, selfOrigin = selfOrigin, username = true, content = displayName, humanTime = v.humanTime})
-- end
local message = v.message
local availableWidth = w
if not isPocket then
availableWidth = 40
end
local textWrapper = {}
local wrapLine = ""
for word in message:gmatch("%S+") do
if #(wrapLine .. word) > availableWidth then
table.insert(textWrapper, wrapLine:sub(1, -2))
wrapLine = ""
end
wrapLine = wrapLine .. word .. " "
end
table.insert(textWrapper, wrapLine)
for k,v in pairs(textWrapper) do
table.insert(displaySim, {block = true, selfOrigin = selfOrigin, content = v})
end
table.insert(displaySim, {spacer = true})
end
end
return displaySim
end
---
--- Drawing the loading screen
---
local function drawLoadingHeader()
t.bg(theme.background)
t.c()
t.o()
t.tc(theme.header)
t.bg(theme.accent)
t.db(4)
t.nl()
center("- Convorse -")
center("A web chat client")
t.nl()
end
local function drawLoading()
drawLoadingHeader()
t.nl(5)
t.tc(theme.accent)
t.bg(theme.background)
center("Logged in!")
t.nl()
t.tc(theme.placeholder)
center("Loading...")
sleep(3)
return
end
-- drawLoading()
---
--- Draw the main interface
---
unreadInteractivity = {}
local function drawTopMenuBar()
t.p(1, 1)
t.bg(theme.accent)
t.tc(theme.header)
t.db(1)
if not isPocket then
t.w(" ")
end
if not isPocket then
if #username > 15 then
t.w("Convorse | " .. username:sub(1, 15))
else
t.w("Convorse | " .. username)
end
else
if #username > 9 then
t.w("Convorse|" .. username:sub(1,9))
else
t.w("Convorse|" .. username)
end
end
t.tc(colors.lightBlue)
if isPocket then
right("Log Out")
else
right("Log Out ")
end
end
local function drawTabMenuBar()
t.bg(theme.accent)
t.cl()
if not isPocket then
t.w(" ")
end
for k, conversation in pairs(activeConversations) do
if conversation.inTabBar then
local toWrite
local maxLimit = 5
if not isPocket then
maxLimit = 8
end
if #conversation.name > maxLimit then
toWrite = conversation.name:sub(1, maxLimit) .. " "
else
toWrite = conversation.name .. " "
end
local x, y = t.gp()
if w - x + 1 < (#toWrite + 2) then
conversation.x = nil
conversation.y = nil
conversation.width = nil
break
end
conversation.x, conversation.y = x, y
if conversation.unread then
t.tc(theme.unfocusedText)
t.w("*")
end
if conversation.selected then
t.bg(theme.selected)
t.tc(theme.header)
else
t.bg(theme.accent)
t.tc(theme.unfocusedText)
end
if not conversation.unread then
t.w(" ")
end
t.w(toWrite)
conversation.width = #toWrite
end
end
t.bg(theme.accent)
t.tc(theme.header)
t.w("+")
end
local function drawMenuBar()
drawTopMenuBar()
drawTabMenuBar()
end
local function clear()
t.bg(theme.background)
t.c()
drawMenuBar()
end
local function drawChatArea(conversationID, scroll)
if not scroll then
scroll = 0
end
local conversation
for k, v in pairs(activeConversations) do
if v.id == conversationID then
conversation = v
v.selected = true
else
v.selected = false
end
end
local conversationRender = processConversation(conversationID)
t.bg(theme.background)
for i = 3, h do
t.p(1, i)
t.cl()
end
if not conversation or not conversationRender then
t.p(1,10)
t.bg(theme.background)
t.tc(theme.err)
if not isPocket then
center("Error loading conversation!")
else
center("Error loading")
center("conversation!")
end
return
end
t.p(1, h)
local screenIncrement = 3
for i = #conversationRender - scroll - (h - 4), #conversationRender - scroll do
if conversationRender[i] then
-- log(conversationRender[i])
if isPocket then
t.p(1, screenIncrement)
else
t.p(6, screenIncrement)
end
if conversationRender[i].block then
t.tc(theme.message)
if conversationRender[i].selfOrigin then
if conversationRender[i].username then
t.tc(theme.selfOrigin)
end
else
if conversationRender[i].username then
t.tc(theme.externalOrigin)
end
end
t.w(string.rep(" ", 40))
if isPocket then
t.p(1, screenIncrement)
else
t.p(6, screenIncrement)
end
t.w(conversationRender[i].content)
if conversationRender[i].humanTime then
t.bg(theme.background)
t.tc(theme.timestamp)
if isPocket then
right(conversationRender[i].humanTime)
else
right(conversationRender[i].humanTime .. string.rep(" ", 6))
end
end
end
screenIncrement = screenIncrement + 1
end
end
end
local function drawHome()
t.p(1,3)
t.nl()
t.bg(theme.background)
t.tc(theme.text)
center("Welcome, " .. username)
t.nl()
local unread = 0
for k,v in pairs(activeConversations) do
if v.unread then
unread = unread + 1
end
end
if unread <= 0 then
if isPocket then
center("You have no")
center("unread conversations")
else
center("You have no unread conversations")
end
else
if not isPocket then
t.w(" ")
end
t.w("Unread conversations:")
t.nl()
t.tc(theme.accent)
for k,v in pairs(activeConversations) do
if v.unread then
if not isPocket then
t.w(" ")
end
table.insert(unreadInteractivity, t.w(v.name))
end
end
end
t.tc(theme.text)
if isPocket then
t.p(1, h - 3)
center("Click on the in the")
t.tc(theme.header)
t.bg(theme.accent)
t.up()
center("+", 3)
t.tc(theme.text)
t.bg(theme.background)
center("tab bar to start")
center("a new conversation")
else
t.p(1, h - 2)
center("Click on the in the tab bar to")
t.tc(theme.header)
t.bg(theme.accent)
t.up()
center("+", -2)
t.tc(theme.text)
t.bg(theme.background)
center("start a new conversation")
end
end
clear()
log("Program start")
local scroll = 0
while true do
local event, amount = os.pullEvent()
if event == "mouse_scroll" then
scroll = scroll + amount
drawChatArea("awdu892qe", scroll)
elseif event == "key" and amount == 28 then
break
end
end
log("Program end")
log({"This is a table", "with string! :D"}, "\nMutli variable too!", 123)
os.pullEvent("key")
term.setBackgroundColor(colors.black)
term.setTextColor(colors.yellow)
term.setCursorPos(1,2)
term.clear()
print("Debugger - Events:")
term.setTextColor(colors.white)
for k,v in pairs(debugLog) do
textutils.pagedPrint(v)
end
os.pullEvent("key")
return shell.run(shell.getRunningProgram())
| mit |
cyberz-eu/octopus | extensions/shop/src/controller/account/AccountOrderPageController.lua | 1 | 2244 | local json = require "json"
local parse = require "parse"
local param = require "param"
local property = require "property"
local localization = require "localization"
local database = require "database"
local exception = require "exception"
local exceptionHandler = require "exceptionHandler"
local util = require "util"
local localeService = require "localeService"
local priceService = require "priceService"
local cartService = require "cartService"
local function process (db, data)
local op = db:operators()
local locale = localeService.getLocale(db)
data.locale = locale
if util.isNotEmpty(param.order) then
local order = db:findOne({order = {id = op.equal(param.order)}})
data.order = cartService.convertCart(db, order)
else
exception("order is required")
end
end
local data = {}
local db = database.connect()
local status, err = pcall(process, db, data)
db:close()
if not status then
exceptionHandler.toData(data, err)
end
ngx.say(parse(require("BaselineHtmlTemplate"), {
title = "Account Order",
externalJS = [[
<script type="text/javascript" src="/baseline/static/js/init-shop.js"></script>
]],
externalCSS = [[
<link href="/shop/static/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
<link rel="stylesheet" href="/shop/static/style.css" type="text/css" />
]],
initJS = parse([[
var vars = {}
vars.locale = {{locale}}
Widget.setContainerToPage([
[
{size: "12u", widget: new Widget.ShopHeader()}
],
[
{size: "3u", medium: "6u", small: "12u", widget: new Widget.Logo()},
{size: "3u", medium: "6u", small: "12u", widget: new Widget.CallUs()},
{size: "3u", medium: "6u", small: "12u", widget: new Widget.Search()},
{size: "3u", medium: "6u", small: "12u", widget: new Widget.MiniCart()}
],
[
{size: "12u", widget: new Widget.Error({{error}})}
],
[
{size: "6u", medium: "8u", small: "12u", widget: "<h2>My Account</h2>"}
],
[
{size: "3u", medium: "6u", small: "12u", widget: new Widget.AccountOptions()},
{size: "9u", medium: "6u", small: "12u", widget: new Widget.Order({{order}})}
]
]);
]], json.encodeProperties(data))
})) | bsd-2-clause |
RokaRoka/MistyWitches | hump/camera.lua | 20 | 6067 | --[[
Copyright (c) 2010-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.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
local _PATH = (...):match('^(.*[%./])[^%.%/]+$') or ''
local cos, sin = math.cos, math.sin
local camera = {}
camera.__index = camera
-- Movement interpolators (for camera locking/windowing)
camera.smooth = {}
function camera.smooth.none()
return function(dx,dy) return dx,dy end
end
function camera.smooth.linear(speed)
assert(type(speed) == "number", "Invalid parameter: speed = "..tostring(speed))
return function(dx,dy, s)
-- normalize direction
local d = math.sqrt(dx*dx+dy*dy)
local dts = math.min((s or speed) * love.timer.getDelta(), d) -- prevent overshooting the goal
if d > 0 then
dx,dy = dx/d, dy/d
end
return dx*dts, dy*dts
end
end
function camera.smooth.damped(stiffness)
assert(type(stiffness) == "number", "Invalid parameter: stiffness = "..tostring(stiffness))
return function(dx,dy, s)
local dts = love.timer.getDelta() * (s or stiffness)
return dx*dts, dy*dts
end
end
local function new(x,y, zoom, rot, smoother)
x,y = x or love.graphics.getWidth()/2, y or love.graphics.getHeight()/2
zoom = zoom or 1
rot = rot or 0
smoother = smoother or camera.smooth.none() -- for locking, see below
return setmetatable({x = x, y = y, scale = zoom, rot = rot, smoother = smoother}, camera)
end
function camera:lookAt(x,y)
self.x, self.y = x, y
return self
end
function camera:move(dx,dy)
self.x, self.y = self.x + dx, self.y + dy
return self
end
function camera:position()
return self.x, self.y
end
function camera:rotate(phi)
self.rot = self.rot + phi
return self
end
function camera:rotateTo(phi)
self.rot = phi
return self
end
function camera:zoom(mul)
self.scale = self.scale * mul
return self
end
function camera:zoomTo(zoom)
self.scale = zoom
return self
end
function camera:attach(x,y,w,h, noclip)
x,y = x or 0, y or 0
w,h = w or love.graphics.getWidth(), h or love.graphics.getHeight()
self._sx,self._sy,self._sw,self._sh = love.graphics.getScissor()
if not noclip then
love.graphics.setScissor(x,y,w,h)
end
local cx,cy = x+w/2, y+h/2
love.graphics.push()
love.graphics.translate(cx, cy)
love.graphics.scale(self.scale)
love.graphics.rotate(self.rot)
love.graphics.translate(-self.x, -self.y)
end
function camera:detach()
love.graphics.pop()
love.graphics.setScissor(self._sx,self._sy,self._sw,self._sh)
end
function camera:draw(...)
local x,y,w,h,noclip,func
local nargs = select("#", ...)
if nargs == 1 then
func = ...
elseif nargs == 5 then
x,y,w,h,func = ...
elseif nargs == 6 then
x,y,w,h,noclip,func = ...
else
error("Invalid arguments to camera:draw()")
end
self:attach(x,y,w,h,noclip)
func()
self:detach()
end
-- world coordinates to camera coordinates
function camera:cameraCoords(x,y, ox,oy,w,h)
ox, oy = ox or 0, oy or 0
w,h = w or love.graphics.getWidth(), h or love.graphics.getHeight()
-- x,y = ((x,y) - (self.x, self.y)):rotated(self.rot) * self.scale + center
local c,s = cos(self.rot), sin(self.rot)
x,y = x - self.x, y - self.y
x,y = c*x - s*y, s*x + c*y
return x*self.scale + w/2 + ox, y*self.scale + h/2 + oy
end
-- camera coordinates to world coordinates
function camera:worldCoords(x,y, ox,oy,w,h)
ox, oy = ox or 0, oy or 0
w,h = w or love.graphics.getWidth(), h or love.graphics.getHeight()
-- x,y = (((x,y) - center) / self.scale):rotated(-self.rot) + (self.x,self.y)
local c,s = cos(-self.rot), sin(-self.rot)
x,y = (x - w/2 - ox) / self.scale, (y - h/2 - oy) / self.scale
x,y = c*x - s*y, s*x + c*y
return x+self.x, y+self.y
end
function camera:mousePosition(ox,oy,w,h)
local mx,my = love.mouse.getPosition()
return self:worldCoords(mx,my, ox,oy,w,h)
end
-- camera scrolling utilities
function camera:lockX(x, smoother, ...)
local dx, dy = (smoother or self.smoother)(x - self.x, self.y, ...)
self.x = self.x + dx
return self
end
function camera:lockY(y, smoother, ...)
local dx, dy = (smoother or self.smoother)(self.x, y - self.y, ...)
self.y = self.y + dy
return self
end
function camera:lockPosition(x,y, smoother, ...)
return self:move((smoother or self.smoother)(x - self.x, y - self.y, ...))
end
function camera:lockWindow(x, y, x_min, x_max, y_min, y_max, smoother, ...)
-- figure out displacement in camera coordinates
x,y = self:cameraCoords(x,y)
local dx, dy = 0,0
if x < x_min then
dx = x - x_min
elseif x > x_max then
dx = x - x_max
end
if y < y_min then
dy = y - y_min
elseif y > y_max then
dy = y - y_max
end
-- transform displacement to movement in world coordinates
local c,s = cos(-self.rot), sin(-self.rot)
dx,dy = (c*dx - s*dy) / self.scale, (s*dx + c*dy) / self.scale
-- move
self:move((smoother or self.smoother)(dx,dy,...))
end
-- the module
return setmetatable({new = new, smooth = camera.smooth},
{__call = function(_, ...) return new(...) end})
| mit |
cyberz-eu/octopus | extensions/security/src/module/UserService.lua | 1 | 5248 | local uuid = require "uuid"
local cookie = require "cookie"
local exception = require "exception"
local util = require "util"
local fileutil = require "fileutil"
local crypto = require "crypto"
local function authenticate (db, email, password)
local property = require "property"
local op = db:operators()
if util.isNotEmpty(email) and util.isNotEmpty(password) then
local user = db:findOne({user = {email = op.equal(email)}})
-- failed authentication policy
if user.failedLoginAttempts and user.failedLoginAttempts - property.failedLoginAttempts >= 0 then
if user.lastFailedLoginTime then
local elapsedTime = os.time() - user.lastFailedLoginTime
if elapsedTime < 0 or elapsedTime < property.failedLoginAttemptsTimeout then
user.token = "" -- terminate session
user.lastFailedLoginTime = os.time()
db:update({user = user})
return
end
else
user.token = "" -- terminate session
user.lastFailedLoginTime = os.time()
db:update({user = user})
return
end
end
local hash = crypto.passwordKey(password, crypto.decodeBase64(user.passwordSalt), 32)
if hash == crypto.decodeBase64(user.passwordHash) then
-- failed authentication policy
user.failedLoginAttempts = 0
user.lastFailedLoginTime = os.time()
db:update({user = user})
return user -- user is successfully authenticated!
else
-- failed authentication policy
user.failedLoginAttempts = user.failedLoginAttempts + 1
user.lastFailedLoginTime = os.time()
if user.failedLoginAttempts >= property.failedLoginAttempts then user.token = "" end -- terminate session
db:update({user = user})
return
end
end
end
local function setToken (db, user)
local property = require "property"
uuid.seed(db:timestamp())
user.token = uuid()
user.lastLoginTime = os.time()
-- persist user's token and lastLoginTime
db:update({user = user})
-- set token in cookie
local ok, err = cookie:set({
key = "token",
value = user.token,
path = "/",
domain = ngx.var.host,
max_age = property.sessionTimeout,
secure = util.requireSecureToken(),
httponly = true
})
if not ok then
exception(err)
end
end
--
-- NOTE: ngx.ctx.user holds the user for the whole request
--
local function authenticatedUser (db)
local property = require "property"
local op = db:operators()
if ngx.ctx.user then
return ngx.ctx.user
end
local token, err = cookie:get("token")
if util.isEmpty(token) or err then
return false
end
local user = db:findOne({user = {token = op.equal(token)}})
if util.isNotEmpty(user.lastLoginTime) then
local elapsedTime = os.time() - user.lastLoginTime
if elapsedTime >= 0 and elapsedTime <= property.sessionTimeout then
ngx.ctx.user = user
return user
end
end
end
local function authorize (db, user, permissions, groups)
if permissions then
for j=1,#permissions do
-- try finding permission in user.permissions
local filtered = user.permissions({code = permissions[j]})
if #filtered == 0 then
-- if not found yet search permission in user.groups
local found = false
for i=1,#user.groups do
-- try finding permission in user.groups[i]
local filtered = user.groups[i].permissions({code = permissions[j]})
if #filtered > 0 then found = true end
end
if not found then return false end
end
end
end
if groups then
for i=1,#groups do
-- try finding group in user.groups
local filtered = user.groups({code = groups[i]})
if #filtered == 0 then return false end
end
end
return true
end
local function loginAndSetToken (db, email, password)
local user = authenticate(db, email, password)
if user then
setToken(db, user)
return true
end
return false
end
local function loggedIn (db, permissions, groups)
local user = authenticatedUser(db)
if user then
return authorize(db, user, permissions, groups)
end
return false
end
local function register (db, email, password)
local hash, salt = crypto.passwordKey(password, nil, 32)
if util.isNotEmpty(hash) and util.isNotEmpty(salt) then
local passwordHash = crypto.encodeBase64(hash)
local passwordSalt = crypto.encodeBase64(salt)
return db:add({user = {email = email, passwordHash = passwordHash, passwordSalt = passwordSalt}})
end
end
local function registerAndSetToken (db, email, password)
local op = db:operators()
local id = register(db, email, password)
local user = db:findOne({user = {id = op.equal(id)}})
setToken(db, user)
end
local function redirectTo (url)
local to
local uri = ngx.var.uri
if uri ~= url then
to = uri:sub(url:len() + 1, uri:len())
local args = ngx.var.args
if util.isNotEmpty(args) then
to = to .. "?" .. args
end
end
return to
end
-- module table --
return {
authenticate = authenticate,
setToken = setToken,
authenticatedUser = authenticatedUser,
authorize = authorize,
loginAndSetToken = loginAndSetToken,
loggedIn = loggedIn,
register = register,
registerAndSetToken = registerAndSetToken,
redirectTo = redirectTo,
} | bsd-2-clause |
nstockton/mushclient-mume | lua/dkjson.lua | 2 | 23130 | -- Module options:
local always_try_using_lpeg = true
local register_global_module_table = false
local global_module_name = 'json'
--[==[
David Kolf's JSON module for Lua 5.1/5.2
Version 2.5
For the documentation see the corresponding readme.txt or visit
<http://dkolf.de/src/dkjson-lua.fsl/>.
You can contact the author by sending an e-mail to 'david' at the
domain 'dkolf.de'.
Copyright (C) 2010-2013 David Heiko Kolf
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]==]
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset
local error, require, pcall, select = error, require, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
local json = { version = "dkjson 2.5" }
if register_global_module_table then
_G[global_module_name] = json
end
local _ENV = nil -- blocking globals in Lua 5.2
pcall (function()
-- Enable access to blocked metatables.
-- Don't worry, this module doesn't change anything in them.
local debmeta = require "debug".getmetatable
if debmeta then getmetatable = debmeta end
end)
json.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
json.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function json.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder, state)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder, state)
end
local function appendcustom(res, buffer, state)
local buflen = state.bufferlen
if type (res) == 'string' then
buflen = buflen + 1
buffer[buflen] = res
end
return buflen
end
local function exception(reason, value, state, buffer, buflen, defaultmessage)
defaultmessage = defaultmessage or reason
local handler = state.exception
if not handler then
return nil, defaultmessage
else
state.bufferlen = buflen
local ret, msg = handler (reason, value, state, defaultmessage)
if not ret then return nil, msg or defaultmessage end
return appendcustom(ret, buffer, state)
end
end
function json.encodeexception(reason, value, state, defaultmessage)
return quotestring("<" .. defaultmessage .. ">")
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder, state)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return exception('reference cycle', value, state, buffer, buflen)
end
tables[value] = true
state.bufferlen = buflen
local ret, msg = valtojson (value, state)
if not ret then return exception('custom encoder failed', value, state, buffer, buflen, msg) end
tables[value] = nil
buflen = appendcustom(ret, buffer, state)
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return exception('reference cycle', value, state, buffer, buflen)
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder, state)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder, state)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder, state)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder, state)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return exception ('unsupported type', value, state, buffer, buflen,
"type '" .. valtype .. "' is not supported by JSON.")
end
return buflen
end
function json.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
state.buffer = buffer
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder, state)
if not ret then
error (msg, 2)
elseif oldbuffer == buffer then
state.bufferlen = ret
return true
else
state.bufferlen = nil
state.buffer = nil
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
local sub2 = strsub (str, pos, pos + 1)
if sub2 == "\239\187" and strsub (str, pos + 2, pos + 2) == "\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
elseif sub2 == "//" then
pos = strfind (str, "[\n\r]", pos + 2)
if not pos then return nil end
elseif sub2 == "/*" then
pos = strfind (str, "*/", pos + 2)
if not pos then return nil end
pos = pos + 2
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function json.use_lpeg ()
local g = require ("lpeg")
if g.version() == "0.11" then
error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
end
local pegmatch = g.match
local P, S, R = g.P, g.S, g.R
local function ErrorCall (str, pos, msg, state)
if not state.msg then
state.msg = msg .. " at " .. loc (str, pos)
state.pos = pos
end
return false
end
local function Err (msg)
return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall)
end
local SingleLineComment = P"//" * (1 - S"\n\r")^0
local MultiLineComment = P"/*" * (1 - P"*/")^0 * P"*/"
local Space = (S" \n\r\t" + P"\239\187\191" + SingleLineComment + MultiLineComment)^0
local PlainChar = 1 - S"\"\\\n\r"
local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars
local HexDigit = R("09", "af", "AF")
local function UTF16Surrogate (match, pos, high, low)
high, low = tonumber (high, 16), tonumber (low, 16)
if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then
return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
else
return false
end
end
local function UTF16BMP (hex)
return unichar (tonumber (hex, 16))
end
local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit))
local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP
local Char = UnicodeEscape + EscapeSequence + PlainChar
local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string")
local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0))
local Fractal = P"." * R"09"^0
local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1
local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num
local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1)
local SimpleValue = Number + String + Constant
local ArrayContent, ObjectContent
-- The functions parsearray and parseobject parse only a single value/pair
-- at a time and store them directly to avoid hitting the LPeg limits.
local function parsearray (str, pos, nullval, state)
local obj, cont
local npos
local t, nt = {}, 0
repeat
obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state)
if not npos then break end
pos = npos
nt = nt + 1
t[nt] = obj
until cont == 'last'
return pos, setmetatable (t, state.arraymeta)
end
local function parseobject (str, pos, nullval, state)
local obj, key, cont
local npos
local t = {}
repeat
key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state)
if not npos then break end
pos = npos
t[key] = obj
until cont == 'last'
return pos, setmetatable (t, state.objectmeta)
end
local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected")
local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected")
local Value = Space * (Array + Object + SimpleValue)
local ExpectedValue = Value + Space * Err "value expected"
ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue)
ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local DecodeValue = ExpectedValue * g.Cp ()
function json.decode (str, pos, nullval, ...)
local state = {}
state.objectmeta, state.arraymeta = optionalmetatables(...)
local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state)
if state.msg then
return nil, state.pos, state.msg
else
return obj, retpos
end
end
-- use this function only once:
json.use_lpeg = function () return json end
json.using_lpeg = true
return json -- so you can get the module using json = require "dkjson".use_lpeg()
end
if always_try_using_lpeg then
pcall (json.use_lpeg)
end
return json
| mpl-2.0 |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/tests/lua-tests/src/UserDefaultTest/UserDefaultTest.lua | 17 | 2518 | -- enable log
local function doTest()
cclog("********************** init value ***********************")
-- set default value
cc.UserDefault:getInstance():setStringForKey("string", "value1")
cc.UserDefault:getInstance():setIntegerForKey("integer", 10)
cc.UserDefault:getInstance():setFloatForKey("float", 2.3)
cc.UserDefault:getInstance():setDoubleForKey("double", 2.4)
cc.UserDefault:getInstance():setBoolForKey("bool", true)
-- print value
local ret = cc.UserDefault:getInstance():getStringForKey("string")
cclog("string is %s", ret)
local d = cc.UserDefault:getInstance():getDoubleForKey("double")
cclog("double is %f", d)
local i = cc.UserDefault:getInstance():getIntegerForKey("integer")
cclog("integer is %d", i)
local f = cc.UserDefault:getInstance():getFloatForKey("float")
cclog("float is %f", f)
local b = cc.UserDefault:getInstance():getBoolForKey("bool")
if b == true then
cclog("bool is true")
else
cclog("bool is false")
end
--cc.UserDefault:getInstance():flush()
cclog("********************** after change value ***********************")
-- change the value
cc.UserDefault:getInstance():setStringForKey("string", "value2")
cc.UserDefault:getInstance():setIntegerForKey("integer", 11)
cc.UserDefault:getInstance():setFloatForKey("float", 2.5)
cc.UserDefault:getInstance():setDoubleForKey("double", 2.6)
cc.UserDefault:getInstance():setBoolForKey("bool", false)
cc.UserDefault:getInstance():flush()
-- print value
ret = cc.UserDefault:getInstance():getStringForKey("string")
cclog("string is %s", ret)
d = cc.UserDefault:getInstance():getDoubleForKey("double")
cclog("double is %f", d)
i = cc.UserDefault:getInstance():getIntegerForKey("integer")
cclog("integer is %d", i)
f = cc.UserDefault:getInstance():getFloatForKey("float")
cclog("float is %f", f)
b = cc.UserDefault:getInstance():getBoolForKey("bool")
if b == true then
cclog("bool is true")
else
cclog("bool is false")
end
end
function UserDefaultTestMain()
local ret = cc.Scene:create()
local s = cc.Director:getInstance():getWinSize()
local label = cc.Label:createWithTTF("UserDefault test see log", s_arialPath, 28)
ret:addChild(label, 0)
label:setAnchorPoint(cc.p(0.5, 0.5))
label:setPosition( cc.p(s.width/2, s.height-50) )
ret:addChild(CreateBackMenuItem())
doTest()
return ret
end
| mit |
danielbarley/dot_files | nvim/lua/config/lsp/handlers.lua | 1 | 3191 | local M = {}
M.setup = function()
local signs = {
{ name = "DiagnosticSignError", text = "E" },
{ name = "DiagnosticSignWarn", text = "W" },
{ name = "DiagnosticSignHint", text = "H" },
{ name = "DiagnosticSignInfo", text = "I" },
}
for _, sign in ipairs(signs) do
vim.fn.sign_define(sign.name, { texthl = sign.name, text = sign.text, numhl = "" })
end
local config = {
-- disable virtual text
virtual_text = true,
-- show signs
signs = {
active = signs,
},
update_in_insert = true,
underline = true,
severity_sort = true,
float = {
focusable = false,
style = "minimal",
border = "rounded",
source = "always",
header = "",
prefix = "",
},
}
vim.diagnostic.config(config)
vim.lsp.handlers["textDocument/hover"] = vim.lsp.with(vim.lsp.handlers.hover, {
border = "rounded",
})
vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with(vim.lsp.handlers.signature_help, {
border = "rounded",
})
end
local function lsp_highlight_document(client)
-- Set autocommands conditional on server_capabilities
if client.resolved_capabilities.document_highlight then
vim.api.nvim_exec(
[[
augroup lsp_document_highlight
autocmd! * <buffer>
autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight()
autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references()
augroup END
]],
false
)
end
end
local function lsp_keymaps(bufnr)
local opts = { noremap = true, silent = true }
vim.api.nvim_buf_set_keymap(bufnr, "n", "gD", "<cmd>lua vim.lsp.buf.declaration()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "gd", "<cmd>lua vim.lsp.buf.definition()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "K", "<cmd>lua vim.lsp.buf.hover()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "gi", "<cmd>lua vim.lsp.buf.implementation()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "<C-k>", "<cmd>lua vim.lsp.buf.signature_help()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>rn", "<cmd>lua vim.lsp.buf.rename()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "gr", "<cmd>lua vim.lsp.buf.references()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>ca", "<cmd>lua vim.lsp.buf.code_action()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "[d", '<cmd>lua vim.diagnostic.goto_prev({ border = "rounded" })<CR>', opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "]d", '<cmd>lua vim.diagnostic.goto_next({ border = "rounded" })<CR>', opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "gl", '<cmd>lua vim.diagnostic.open_float()<CR>', opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>q", "<cmd>lua vim.diagnostic.setloclist()<CR>", opts)
vim.cmd [[ command! Format execute 'lua vim.lsp.buf.formatting()' ]]
end
M.on_attach = function(client, bufnr)
if client.name == "tsserver" then
client.resolved_capabilities.document_formatting = false
end
lsp_keymaps(bufnr)
lsp_highlight_document(client)
end
local capabilities = vim.lsp.protocol.make_client_capabilities()
local status_ok, cmp_nvim_lsp = pcall(require, "cmp_nvim_lsp")
if not status_ok then
return
end
M.capabilities = cmp_nvim_lsp.update_capabilities(capabilities)
return M
| unlicense |
lizh06/premake-core | tests/base/test_include.lua | 16 | 1701 | --
-- tests/base/test_include.lua
-- Test the include() function, for including external scripts
-- Copyright (c) 2011-2014 Jason Perkins and the Premake project
--
local suite = test.declare("include")
--
-- Setup and teardown
--
function suite.teardown()
-- clear the list of included files after each run
io._includedFiles = { }
end
--
-- Tests
--
function suite.include_findsPremakeFile_onFolderNameOnly()
include (_TESTS_DIR .. "/folder")
test.isequal("ok", premake.captured())
end
function suite.include_onExactFilename()
include (_TESTS_DIR .. "/folder/premake5.lua")
test.isequal("ok", premake.captured())
end
function suite.include_runsOnlyOnce_onMultipleIncludes()
include (_TESTS_DIR .. "/folder/premake5.lua")
include (_TESTS_DIR .. "/folder/premake5.lua")
test.isequal("ok", premake.captured())
end
function suite.include_runsOnlyOnce_onMultipleIncludesWithDifferentPaths()
include (_TESTS_DIR .. "/folder/premake5.lua")
include (_TESTS_DIR .. "/../tests/folder/premake5.lua")
test.isequal("ok", premake.captured())
end
function suite.includeexternal_runs()
includeexternal (_TESTS_DIR .. "/folder/premake5.lua")
test.isequal("ok", premake.captured())
end
function suite.includeexternal_runsAfterInclude()
include (_TESTS_DIR .. "/folder/premake5.lua")
includeexternal (_TESTS_DIR .. "/folder/premake5.lua")
test.isequal("okok", premake.captured())
end
function suite.includeexternal_runsTwiceAfterInclude()
include (_TESTS_DIR .. "/folder/premake5.lua")
includeexternal (_TESTS_DIR .. "/folder/premake5.lua")
includeexternal (_TESTS_DIR .. "/folder/premake5.lua")
test.isequal("okokok", premake.captured())
end
| bsd-3-clause |
ecnumjc/NAMAS | summary/util.lua | 9 | 1617 | --
-- Copyright (c) 2015, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- Author: Alexander M Rush <srush@seas.harvard.edu>
-- Sumit Chopra <spchopra@fb.com>
-- Jason Weston <jase@fb.com>
-- The utility tool box
local util = {}
function util.string_shortfloat(t)
return string.format('%2.4g', t)
end
function util.shuffleTable(t)
local rand = math.random
local iterations = #t
local j
for i = iterations, 2, -1 do
j = rand(i)
t[i], t[j] = t[j], t[i]
end
end
function util.string_split(s, c)
if c==nil then c=' ' end
local t={}
while true do
local f=s:find(c)
if f==nil then
if s:len()>0 then
table.insert(t, s)
end
break
end
if f > 1 then
table.insert(t, s:sub(1,f-1))
end
s=s:sub(f+1,s:len())
end
return t
end
function util.add(tab, key)
local cur = tab
for i = 1, #key-1 do
local new_cur = cur[key[i]]
if new_cur == nil then
cur[key[i]] = {}
new_cur = cur[key[i]]
end
cur = new_cur
end
cur[key[#key]] = true
end
function util.has(tab, key)
local cur = tab
for i = 1, #key do
cur = cur[key[i]]
if cur == nil then
return false
end
end
return true
end
function util.isnan(x)
return x ~= x
end
return util
| bsd-3-clause |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/tools/cocos2d-console/plugins/plugin_luacompile/bin/lua/jit/vmdef.lua | 5 | 6999 | -- This is a generated file. DO NOT EDIT!
module(...)
bcnames = "ISLT ISGE ISLE ISGT ISEQV ISNEV ISEQS ISNES ISEQN ISNEN ISEQP ISNEP ISTC ISFC IST ISF MOV NOT UNM LEN ADDVN SUBVN MULVN DIVVN MODVN ADDNV SUBNV MULNV DIVNV MODNV ADDVV SUBVV MULVV DIVVV MODVV POW CAT KSTR KCDATAKSHORTKNUM KPRI KNIL UGET USETV USETS USETN USETP UCLO FNEW TNEW TDUP GGET GSET TGETV TGETS TGETB TSETV TSETS TSETB TSETM CALLM CALL CALLMTCALLT ITERC ITERN VARG ISNEXTRETM RET RET0 RET1 FORI JFORI FORL IFORL JFORL ITERL IITERLJITERLLOOP ILOOP JLOOP JMP FUNCF IFUNCFJFUNCFFUNCV IFUNCVJFUNCVFUNCC FUNCCW"
irnames = "LT GE LE GT ULT UGE ULE UGT EQ NE ABC RETF NOP BASE PVAL GCSTEPHIOP LOOP USE PHI RENAMEKPRI KINT KGC KPTR KKPTR KNULL KNUM KINT64KSLOT BNOT BSWAP BAND BOR BXOR BSHL BSHR BSAR BROL BROR ADD SUB MUL DIV MOD POW NEG ABS ATAN2 LDEXP MIN MAX FPMATHADDOV SUBOV MULOV AREF HREFK HREF NEWREFUREFO UREFC FREF STRREFALOAD HLOAD ULOAD FLOAD XLOAD SLOAD VLOAD ASTOREHSTOREUSTOREFSTOREXSTORESNEW XSNEW TNEW TDUP CNEW CNEWI TBAR OBAR XBAR CONV TOBIT TOSTR STRTO CALLN CALLL CALLS CALLXSCARG "
irfpm = { [0]="floor", "ceil", "trunc", "sqrt", "exp", "exp2", "log", "log2", "log10", "sin", "cos", "tan", "other", }
irfield = { [0]="str.len", "func.env", "func.pc", "tab.meta", "tab.array", "tab.node", "tab.asize", "tab.hmask", "tab.nomm", "udata.meta", "udata.udtype", "udata.file", "cdata.ctypeid", "cdata.ptr", "cdata.int", "cdata.int64", "cdata.int64_4", }
ircall = {
[0]="lj_str_cmp",
"lj_str_new",
"lj_strscan_num",
"lj_str_fromint",
"lj_str_fromnum",
"lj_tab_new1",
"lj_tab_dup",
"lj_tab_newkey",
"lj_tab_len",
"lj_gc_step_jit",
"lj_gc_barrieruv",
"lj_mem_newgco",
"lj_math_random_step",
"lj_vm_modi",
"sinh",
"cosh",
"tanh",
"fputc",
"fwrite",
"fflush",
"lj_vm_floor",
"lj_vm_ceil",
"lj_vm_trunc",
"sqrt",
"exp",
"lj_vm_exp2",
"log",
"lj_vm_log2",
"log10",
"sin",
"cos",
"tan",
"lj_vm_powi",
"pow",
"atan2",
"ldexp",
"lj_vm_tobit",
"softfp_add",
"softfp_sub",
"softfp_mul",
"softfp_div",
"softfp_cmp",
"softfp_i2d",
"softfp_d2i",
"softfp_ui2d",
"softfp_f2d",
"softfp_d2ui",
"softfp_d2f",
"softfp_i2f",
"softfp_ui2f",
"softfp_f2i",
"softfp_f2ui",
"fp64_l2d",
"fp64_ul2d",
"fp64_l2f",
"fp64_ul2f",
"fp64_d2l",
"fp64_d2ul",
"fp64_f2l",
"fp64_f2ul",
"lj_carith_divi64",
"lj_carith_divu64",
"lj_carith_modi64",
"lj_carith_modu64",
"lj_carith_powi64",
"lj_carith_powu64",
"lj_cdata_setfin",
"strlen",
"memcpy",
"memset",
"lj_vm_errno",
"lj_carith_mul64",
}
traceerr = {
[0]="error thrown or hook called during recording",
"trace too long",
"trace too deep",
"too many snapshots",
"blacklisted",
"NYI: bytecode %d",
"leaving loop in root trace",
"inner loop in root trace",
"loop unroll limit reached",
"bad argument type",
"call to JIT-disabled function",
"call unroll limit reached",
"down-recursion, restarting",
"NYI: C function %p",
"NYI: FastFunc %s",
"NYI: unsupported variant of FastFunc %s",
"NYI: return to lower frame",
"store with nil or NaN key",
"missing metamethod",
"looping index lookup",
"NYI: mixed sparse/dense table",
"symbol not in cache",
"NYI: unsupported C type conversion",
"NYI: unsupported C function type",
"guard would always fail",
"too many PHIs",
"persistent type instability",
"failed to allocate mcode memory",
"machine code too long",
"hit mcode limit (retrying)",
"too many spill slots",
"inconsistent register allocation",
"NYI: cannot assemble IR instruction %d",
"NYI: PHI shuffling too complex",
"NYI: register coalescing too complex",
}
ffnames = {
[0]="Lua",
"C",
"assert",
"type",
"next",
"pairs",
"ipairs_aux",
"ipairs",
"getmetatable",
"setmetatable",
"getfenv",
"setfenv",
"rawget",
"rawset",
"rawequal",
"unpack",
"select",
"tonumber",
"tostring",
"error",
"pcall",
"xpcall",
"loadfile",
"load",
"loadstring",
"dofile",
"gcinfo",
"collectgarbage",
"newproxy",
"print",
"coroutine.status",
"coroutine.running",
"coroutine.create",
"coroutine.yield",
"coroutine.resume",
"coroutine.wrap_aux",
"coroutine.wrap",
"math.abs",
"math.floor",
"math.ceil",
"math.sqrt",
"math.log10",
"math.exp",
"math.sin",
"math.cos",
"math.tan",
"math.asin",
"math.acos",
"math.atan",
"math.sinh",
"math.cosh",
"math.tanh",
"math.frexp",
"math.modf",
"math.log",
"math.deg",
"math.rad",
"math.atan2",
"math.pow",
"math.fmod",
"math.ldexp",
"math.min",
"math.max",
"math.random",
"math.randomseed",
"bit.tobit",
"bit.bnot",
"bit.bswap",
"bit.lshift",
"bit.rshift",
"bit.arshift",
"bit.rol",
"bit.ror",
"bit.band",
"bit.bor",
"bit.bxor",
"bit.tohex",
"string.len",
"string.byte",
"string.char",
"string.sub",
"string.rep",
"string.reverse",
"string.lower",
"string.upper",
"string.dump",
"string.find",
"string.match",
"string.gmatch_aux",
"string.gmatch",
"string.gsub",
"string.format",
"table.foreachi",
"table.foreach",
"table.getn",
"table.maxn",
"table.insert",
"table.remove",
"table.concat",
"table.sort",
"io.method.close",
"io.method.read",
"io.method.write",
"io.method.flush",
"io.method.seek",
"io.method.setvbuf",
"io.method.lines",
"io.method.__gc",
"io.method.__tostring",
"io.open",
"io.popen",
"io.tmpfile",
"io.close",
"io.read",
"io.write",
"io.flush",
"io.input",
"io.output",
"io.lines",
"io.type",
"os.execute",
"os.remove",
"os.rename",
"os.tmpname",
"os.getenv",
"os.exit",
"os.clock",
"os.date",
"os.time",
"os.difftime",
"os.setlocale",
"debug.getregistry",
"debug.getmetatable",
"debug.setmetatable",
"debug.getfenv",
"debug.setfenv",
"debug.getinfo",
"debug.getlocal",
"debug.setlocal",
"debug.getupvalue",
"debug.setupvalue",
"debug.upvalueid",
"debug.upvaluejoin",
"debug.sethook",
"debug.gethook",
"debug.debug",
"debug.traceback",
"jit.on",
"jit.off",
"jit.flush",
"jit.status",
"jit.attach",
"jit.util.funcinfo",
"jit.util.funcbc",
"jit.util.funck",
"jit.util.funcuvname",
"jit.util.traceinfo",
"jit.util.traceir",
"jit.util.tracek",
"jit.util.tracesnap",
"jit.util.tracemc",
"jit.util.traceexitstub",
"jit.util.ircalladdr",
"jit.opt.start",
"ffi.meta.__index",
"ffi.meta.__newindex",
"ffi.meta.__eq",
"ffi.meta.__len",
"ffi.meta.__lt",
"ffi.meta.__le",
"ffi.meta.__concat",
"ffi.meta.__call",
"ffi.meta.__add",
"ffi.meta.__sub",
"ffi.meta.__mul",
"ffi.meta.__div",
"ffi.meta.__mod",
"ffi.meta.__pow",
"ffi.meta.__unm",
"ffi.meta.__tostring",
"ffi.meta.__pairs",
"ffi.meta.__ipairs",
"ffi.clib.__index",
"ffi.clib.__newindex",
"ffi.clib.__gc",
"ffi.callback.free",
"ffi.callback.set",
"ffi.cdef",
"ffi.new",
"ffi.cast",
"ffi.typeof",
"ffi.istype",
"ffi.sizeof",
"ffi.alignof",
"ffi.offsetof",
"ffi.errno",
"ffi.string",
"ffi.copy",
"ffi.fill",
"ffi.abi",
"ffi.metatype",
"ffi.gc",
"ffi.load",
}
| mit |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/EventListenerTouchOneByOne.lua | 11 | 1575 |
--------------------------------
-- @module EventListenerTouchOneByOne
-- @extend EventListener
-- @parent_module cc
--------------------------------
-- Is swall touches or not.<br>
-- return True if needs to swall touches.
-- @function [parent=#EventListenerTouchOneByOne] isSwallowTouches
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Whether or not to swall touches.<br>
-- param needSwallow True if needs to swall touches.
-- @function [parent=#EventListenerTouchOneByOne] setSwallowTouches
-- @param self
-- @param #bool needSwallow
-- @return EventListenerTouchOneByOne#EventListenerTouchOneByOne self (return value: cc.EventListenerTouchOneByOne)
--------------------------------
--
-- @function [parent=#EventListenerTouchOneByOne] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- / Overrides
-- @function [parent=#EventListenerTouchOneByOne] clone
-- @param self
-- @return EventListenerTouchOneByOne#EventListenerTouchOneByOne ret (return value: cc.EventListenerTouchOneByOne)
--------------------------------
--
-- @function [parent=#EventListenerTouchOneByOne] checkAvailable
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#EventListenerTouchOneByOne] EventListenerTouchOneByOne
-- @param self
-- @return EventListenerTouchOneByOne#EventListenerTouchOneByOne self (return value: cc.EventListenerTouchOneByOne)
return nil
| mit |
cooljeanius/CEGUI | cegui/src/ScriptingModules/LuaScriptModule/support/tolua++bin/lua/container.lua | 15 | 16995 | -- tolua: container abstract class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id$
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- table to store namespaced typedefs/enums in global scope
global_typedefs = {}
global_enums = {}
-- Container class
-- Represents a container of features to be bound
-- to lua.
classContainer =
{
curr = nil,
}
classContainer.__index = classContainer
setmetatable(classContainer,classFeature)
-- output tags
function classContainer:decltype ()
push(self)
local i=1
while self[i] do
self[i]:decltype()
i = i+1
end
pop()
end
-- write support code
function classContainer:supcode ()
if not self:check_public_access() then
return
end
push(self)
local i=1
while self[i] do
if self[i]:check_public_access() then
self[i]:supcode()
end
i = i+1
end
pop()
end
function classContainer:hasvar ()
local i=1
while self[i] do
if self[i]:isvariable() then
return 1
end
i = i+1
end
return 0
end
-- Internal container constructor
function _Container (self)
setmetatable(self,classContainer)
self.n = 0
self.typedefs = {tolua_n=0}
self.usertypes = {}
self.enums = {tolua_n=0}
self.lnames = {}
return self
end
-- push container
function push (t)
t.prox = classContainer.curr
classContainer.curr = t
end
-- pop container
function pop ()
--print("name",classContainer.curr.name)
--foreach(classContainer.curr.usertypes,print)
--print("______________")
classContainer.curr = classContainer.curr.prox
end
-- get current namespace
function getcurrnamespace ()
return getnamespace(classContainer.curr)
end
-- append to current container
function append (t)
return classContainer.curr:append(t)
end
-- append typedef to current container
function appendtypedef (t)
return classContainer.curr:appendtypedef(t)
end
-- append usertype to current container
function appendusertype (t)
return classContainer.curr:appendusertype(t)
end
-- append enum to current container
function appendenum (t)
return classContainer.curr:appendenum(t)
end
-- substitute typedef
function applytypedef (mod,type)
return classContainer.curr:applytypedef(mod,type)
end
-- check if is type
function findtype (type)
local t = classContainer.curr:findtype(type)
return t
end
-- check if is typedef
function istypedef (type)
return classContainer.curr:istypedef(type)
end
-- get fulltype (with namespace)
function fulltype (t)
local curr = classContainer.curr
while curr do
if curr then
if curr.typedefs and curr.typedefs[t] then
return curr.typedefs[t]
elseif curr.usertypes and curr.usertypes[t] then
return curr.usertypes[t]
end
end
curr = curr.prox
end
return t
end
-- checks if it requires collection
function classContainer:requirecollection (t)
push(self)
local i=1
local r = false
while self[i] do
r = self[i]:requirecollection(t) or r
i = i+1
end
pop()
return r
end
-- get namesapce
function getnamespace (curr)
local namespace = ''
while curr do
if curr and
( curr.classtype == 'class' or curr.classtype == 'namespace')
then
namespace = (curr.original_name or curr.name) .. '::' .. namespace
--namespace = curr.name .. '::' .. namespace
end
curr = curr.prox
end
return namespace
end
-- get namespace (only namespace)
function getonlynamespace ()
local curr = classContainer.curr
local namespace = ''
while curr do
if curr.classtype == 'class' then
return namespace
elseif curr.classtype == 'namespace' then
namespace = curr.name .. '::' .. namespace
end
curr = curr.prox
end
return namespace
end
-- check if is enum
function isenum (type)
return classContainer.curr:isenum(type)
end
-- append feature to container
function classContainer:append (t)
self.n = self.n + 1
self[self.n] = t
t.parent = self
end
-- append typedef
function classContainer:appendtypedef (t)
local namespace = getnamespace(classContainer.curr)
self.typedefs.tolua_n = self.typedefs.tolua_n + 1
self.typedefs[self.typedefs.tolua_n] = t
self.typedefs[t.utype] = namespace .. t.utype
global_typedefs[namespace..t.utype] = t
t.ftype = findtype(t.type) or t.type
--print("appending typedef "..t.utype.." as "..namespace..t.utype.." with ftype "..t.ftype)
append_global_type(namespace..t.utype)
if t.ftype and isenum(t.ftype) then
global_enums[namespace..t.utype] = true
end
end
-- append usertype: return full type
function classContainer:appendusertype (t)
local container
if t == (self.original_name or self.name) then
container = self.prox
else
container = self
end
local ft = getnamespace(container) .. t
container.usertypes[t] = ft
_usertype[ft] = ft
return ft
end
-- append enum
function classContainer:appendenum (t)
local namespace = getnamespace(classContainer.curr)
self.enums.tolua_n = self.enums.tolua_n + 1
self.enums[self.enums.tolua_n] = t
global_enums[namespace..t.name] = t
end
-- determine lua function name overload
function classContainer:overload (lname)
if not self.lnames[lname] then
self.lnames[lname] = 0
else
self.lnames[lname] = self.lnames[lname] + 1
end
return format("%02d",self.lnames[lname])
end
-- applies typedef: returns the 'the facto' modifier and type
function classContainer:applytypedef (mod,type)
if global_typedefs[type] then
--print("found typedef "..global_typedefs[type].type)
local mod1, type1 = global_typedefs[type].mod, global_typedefs[type].ftype
local mod2, type2 = applytypedef(mod.." "..mod1, type1)
--return mod2 .. ' ' .. mod1, type2
return mod2, type2
end
do return mod,type end
end
-- check if it is a typedef
function classContainer:istypedef (type)
local env = self
while env do
if env.typedefs then
local i=1
while env.typedefs[i] do
if env.typedefs[i].utype == type then
return type
end
i = i+1
end
end
env = env.parent
end
return nil
end
function find_enum_var(var)
if tonumber(var) then return var end
local c = classContainer.curr
while c do
local ns = getnamespace(c)
for k,v in pairs(_global_enums) do
if match_type(var, v, ns) then
return v
end
end
if c.base and c.base ~= '' then
c = _global_classes[c:findtype(c.base)]
else
c = nil
end
end
return var
end
-- check if is a registered type: return full type or nil
function classContainer:findtype (t)
t = string.gsub(t, "=.*", "")
if _basic[t] then
return t
end
local _,_,em = string.find(t, "([&%*])%s*$")
t = string.gsub(t, "%s*([&%*])%s*$", "")
p = self
while p and type(p)=='table' do
local st = getnamespace(p)
for i=_global_types.n,1,-1 do -- in reverse order
if match_type(t, _global_types[i], st) then
return _global_types[i]..(em or "")
end
end
if p.base and p.base ~= '' and p.base ~= t then
--print("type is "..t..", p is "..p.base.." self.type is "..self.type.." self.name is "..self.name)
p = _global_classes[p:findtype(p.base)]
else
p = nil
end
end
return nil
end
function append_global_type(t, class)
_global_types.n = _global_types.n +1
_global_types[_global_types.n] = t
_global_types_hash[t] = 1
if class then append_class_type(t, class) end
end
function append_class_type(t,class)
if _global_classes[t] then
class.flags = _global_classes[t].flags
class.lnames = _global_classes[t].lnames
if _global_classes[t].base and (_global_classes[t].base ~= '') then
class.base = _global_classes[t].base or class.base
end
end
_global_classes[t] = class
class.flags = class.flags or {}
end
function match_type(childtype, regtype, st)
--print("findtype "..childtype..", "..regtype..", "..st)
local b,e = string.find(regtype, childtype, -string.len(childtype), true)
if b then
if e == string.len(regtype) and
(b == 1 or (string.sub(regtype, b-1, b-1) == ':' and
string.sub(regtype, 1, b-1) == string.sub(st, 1, b-1))) then
return true
end
end
return false
end
function findtype_on_childs(self, t)
local tchild
if self.classtype == 'class' or self.classtype == 'namespace' then
for k,v in ipairs(self) do
if v.classtype == 'class' or v.classtype == 'namespace' then
if v.typedefs and v.typedefs[t] then
return v.typedefs[t]
elseif v.usertypes and v.usertypes[t] then
return v.usertypes[t]
end
tchild = findtype_on_childs(v, t)
if tchild then return tchild end
end
end
end
return nil
end
function classContainer:isenum (type)
if global_enums[type] then
return type
else
return false
end
local basetype = gsub(type,"^.*::","")
local env = self
while env do
if env.enums then
local i=1
while env.enums[i] do
if env.enums[i].name == basetype then
return true
end
i = i+1
end
end
env = env.parent
end
return false
end
methodisvirtual = false -- a global
-- parse chunk
function classContainer:doparse (s)
--print ("parse "..s)
-- try the parser hook
do
local sub = parser_hook(s)
if sub then
return sub
end
end
-- try the null statement
do
local b,e,code = string.find(s, "^%s*;")
if b then
return strsub(s,e+1)
end
end
-- try empty verbatim line
do
local b,e,code = string.find(s, "^%s*$\n")
if b then
return strsub(s,e+1)
end
end
-- try Lua code
do
local b,e,code = strfind(s,"^%s*(%b\1\2)")
if b then
Code(strsub(code,2,-2))
return strsub(s,e+1)
end
end
-- try C code
do
local b,e,code = strfind(s,"^%s*(%b\3\4)")
if b then
code = '{'..strsub(code,2,-2)..'\n}\n'
Verbatim(code,'r') -- verbatim code for 'r'egister fragment
return strsub(s,e+1)
end
end
-- try C code for preamble section
do
local b,e,code = string.find(s, "^%s*(%b\5\6)")
if b then
code = string.sub(code, 2, -2).."\n"
Verbatim(code, '')
return string.sub(s, e+1)
end
end
-- try default_property directive
do
local b,e,ptype = strfind(s, "^%s*TOLUA_PROPERTY_TYPE%s*%(+%s*([^%)%s]*)%s*%)+%s*;?")
if b then
if not ptype or ptype == "" then
ptype = "default"
end
self:set_property_type(ptype)
return strsub(s, e+1)
end
end
-- try protected_destructor directive
do
local b,e = string.find(s, "^%s*TOLUA_PROTECTED_DESTRUCTOR%s*;?")
if b then
if self.set_protected_destructor then
self:set_protected_destructor(true)
end
return strsub(s, e+1)
end
end
-- try 'extern' keyword
do
local b,e = string.find(s, "^%s*extern%s+")
if b then
-- do nothing
return strsub(s, e+1)
end
end
-- try 'virtual' keyworkd
do
local b,e = string.find(s, "^%s*virtual%s+")
if b then
methodisvirtual = true
return strsub(s, e+1)
end
end
-- try labels (public, private, etc)
do
local b,e = string.find(s, "^%s*%w*%s*:[^:]")
if b then
return strsub(s, e) -- preserve the [^:]
end
end
-- try module
do
local b,e,name,body = strfind(s,"^%s*module%s%s*([_%w][_%w]*)%s*(%b{})%s*")
if b then
_curr_code = strsub(s,b,e)
Module(name,body)
return strsub(s,e+1)
end
end
-- try namesapce
do
local b,e,name,body = strfind(s,"^%s*namespace%s%s*([_%w][_%w]*)%s*(%b{})%s*;?")
if b then
_curr_code = strsub(s,b,e)
Namespace(name,body)
return strsub(s,e+1)
end
end
-- try define
do
local b,e,name = strfind(s,"^%s*#define%s%s*([^%s]*)[^\n]*\n%s*")
if b then
_curr_code = strsub(s,b,e)
Define(name)
return strsub(s,e+1)
end
end
-- try enumerates
do
local b,e,name,body,varname = strfind(s,"^%s*enum%s+(%S*)%s*(%b{})%s*([^%s;]*)%s*;?%s*")
if b then
--error("#Sorry, declaration of enums and variables on the same statement is not supported.\nDeclare your variable separately (example: '"..name.." "..varname..";')")
_curr_code = strsub(s,b,e)
Enumerate(name,body,varname)
return strsub(s,e+1)
end
end
-- do
-- local b,e,name,body = strfind(s,"^%s*enum%s+(%S*)%s*(%b{})%s*;?%s*")
-- if b then
-- _curr_code = strsub(s,b,e)
-- Enumerate(name,body)
-- return strsub(s,e+1)
-- end
-- end
do
local b,e,body,name = strfind(s,"^%s*typedef%s+enum[^{]*(%b{})%s*([%w_][^%s]*)%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Enumerate(name,body)
return strsub(s,e+1)
end
end
-- try operator
do
local b,e,decl,kind,arg,const = strfind(s,"^%s*([_%w][_%w%s%*&:<>,]-%s+operator)%s*([^%s][^%s]*)%s*(%b())%s*(c?o?n?s?t?)%s*;%s*")
if not b then
-- try inline
b,e,decl,kind,arg,const = strfind(s,"^%s*([_%w][_%w%s%*&:<>,]-%s+operator)%s*([^%s][^%s]*)%s*(%b())%s*(c?o?n?s?t?)[%s\n]*%b{}%s*;?%s*")
end
if not b then
-- try cast operator
b,e,decl,kind,arg,const = strfind(s, "^%s*(operator)%s+([%w_:%d<>%*%&%s]+)%s*(%b())%s*(c?o?n?s?t?)");
if b then
local _,ie = string.find(s, "^%s*%b{}", e+1)
if ie then
e = ie
end
end
end
if b then
_curr_code = strsub(s,b,e)
Operator(decl,kind,arg,const)
return strsub(s,e+1)
end
end
-- try function
do
--local b,e,decl,arg,const = strfind(s,"^%s*([~_%w][_@%w%s%*&:<>]*[_%w])%s*(%b())%s*(c?o?n?s?t?)%s*=?%s*0?%s*;%s*")
local b,e,decl,arg,const,virt = strfind(s,"^%s*([^%(\n]+)%s*(%b())%s*(c?o?n?s?t?)%s*(=?%s*0?)%s*;%s*")
if not b then
-- try function with template
b,e,decl,arg,const = strfind(s,"^%s*([~_%w][_@%w%s%*&:<>]*[_%w]%b<>)%s*(%b())%s*(c?o?n?s?t?)%s*=?%s*0?%s*;%s*")
end
if not b then
-- try a single letter function name
b,e,decl,arg,const = strfind(s,"^%s*([_%w])%s*(%b())%s*(c?o?n?s?t?)%s*;%s*")
end
if b then
if virt and string.find(virt, "[=0]") then
if self.flags then
self.flags.pure_virtual = true
end
end
_curr_code = strsub(s,b,e)
Function(decl,arg,const)
return strsub(s,e+1)
end
end
-- try inline function
do
local b,e,decl,arg,const = strfind(s,"^%s*([^%(\n]+)%s*(%b())%s*(c?o?n?s?t?)[^;{]*%b{}%s*;?%s*")
--local b,e,decl,arg,const = strfind(s,"^%s*([~_%w][_@%w%s%*&:<>]*[_%w>])%s*(%b())%s*(c?o?n?s?t?)[^;]*%b{}%s*;?%s*")
if not b then
-- try a single letter function name
b,e,decl,arg,const = strfind(s,"^%s*([_%w])%s*(%b())%s*(c?o?n?s?t?).-%b{}%s*;?%s*")
end
if b then
_curr_code = strsub(s,b,e)
Function(decl,arg,const)
return strsub(s,e+1)
end
end
-- try class
do
local b,e,name,base,body
base = '' body = ''
b,e,name = strfind(s,"^%s*class%s*([_%w][_%w@]*)%s*;") -- dummy class
if not b then
b,e,name = strfind(s,"^%s*struct%s*([_%w][_%w@]*)%s*;") -- dummy struct
if not b then
b,e,name,base,body = strfind(s,"^%s*class%s*([_%w][_%w@]*)%s*(.-)%s*(%b{})%s*;%s*")
if not b then
b,e,name,base,body = strfind(s,"^%s*struct%s*([_%w][_%w@]*)%s*(.-)%s*(%b{})%s*;%s*")
if not b then
b,e,name,base,body = strfind(s,"^%s*union%s*([_%w][_%w@]*)%s*(.-)%s*(%b{})%s*;%s*")
if not b then
base = ''
b,e,body,name = strfind(s,"^%s*typedef%s%s*struct%s%s*[_%w]*%s*(%b{})%s*([_%w][_%w@]*)%s*;%s*")
end
end
end
end
end
if b then
if base ~= '' then
base = string.gsub(base, "^%s*:%s*", "")
base = string.gsub(base, "%s*public%s*", "")
base = split(base, ",")
--local b,e
--b,e,base = strfind(base,".-([_%w][_%w<>,:]*)$")
else
base = {}
end
_curr_code = strsub(s,b,e)
Class(name,base,body)
return strsub(s,e+1)
end
end
-- try typedef
do
local b,e,types = strfind(s,"^%s*typedef%s%s*(.-)%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Typedef(types)
return strsub(s,e+1)
end
end
-- try variable
do
local b,e,decl = strfind(s,"^%s*([_%w][_@%s%w%d%*&:<>,]*[_%w%d])%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
local list = split_c_tokens(decl, ",")
Variable(list[1])
if list.n > 1 then
local _,_,type = strfind(list[1], "(.-)%s+([^%s]*)$");
local i =2;
while list[i] do
Variable(type.." "..list[i])
i=i+1
end
end
--Variable(decl)
return strsub(s,e+1)
end
end
-- try string
do
local b,e,decl = strfind(s,"^%s*([_%w]?[_%s%w%d]-char%s+[_@%w%d]*%s*%[%s*%S+%s*%])%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Variable(decl)
return strsub(s,e+1)
end
end
-- try array
do
local b,e,decl = strfind(s,"^%s*([_%w][][_@%s%w%d%*&:]*[]_%w%d])%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Array(decl)
return strsub(s,e+1)
end
end
-- no matching
if gsub(s,"%s%s*","") ~= "" then
_curr_code = s
error("#parse error")
else
return ""
end
end
function classContainer:parse (s)
self.curr_member_access = nil
while s ~= '' do
s = self:doparse(s)
methodisvirtual = false
end
end
-- property types
function get_property_type()
return classContainer.curr:get_property_type()
end
function classContainer:set_property_type(ptype)
ptype = string.gsub(ptype, "^%s*", "")
ptype = string.gsub(ptype, "%s*$", "")
self.property_type = ptype
end
function classContainer:get_property_type()
return self.property_type or (self.parent and self.parent:get_property_type()) or "default"
end
| gpl-3.0 |
jmptrader/duktape | tests/perf/test-reg-readwrite-plain.lua | 19 | 7981 | function test()
local a, b, c, d, i;
a = 1
b = 2
c = 3
d = 4
for i=1,1e6 do
-- 100
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
-- 100
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
-- 100
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
-- 100
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
-- 100
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
-- 100
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
-- 100
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
-- 100
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
-- 100
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
-- 100
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
end
end
test()
| mit |
opentechinstitute/luci | applications/luci-statistics/luasrc/model/cbi/luci_statistics/email.lua | 78 | 1934 | --[[
Luci configuration model for statistics - collectd email plugin configuration
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("luci_statistics",
translate("E-Mail Plugin Configuration"),
translate(
"The email plugin creates a unix socket which can be used " ..
"to transmit email-statistics to a running collectd daemon. " ..
"This plugin is primarily intended to be used in conjunction " ..
"with Mail::SpamAssasin::Plugin::Collectd but can be used in " ..
"other ways as well."
))
-- collectd_email config section
s = m:section( NamedSection, "collectd_email", "luci_statistics" )
-- collectd_email.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_email.socketfile (SocketFile)
socketfile = s:option( Value, "SocketFile", translate("Socket file") )
socketfile.default = "/var/run/collect-email.sock"
socketfile:depends( "enable", 1 )
-- collectd_email.socketgroup (SocketGroup)
socketgroup = s:option( Value, "SocketGroup", translate("Socket group") )
socketgroup.default = "nobody"
socketgroup.rmempty = true
socketgroup.optional = true
socketgroup:depends( "enable", 1 )
-- collectd_email.socketperms (SocketPerms)
socketperms = s:option( Value, "SocketPerms", translate("Socket permissions") )
socketperms.default = "0770"
socketperms.rmempty = true
socketperms.optional = true
socketperms:depends( "enable", 1 )
-- collectd_email.maxconns (MaxConns)
maxconns = s:option( Value, "MaxConns", translate("Maximum allowed connections") )
maxconns.default = 5
maxconns.isinteger = true
maxconns.rmempty = true
maxconns.optional = true
maxconns:depends( "enable", 1 )
return m
| apache-2.0 |
lizh06/premake-core | tests/project/test_vpaths.lua | 16 | 3799 | --
-- tests/project/test_vpaths.lua
-- Automated test suite for the project support functions.
-- Copyright (c) 2011-2013 Jason Perkins and the Premake project
--
local suite = test.declare("project_vpaths")
local project = premake.project
--
-- Setup and teardown
--
local wks, prj
function suite.setup()
wks, prj = test.createWorkspace()
end
local function run()
local cfg = test.getconfig(prj, "Debug")
return project.getvpath(prj, cfg.files[1])
end
--
-- Test simple replacements
--
function suite.ReturnsOriginalPath_OnNoVpaths()
files { "hello.c" }
test.isequal(path.join(os.getcwd(), "hello.c"), run())
end
function suite.ReturnsOriginalPath_OnNoMatches()
files { "hello.c" }
vpaths { ["Headers"] = "**.h" }
test.isequal(path.join(os.getcwd(), "hello.c"), run())
end
function suite.CanStripPaths()
files { "src/myproject/hello.c" }
vpaths { [""] = "src" }
run()
test.isequal("hello.c", run())
end
function suite.CanTrimLeadingPaths()
files { "src/myproject/hello.c" }
vpaths { ["*"] = "src" }
test.isequal("myproject/hello.c", run())
end
function suite.PatternMayIncludeTrailingSlash()
files { "src/myproject/hello.c" }
vpaths { [""] = "src/myproject/" }
test.isequal("hello.c", run())
end
function suite.SimpleReplacementPatterns()
files { "src/myproject/hello.c" }
vpaths { ["sources"] = "src/myproject" }
test.isequal("sources/hello.c", run())
end
function suite.ExactFilenameMatch()
files { "src/hello.c" }
vpaths { ["sources"] = "src/hello.c" }
test.isequal("sources/hello.c", run())
end
--
-- Test wildcard patterns
--
function suite.MatchFilePattern_ToGroup_Flat()
files { "src/myproject/hello.h" }
vpaths { ["Headers"] = "**.h" }
test.isequal("Headers/hello.h", run())
end
function suite.MatchFilePattern_ToNone_Flat()
files { "src/myproject/hello.h" }
vpaths { [""] = "**.h" }
test.isequal("hello.h", run())
end
function suite.MatchFilePattern_ToNestedGroup_Flat()
files { "src/myproject/hello.h" }
vpaths { ["Source/Headers"] = "**.h" }
test.isequal("Source/Headers/hello.h", run())
end
function suite.MatchFilePattern_ToGroup_WithTrailingSlash()
files { "src/myproject/hello.h" }
vpaths { ["Headers/"] = "**.h" }
test.isequal("Headers/hello.h", run())
end
function suite.MatchFilePattern_ToNestedGroup_Flat()
files { "src/myproject/hello.h" }
vpaths { ["Group/Headers"] = "**.h" }
test.isequal("Group/Headers/hello.h", run())
end
function suite.MatchFilePattern_ToGroup_Nested()
files { "src/myproject/hello.h" }
vpaths { ["Headers/*"] = "**.h" }
test.isequal("Headers/src/myproject/hello.h", run())
end
function suite.MatchFilePattern_ToGroup_Nested_OneStar()
files { "src/myproject/hello.h" }
vpaths { ["Headers/*"] = "**.h" }
test.isequal("Headers/src/myproject/hello.h", run())
end
function suite.MatchFilePatternWithPath_ToGroup_Nested()
files { "src/myproject/hello.h" }
vpaths { ["Headers/*"] = "src/**.h" }
test.isequal("Headers/myproject/hello.h", run())
end
function suite.matchBaseFileName_onWildcardExtension()
files { "hello.cpp" }
vpaths { ["Sources"] = "hello.*" }
test.isequal("Sources/hello.cpp", run())
end
--
-- Test with project locations
--
function suite.MatchPath_OnProjectLocationSet()
location "build"
files "src/hello.h"
vpaths { [""] = "src" }
test.isequal("hello.h", run())
end
function suite.MatchFilePattern_OnProjectLocationSet()
location "build"
files "src/hello.h"
vpaths { ["Headers"] = "**.h" }
test.isequal("Headers/hello.h", run())
end
function suite.MatchFilePatternWithPath_OnProjectLocationSet()
location "build"
files "src/hello.h"
vpaths { ["Headers"] = "src/**.h" }
test.isequal("Headers/hello.h", run())
end
| bsd-3-clause |
mattico/planets | quickie/core.lua | 15 | 3418 | --[[
Copyright (c) 2012 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.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
local BASE = (...):match("(.-)[^%.]+$")
local group = require(BASE .. 'group')
local mouse = require(BASE .. 'mouse')
local keyboard = require(BASE .. 'keyboard')
--
-- Helper functions
--
-- evaluates all arguments
local function strictAnd(...)
local n = select("#", ...)
local ret = true
for i = 1,n do ret = select(i, ...) and ret end
return ret
end
local function strictOr(...)
local n = select("#", ...)
local ret = false
for i = 1,n do ret = select(i, ...) or ret end
return ret
end
--
-- Widget ID
--
local maxid, uids = 0, {}
setmetatable(uids, {__index = function(t, i)
t[i] = {}
return t[i]
end})
local function generateID()
maxid = maxid + 1
return uids[maxid]
end
--
-- Drawing / Frame update
--
local draw_items = {n = 0}
local function registerDraw(id, f, ...)
assert(type(f) == 'function' or (getmetatable(f) or {}).__call,
'Drawing function is not a callable type!')
local font = love.graphics.getFont()
local state = 'normal'
if mouse.isHot(id) or keyboard.hasFocus(id) then
state = mouse.isActive(id) and 'active' or 'hot'
end
local rest = {n = select('#', ...), ...}
draw_items.n = draw_items.n + 1
draw_items[draw_items.n] = function()
if font then love.graphics.setFont(font) end
f(state, unpack(rest, 1, rest.n))
end
end
-- actually update-and-draw
local function draw()
keyboard.endFrame()
mouse.endFrame()
group.endFrame()
-- save graphics state
local c = {love.graphics.getColor()}
local f = love.graphics.getFont()
local lw = love.graphics.getLineWidth()
local ls = love.graphics.getLineStyle()
for i = 1,draw_items.n do draw_items[i]() end
-- restore graphics state
love.graphics.setLineWidth(lw)
love.graphics.setLineStyle(ls)
if f then love.graphics.setFont(f) end
love.graphics.setColor(c)
draw_items.n = 0
maxid = 0
group.beginFrame()
mouse.beginFrame()
keyboard.beginFrame()
end
--
-- The Module
--
return {
generateID = generateID,
style = require((...):match("(.-)[^%.]+$") .. 'style-default'),
registerDraw = registerDraw,
draw = draw,
strictAnd = strictAnd,
strictOr = strictOr,
}
| mit |
tinydanbo/Impoverished-Starfighter | lib/loveframes/objects/internal/multichoice/multichoicelist.lua | 5 | 10206 | --[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2012-2014 Kenny Shields --
--]]------------------------------------------------
-- multichoicelist class
local newobject = loveframes.NewObject("multichoicelist", "loveframes_object_multichoicelist", true)
--[[---------------------------------------------------------
- func: initialize()
- desc: initializes the object
--]]---------------------------------------------------------
function newobject:initialize(object)
self.type = "multichoicelist"
self.parent = loveframes.base
self.list = object
self.x = object.x
self.y = object.y + self.list.height
self.width = self.list.width
self.height = 0
self.clickx = 0
self.clicky = 0
self.padding = self.list.listpadding
self.spacing = self.list.listspacing
self.buttonscrollamount = object.buttonscrollamount
self.mousewheelscrollamount = object.mousewheelscrollamount
self.offsety = 0
self.offsetx = 0
self.extrawidth = 0
self.extraheight = 0
self.canremove = false
self.dtscrolling = self.list.dtscrolling
self.internal = true
self.vbar = false
self.children = {}
self.internals = {}
for k, v in ipairs(object.choices) do
local row = loveframes.objects["multichoicerow"]:new()
row:SetText(v)
self:AddItem(row)
end
table.insert(loveframes.base.internals, self)
-- apply template properties to the object
loveframes.templates.ApplyToObject(self)
end
--[[---------------------------------------------------------
- func: update(deltatime)
- desc: updates the object
--]]---------------------------------------------------------
function newobject:update(dt)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
local alwaysupdate = self.alwaysupdate
if not visible then
if not alwaysupdate then
return
end
end
local width = love.graphics.getWidth()
local height = love.graphics.getHeight()
local x, y = love.mouse.getPosition()
local selfcol = loveframes.util.BoundingBox(x, self.x, y, self.y, 1, self.width, 1, self.height)
local parent = self.parent
local base = loveframes.base
local upadte = self.Update
local internals = self.internals
local children = self.children
-- move to parent if there is a parent
if parent ~= base then
self.x = parent.x + self.staticx
self.y = parent.y + self.staticy
end
if self.x < 0 then
self.x = 0
end
if self.x + self.width > width then
self.x = width - self.width
end
if self.y < 0 then
self.y = 0
end
if self.y + self.height > height then
self.y = height - self.height
end
for k, v in ipairs(internals) do
v:update(dt)
end
for k, v in ipairs(children) do
v:update(dt)
v:SetClickBounds(self.x, self.y, self.width, self.height)
v.y = (v.parent.y + v.staticy) - self.offsety
v.x = (v.parent.x + v.staticx) - self.offsetx
end
if upadte then
upadte(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 x = self.x
local y = self.y
local width = self.width
local height = self.height
local stencilfunc = function() love.graphics.rectangle("fill", x, y, width, height) end
local skins = loveframes.skins.available
local skinindex = loveframes.config["ACTIVESKIN"]
local defaultskin = loveframes.config["DEFAULTSKIN"]
local selfskin = self.skin
local skin = skins[selfskin] or skins[skinindex]
local drawfunc = skin.DrawMultiChoiceList or skins[defaultskin].DrawMultiChoiceList
local drawoverfunc = skin.DrawOverMultiChoiceList or skins[defaultskin].DrawOverMultiChoiceList
local draw = self.Draw
local drawcount = loveframes.drawcount
local internals = self.internals
local children = self.children
-- set the object's draw order
self:SetDrawOrder()
if draw then
draw(self)
else
drawfunc(self)
end
for k, v in ipairs(internals) do
v:draw()
end
love.graphics.setStencil(stencilfunc)
for k, v in ipairs(children) do
local col = loveframes.util.BoundingBox(self.x, v.x, self.y, v.y, self.width, v.width, self.height, v.height)
if col then
v:draw()
end
end
love.graphics.setStencil()
if not draw then
drawoverfunc(self)
end
end
--[[---------------------------------------------------------
- func: mousepressed(x, y, button)
- desc: called when the player presses a mouse button
--]]---------------------------------------------------------
function newobject:mousepressed(x, y, button)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
local selfcol = loveframes.util.BoundingBox(x, self.x, y, self.y, 1, self.width, 1, self.height)
local toplist = self:IsTopList()
local internals = self.internals
local children = self.children
local scrollamount = self.mousewheelscrollamount
if not selfcol and self.canremove and button == "l" then
self:Close()
end
if self.vbar and toplist then
local bar = internals[1].internals[1].internals[1]
local dtscrolling = self.dtscrolling
if dtscrolling then
local dt = love.timer.getDelta()
if button == "wu" then
bar:Scroll(-scrollamount * dt)
elseif button == "wd" then
bar:Scroll(scrollamount * dt)
end
else
if button == "wu" then
bar:Scroll(-scrollamount)
elseif button == "wd" then
bar:Scroll(scrollamount)
end
end
end
for k, v in ipairs(internals) do
v:mousepressed(x, y, button)
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
if not visible then
return
end
local internals = self.internals
local children = self.children
self.canremove = true
for k, v in ipairs(internals) do
v:mousereleased(x, y, button)
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)
if object.type ~= "multichoicerow" then
return
end
object.parent = self
table.insert(self.children, object)
self:CalculateSize()
self:RedoLayout()
end
--[[---------------------------------------------------------
- func: RemoveItem(object)
- desc: removes an item from the object
--]]---------------------------------------------------------
function newobject:RemoveItem(object)
local children = self.children
for k, v in ipairs(children) do
if v == object then
table.remove(children, k)
end
end
self:CalculateSize()
self:RedoLayout()
end
--[[---------------------------------------------------------
- func: CalculateSize()
- desc: calculates the size of the object's children
--]]---------------------------------------------------------
function newobject:CalculateSize()
self.height = self.padding
if self.list.listheight then
self.height = self.list.listheight
else
for k, v in ipairs(self.children) do
self.height = self.height + (v.height + self.spacing)
end
end
if self.height > love.graphics.getHeight() then
self.height = love.graphics.getHeight()
end
local numitems = #self.children
local height = self.height
local padding = self.padding
local spacing = self.spacing
local itemheight = self.padding
local vbar = self.vbar
local children = self.children
for k, v in ipairs(children) do
itemheight = itemheight + v.height + spacing
end
self.itemheight = (itemheight - spacing) + padding
if self.itemheight > height then
self.extraheight = self.itemheight - height
if not vbar then
local scroll = loveframes.objects["scrollbody"]:new(self, "vertical")
table.insert(self.internals, scroll)
self.vbar = true
end
else
if vbar then
self.internals[1]:Remove()
self.vbar = false
self.offsety = 0
end
end
end
--[[---------------------------------------------------------
- func: RedoLayout()
- desc: used to redo the layour of the object
--]]---------------------------------------------------------
function newobject:RedoLayout()
local children = self.children
local padding = self.padding
local spacing = self.spacing
local starty = padding
local vbar = self.vbar
if #children > 0 then
for k, v in ipairs(children) do
v.staticx = padding
v.staticy = starty
if vbar then
v.width = (self.width - self.internals[1].width) - padding * 2
self.internals[1].staticx = self.width - self.internals[1].width
self.internals[1].height = self.height
else
v.width = self.width - padding * 2
end
starty = starty + v.height
starty = starty + spacing
end
end
end
--[[---------------------------------------------------------
- func: SetPadding(amount)
- desc: sets the object's padding
--]]---------------------------------------------------------
function newobject:SetPadding(amount)
self.padding = amount
end
--[[---------------------------------------------------------
- func: SetSpacing(amount)
- desc: sets the object's spacing
--]]---------------------------------------------------------
function newobject:SetSpacing(amount)
self.spacing = amount
end
--[[---------------------------------------------------------
- func: Close()
- desc: closes the object
--]]---------------------------------------------------------
function newobject:Close()
self:Remove()
self.list.haslist = false
end | mit |
HEYAHONG/nodemcu-firmware | lua_examples/ucglib/GT_pixel_and_lines.lua | 7 | 1116 | -- luacheck: globals T r disp millis lcg_rnd
local M, module = {}, ...
_G[module] = M
function M.run()
-- make this a volatile module:
package.loaded[module] = nil
print("Running component pixel_and_lines...")
local mx
local x, xx
mx = disp:getWidth() / 2
--my = disp:getHeight() / 2
disp:setColor(0, 0, 0, 150)
disp:setColor(1, 0, 60, 40)
disp:setColor(2, 60, 0, 40)
disp:setColor(3, 120, 120, 200)
disp:drawGradientBox(0, 0, disp:getWidth(), disp:getHeight())
disp:setColor(255, 255, 255)
disp:setPrintPos(2, 18)
disp:setPrintDir(0)
disp:print("Pix&Line")
disp:drawPixel(0, 0)
disp:drawPixel(1, 0)
--disp:drawPixel(disp:getWidth()-1, 0)
--disp:drawPixel(0, disp:getHeight()-1)
disp:drawPixel(disp:getWidth()-1, disp:getHeight()-1)
disp:drawPixel(disp:getWidth()-1-1, disp:getHeight()-1)
x = 0
while x < mx do
xx = ((x)*255)/mx
disp:setColor(255, 255-xx/2, 255-xx)
disp:drawPixel(x, 24)
disp:drawVLine(x+7, 26, 13)
x = x + 1
end
print("...done")
end
return M
| mit |
JarnoVgr/Mr.Green-MTA-Resources | resources/[gameplay]/missiontimer/missiontimer_client.lua | 4 | 4262 | rootElement = getRootElement()
thisResource = getThisResource()
missionTimers = {}
bool = { [false]=true, [true]=true }
addEvent ( "onClientMissionTimerElapsed", true )
addEventHandler("onClientResourceStart",resourceRoot,
function()
triggerServerEvent ( "onClientMissionTimerDownloaded", getLocalPlayer() )
end
)
addEventHandler ("onClientResourceStop",rootElement,
function()
for i,timer in ipairs(getElementsByType("missiontimer",source)) do
destroyElement(timer)
end
end
)
function createMissionTimer ( duration, countdown, timerFormat, x, y, bg, font, scale, r, g, b )
sourceResource = sourceResource or thisResource
local element = createElement ( "missiontimer" )
setElementParent ( element, getResourceDynamicElementRoot(sourceResource) )
setupMissionTimer ( element, duration, countdown, timerFormat, x, y, bg, font, scale, r, g, b )
return element
end
function setupMissionTimer ( element, duration, countdown, timerFormat, x, y, bg, font, scale, r, g, b )
if missionTimers[element] then return end
addEventHandler ( "onClientElementDestroy", element, onMissionTimerDestroy )
missionTimers[element] = {}
missionTimers[element].x = tonumber(x) or 0
missionTimers[element].y = tonumber(y) or 0
missionTimers[element].countdown = countdown
missionTimers[element].duration = duration
missionTimers[element].originalTick = getTickCount()
missionTimers[element].timerFormat = type( timerFormat ) == "string" and timerFormat or "%m:%s:%cs"
missionTimers[element].bg = (bool[bg] == nil and true) or bg
missionTimers[element].font = font or "default-bold"
missionTimers[element].scale = tonumber(scale) or 1
missionTimers[element].hurrytime = 15000
missionTimers[element].formatWidth = dxGetTextWidth(missionTimers[element].timerFormat, missionTimers[element].scale, missionTimers[element].font)
missionTimers[element].colour = (r and g and b) and tocolor(r, g, b) or tocolor(255,255,255)
missionTimers[element].timer = setTimer ( triggerEvent, duration, 1, "onClientMissionTimerElapsed", element )
end
function setMissionTimerTime ( timer, time )
if missionTimers[timer] then
missionTimers[timer].duration = tonumber(time) or missionTimers[timer].remaining
missionTimers[timer].originalTick = getTickCount()
if isTimer( missionTimers[timer].timer ) then
killTimer ( missionTimers[timer].timer )
end
missionTimers[timer].timer = setTimer ( triggerEvent, missionTimers[timer].duration, 1, "onClientMissionTimerElapsed", element )
return true
end
return false
end
function getMissionTimerTime ( timer )
if missionTimers[timer] then
if missionTimers[timer].countdown then
return math.max(missionTimers[timer].duration - (getTickCount() - missionTimers[timer].originalTick),0)
else
return (getTickCount() - missionTimers[timer].originalTick)
end
end
return false
end
function setMissionTimerFrozen ( timer, frozen )
if frozen == not not missionTimers[timer].frozen then return false end
if missionTimers[timer] and bool[frozen] then
missionTimers[timer].frozen = frozen or nil
if frozen then
if isTimer( missionTimers[timer].timer ) then
killTimer ( missionTimers[timer].timer )
end
missionTimers[timer].timer = nil
missionTimers[timer].duration = getMissionTimerTime ( timer )
else
missionTimers[timer].timer = setTimer ( triggerEvent, missionTimers[timer].duration, 1, "onClientMissionTimerElapsed", timer )
missionTimers[timer].originalTick = getTickCount()
end
return true
end
return false
end
function isMissionTimerFrozen ( timer )
return not not missionTimers[timer].frozen
end
function setMissionTimerHurryTime ( timer, time )
missionTimers[timer].hurrytime = tonumber(time) or 15000
end
function setMissionTimerFormat( timer, timerFormat )
if type( timerFormat ) ~= "string" then return false end
if missionTimers[timer] then
missionTimers[timer].timerFormat = timerFormat
missionTimers[timer].formatWidth = dxGetTextWidth(missionTimers[timer].timerFormat, missionTimers[timer].scale, missionTimers[timer].font)
end
end
function onMissionTimerDestroy()
for i,timer in ipairs(getTimers()) do
if timer == missionTimers[source].timer then
killTimer ( timer )
break
end
end
missionTimers[source] = nil
end
| mit |
JarnoVgr/Mr.Green-MTA-Resources | resources/[race]/race/modes/rtf.lua | 3 | 4496 | RTF = setmetatable({}, RaceMode)
RTF.__index = RTF
RTF:register('rtf')
function RTF:isMapValid()
-- Check if there is only one object for each flag in the map
local flagObjects = #getElementsByType'rtf'
if flagObjects ~= 1 then
outputRace('Error. RTF map should have 1 flag (' .. flagObjects .. ')')
return false
elseif self.getNumberOfCheckpoints() > 0 then
outputRace('Error. RTF map shouldn\'t have checkpoints')
return false
end
return true
end
function RTF:start()
self:cleanup()
local flagElement = getElementsByType'rtf'[1]
self.object = createObject(self.FlagModel, getElementPosition(flagElement))
self:createFlag(self.object)
end
function RTF:createFlag(object)
local flag = {}
local x, y, z = getElementPosition(object)
flag.marker = createMarker ( x, y, z-0.5, 'corona', 1.5 )
flag.col = createColSphere ( x, y, z+0.6, 5 )
flag.blip = createBlipAttachedTo(object, 19, 5, 255, 255, 255, 255, 500)
setElementParent(flag.marker, object)
setElementParent(flag.col, object)
setElementParent(flag.blip, object)
setElementData(flag.blip,"customBlipPath",':race/model/Blipid53.png')
addEventHandler('onColShapeHit', flag.col, RTF.hit)
RTF.flags[object] = flag
setElementData(object, 'race.rtf_flag', true)
end
function RTF.hit(hitElement)
if not (getElementType(hitElement) == 'vehicle' and not isVehicleBlown(hitElement) and getVehicleController(hitElement) and getElementHealth(getVehicleController(hitElement)) ~= 0) then return end
-- outputDebugString('hit col')
for k, v in pairs(RTF.flags) do
-- outputDebugString('checking hit known col')
if (v.col == source) then
-- outputDebugString('hit known col')
return g_CurrentRaceMode:hitColshape(k, getVehicleController(hitElement))
end
end
end
function RTF:hitColshape(object, player)
-- outputDebugString('player hit known col')
self:playerWon(player)
end
function RTF:playerWon(player)
if not isElement(player) then return end
-- outputDebugString('player won')
showMessage(getPlayerName(player) .. ' has reached the flag!', 0, 255, 0)
playSoundFrontEnd(player, 11)
self.setPlayerIsFinished(player)
triggerEvent('onPlayerFinish', player, 1, self:getTimePassed())
self:cleanup()
self:endMap()
clientCall(g_Root, 'raceTimeout')
end
function RTF:isRanked()
return true
end
function RTF:updateRanks()
-- Make a table with the active players
local sortinfo = {}
for i,player in ipairs(getActivePlayers()) do
sortinfo[i] = {}
sortinfo[i].player = player
sortinfo[i].cpdist = self:shortestDistanceFromPlayerToFlag(player)
end
-- Order by cp
table.sort( sortinfo, function(a,b)
return a.cpdist < b.cpdist
end )
-- Copy back into active players list to speed up sort next time
for i,info in ipairs(sortinfo) do
g_CurrentRaceMode.activePlayerList[i] = info.player
end
-- Update data
local rankOffset = getFinishedPlayerCount()
for i,info in ipairs(sortinfo) do
setElementData(info.player, 'race rank', i + rankOffset )
end
-- Make text look good at the start
if not self.running then
for i,player in ipairs(g_Players) do
setElementData(player, 'race rank', 1 )
end
end
end
function RTF:shortestDistanceFromPlayerToFlag(player)
local shortest = 1000000
local pos1 = {getElementPosition(player)}
for object, _ in pairs(RTF.flags) do
if isElement(object) then
local pos2 = {getElementPosition(object)}
local dist = getDistanceBetweenPoints3D (pos1[1], pos1[2], pos1[3], pos2[1], pos2[2], pos2[3])
if dist < shortest then
shortest = dist
end
end
end
return shortest
end
function RTF:cleanup()
-- Cleanup for next mode
-- clientCall(root, 'ctfStop')
for object, flag in pairs(RTF.flags) do
for _, ele in pairs(flag) do
if ele and isElement(ele) then
destroyElement(ele)
end
end
if object and isElement(object) then
destroyElement(object)
end
RTF.flags[object] = nil
end
RTF.flags = {}
RTF.object = nil
end
function RTF:destroy()
self:cleanup()
if self.rankingBoard then
self.rankingBoard:destroy()
self.rankingBoard = nil
end
TimerManager.destroyTimersFor("checkpointBackup")
RaceMode.instances[self.id] = nil
end
RTF.FlagModel = 2914
RTF.FlagBlip = 19
RTF.flags = {}
RTF.object = nil
RTF.name = 'Reach the flag'
RTF.modeOptions = {
respawn = 'timelimit',
respawntime = 5,
autopimp = false,
autopimp_map_can_override = false,
ghostmode = true,
ghostmode_map_can_override = false,
duration = (g_MapOptions and (g_MapOptions.duration < 600)) or 10*60*1000,
} | mit |
minecraftgame-andrd/minecraftgame | 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 |
shadoalzupedy/shadow | plugins/infoeng.lua | 7 | 9964 | --[[
#
#ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ
#:((
# For More Information ....!
# Developer : Aziz < @TH3_GHOST >
# our channel: @DevPointTeam
# Version: 1.1
#:))
#ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ
#
]]
do
local Arian = 119626024 --put your id here(BOT OWNER ID)
local function setrank(msg, name, value) -- setrank function
local hash = nil
if msg.to.type == 'chat' then
hash = 'rank:'..msg.to.id..':variables'
end
if hash then
redis:hset(hash, name, value)
return send_msg('chat#id'..msg.to.id, 'مقام کاربر ('..name..') به\n '..value..' تغییر داده شد. ', ok_cb, true)
end
end
local function res_user_callback(extra, success, result) -- /info <username> function
if success == 1 then
if result.username then
Username = '@'..result.username
else
Username = 'لايوجد'
end
local text = '› الاسم : '..(result.first_name or '')..' '..(result.last_name or '')..'\n'
..'› المعرف : '..Username..'\n'
..'› الايدي : '..result.id..'\n\n'
local hash = 'whois:'..extra.chat2..':variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == tonumber(Arian) then
text = text..'› whois: (Sudo) \n\n'
elseif is_admin2(result.id) then
text = text..'› whois: (Admin) \n\n'
elseif is_owner2(result.id, extra.chat2) then
text = text..'› whois: (Owner) \n\n'
elseif is_momod2(result.id, extra.chat2) then
text = text..'›whois: (Moderator) \n\n'
else
text = text..'›whois: (Member) \n\n'
end
else
text = text..'› whois : '..value..'\n\n'
end
local uhash = 'user:'..result.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.id..':'..extra.chat2
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'› msg : '..user_info_msgs..'\n\n'
text = text..'ِ'
send_msg(extra.receiver, text, ok_cb, true)
else
send_msg(extra.receiver, extra.user..' نام کاربری مورد نظر یافت نشد.', ok_cb, false)
end
end
local function action_by_id(extra, success, result) -- /info <ID> function
if success == 1 then
if result.username then
Username = '@'..result.username
else
Username = 'لايوجد'
end
local text = '› الاسم : '..(result.first_name or '')..' '..(result.last_name or '')..'\n'
..'› المعرف : '..Username..'\n'
..'› الايدي : '..result.id..'\n\n'
local hash = 'whois:'..extra.chat2..':variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == tonumber(Arian) then
text = text..'› whois: (Sudo) \n\n'
elseif is_admin2(result.id) then
text = text..'› whois: (Admin) \n\n'
elseif is_owner2(result.id, extra.chat2) then
text = text..'› whois: (Owner) \n\n'
elseif is_momod2(result.id, extra.chat2) then
text = text..'› whois: (Moderator) \n\n'
else
text = text..'› whois: (Member) \n\n'
end
else
text = text..'› whois : '..value..'\n\n'
end
local uhash = 'user:'..result.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.id..':'..extra.chat2
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'› msg : '..user_info_msgs..'\n\n'
text = text..'ِ'
send_msg(extra.receiver, text, ok_cb, true)
else
send_msg(extra.receiver, 'آیدی شخص مورد نظر در سیستم ثبت نشده است.\nاز دستور زیر استفاده کنید\n/info @username', ok_cb, false)
end
end
local function action_by_reply(extra, success, result)-- (reply) /info function
if result.from.username then
Username = '@'..result.from.username
else
Username = 'لايوجد'
end
local text = '♍️- name : '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n'
..'♑️- username : '..Username..'\n'
..'♑️- your ID : '..result.from.id..'\n\n'
local hash = 'whois:'..result.to.id..':variables'
local value = redis:hget(hash, result.from.id)
if not value then
if result.from.id == tonumber(Arian) then
text = text..'💟- whois: (Sudo) \n\n'
elseif is_admin2(result.from.id) then
text = text..'💟- whois: (Admin) \n\n'
elseif is_owner2(result.from.id, result.to.id) then
text = text..'💟- whois: (Owner) \n\n'
elseif is_momod2(result.from.id, result.to.id) then
text = text..'💟- whois: (Moderator) \n\n'
else
text = text..'💟- whois: (Member) \n\n'
end
else
text = text..'› whois : '..value..'\n\n'
end
local user_info = {}
local uhash = 'user:'..result.from.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.from.id..':'..result.to.id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'ℹ️- msgs : '..user_info_msgs..'\n'
text = text..'ِ'
send_msg(extra.receiver, text, ok_cb, true)
end
local function action_by_reply2(extra, success, result)
local value = extra.value
setrank(result, result.from.id, value)
end
local function run(msg, matches)
if matches[1]:lower() == 'setrank' then
local hash = 'usecommands:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
if not is_sudo(msg) then
return "Only Owners !"
end
local receiver = get_receiver(msg)
local Reply = msg.reply_id
if msg.reply_id then
local value = string.sub(matches[2], 1, 1000)
msgr = get_message(msg.reply_id, action_by_reply2, {receiver=receiver, Reply=Reply, value=value})
else
local name = string.sub(matches[2], 1, 50)
local value = string.sub(matches[3], 1, 1000)
local text = setrank(msg, name, value)
return text
end
end
if matches[1]:lower() == 'info' and not matches[2] then
local receiver = get_receiver(msg)
local Reply = msg.reply_id
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {receiver=receiver, Reply=Reply})
else
if msg.from.username then
Username = '@'..msg.from.username
else
Username = 'لايوجد'
end
local text = '♍️- First Name : '..(msg.from.first_name or 'لا يوجد ')..'\n'
local text = text..'♒️- Last Name : '..(msg.from.last_name or 'لا يوجد ')..'\n'
local text = text..'♑️- Username : '..Username..'\n'
local text = text..'🆔- Your id : '..msg.from.id..'\n'
local text = text..'📲- phone : '..(msg.from.phone or 'لا يوجد ')..'\n'
local hash = 'rank:'..msg.to.id..':variables'
if hash then
local value = redis:hget(hash, msg.from.id)
if not value then
if msg.from.id == tonumber(Arian) then
text = text..'💟- Your : --انت مطور-- \n'
elseif is_sudo(msg) then
text = text..'💟- Your : --انت مطور-- \n'
elseif is_owner(msg) then
text = text..'💟- Your : --انت مشرف-- \n'
elseif is_momod(msg) then
text = text..'💟- Your : --انت ادمن-- \n'
else
text = text..'💟- Your : --انت عضو--\n'
end
else
text = text..'💡 whois : '..value..'\n'
end
end
local uhash = 'user:'..msg.from.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..msg.from.id..':'..msg.to.id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'ℹ️- Msgs :'..user_info_msgs..'\n\n'
if msg.to.type == 'chat' then
text = text..'› اسم المجموعه : '..msg.to.title..'\n'
text = text..'› ايدي المجموعه : '..msg.to.id
return reply_msg(msg.id, text, ok_cb, false)
end
return send_msg(receiver, text, ok_cb, true)
end
end
if matches[1]:lower() == '' and matches[2] then
local user = matches[2]
local chat2 = msg.to.id
local receiver = get_receiver(msg)
if string.match(user, '^%d+$') then
user_info('user#id'..user, action_by_id, {receiver=receiver, user=user, text=text, chat2=chat2})
elseif string.match(user, '^@.+$') then
username = string.gsub(user, '@', '')
msgr = res_user(username, res_user_callback, {receiver=receiver, user=user, text=text, chat2=chat2})
end
end
end
return {
description = 'Know your information or the info of a chat members.',
usage = {
'!info: Return your info and the chat info if you are in one.',
'(Reply)!info: Return info of replied user if used by reply.',
'!info <id>: Return the info\'s of the <id>.',
'!info @<user_name>: Return the member @<user_name> information from the current chat.',
'!setrank <userid> <rank>: change members rank.',
'(Reply)!setrank <rank>: change members rank.',
},
patterns = {
"^[/!](info)$",
"^[/!](info) (.*)$",
"^[/!]([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (%d+) (.*)$",
"^[/!]([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (.*)$",
"^[/!](info)$",
"^[/!](info) (.*)$",
"^[Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (%d+) (.*)$",
"^([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (.*)$",
},
run = run
}
end
-- post by : @devpointch
--[[ ldocal geroup_ovwner = dpata[toostring(misg.tno.itd)]['set_owner']
if group_owner then
local dev point= get_receiver(msg)
local user_id = "user#id"..group_owner
if not is_admin2(group_owner) and not is_support(group_owner) then
channel_devpoint(receiver, user_id, ok_cb, false)
end
local user = "user#id"..matches[2]
channel_set_admin(receiver, user, ok_cb, false)
data[tostring(msg.to.id)]['set_owner'] = devpoint(matches[2])
save_data(_config.moderation.data, data)
dev[point(msg.to.id, name_log.." ["..dev.point.id.."] set ["..matches[2].."] as owner")
local text = "[ "..matches[2].." ] added as owner"
return text
end]]
| gpl-2.0 |
Zefiros-Software/ZPM | extern/pepperfish_profiler.lua | 1 | 18784 | --
-- http://lua-users.org/wiki/PepperfishProfiler
--
-- == Introduction ==
--
-- Note that this requires os.clock(), debug.sethook(),
-- and debug.getinfo() or your equivalent replacements to
-- be available if this is an embedded application.
--
-- Example usage:
--
-- profiler = newProfiler()
-- profiler:start()
--
-- < call some functions that take time >
--
-- profiler:stop()
--
-- local outfile = io.open( "profile.txt", "w+" )
-- profiler:report( outfile )
-- outfile:close()
--
-- == Optionally choosing profiling method ==
--
-- The rest of this comment can be ignored if you merely want a good profiler.
--
-- newProfiler(method, sampledelay):
--
-- If method is omitted or "time", will profile based on real performance.
-- optionally, frequency can be provided to control the number of opcodes
-- per profiling tick. By default this is 100000, which (on my system) provides
-- one tick approximately every 2ms and reduces system performance by about 10%.
-- This can be reduced to increase accuracy at the cost of performance, or
-- increased for the opposite effect.
--
-- If method is "call", will profile based on function calls. Frequency is
-- ignored.
--
--
-- "time" may bias profiling somewhat towards large areas with "simple opcodes",
-- as the profiling function (which introduces a certain amount of unavoidable
-- overhead) will be called more often. This can be minimized by using a larger
-- sample delay - the default should leave any error largely overshadowed by
-- statistical noise. With a delay of 1000 I was able to achieve inaccuray of
-- approximately 25%. Increasing the delay to 100000 left inaccuracy below my
-- testing error.
--
-- "call" may bias profiling heavily towards areas with many function calls.
-- Testing found a degenerate case giving a figure inaccurate by approximately
-- 20,000%. (Yes, a multiple of 200.) This is, however, more directly comparable
-- to common profilers (such as gprof) and also gives accurate function call
-- counts, which cannot be retrieved from "time".
--
-- I strongly recommend "time" mode, and it is now the default.
--
-- == History ==
--
-- 2008-09-16 - Time-based profiling and conversion to Lua 5.1
-- by Ben Wilhelm ( zorba-pepperfish@pavlovian.net ).
-- Added the ability to optionally choose profiling methods, along with a new
-- profiling method.
--
-- Converted to Lua 5, a few improvements, and
-- additional documentation by Tom Spilman ( tom@sickheadgames.com )
--
-- Additional corrections and tidying by original author
-- Daniel Silverstone ( dsilvers@pepperfish.net )
--
-- == Status ==
--
-- Daniel Silverstone is no longer using this code, and judging by how long it's
-- been waiting for Lua 5.1 support, I don't think Tom Spilman is either. I'm
-- perfectly willing to take on maintenance, so if you have problems or
-- questions, go ahead and email me :)
-- -- Ben Wilhelm ( zorba-pepperfish@pavlovian.net ) '
--
-- == Copyright ==
--
-- Lua profiler - Copyright Pepperfish 2002,2003,2004
--
-- 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, 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.
--
--
-- All profiler related stuff is stored in the top level table '_profiler'
--
_profiler = {}
--
-- newProfiler() creates a new profiler object for managing
-- the profiler and storing state. Note that only one profiler
-- object can be executing at one time.
--
function newProfiler(variant, sampledelay)
if _profiler.running then
print("Profiler already running.")
return
end
variant = variant or "time"
if variant ~= "time" and variant ~= "call" then
print("Profiler method must be 'time' or 'call'.")
return
end
local newprof = {}
for k,v in pairs(_profiler) do
newprof[k] = v
end
newprof.variant = variant
newprof.sampledelay = sampledelay or 100000
return newprof
end
--
-- This function starts the profiler. It will do nothing
-- if this (or any other) profiler is already running.
--
function _profiler.start(self)
if _profiler.running then
return
end
-- Start the profiler. This begins by setting up internal profiler state
_profiler.running = self
self.rawstats = {}
self.callstack = {}
if self.variant == "time" then
self.lastclock = os.clock()
debug.sethook( _profiler_hook_wrapper_by_time, "", self.sampledelay )
elseif self.variant == "call" then
debug.sethook( _profiler_hook_wrapper_by_call, "cr" )
else
print("Profiler method must be 'time' or 'call'.")
sys.exit(1)
end
end
--
-- This function stops the profiler. It will do nothing
-- if a profiler is not running, and nothing if it isn't
-- the currently running profiler.
--
function _profiler.stop(self)
if _profiler.running ~= self then
return
end
-- Stop the profiler.
debug.sethook( nil )
_profiler.running = nil
end
--
-- Simple wrapper to handle the hook. You should not
-- be calling this directly. Duplicated to reduce overhead.
--
function _profiler_hook_wrapper_by_call(action)
if _profiler.running == nil then
debug.sethook( nil )
end
_profiler.running:_internal_profile_by_call(action)
end
function _profiler_hook_wrapper_by_time(action)
if _profiler.running == nil then
debug.sethook( nil )
end
_profiler.running:_internal_profile_by_time(action)
end
--
-- This is the main by-function-call function of the profiler and should not
-- be called except by the hook wrapper
--
function _profiler._internal_profile_by_call(self,action)
-- Since we can obtain the 'function' for the item we've had call us, we
-- can use that...
local caller_info = debug.getinfo( 3 )
if caller_info == nil then
print "No caller_info"
return
end
--SHG_LOG("[_profiler._internal_profile] "..(caller_info.name or "<nil>"))
-- Retrieve the most recent activation record...
local latest_ar = nil
if #self.callstack > 0 then
latest_ar = self.callstack[#self.callstack]
end
-- Are we allowed to profile this function?
local should_not_profile = 0
for k,v in pairs(self.prevented_functions) do
if k == caller_info.func then
should_not_profile = v
end
end
-- Also check the top activation record...
if latest_ar then
if latest_ar.should_not_profile == 2 then
should_not_profile = 2
end
end
-- Now then, are we in 'call' or 'return' ?
-- print("Profile:", caller_info.name, "SNP:", should_not_profile,
-- "Action:", action )
if action == "call" then
-- Making a call...
local this_ar = {}
this_ar.should_not_profile = should_not_profile
this_ar.parent_ar = latest_ar
this_ar.anon_child = 0
this_ar.name_child = 0
this_ar.children = {}
this_ar.children_time = {}
this_ar.clock_start = os.clock()
-- Last thing to do on a call is to insert this onto the ar stack...
table.insert( self.callstack, this_ar )
else
local this_ar = latest_ar
if this_ar == nil then
return -- No point in doing anything if no upper activation record
end
-- Right, calculate the time in this function...
this_ar.clock_end = os.clock()
this_ar.this_time = this_ar.clock_end - this_ar.clock_start
-- Now, if we have a parent, update its call info...
if this_ar.parent_ar then
this_ar.parent_ar.children[caller_info.func] =
(this_ar.parent_ar.children[caller_info.func] or 0) + 1
this_ar.parent_ar.children_time[caller_info.func] =
(this_ar.parent_ar.children_time[caller_info.func] or 0 ) +
this_ar.this_time
if caller_info.name == nil then
this_ar.parent_ar.anon_child =
this_ar.parent_ar.anon_child + this_ar.this_time
else
this_ar.parent_ar.name_child =
this_ar.parent_ar.name_child + this_ar.this_time
end
end
-- Now if we're meant to record information about ourselves, do so...
if this_ar.should_not_profile == 0 then
local inforec = self:_get_func_rec(caller_info.func,1)
inforec.count = inforec.count + 1
inforec.time = inforec.time + this_ar.this_time
inforec.anon_child_time = inforec.anon_child_time + this_ar.anon_child
inforec.name_child_time = inforec.name_child_time + this_ar.name_child
inforec.func_info = caller_info
for k,v in pairs(this_ar.children) do
inforec.children[k] = (inforec.children[k] or 0) + v
inforec.children_time[k] =
(inforec.children_time[k] or 0) + this_ar.children_time[k]
end
end
-- Last thing to do on return is to drop the last activation record...
table.remove( self.callstack, #self.callstack )
end
end
--
-- This is the main by-time internal function of the profiler and should not
-- be called except by the hook wrapper
--
function _profiler._internal_profile_by_time(self,action)
-- we do this first so we add the minimum amount of extra time to this call
local timetaken = os.clock() - self.lastclock
local depth = 3
local at_top = true
local last_caller
local caller = debug.getinfo(depth)
while caller do
if not caller.func then caller.func = "(tail call)" end
if self.prevented_functions[caller.func] == nil then
local info = self:_get_func_rec(caller.func, 1, caller)
info.count = info.count + 1
info.time = info.time + timetaken
if last_caller then
-- we're not the head, so update the "children" times also
if last_caller.name then
info.name_child_time = info.name_child_time + timetaken
else
info.anon_child_time = info.anon_child_time + timetaken
end
info.children[last_caller.func] =
(info.children[last_caller.func] or 0) + 1
info.children_time[last_caller.func] =
(info.children_time[last_caller.func] or 0) + timetaken
end
end
depth = depth + 1
last_caller = caller
caller = debug.getinfo(depth)
end
self.lastclock = os.clock()
end
--
-- This returns a (possibly empty) function record for
-- the specified function. It is for internal profiler use.
--
function _profiler._get_func_rec(self,func,force,info)
-- Find the function ref for 'func' (if force and not present, create one)
local ret = self.rawstats[func]
if ret == nil and force ~= 1 then
return nil
end
if ret == nil then
-- Build a new function statistics table
ret = {}
ret.func = func
ret.count = 0
ret.time = 0
ret.anon_child_time = 0
ret.name_child_time = 0
ret.children = {}
ret.children_time = {}
ret.func_info = info
self.rawstats[func] = ret
end
return ret
end
--
-- This writes a profile report to the output file object. If
-- sort_by_total_time is nil or false the output is sorted by
-- the function time minus the time in it's children.
--
function _profiler.report( self, outfile, sort_by_total_time )
outfile:write
[[Lua Profile output created by profiler.lua. Copyright Pepperfish 2002+
]]
-- This is pretty awful.
local terms = {}
if self.variant == "time" then
terms.capitalized = "Sample"
terms.single = "sample"
terms.pastverb = "sampled"
elseif self.variant == "call" then
terms.capitalized = "Call"
terms.single = "call"
terms.pastverb = "called"
else
assert(false)
end
local total_time = 0
local ordering = {}
for func,record in pairs(self.rawstats) do
table.insert(ordering, func)
end
if sort_by_total_time then
table.sort( ordering,
function(a,b) return self.rawstats[a].time > self.rawstats[b].time end
)
else
table.sort( ordering,
function(a,b)
local arec = self.rawstats[a]
local brec = self.rawstats[b]
local atime = arec.time - (arec.anon_child_time + arec.name_child_time)
local btime = brec.time - (brec.anon_child_time + brec.name_child_time)
return atime > btime
end
)
end
for i=1,#ordering do
local func = ordering[i]
local record = self.rawstats[func]
local thisfuncname = " " .. self:_pretty_name(func) .. " "
if string.len( thisfuncname ) < 42 then
thisfuncname = string.rep( "-", math.floor((42 - string.len(thisfuncname))/2) ) .. thisfuncname
thisfuncname = thisfuncname .. string.rep( "-", 42 - string.len(thisfuncname) )
end
total_time = total_time + ( record.time - ( record.anon_child_time +
record.name_child_time ) )
outfile:write( string.rep( "-", 19 ) .. thisfuncname ..
string.rep( "-", 19 ) .. "\n" )
outfile:write( terms.capitalized.." count: " ..
string.format( "%4d", record.count ) .. "\n" )
outfile:write( "Time spend total: " ..
string.format( "%4.3f", record.time ) .. "s\n" )
outfile:write( "Time spent in children: " ..
string.format("%4.3f",record.anon_child_time+record.name_child_time) ..
"s\n" )
local timeinself =
record.time - (record.anon_child_time + record.name_child_time)
outfile:write( "Time spent in self: " ..
string.format("%4.3f", timeinself) .. "s\n" )
outfile:write( "Time spent per " .. terms.single .. ": " ..
string.format("%4.5f", record.time/record.count) ..
"s/" .. terms.single .. "\n" )
outfile:write( "Time spent in self per "..terms.single..": " ..
string.format( "%4.5f", timeinself/record.count ) .. "s/" ..
terms.single.."\n" )
-- Report on each child in the form
-- Child <funcname> called n times and took a.bs
local added_blank = 0
for k,v in pairs(record.children) do
if self.prevented_functions[k] == nil or
self.prevented_functions[k] == 0
then
if added_blank == 0 then
outfile:write( "\n" ) -- extra separation line
added_blank = 1
end
outfile:write( "Child " .. self:_pretty_name(k) ..
string.rep( " ", 41-string.len(self:_pretty_name(k)) ) .. " " ..
terms.pastverb.." " .. string.format("%6d", v) )
outfile:write( " times. Took " ..
string.format("%4.2f", record.children_time[k] ) .. "s\n" )
end
end
outfile:write( "\n" ) -- extra separation line
outfile:flush()
end
outfile:write( "\n\n" )
outfile:write( "Total time spent in profiled functions: " ..
string.format("%5.3g",total_time) .. "s\n" )
outfile:write( [[
END
]] )
outfile:flush()
end
--
-- This writes the profile to the output file object as
-- loadable Lua source.
--
function _profiler.lua_report(self,outfile)
-- Purpose: Write out the entire raw state in a cross-referenceable form.
local ordering = {}
local functonum = {}
for func,record in pairs(self.rawstats) do
table.insert(ordering, func)
functonum[func] = #ordering
end
outfile:write(
"-- Profile generated by profiler.lua Copyright Pepperfish 2002+\n\n" )
outfile:write( "-- Function names\nfuncnames = {}\n" )
for i=1,#ordering do
local thisfunc = ordering[i]
outfile:write( "funcnames[" .. i .. "] = " ..
string.format("%q", self:_pretty_name(thisfunc)) .. "\n" )
end
outfile:write( "\n" )
outfile:write( "-- Function times\nfunctimes = {}\n" )
for i=1,#ordering do
local thisfunc = ordering[i]
local record = self.rawstats[thisfunc]
outfile:write( "functimes[" .. i .. "] = { " )
outfile:write( "tot=" .. record.time .. ", " )
outfile:write( "achild=" .. record.anon_child_time .. ", " )
outfile:write( "nchild=" .. record.name_child_time .. ", " )
outfile:write( "count=" .. record.count .. " }\n" )
end
outfile:write( "\n" )
outfile:write( "-- Child links\nchildren = {}\n" )
for i=1,#ordering do
local thisfunc = ordering[i]
local record = self.rawstats[thisfunc]
outfile:write( "children[" .. i .. "] = { " )
for k,v in pairs(record.children) do
if functonum[k] then -- non-recorded functions will be ignored now
outfile:write( functonum[k] .. ", " )
end
end
outfile:write( "}\n" )
end
outfile:write( "\n" )
outfile:write( "-- Child call counts\nchildcounts = {}\n" )
for i=1,#ordering do
local thisfunc = ordering[i]
local record = self.rawstats[thisfunc]
outfile:write( "children[" .. i .. "] = { " )
for k,v in record.children do
if functonum[k] then -- non-recorded functions will be ignored now
outfile:write( v .. ", " )
end
end
outfile:write( "}\n" )
end
outfile:write( "\n" )
outfile:write( "-- Child call time\nchildtimes = {}\n" )
for i=1,#ordering do
local thisfunc = ordering[i]
local record = self.rawstats[thisfunc];
outfile:write( "children[" .. i .. "] = { " )
for k,v in pairs(record.children) do
if functonum[k] then -- non-recorded functions will be ignored now
outfile:write( record.children_time[k] .. ", " )
end
end
outfile:write( "}\n" )
end
outfile:write( "\n\n-- That is all.\n\n" )
outfile:flush()
end
-- Internal function to calculate a pretty name for the profile output
function _profiler._pretty_name(self,func)
-- Only the data collected during the actual
-- run seems to be correct.... why?
local info = self.rawstats[ func ].func_info
-- local info = debug.getinfo( func )
local name = ""
if info.what == "Lua" then
name = "L:"
end
if info.what == "C" then
name = "C:"
end
if info.what == "main" then
name = " :"
end
if info.name == nil then
name = name .. "<"..tostring(func) .. ">"
else
name = name .. info.name
end
if info.source then
name = name
else
if info.what == "C" then
name = name .. "@?"
else
name = name .. "@<string>"
end
end
name = name .. ":"
if info.what == "C" then
name = name .. "?"
else
name = name .. info.linedefined
end
return name
end
--
-- This allows you to specify functions which you do
-- not want profiled. Setting level to 1 keeps the
-- function from being profiled. Setting level to 2
-- keeps both the function and its children from
-- being profiled.
--
-- BUG: 2 will probably act exactly like 1 in "time" mode.
-- If anyone cares, let me (zorba) know and it can be fixed.
--
function _profiler.prevent(self, func, level)
self.prevented_functions[func] = (level or 1)
end
_profiler.prevented_functions = {
[_profiler.start] = 2,
[_profiler.stop] = 2,
[_profiler._internal_profile_by_time] = 2,
[_profiler._internal_profile_by_call] = 2,
[_profiler_hook_wrapper_by_time] = 2,
[_profiler_hook_wrapper_by_call] = 2,
[_profiler.prevent] = 2,
[_profiler._get_func_rec] = 2,
[_profiler.report] = 2,
[_profiler.lua_report] = 2,
[_profiler._pretty_name] = 2
} | mit |
JarnoVgr/Mr.Green-MTA-Resources | resources/[gameplay]/freecam/freecam.lua | 4 | 9416 | -- state variables
local speed = 0
local strafespeed = 0
local rotX, rotY = 0,0
local velocityX, velocityY, velocityZ
-- configurable parameters
local options = {
invertMouseLook = false,
normalMaxSpeed = 2,
slowMaxSpeed = 0.2,
fastMaxSpeed = 12,
smoothMovement = true,
acceleration = 0.3,
decceleration = 0.15,
mouseSensitivity = 0.3,
maxYAngle = 188,
key_fastMove = "lshift",
key_slowMove = "lalt",
key_forward = "w",
key_backward = "s",
key_left = "a",
key_right = "d"
}
local mouseFrameDelay = 0
local rootElement = getRootElement()
local getKeyState = getKeyState
do
local mta_getKeyState = getKeyState
function getKeyState(key)
if isMTAWindowActive() then
return false
else
return mta_getKeyState(key)
end
end
end
-- PRIVATE
local function freecamFrame ()
-- work out an angle in radians based on the number of pixels the cursor has moved (ever)
local cameraAngleX = rotX
local cameraAngleY = rotY
local freeModeAngleZ = math.sin(cameraAngleY)
local freeModeAngleY = math.cos(cameraAngleY) * math.cos(cameraAngleX)
local freeModeAngleX = math.cos(cameraAngleY) * math.sin(cameraAngleX)
local camPosX, camPosY, camPosZ = getCameraMatrix()
-- calculate a target based on the current position and an offset based on the angle
local camTargetX = camPosX + freeModeAngleX * 100
local camTargetY = camPosY + freeModeAngleY * 100
local camTargetZ = camPosZ + freeModeAngleZ * 100
-- Calculate what the maximum speed that the camera should be able to move at.
local mspeed = options.normalMaxSpeed
if getKeyState ( options.key_fastMove ) then
mspeed = options.fastMaxSpeed
elseif getKeyState ( options.key_slowMove ) then
mspeed = options.slowMaxSpeed
end
if options.smoothMovement then
local acceleration = options.acceleration
local decceleration = options.decceleration
-- Check to see if the forwards/backwards keys are pressed
local speedKeyPressed = false
if getKeyState ( options.key_forward ) then
speed = speed + acceleration
speedKeyPressed = true
end
if getKeyState ( options.key_backward ) then
speed = speed - acceleration
speedKeyPressed = true
end
-- Check to see if the strafe keys are pressed
local strafeSpeedKeyPressed = false
if getKeyState ( options.key_right ) then
if strafespeed > 0 then -- for instance response
strafespeed = 0
end
strafespeed = strafespeed - acceleration / 2
strafeSpeedKeyPressed = true
end
if getKeyState ( options.key_left ) then
if strafespeed < 0 then -- for instance response
strafespeed = 0
end
strafespeed = strafespeed + acceleration / 2
strafeSpeedKeyPressed = true
end
-- If no forwards/backwards keys were pressed, then gradually slow down the movement towards 0
if speedKeyPressed ~= true then
if speed > 0 then
speed = speed - decceleration
elseif speed < 0 then
speed = speed + decceleration
end
end
-- If no strafe keys were pressed, then gradually slow down the movement towards 0
if strafeSpeedKeyPressed ~= true then
if strafespeed > 0 then
strafespeed = strafespeed - decceleration
elseif strafespeed < 0 then
strafespeed = strafespeed + decceleration
end
end
-- Check the ranges of values - set the speed to 0 if its very close to 0 (stops jittering), and limit to the maximum speed
if speed > -decceleration and speed < decceleration then
speed = 0
elseif speed > mspeed then
speed = mspeed
elseif speed < -mspeed then
speed = -mspeed
end
if strafespeed > -(acceleration / 2) and strafespeed < (acceleration / 2) then
strafespeed = 0
elseif strafespeed > mspeed then
strafespeed = mspeed
elseif strafespeed < -mspeed then
strafespeed = -mspeed
end
else
speed = 0
strafespeed = 0
if getKeyState ( options.key_forward ) then speed = mspeed end
if getKeyState ( options.key_backward ) then speed = -mspeed end
if getKeyState ( options.key_left ) then strafespeed = mspeed end
if getKeyState ( options.key_right ) then strafespeed = -mspeed end
end
-- Work out the distance between the target and the camera (should be 100 units)
local camAngleX = camPosX - camTargetX
local camAngleY = camPosY - camTargetY
local camAngleZ = 0 -- we ignore this otherwise our vertical angle affects how fast you can strafe
-- Calulcate the length of the vector
local angleLength = math.sqrt(camAngleX*camAngleX+camAngleY*camAngleY+camAngleZ*camAngleZ)
-- Normalize the vector, ignoring the Z axis, as the camera is stuck to the XY plane (it can't roll)
local camNormalizedAngleX = camAngleX / angleLength
local camNormalizedAngleY = camAngleY / angleLength
local camNormalizedAngleZ = 0
-- We use this as our rotation vector
local normalAngleX = 0
local normalAngleY = 0
local normalAngleZ = 1
-- Perform a cross product with the rotation vector and the normalzied angle
local normalX = (camNormalizedAngleY * normalAngleZ - camNormalizedAngleZ * normalAngleY)
local normalY = (camNormalizedAngleZ * normalAngleX - camNormalizedAngleX * normalAngleZ)
local normalZ = (camNormalizedAngleX * normalAngleY - camNormalizedAngleY * normalAngleX)
-- Update the camera position based on the forwards/backwards speed
camPosX = camPosX + freeModeAngleX * speed
camPosY = camPosY + freeModeAngleY * speed
camPosZ = camPosZ + freeModeAngleZ * speed
-- Update the camera position based on the strafe speed
camPosX = camPosX + normalX * strafespeed
camPosY = camPosY + normalY * strafespeed
camPosZ = camPosZ + normalZ * strafespeed
--Store the velocity
velocityX = (freeModeAngleX * speed) + (normalX * strafespeed)
velocityY = (freeModeAngleY * speed) + (normalY * strafespeed)
velocityZ = (freeModeAngleZ * speed) + (normalZ * strafespeed)
-- Update the target based on the new camera position (again, otherwise the camera kind of sways as the target is out by a frame)
camTargetX = camPosX + freeModeAngleX * 100
camTargetY = camPosY + freeModeAngleY * 100
camTargetZ = camPosZ + freeModeAngleZ * 100
-- Set the new camera position and target
setCameraMatrix ( camPosX, camPosY, camPosZ, camTargetX, camTargetY, camTargetZ )
end
local function freecamMouse (cX,cY,aX,aY)
--ignore mouse movement if the cursor or MTA window is on
--and do not resume it until at least 5 frames after it is toggled off
--(prevents cursor mousemove data from reaching this handler)
if isCursorShowing() or isMTAWindowActive() then
mouseFrameDelay = 5
return
elseif mouseFrameDelay > 0 then
mouseFrameDelay = mouseFrameDelay - 1
return
end
-- how far have we moved the mouse from the screen center?
local width, height = guiGetScreenSize()
aX = aX - width / 2
aY = aY - height / 2
--invert the mouse look if specified
if options.invertMouseLook then
aY = -aY
end
rotX = rotX + aX * options.mouseSensitivity * 0.01745
rotY = rotY - aY * options.mouseSensitivity * 0.01745
local PI = math.pi
if rotX > PI then
rotX = rotX - 2 * PI
elseif rotX < -PI then
rotX = rotX + 2 * PI
end
if rotY > PI then
rotY = rotY - 2 * PI
elseif rotY < -PI then
rotY = rotY + 2 * PI
end
-- limit the camera to stop it going too far up or down - PI/2 is the limit, but we can't let it quite reach that or it will lock up
-- and strafeing will break entirely as the camera loses any concept of what is 'up'
if rotY < -PI / 2.05 then
rotY = -PI / 2.05
elseif rotY > PI / 2.05 then
rotY = PI / 2.05
end
end
-- PUBLIC
function getFreecamVelocity()
return velocityX,velocityY,velocityZ
end
-- params: x, y, z sets camera's position (optional)
function setFreecamEnabled (x, y, z)
if isFreecamEnabled() then
return false
end
if (x and y and z) then
setCameraMatrix ( camPosX, camPosY, camPosZ )
end
addEventHandler("onClientRender", rootElement, freecamFrame)
addEventHandler("onClientCursorMove",rootElement, freecamMouse)
setElementData(localPlayer, "freecam:state", true)
return true
end
-- param: dontChangeFixedMode leaves toggleCameraFixedMode alone if true, disables it if false or nil (optional)
function setFreecamDisabled()
if not isFreecamEnabled() then
return false
end
velocityX,velocityY,velocityZ = 0,0,0
speed = 0
strafespeed = 0
removeEventHandler("onClientRender", rootElement, freecamFrame)
removeEventHandler("onClientCursorMove",rootElement, freecamMouse)
setElementData(localPlayer, "freecam:state", false)
return true
end
function isFreecamEnabled()
return getElementData(localPlayer,"freecam:state")
end
function getFreecamOption(theOption, value)
return options[theOption]
end
function setFreecamOption(theOption, value)
if options[theOption] ~= nil then
options[theOption] = value
return true
else
return false
end
end
addEvent("doSetFreecamEnabled")
addEventHandler("doSetFreecamEnabled", rootElement, setFreecamEnabled)
addEvent("doSetFreecamDisabled")
addEventHandler("doSetFreecamDisabled", rootElement, setFreecamDisabled)
addEvent("doSetFreecamOption")
addEventHandler("doSetFreecamOption", rootElement, setFreecamOption)
| mit |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/RichText.lua | 1 | 3399 |
--------------------------------
-- @module RichText
-- @extend Widget
-- @parent_module ccui
--------------------------------
-- brief Insert a RichElement at a given index.<br>
-- param element A RichElement type.<br>
-- param index A given index.
-- @function [parent=#RichText] insertElement
-- @param self
-- @param #ccui.RichElement element
-- @param #int index
-- @return RichText#RichText self (return value: ccui.RichText)
--------------------------------
-- brief Add a RichElement at the end of RichText.<br>
-- param element A RichElement instance.
-- @function [parent=#RichText] pushBackElement
-- @param self
-- @param #ccui.RichElement element
-- @return RichText#RichText self (return value: ccui.RichText)
--------------------------------
-- @brief sets the wrapping mode: WRAP_PER_CHAR or WRAP_PER_WORD
-- @function [parent=#RichText] setWrapMode
-- @param self
-- @param #int wrapMode
-- @return RichText#RichText self (return value: ccui.RichText)
--------------------------------
-- brief Set vertical space between each RichElement.<br>
-- param space Point in float.
-- @function [parent=#RichText] setVerticalSpace
-- @param self
-- @param #float space
-- @return RichText#RichText self (return value: ccui.RichText)
--------------------------------
-- @brief returns the current wrapping mode
-- @function [parent=#RichText] getWrapMode
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- brief Rearrange all RichElement in the RichText.<br>
-- It's usually called internally.
-- @function [parent=#RichText] formatText
-- @param self
-- @return RichText#RichText self (return value: ccui.RichText)
--------------------------------
--
-- @function [parent=#RichText] initWithXML
-- @param self
-- @param #string xml
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @overload self, ccui.RichElement
-- @overload self, int
-- @function [parent=#RichText] removeElement
-- @param self
-- @param #int index
-- @return RichText#RichText self (return value: ccui.RichText)
--------------------------------
-- brief Create a empty RichText.<br>
-- return RichText instance.
-- @function [parent=#RichText] create
-- @param self
-- @return RichText#RichText ret (return value: ccui.RichText)
--------------------------------
-- brief Create a RichText from an XML<br>
-- return RichText instance.
-- @function [parent=#RichText] createWithXML
-- @param self
-- @param #string xml
-- @return RichText#RichText ret (return value: ccui.RichText)
--------------------------------
--
-- @function [parent=#RichText] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#RichText] getDescription
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
--
-- @function [parent=#RichText] ignoreContentAdaptWithSize
-- @param self
-- @param #bool ignore
-- @return RichText#RichText self (return value: ccui.RichText)
--------------------------------
-- brief Default constructor.<br>
-- js ctor<br>
-- lua new
-- @function [parent=#RichText] RichText
-- @param self
-- @return RichText#RichText self (return value: ccui.RichText)
return nil
| mit |
maxrio/packages981213 | net/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan/rule.lua | 80 | 4829 | -- ------ extra functions ------ --
function ruleCheck() -- determine if rules needs a proper protocol configured
uci.cursor():foreach("mwan3", "rule",
function (section)
local sourcePort = ut.trim(sys.exec("uci -p /var/state get mwan3." .. section[".name"] .. ".src_port"))
local destPort = ut.trim(sys.exec("uci -p /var/state get mwan3." .. section[".name"] .. ".dest_port"))
if sourcePort ~= "" or destPort ~= "" then -- ports configured
local protocol = ut.trim(sys.exec("uci -p /var/state get mwan3." .. section[".name"] .. ".proto"))
if protocol == "" or protocol == "all" then -- no or improper protocol
error_protocol_list = error_protocol_list .. section[".name"] .. " "
end
end
end
)
end
function ruleWarn() -- display warning messages at the top of the page
if error_protocol_list ~= " " then
return "<font color=\"ff0000\"><strong>WARNING: some rules have a port configured with no or improper protocol specified! Please configure a specific protocol!</strong></font>"
else
return ""
end
end
-- ------ rule configuration ------ --
dsp = require "luci.dispatcher"
sys = require "luci.sys"
ut = require "luci.util"
error_protocol_list = " "
ruleCheck()
m5 = Map("mwan3", translate("MWAN Rule Configuration"),
translate(ruleWarn()))
m5:append(Template("mwan/config_css"))
mwan_rule = m5:section(TypedSection, "rule", translate("Traffic Rules"),
translate("Rules specify which traffic will use a particular MWAN policy based on IP address, port or protocol<br />" ..
"Rules are matched from top to bottom. Rules below a matching rule are ignored. Traffic not matching any rule is routed using the main routing table<br />" ..
"Traffic destined for known (other than default) networks is handled by the main routing table. Traffic matching a rule, but all WAN interfaces for that policy are down will be blackholed<br />" ..
"Names may contain characters A-Z, a-z, 0-9, _ and no spaces<br />" ..
"Rules may not share the same name as configured interfaces, members or policies"))
mwan_rule.addremove = true
mwan_rule.anonymous = false
mwan_rule.dynamic = false
mwan_rule.sectionhead = "Rule"
mwan_rule.sortable = true
mwan_rule.template = "cbi/tblsection"
mwan_rule.extedit = dsp.build_url("admin", "network", "mwan", "configuration", "rule", "%s")
function mwan_rule.create(self, section)
TypedSection.create(self, section)
m5.uci:save("mwan3")
luci.http.redirect(dsp.build_url("admin", "network", "mwan", "configuration", "rule", section))
end
src_ip = mwan_rule:option(DummyValue, "src_ip", translate("Source address"))
src_ip.rawhtml = true
function src_ip.cfgvalue(self, s)
return self.map:get(s, "src_ip") or "—"
end
src_port = mwan_rule:option(DummyValue, "src_port", translate("Source port"))
src_port.rawhtml = true
function src_port.cfgvalue(self, s)
return self.map:get(s, "src_port") or "—"
end
dest_ip = mwan_rule:option(DummyValue, "dest_ip", translate("Destination address"))
dest_ip.rawhtml = true
function dest_ip.cfgvalue(self, s)
return self.map:get(s, "dest_ip") or "—"
end
dest_port = mwan_rule:option(DummyValue, "dest_port", translate("Destination port"))
dest_port.rawhtml = true
function dest_port.cfgvalue(self, s)
return self.map:get(s, "dest_port") or "—"
end
proto = mwan_rule:option(DummyValue, "proto", translate("Protocol"))
proto.rawhtml = true
function proto.cfgvalue(self, s)
return self.map:get(s, "proto") or "all"
end
sticky = mwan_rule:option(DummyValue, "sticky", translate("Sticky"))
sticky.rawhtml = true
function sticky.cfgvalue(self, s)
if self.map:get(s, "sticky") == "1" then
stickied = 1
return "Yes"
else
stickied = nil
return "No"
end
end
timeout = mwan_rule:option(DummyValue, "timeout", translate("Sticky timeout"))
timeout.rawhtml = true
function timeout.cfgvalue(self, s)
if stickied then
local timeoutValue = self.map:get(s, "timeout")
if timeoutValue then
return timeoutValue .. "s"
else
return "600s"
end
else
return "—"
end
end
ipset = mwan_rule:option(DummyValue, "ipset", translate("IPset"))
ipset.rawhtml = true
function ipset.cfgvalue(self, s)
return self.map:get(s, "ipset") or "—"
end
use_policy = mwan_rule:option(DummyValue, "use_policy", translate("Policy assigned"))
use_policy.rawhtml = true
function use_policy.cfgvalue(self, s)
return self.map:get(s, "use_policy") or "—"
end
errors = mwan_rule:option(DummyValue, "errors", translate("Errors"))
errors.rawhtml = true
function errors.cfgvalue(self, s)
if not string.find(error_protocol_list, " " .. s .. " ") then
return ""
else
return "<span title=\"No protocol specified\"><img src=\"/luci-static/resources/cbi/reset.gif\" alt=\"error\"></img></span>"
end
end
return m5
| gpl-2.0 |
lyhcode/modern-java-programming | bbcode.lua | 1 | 3816 | -- Invoke with: pandoc -t sample.lua
-- Blocksep is used to separate block elements.
function Blocksep()
return "\n\n"
end
-- This function is called once for the whole document. Parameters:
-- body, title, date are strings; authors is an array of strings;
-- variables is a table. One could use some kind of templating
-- system here; this just gives you a simple standalone HTML file.
function Doc(body, title, authors, date, variables)
return body .. '\n'
end
-- The functions that follow render corresponding pandoc elements.
-- s is always a string, attr is always a table of attributes, and
-- items is always an array of strings (the items in a list).
-- Comments indicate the types of other variables.
function Str(s)
return s
end
function Space()
return " "
end
function LineBreak()
return "\n"
end
function Emph(s)
return "[em]" .. s .. "[/em]"
end
function Strong(s)
return "[b]" .. s .. "[/b]"
end
function Subscript(s)
error("Subscript isn't supported")
end
function Superscript(s)
error("Superscript isn't supported")
end
function SmallCaps(s)
error("SmallCaps isn't supported")
end
function Strikeout(s)
return '[del]' .. s .. '[/del]'
end
function Link(s, src, tit)
local ret = '[url'
if s then
ret = ret .. '=' .. src
else
s = src
end
ret = ret .. "]" .. s .. "[/url]"
end
function Image(s, src, tit)
return "[img=" .. tit .. "]" .. src .. "[/img]"
end
function Code(s, attr)
return "[u]" .. s .. "[/u]"
end
function InlineMath(s)
error("InlineMath isn't supported")
end
function DisplayMath(s)
error("DisplayMath isn't supported")
end
function Note(s)
error("Note isn't supported")
end
function Plain(s)
return s
end
function Para(s)
return s
end
-- lev is an integer, the header level.
function Header(lev, s, attr)
return "[h]" .. s .. "[/h]"
end
function BlockQuote(s)
return "[quote]\n" .. s .. "\n[/quote]"
end
function HorizontalRule()
return "--------------------------------------------------------------------------------"
end
function CodeBlock(s, attr)
return "[code]\n" .. s .. '\n[/code]'
end
function BulletList(items)
local buffer = {}
for _, item in ipairs(items) do
table.insert(buffer, "[*]" .. item)
end
return "[list]\n" .. table.concat(buffer, "\n") .. "\n[/list]"
end
function OrderedList(items)
local buffer = {}
for _, item in ipairs(items) do
table.insert(buffer, "[*]" .. item)
end
return "[list=1]\n" .. table.concat(buffer, "\n") .. "\n[/list]"
end
-- Revisit association list STackValue instance.
function DefinitionList(items)
local buffer = {}
for _, item in pairs(items) do
for k, v in pairs(item) do
table.insert(buffer, "[b]" .. k .. "[/b]:\n" ..
table.concat(v, "\n"))
end
end
return table.concat(buffer, "\n")
end
-- Convert pandoc alignment to something HTML can use.
-- align is AlignLeft, AlignRight, AlignCenter, or AlignDefault.
function html_align(align)
if align == 'AlignLeft' then
return 'left'
elseif align == 'AlignRight' then
return 'right'
elseif align == 'AlignCenter' then
return 'center'
else
return 'left'
end
end
-- Caption is a string, aligns is an array of strings,
-- widths is an array of floats, headers is an array of
-- strings, rows is an array of arrays of strings.
function Table(caption, aligns, widths, headers, rows)
error("Table isn't supported")
end
-- The following code will produce runtime warnings when you haven't defined
-- all of the functions you need for the custom writer, so it's useful
-- to include when you're working on a writer.
local meta = {}
meta.__index =
function(_, key)
io.stderr:write(string.format("WARNING: Undefined function '%s'\n",key))
return function() return "" end
end
setmetatable(_G, meta) | mit |
opentechinstitute/luci | modules/base/luasrc/http.lua | 27 | 8237 | --[[
LuCI - HTTP-Interaction
Description:
HTTP-Header manipulator and form variable preprocessor
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local ltn12 = require "luci.ltn12"
local protocol = require "luci.http.protocol"
local util = require "luci.util"
local string = require "string"
local coroutine = require "coroutine"
local table = require "table"
local ipairs, pairs, next, type, tostring, error =
ipairs, pairs, next, type, tostring, error
--- LuCI Web Framework high-level HTTP functions.
module "luci.http"
context = util.threadlocal()
Request = util.class()
function Request.__init__(self, env, sourcein, sinkerr)
self.input = sourcein
self.error = sinkerr
-- File handler nil by default to let .content() work
self.filehandler = nil
-- HTTP-Message table
self.message = {
env = env,
headers = {},
params = protocol.urldecode_params(env.QUERY_STRING or ""),
}
self.parsed_input = false
end
function Request.formvalue(self, name, noparse)
if not noparse and not self.parsed_input then
self:_parse_input()
end
if name then
return self.message.params[name]
else
return self.message.params
end
end
function Request.formvaluetable(self, prefix)
local vals = {}
prefix = prefix and prefix .. "." or "."
if not self.parsed_input then
self:_parse_input()
end
local void = self.message.params[nil]
for k, v in pairs(self.message.params) do
if k:find(prefix, 1, true) == 1 then
vals[k:sub(#prefix + 1)] = tostring(v)
end
end
return vals
end
function Request.content(self)
if not self.parsed_input then
self:_parse_input()
end
return self.message.content, self.message.content_length
end
function Request.getcookie(self, name)
local c = string.gsub(";" .. (self:getenv("HTTP_COOKIE") or "") .. ";", "%s*;%s*", ";")
local p = ";" .. name .. "=(.-);"
local i, j, value = c:find(p)
return value and urldecode(value)
end
function Request.getenv(self, name)
if name then
return self.message.env[name]
else
return self.message.env
end
end
function Request.setfilehandler(self, callback)
self.filehandler = callback
end
function Request._parse_input(self)
protocol.parse_message_body(
self.input,
self.message,
self.filehandler
)
self.parsed_input = true
end
--- Close the HTTP-Connection.
function close()
if not context.eoh then
context.eoh = true
coroutine.yield(3)
end
if not context.closed then
context.closed = true
coroutine.yield(5)
end
end
--- Return the request content if the request was of unknown type.
-- @return HTTP request body
-- @return HTTP request body length
function content()
return context.request:content()
end
--- Get a certain HTTP input value or a table of all input values.
-- @param name Name of the GET or POST variable to fetch
-- @param noparse Don't parse POST data before getting the value
-- @return HTTP input value or table of all input value
function formvalue(name, noparse)
return context.request:formvalue(name, noparse)
end
--- Get a table of all HTTP input values with a certain prefix.
-- @param prefix Prefix
-- @return Table of all HTTP input values with given prefix
function formvaluetable(prefix)
return context.request:formvaluetable(prefix)
end
--- Get the value of a certain HTTP-Cookie.
-- @param name Cookie Name
-- @return String containing cookie data
function getcookie(name)
return context.request:getcookie(name)
end
--- Get the value of a certain HTTP environment variable
-- or the environment table itself.
-- @param name Environment variable
-- @return HTTP environment value or environment table
function getenv(name)
return context.request:getenv(name)
end
--- Set a handler function for incoming user file uploads.
-- @param callback Handler function
function setfilehandler(callback)
return context.request:setfilehandler(callback)
end
--- Send a HTTP-Header.
-- @param key Header key
-- @param value Header value
function header(key, value)
if not context.headers then
context.headers = {}
end
context.headers[key:lower()] = value
coroutine.yield(2, key, value)
end
--- Set the mime type of following content data.
-- @param mime Mimetype of following content
function prepare_content(mime)
if not context.headers or not context.headers["content-type"] then
if mime == "application/xhtml+xml" then
if not getenv("HTTP_ACCEPT") or
not getenv("HTTP_ACCEPT"):find("application/xhtml+xml", nil, true) then
mime = "text/html; charset=UTF-8"
end
header("Vary", "Accept")
end
header("Content-Type", mime)
end
end
--- Get the RAW HTTP input source
-- @return HTTP LTN12 source
function source()
return context.request.input
end
--- Set the HTTP status code and status message.
-- @param code Status code
-- @param message Status message
function status(code, message)
code = code or 200
message = message or "OK"
context.status = code
coroutine.yield(1, code, message)
end
--- Send a chunk of content data to the client.
-- This function is as a valid LTN12 sink.
-- If the content chunk is nil this function will automatically invoke close.
-- @param content Content chunk
-- @param src_err Error object from source (optional)
-- @see close
function write(content, src_err)
if not content then
if src_err then
error(src_err)
else
close()
end
return true
elseif #content == 0 then
return true
else
if not context.eoh then
if not context.status then
status()
end
if not context.headers or not context.headers["content-type"] then
header("Content-Type", "text/html; charset=utf-8")
end
if not context.headers["cache-control"] then
header("Cache-Control", "no-cache")
header("Expires", "0")
end
context.eoh = true
coroutine.yield(3)
end
coroutine.yield(4, content)
return true
end
end
--- Splice data from a filedescriptor to the client.
-- @param fp File descriptor
-- @param size Bytes to splice (optional)
function splice(fd, size)
coroutine.yield(6, fd, size)
end
--- Redirects the client to a new URL and closes the connection.
-- @param url Target URL
function redirect(url)
status(302, "Found")
header("Location", url)
close()
end
--- Create a querystring out of a table of key - value pairs.
-- @param table Query string source table
-- @return Encoded HTTP query string
function build_querystring(q)
local s = { "?" }
for k, v in pairs(q) do
if #s > 1 then s[#s+1] = "&" end
s[#s+1] = urldecode(k)
s[#s+1] = "="
s[#s+1] = urldecode(v)
end
return table.concat(s, "")
end
--- Return the URL-decoded equivalent of a string.
-- @param str URL-encoded string
-- @param no_plus Don't decode + to " "
-- @return URL-decoded string
-- @see urlencode
urldecode = protocol.urldecode
--- Return the URL-encoded equivalent of a string.
-- @param str Source string
-- @return URL-encoded string
-- @see urldecode
urlencode = protocol.urlencode
--- Send the given data as JSON encoded string.
-- @param data Data to send
function write_json(x)
if x == nil then
write("null")
elseif type(x) == "table" then
local k, v
if type(next(x)) == "number" then
write("[ ")
for k, v in ipairs(x) do
write_json(v)
if next(x, k) then
write(", ")
end
end
write(" ]")
else
write("{ ")
for k, v in pairs(x) do
write("%q: " % k)
write_json(v)
if next(x, k) then
write(", ")
end
end
write(" }")
end
elseif type(x) == "number" or type(x) == "boolean" then
if (x ~= x) then
-- NaN is the only value that doesn't equal to itself.
write("Number.NaN")
else
write(tostring(x))
end
else
write('"%s"' % tostring(x):gsub('["%z\1-\31]', function(c)
return '\\u%04x' % c:byte(1)
end))
end
end
| apache-2.0 |
Mahdi2001bk/TELEHACK | plugins/info.lua | 9 | 9083 | do
local AmirSbss = 122774063
local function setrank(msg, name, value) -- setrank function
local hash = nil
if msg.to.type == 'chat' then
hash = 'rank:'..msg.to.id..':variables'
end
if hash then
redis:hset(hash, name, value)
return send_msg('chat#id'..msg.to.id, 'set Rank for ('..name..') To : '..value, ok_cb, true)
end
end
local function res_user_callback(extra, success, result) -- /info <username> function
if success == 1 then
if result.username then
Username = '@'..result.username
else
Username = '----'
end
local text = 'Full name : '..(result.first_name or '')..' '..(result.last_name or '')..'\n'
..'User name: '..Username..'\n'
..'ID : '..result.id..'\n\n'
local hash = 'rank:'..extra.chat2..':variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == tonumber(AmirSbss) then
text = text..'Rank : Amir Sbss \n\n'
elseif is_admin2(result.id) then
text = text..'Rank : Admin \n\n'
elseif is_owner2(result.id, extra.chat2) then
text = text..'Rank : Owner \n\n'
elseif is_momod2(result.id, extra.chat2) then
text = text..'Rank : Moderator \n\n'
else
text = text..'Rank : Member \n\n'
end
else
text = text..'Rank : '..value..'\n\n'
end
local uhash = 'user:'..result.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.id..':'..extra.chat2
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n\n'
text = text..'#Sbss_Team'
send_msg(extra.receiver, text, ok_cb, true)
else
send_msg(extra.receiver, ' Username not found.', ok_cb, false)
end
end
local function action_by_id(extra, success, result) -- /info <ID> function
if success == 1 then
if result.username then
Username = '@'..result.username
else
Username = '----'
end
local text = 'Full name : '..(result.first_name or '')..' '..(result.last_name or '')..'\n'
..'Username: '..Username..'\n'
..'ID : '..result.id..'\n\n'
local hash = 'rank:'..extra.chat2..':variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == tonumber(AmirSbss) then
text = text..'Rank : Amir Sbss \n\n'
elseif is_admin2(result.id) then
text = text..'Rank : Admin \n\n'
elseif is_owner2(result.id, extra.chat2) then
text = text..'Rank : Owner \n\n'
elseif is_momod2(result.id, extra.chat2) then
text = text..'Rank : Moderator \n\n'
else
text = text..'Rank : Member \n\n'
end
else
text = text..'Rank : '..value..'\n\n'
end
local uhash = 'user:'..result.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.id..':'..extra.chat2
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n\n'
text = text..'#Sbss_Team'
send_msg(extra.receiver, text, ok_cb, true)
else
send_msg(extra.receiver, 'id not found.\nuse : /info @username', ok_cb, false)
end
end
local function action_by_reply(extra, success, result)-- (reply) /info function
if result.from.username then
Username = '@'..result.from.username
else
Username = '----'
end
local text = 'Full name : '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n'
..'Username : '..Username..'\n'
..'ID : '..result.from.id..'\n\n'
local hash = 'rank:'..result.to.id..':variables'
local value = redis:hget(hash, result.from.id)
if not value then
if result.from.id == tonumber(AmirSbss) then
text = text..'Rank : Amir Sbss \n\n'
elseif is_admin2(result.from.id) then
text = text..'Rank : Admin \n\n'
elseif is_owner2(result.from.id, result.to.id) then
text = text..'Rank : Owner \n\n'
elseif is_momod2(result.from.id, result.to.id) then
text = text..'Rank : Moderator \n\n'
else
text = text..'Rank : Member \n\n'
end
else
text = text..'Rank : '..value..'\n\n'
end
local user_info = {}
local uhash = 'user:'..result.from.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.from.id..':'..result.to.id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n\n'
text = text..'#Sbss_Team'
send_msg(extra.receiver, text, ok_cb, true)
end
local function action_by_reply2(extra, success, result)
local value = extra.value
setrank(result, result.from.id, value)
end
local function run(msg, matches)
if matches[1]:lower() == 'setrank' or matches[1]:lower() == 'تنظیم مقام' then
local hash = 'usecommands:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
if not is_sudo(msg) then
return "Only for Sudo"
end
local receiver = get_receiver(msg)
local Reply = msg.reply_id
if msg.reply_id then
local value = string.sub(matches[2], 1, 1000)
msgr = get_message(msg.reply_id, action_by_reply2, {receiver=receiver, Reply=Reply, value=value})
else
local name = string.sub(matches[2], 1, 50)
local value = string.sub(matches[3], 1, 1000)
local text = setrank(msg, name, value)
return text
end
end
if matches[1]:lower() == 'info' or matches[1]:lower() == 'اینفو' and not matches[2] then
local receiver = get_receiver(msg)
local Reply = msg.reply_id
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {receiver=receiver, Reply=Reply})
else
if msg.from.username then
Username = '@'..msg.from.username
else
Username = '----'
end
local text = 'First name : '..(msg.from.first_name or '----')..'\n'
local text = text..'Last name : '..(msg.from.last_name or '----')..'\n'
local text = text..'Username : '..Username..'\n'
local text = text..'ID : '..msg.from.id..'\n\n'
local hash = 'rank:'..msg.to.id..':variables'
if hash then
local value = redis:hget(hash, msg.from.id)
if not value then
if msg.from.id == tonumber(AmirSbss) then
text = text..'Rank : Amir Sbss \n\n'
send_document(get_receiver(msg), "/root/robot/amirsbss.webp", ok_cb, false)
elseif is_sudo(msg) then
text = text..'Rank : Sudo \n\n'
send_document(get_receiver(msg), "/root/robot/sudo.webp", ok_cb, false)
elseif is_admin(msg) then
text = text..'Rank = Admin \n\n'
send_document(get_receiver(msg), "/root/robot/admin.webp", ok_cb, false)
elseif is_owner(msg) then
text = text..'Rank : Owner \n\n'
send_document(get_receiver(msg), "/root/robot/owner.webp", ok_cb, false)
elseif is_momod(msg) then
text = text..'Rank : Moderator \n\n'
send_document(get_receiver(msg), "/root/robot/mod.webp", ok_cb, false)
else
text = text..'Rank : Member \n\n'
send_document(get_receiver(msg), "/root/robot/mmbr.webp", ok_cb, false)
end
else
text = text..'Rank : '..value..'\n'
end
end
local uhash = 'user:'..msg.from.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..msg.from.id..':'..msg.to.id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n\n'
if msg.to.type == 'chat' then
text = text..'Group name : '..msg.to.title..'\n'
text = text..'Group ID : '..msg.to.id
end
text = text..'\n\n#Sbss_Team'
return send_msg(receiver, text, ok_cb, true)
end
end
if matches[1]:lower() == 'info' or matches[1]:lower() == 'اینفو' and matches[2] then
local user = matches[2]
local chat2 = msg.to.id
local receiver = get_receiver(msg)
if string.match(user, '^%d+$') then
user_info('user#id'..user, action_by_id, {receiver=receiver, user=user, text=text, chat2=chat2})
elseif string.match(user, '^@.+$') then
username = string.gsub(user, '@', '')
msgr = res_user(username, res_user_callback, {receiver=receiver, user=user, text=text, chat2=chat2})
end
end
end
return {
description = 'Know your information or the info of a chat members.',
usage = {
'!info: Return your info and the chat info if you are in one.',
'(Reply)!info: Return info of replied user if used by reply.',
'!info <id>: Return the info\'s of the <id>.',
'!info @<user_name>: Return the member @<user_name> information from the current chat.',
'!setrank <userid> <rank>: change members rank.',
'(Reply)!setrank <rank>: change members rank.',
},
patterns = {
"^[/!#]([Ii][Nn][Ff][Oo])$",
"^[/!#]([Ii][Nn][Ff][Oo]) (.*)$",
"^[/!#]([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (%d+) (.*)$",
"^[/!#]([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (.*)$",
"^([Ii][Nn][Ff][Oo])$",
"^([Ii][Nn][Ff][Oo]) (.*)$",
"^([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (%d+) (.*)$",
"^([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (.*)$",
"^(اینفو)$",
"^(اینفو) (.*)$",
"^(تنظیم مقام) (%d+) (.*)$",
"^(تنظیم مقام) (.*)$",
},
run = run
}
end
| gpl-2.0 |
mobarski/sandbox | scite/old/wscite_zzz/lexers/notused/actionscript.lua | 5 | 2400 | -- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE.
-- Actionscript LPeg lexer.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'actionscript'}
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local line_comment = '//' * l.nonnewline^0
local block_comment = '/*' * (l.any - '*/')^0 * P('*/')^-1
local comment = token(l.COMMENT, line_comment + block_comment)
-- Strings.
local sq_str = l.delimited_range("'", true)
local dq_str = l.delimited_range('"', true)
local ml_str = '<![CDATA[' * (l.any - ']]>')^0 * ']]>'
local string = token(l.STRING, sq_str + dq_str + ml_str)
-- Numbers.
local number = token(l.NUMBER, (l.float + l.integer) * S('LlUuFf')^-2)
-- Keywords.
local keyword = token(l.KEYWORD, word_match{
'break', 'continue', 'delete', 'do', 'else', 'for', 'function', 'if', 'in',
'new', 'on', 'return', 'this', 'typeof', 'var', 'void', 'while', 'with',
'NaN', 'Infinity', 'false', 'null', 'true', 'undefined',
-- Reserved for future use.
'abstract', 'case', 'catch', 'class', 'const', 'debugger', 'default',
'export', 'extends', 'final', 'finally', 'goto', 'implements', 'import',
'instanceof', 'interface', 'native', 'package', 'private', 'Void',
'protected', 'public', 'dynamic', 'static', 'super', 'switch', 'synchonized',
'throw', 'throws', 'transient', 'try', 'volatile'
})
-- Types.
local type = token(l.TYPE, word_match{
'Array', 'Boolean', 'Color', 'Date', 'Function', 'Key', 'MovieClip', 'Math',
'Mouse', 'Number', 'Object', 'Selection', 'Sound', 'String', 'XML', 'XMLNode',
'XMLSocket',
-- Reserved for future use.
'boolean', 'byte', 'char', 'double', 'enum', 'float', 'int', 'long', 'short'
})
-- Identifiers.
local identifier = token(l.IDENTIFIER, l.word)
-- Operators.
local operator = token(l.OPERATOR, S('=!<>+-/*%&|^~.,;?()[]{}'))
M._rules = {
{'whitespace', ws},
{'keyword', keyword},
{'type', type},
{'identifier', identifier},
{'string', string},
{'comment', comment},
{'number', number},
{'operator', operator},
}
M._foldsymbols = {
_patterns = {'[{}]', '/%*', '%*/', '//', '<!%[CDATA%[', '%]%]>'},
[l.OPERATOR] = {['{'] = 1, ['}'] = -1},
[l.COMMENT] = {
['/*'] = 1, ['*/'] = -1, ['//'] = l.fold_line_comments('//')
},
[l.STRING] = {['<![CDATA['] = 1, [']]>'] = -1}
}
return M
| mit |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/tests/lua-tests/src/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest.lua | 14 | 40820 | local itemTagBasic = 1000
local armaturePerformanceTag = 20000
local frameEventActionTag = 10000
local winSize = cc.Director:getInstance():getWinSize()
local scheduler = cc.Director:getInstance():getScheduler()
local ArmatureTestIndex =
{
TEST_ASYNCHRONOUS_LOADING = 1,
TEST_DIRECT_LOADING = 2,
TEST_COCOSTUDIO_WITH_SKELETON = 3,
TEST_DRAGON_BONES_2_0 = 4,
TEST_PERFORMANCE = 5,
TEST_CHANGE_ZORDER = 6,
TEST_ANIMATION_EVENT = 7,
TEST_FRAME_EVENT = 8,
TEST_PARTICLE_DISPLAY = 9,
TEST_USE_DIFFERENT_PICTURE = 10,
TEST_ANCHORPOINT = 11,
TEST_ARMATURE_NESTING = 12,
TEST_ARMATURE_NESTING_2 = 13,
}
local armatureSceneIdx = ArmatureTestIndex.TEST_ASYNCHRONOUS_LOADING
local ArmatureTestScene = class("ArmatureTestScene")
ArmatureTestScene.__index = ArmatureTestScene
function ArmatureTestScene.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, ArmatureTestScene)
return target
end
function ArmatureTestScene:runThisTest()
armatureSceneIdx = ArmatureTestIndex.TEST_ASYNCHRONOUS_LOADING
self:addChild(restartArmatureTest())
end
function ArmatureTestScene.create()
local scene = ArmatureTestScene.extend(cc.Scene:create())
local bg = cc.Sprite:create("armature/bg.jpg")
bg:setPosition(VisibleRect:center())
local scaleX = VisibleRect:getVisibleRect().width / bg:getContentSize().width
local scaleY = VisibleRect:getVisibleRect().height / bg:getContentSize().height
bg:setScaleX(scaleX)
bg:setScaleY(scaleY)
scene:addChild(bg)
return scene
end
function ArmatureTestScene.toMainMenuCallback()
ccs.ArmatureDataManager:purgeArmatureSystem()
end
local ArmatureTestLayer = class("ArmatureTestLayer")
ArmatureTestLayer.__index = ArmatureTestLayer
ArmatureTestLayer._backItem = nil
ArmatureTestLayer._restarItem = nil
ArmatureTestLayer._nextItem = nil
function ArmatureTestLayer:onEnter()
end
function ArmatureTestLayer.title(idx)
if ArmatureTestIndex.TEST_ASYNCHRONOUS_LOADING == idx then
return "Test Asynchronous Loading"
elseif ArmatureTestIndex.TEST_DIRECT_LOADING == idx then
return "Test Direct Loading"
elseif ArmatureTestIndex.TEST_COCOSTUDIO_WITH_SKELETON == idx then
return "Test Export From CocoStudio With Skeleton Effect"
elseif ArmatureTestIndex.TEST_DRAGON_BONES_2_0 == idx then
return "Test Export From DragonBones version 2.0"
elseif ArmatureTestIndex.TEST_PERFORMANCE == idx then
return "Test Performance"
elseif ArmatureTestIndex.TEST_CHANGE_ZORDER == idx then
return "Test Change ZOrder Of Different Armature"
elseif ArmatureTestIndex.TEST_ANIMATION_EVENT == idx then
return "Test Armature Animation Event"
elseif ArmatureTestIndex.TEST_FRAME_EVENT == idx then
return "Test Frame Event"
elseif ArmatureTestIndex.TEST_PARTICLE_DISPLAY == idx then
return "Test Particle Display"
elseif ArmatureTestIndex.TEST_USE_DIFFERENT_PICTURE == idx then
return "Test One Armature Use Different Picture"
elseif ArmatureTestIndex.TEST_ANCHORPOINT == idx then
return "Test Set AnchorPoint"
elseif ArmatureTestIndex.TEST_ARMATURE_NESTING == idx then
return "Test Armature Nesting"
elseif ArmatureTestIndex.TEST_ARMATURE_NESTING_2 == idx then
return "Test Armature Nesting 2"
end
end
function ArmatureTestLayer.subTitle(idx)
if ArmatureTestIndex.TEST_ASYNCHRONOUS_LOADING == idx then
return "current percent :"
elseif ArmatureTestIndex.TEST_PERFORMANCE == idx then
return "Current Armature Count : "
elseif ArmatureTestIndex.TEST_PARTICLE_DISPLAY == idx then
return "Touch to change animation"
elseif ArmatureTestIndex.TEST_USE_DIFFERENT_PICTURE == idx then
return "weapon and armature are in different picture"
elseif ArmatureTestIndex.TEST_ARMATURE_NESTING_2 == idx then
return "Move to a mount and press the ChangeMount Button."
else
return ""
end
end
function ArmatureTestLayer.create()
local layer = ArmatureTestLayer.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
local function onNodeEvent(event)
if "enter" == event then
layer:onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
layer:creatTitleAndSubTitle(armatureSceneIdx)
end
return layer
end
function ArmatureTestLayer.backCallback()
local newScene = ArmatureTestScene.create()
newScene:addChild(backArmatureTest())
cc.Director:getInstance():replaceScene(newScene)
end
function ArmatureTestLayer.restartCallback()
local newScene = ArmatureTestScene.create()
newScene:addChild(restartArmatureTest())
cc.Director:getInstance():replaceScene(newScene)
end
function ArmatureTestLayer.nextCallback()
local newScene = ArmatureTestScene.create()
newScene:addChild(nextArmatureTest())
cc.Director:getInstance():replaceScene(newScene)
end
function ArmatureTestLayer:createMenu()
local menu = cc.Menu:create()
self._backItem = cc.MenuItemImage:create(s_pPathB1, s_pPathB2)
self._backItem:registerScriptTapHandler(self.backCallback)
menu:addChild(self._backItem,itemTagBasic)
self._restarItem = cc.MenuItemImage:create(s_pPathR1, s_pPathR2)
self._restarItem:registerScriptTapHandler(self.restartCallback)
menu:addChild(self._restarItem,itemTagBasic)
self._nextItem = cc.MenuItemImage:create(s_pPathF1, s_pPathF2)
menu:addChild(self._nextItem,itemTagBasic)
self._nextItem:registerScriptTapHandler(self.nextCallback)
local size = cc.Director:getInstance():getWinSize()
self._backItem:setPosition(cc.p(size.width / 2 - self._restarItem:getContentSize().width * 2, self._restarItem:getContentSize().height / 2))
self._restarItem:setPosition(cc.p(size.width / 2, self._restarItem:getContentSize().height / 2))
self._nextItem:setPosition(cc.p(size.width / 2 + self._restarItem:getContentSize().width * 2, self._restarItem:getContentSize().height / 2))
menu:setPosition(cc.p(0, 0))
self:addChild(menu)
end
function ArmatureTestLayer.toExtensionMenu()
ccs.ArmatureDataManager:destroyInstance()
local scene = CocoStudioTestMain()
if scene ~= nil then
cc.Director:getInstance():replaceScene(scene)
end
end
function ArmatureTestLayer:createToExtensionMenu()
cc.MenuItemFont:setFontName("Arial")
cc.MenuItemFont:setFontSize(24)
local menuItemFont = cc.MenuItemFont:create("Back")
menuItemFont:setPosition(cc.p(VisibleRect:rightBottom().x - 50, VisibleRect:rightBottom().y + 25))
menuItemFont:registerScriptTapHandler(ArmatureTestLayer.toExtensionMenu)
local backMenu = cc.Menu:create()
backMenu:addChild(menuItemFont)
backMenu:setPosition(cc.p(0, 0))
self:addChild(backMenu,10)
end
function ArmatureTestLayer:creatTitleAndSubTitle(idx)
local title = cc.Label:createWithTTF(ArmatureTestLayer.title(idx), s_arialPath, 18)
title:setColor(cc.c3b(0,0,0))
self:addChild(title, 1, 10000)
title:setAnchorPoint(cc.p(0.5, 0.5))
title:setPosition( cc.p(VisibleRect:center().x, VisibleRect:top().y - 30))
local subTitle = nil
if "" ~= ArmatureTestLayer.subTitle(idx) then
local subTitle = cc.Label:createWithTTF(ArmatureTestLayer.subTitle(idx), s_arialPath, 18)
subTitle:setColor(cc.c3b(0,0,0))
self:addChild(subTitle, 1, 10001)
subTitle:setAnchorPoint(cc.p(0.5, 0.5))
subTitle:setPosition( cc.p(VisibleRect:center().x, VisibleRect:top().y - 60) )
end
end
local TestAsynchronousLoading = class("TestAsynchronousLoading",ArmatureTestLayer)
TestAsynchronousLoading.__index = TestAsynchronousLoading
function TestAsynchronousLoading.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestAsynchronousLoading)
return target
end
function TestAsynchronousLoading:onEnter()
self._backItem:setEnabled(false)
self._restarItem:setEnabled(false)
self._nextItem:setEnabled(false)
local title = cc.Label:createWithTTF(ArmatureTestLayer.title(1), s_arialPath, 18)
title:setColor(cc.c3b(0,0,0))
self:addChild(title, 1, 10000)
title:setAnchorPoint(cc.p(0.5, 0.5))
title:setPosition( cc.p(VisibleRect:center().x, VisibleRect:top().y - 30))
local subTitle = nil
if "" ~= ArmatureTestLayer.subTitle(1) then
local subInfo = ArmatureTestLayer.subTitle(1) .. 0.0
local subTitle = cc.Label:createWithTTF(subInfo, s_arialPath, 18)
subTitle:setColor(cc.c3b(0,0,0))
self:addChild(subTitle, 1, 10001)
subTitle:setAnchorPoint(cc.p(0.5, 0.5))
subTitle:setPosition( cc.p(VisibleRect:center().x, VisibleRect:top().y - 60) )
end
local function dataLoaded(percent)
local label = self:getChildByTag(10001)
if nil ~= label then
local subInfo = ArmatureTestLayer.subTitle(1) .. (percent * 100)
label:setString(subInfo)
end
if percent >= 1 and nil ~= self._backItem and nil ~= self._restarItem and nil ~= self._nextItem then
self._backItem:setEnabled(true)
self._restarItem:setEnabled(true)
self._nextItem:setEnabled(true)
end
end
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/knight.png", "armature/knight.plist", "armature/knight.xml", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/weapon.png", "armature/weapon.plist", "armature/weapon.xml", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/robot.png", "armature/robot.plist", "armature/robot.xml", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/cyborg.png", "armature/cyborg.plist", "armature/cyborg.xml", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/Dragon.png", "armature/Dragon.plist", "armature/Dragon.xml", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/Cowboy.ExportJson", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/hero.ExportJson", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/horse.ExportJson", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/bear.ExportJson", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/HeroAnimation.ExportJson", dataLoaded)
end
function TestAsynchronousLoading.restartCallback()
ccs.ArmatureDataManager:destroyInstance()
local newScene = ArmatureTestScene.create()
newScene:addChild(restartArmatureTest())
cc.Director:getInstance():replaceScene(newScene)
end
function TestAsynchronousLoading.create()
local layer = TestAsynchronousLoading.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
local function onNodeEvent(event)
if "enter" == event then
layer:onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
end
return layer
end
local TestDirectLoading = class("TestDirectLoading",ArmatureTestLayer)
TestDirectLoading.__index = TestDirectLoading
function TestDirectLoading.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestDirectLoading)
return target
end
function TestDirectLoading:onEnter()
ccs.ArmatureDataManager:getInstance():removeArmatureFileInfo("armature/bear.ExportJson")
ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/bear.ExportJson")
local armature = ccs.Armature:create("bear")
armature:getAnimation():playWithIndex(0)
armature:setPosition(cc.p(VisibleRect:center()))
self:addChild(armature)
end
function TestDirectLoading.create()
local layer = TestDirectLoading.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
local function onNodeEvent(event)
if "enter" == event then
layer:onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
layer:creatTitleAndSubTitle(armatureSceneIdx)
end
return layer
end
local TestCSWithSkeleton = class("TestCSWithSkeleton",ArmatureTestLayer)
TestCSWithSkeleton.__index = TestCSWithSkeleton
function TestCSWithSkeleton.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestCSWithSkeleton)
return target
end
function TestCSWithSkeleton:onEnter()
local armature = ccs.Armature:create("Cowboy")
armature:getAnimation():playWithIndex(0)
armature:setScale(0.2)
armature:setAnchorPoint(cc.p(0.5, 0.5))
armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2))
self:addChild(armature)
end
function TestCSWithSkeleton.create()
local layer = TestCSWithSkeleton.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
local function onNodeEvent(event)
if "enter" == event then
layer:onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
layer:creatTitleAndSubTitle(armatureSceneIdx)
end
return layer
end
local TestDragonBones20 = class("TestDragonBones20",ArmatureTestLayer)
TestDragonBones20.__index = TestDragonBones20
function TestDragonBones20.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestDragonBones20)
return target
end
function TestDragonBones20:onEnter()
local armature = ccs.Armature:create("Dragon")
armature:getAnimation():playWithIndex(1)
armature:getAnimation():setSpeedScale(0.4)
armature:setPosition(cc.p(VisibleRect:center().x, VisibleRect:center().y * 0.3))
armature:setScale(0.6)
self:addChild(armature)
end
function TestDragonBones20.create()
local layer = TestDragonBones20.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
local function onNodeEvent(event)
if "enter" == event then
layer:onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
layer:creatTitleAndSubTitle(armatureSceneIdx)
end
return layer
end
local TestPerformance = class("TestPerformance",ArmatureTestLayer)
TestPerformance.__index = TestPerformance
TestPerformance._armatureCount = 0
TestPerformance._frames = 0
TestPerformance._times = 0
TestPerformance._lastTimes = 0
TestPerformance._generated = false
function TestPerformance.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestPerformance)
return target
end
function TestPerformance:refreshTitle()
local subTitleInfo = ArmatureTestLayer.subTitle(5) .. self._armatureCount
local label = self:getChildByTag(10001)
label:setString(subTitleInfo)
end
function TestPerformance:addArmatureToParent(armature)
self:addChild(armature, 0, armaturePerformanceTag + self._armatureCount)
end
function TestPerformance:removeArmatureFromParent(tag)
self:removeChildByTag(armaturePerformanceTag + self._armatureCount, true)
end
function TestPerformance:addArmature(num)
for i = 1, num do
self._armatureCount = self._armatureCount + 1
local armature = ccs.Armature:create("Knight_f/Knight")
armature:getAnimation():playWithIndex(0)
armature:setPosition(50 + self._armatureCount * 2, 150)
armature:setScale(0.6)
self:addArmatureToParent(armature)
end
self:refreshTitle()
end
function TestPerformance:onEnter()
local function onIncrease(sender)
self:addArmature(20)
end
local function onDecrease(sender)
if self._armatureCount == 0 then
return
end
for i = 1, 20 do
self:removeArmatureFromParent(armaturePerformanceTag + self._armatureCount)
self._armatureCount = self._armatureCount - 1
self:refreshTitle()
end
end
cc.MenuItemFont:setFontSize(65)
local decrease = cc.MenuItemFont:create(" - ")
decrease:setColor(cc.c3b(0,200,20))
decrease:registerScriptTapHandler(onDecrease)
local increase = cc.MenuItemFont:create(" + ")
increase:setColor(cc.c3b(0,200,20))
increase:registerScriptTapHandler(onIncrease)
local menu = cc.Menu:create(decrease, increase )
menu:alignItemsHorizontally()
menu:setPosition(cc.p(VisibleRect:getVisibleRect().width/2, VisibleRect:getVisibleRect().height-100))
self:addChild(menu, 10000)
self._armatureCount = 0
self._frames = 0
self._times = 0
self._lastTimes = 0
self._generated = false
self:addArmature(100)
end
function TestPerformance.create()
local layer = TestPerformance.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:creatTitleAndSubTitle(armatureSceneIdx)
local function onNodeEvent(event)
if "enter" == event then
layer:onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
end
return layer
end
local TestPerformanceBatchNode = class("TestPerformanceBatchNode",TestPerformance)
TestPerformanceBatchNode.__index = TestPerformanceBatchNode
TestPerformanceBatchNode._batchNode = nil
function TestPerformanceBatchNode.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestPerformanceBatchNode)
return target
end
function TestPerformanceBatchNode:addArmatureToParent(armature)
self._batchNode:addChild(armature, 0, armaturePerformanceTag + self._armatureCount)
end
function TestPerformanceBatchNode:removeArmatureFromParent(tag)
self._batchNode:removeChildByTag(armaturePerformanceTag + self._armatureCount, true)
end
function TestPerformanceBatchNode:onEnter()
self._batchNode = ccs.BatchNode:create()
self:addChild(self._batchNode)
local function onIncrease(sender)
self:addArmature(20)
end
local function onDecrease(sender)
if self._armatureCount == 0 then
return
end
for i = 1, 20 do
self:removeArmatureFromParent(armaturePerformanceTag + self._armatureCount)
self._armatureCount = self._armatureCount - 1
self:refreshTitle()
end
end
cc.MenuItemFont:setFontSize(65)
local decrease = cc.MenuItemFont:create(" - ")
decrease:setColor(cc.c3b(0,200,20))
decrease:registerScriptTapHandler(onDecrease)
local increase = cc.MenuItemFont:create(" + ")
increase:setColor(cc.c3b(0,200,20))
increase:registerScriptTapHandler(onIncrease)
local menu = cc.Menu:create(decrease, increase )
menu:alignItemsHorizontally()
menu:setPosition(cc.p(VisibleRect:getVisibleRect().width/2, VisibleRect:getVisibleRect().height-100))
self:addChild(menu, 10000)
self._armatureCount = 0
self._frames = 0
self._times = 0
self._lastTimes = 0
self._generated = false
self:addArmature(100)
end
function TestPerformanceBatchNode.create()
local layer = TestPerformanceBatchNode.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:creatTitleAndSubTitle(armatureSceneIdx)
local function onNodeEvent(event)
if "enter" == event then
layer:onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
end
return layer
end
local TestChangeZorder = class("TestChangeZorder",ArmatureTestLayer)
TestChangeZorder.__index = TestChangeZorder
TestChangeZorder.currentTag = -1
function TestChangeZorder.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestChangeZorder)
return target
end
function TestChangeZorder:onEnter()
self.currentTag = -1
local armature = ccs.Armature:create("Knight_f/Knight")
armature:getAnimation():playWithIndex(0)
armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100 ))
armature:setScale(0.6)
self.currentTag = self.currentTag + 1
self:addChild(armature, self.currentTag, self.currentTag)
armature = ccs.Armature:create("Cowboy")
armature:getAnimation():playWithIndex(0)
armature:setScale(0.24)
armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100))
self.currentTag = self.currentTag + 1
self:addChild(armature, self.currentTag, self.currentTag)
armature = ccs.Armature:create("Dragon")
armature:getAnimation():playWithIndex(0)
armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100))
armature:setScale(0.6)
self.currentTag = self.currentTag + 1
self:addChild(armature, self.currentTag, self.currentTag)
local function changeZorder(dt)
local node = self:getChildByTag(self.currentTag)
node:setLocalZOrder(math.random(0,1) * 3)
self.currentTag = (self.currentTag + 1) % 3
end
schedule(self,changeZorder, 1)
end
function TestChangeZorder.create()
local layer = TestChangeZorder.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:creatTitleAndSubTitle(armatureSceneIdx)
local function onNodeEvent(event)
if "enter" == event then
layer:onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
end
return layer
end
--UNDO callback
local TestAnimationEvent = class("TestAnimationEvent",ArmatureTestLayer)
TestAnimationEvent.__index = TestAnimationEvent
function TestAnimationEvent.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestAnimationEvent)
return target
end
function TestAnimationEvent:onEnter()
local armature = ccs.Armature:create("Cowboy")
armature:getAnimation():play("Fire")
armature:setScaleX(-0.24)
armature:setScaleY(0.24)
armature:setPosition(cc.p(VisibleRect:left().x + 50, VisibleRect:left().y))
local function callback1()
armature:runAction(cc.ScaleTo:create(0.3, 0.24, 0.24))
armature:getAnimation():play("FireMax", 10)
end
local function callback2()
armature:runAction(cc.ScaleTo:create(0.3, -0.24, 0.24))
armature:getAnimation():play("Fire", 10)
end
local function animationEvent(armatureBack,movementType,movementID)
local id = movementID
if movementType == ccs.MovementEventType.loopComplete then
if id == "Fire" then
local actionToRight = cc.MoveTo:create(2, cc.p(VisibleRect:right().x - 50, VisibleRect:right().y))
armatureBack:stopAllActions()
armatureBack:runAction(cc.Sequence:create(actionToRight,cc.CallFunc:create(callback1)))
armatureBack:getAnimation():play("Walk")
elseif id == "FireMax" then
local actionToLeft = cc.MoveTo:create(2, cc.p(VisibleRect:left().x + 50, VisibleRect:left().y))
armatureBack:stopAllActions()
armatureBack:runAction(cc.Sequence:create(actionToLeft, cc.CallFunc:create(callback2)))
armatureBack:getAnimation():play("Walk")
end
end
end
armature:getAnimation():setMovementEventCallFunc(animationEvent)
self:addChild(armature)
end
function TestAnimationEvent.create()
local layer = TestAnimationEvent.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:creatTitleAndSubTitle(armatureSceneIdx)
local function onNodeEvent(event)
if "enter" == event then
layer:onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
end
return layer
end
local TestFrameEvent = class("TestFrameEvent",ArmatureTestLayer)
TestFrameEvent.__index = TestFrameEvent
function TestFrameEvent.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestFrameEvent)
return target
end
function TestFrameEvent:onEnter()
local gridNode = cc.NodeGrid:create()
local armature = ccs.Armature:create("HeroAnimation")
armature:getAnimation():play("attack")
armature:getAnimation():setSpeedScale(0.5)
armature:setPosition(cc.p(VisibleRect:center().x - 50, VisibleRect:center().y -100))
local function onFrameEvent( bone,evt,originFrameIndex,currentFrameIndex)
if (not gridNode:getActionByTag(frameEventActionTag)) or (not gridNode:getActionByTag(frameEventActionTag):isDone()) then
gridNode:stopAllActions()
local action = cc.ShatteredTiles3D:create(0.2, cc.size(16,12), 5, false)
action:setTag(frameEventActionTag)
gridNode:runAction(action)
end
end
armature:getAnimation():setFrameEventCallFunc(onFrameEvent)
gridNode:addChild(armature)
self:addChild(gridNode)
local function checkAction(dt)
if gridNode:getNumberOfRunningActions() == 0 and gridNode:getGrid() ~= nil then
gridNode:setGrid(nil)
end
end
self:scheduleUpdateWithPriorityLua(checkAction,0)
local function onNodeEvent(tag)
if "exit" == tag then
self:unscheduleUpdate()
end
end
end
function TestFrameEvent.create()
local layer = TestFrameEvent.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:creatTitleAndSubTitle(armatureSceneIdx)
local function onNodeEvent(event)
if "enter" == event then
layer:onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
end
return layer
end
local TestParticleDisplay = class("TestParticleDisplay",ArmatureTestLayer)
TestParticleDisplay.__index = TestParticleDisplay
TestParticleDisplay.animationID = 0
TestParticleDisplay.armature = nil
function TestParticleDisplay.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestParticleDisplay)
return target
end
function TestParticleDisplay:onEnter()
self.animationID = 0
self.armature = ccs.Armature:create("robot")
self.armature:getAnimation():playWithIndex(0)
self.armature:setPosition(VisibleRect:center())
self.armature:setScale(0.48)
self:addChild(self.armature)
local p1 = cc.ParticleSystemQuad:create("Particles/SmallSun.plist")
local p2 = cc.ParticleSystemQuad:create("Particles/SmallSun.plist")
local bone = ccs.Bone:create("p1")
bone:addDisplay(p1, 0)
bone:changeDisplayWithIndex(0, true)
bone:setIgnoreMovementBoneData(true)
bone:setLocalZOrder(100)
bone:setScale(1.2)
self.armature:addBone(bone, "bady-a3")
bone = ccs.Bone:create("p2")
bone:addDisplay(p2, 0)
bone:changeDisplayWithIndex(0, true)
bone:setIgnoreMovementBoneData(true)
bone:setLocalZOrder(100)
bone:setScale(1.2)
self.armature:addBone(bone, "bady-a30")
-- handling touch events
local function onTouchEnded(touches, event)
self.animationID = (self.animationID + 1) % self.armature:getAnimation():getMovementCount()
self.armature:getAnimation():playWithIndex(self.animationID)
end
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCHES_ENDED )
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
end
function TestParticleDisplay.create()
local layer = TestParticleDisplay.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:creatTitleAndSubTitle(armatureSceneIdx)
local function onNodeEvent(event)
if "enter" == event then
layer:onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
end
return layer
end
local TestUseMutiplePicture = class("TestUseMutiplePicture",ArmatureTestLayer)
TestUseMutiplePicture.__index = TestUseMutiplePicture
TestUseMutiplePicture.displayIndex = 0
TestUseMutiplePicture.armature = nil
function TestUseMutiplePicture.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestUseMutiplePicture)
return target
end
function TestUseMutiplePicture:onEnter()
self.displayIndex = 1
self.armature = ccs.Armature:create("Knight_f/Knight")
self.armature:getAnimation():playWithIndex(0)
self.armature:setPosition(cc.p(VisibleRect:left().x + 70, VisibleRect:left().y))
self.armature:setScale(1.2)
self:addChild(self.armature)
local weapon =
{
"weapon_f-sword.png",
"weapon_f-sword2.png",
"weapon_f-sword3.png",
"weapon_f-sword4.png",
"weapon_f-sword5.png",
"weapon_f-knife.png",
"weapon_f-hammer.png",
}
local i = 1
for i = 1,table.getn(weapon) do
local skin = ccs.Skin:createWithSpriteFrameName(weapon[i])
self.armature:getBone("weapon"):addDisplay(skin, i - 1)
end
-- handling touch events
local function onTouchEnded(touches, event)
self.displayIndex = (self.displayIndex + 1) % (table.getn(weapon) - 1)
self.armature:getBone("weapon"):changeDisplayWithIndex(self.displayIndex, true)
end
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCHES_ENDED )
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
end
function TestUseMutiplePicture.create()
local layer = TestUseMutiplePicture.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:creatTitleAndSubTitle(armatureSceneIdx)
local function onNodeEvent(event)
if "enter" == event then
layer:onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
end
return layer
end
local TestAnchorPoint = class("TestAnchorPoint",ArmatureTestLayer)
TestAnchorPoint.__index = TestAnchorPoint
function TestAnchorPoint.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestAnchorPoint)
return target
end
function TestAnchorPoint:onEnter()
local i = 1
for i = 1 , 5 do
local armature = ccs.Armature:create("Cowboy")
armature:getAnimation():playWithIndex(0)
armature:setPosition(VisibleRect:center())
armature:setScale(0.2)
self:addChild(armature, 0, i - 1)
end
self:getChildByTag(0):setAnchorPoint(cc.p(0,0))
self:getChildByTag(1):setAnchorPoint(cc.p(0,1))
self:getChildByTag(2):setAnchorPoint(cc.p(1,0))
self:getChildByTag(3):setAnchorPoint(cc.p(1,1))
self:getChildByTag(4):setAnchorPoint(cc.p(0.5,0.5))
end
function TestAnchorPoint.create()
local layer = TestAnchorPoint.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:creatTitleAndSubTitle(armatureSceneIdx)
local function onNodeEvent(event)
if "enter" == event then
layer:onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
end
return layer
end
local TestArmatureNesting = class("TestArmatureNesting",ArmatureTestLayer)
TestArmatureNesting.__index = TestArmatureNesting
TestArmatureNesting.weaponIndex = 0
TestArmatureNesting.armature = nil
function TestArmatureNesting.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestArmatureNesting)
return target
end
function TestArmatureNesting:onEnter()
self.weaponIndex = 0
self.armature = ccs.Armature:create("cyborg")
self.armature:getAnimation():playWithIndex(1)
self.armature:setPosition(VisibleRect:center())
self.armature:setScale(1.2)
self.armature:getAnimation():setSpeedScale(0.4)
self:addChild(self.armature)
-- handling touch events
local function onTouchEnded(touches, event)
self.weaponIndex = (self.weaponIndex + 1) % 4
self.armature:getBone("armInside"):getChildArmature():getAnimation():playWithIndex(self.weaponIndex)
self.armature:getBone("armOutside"):getChildArmature():getAnimation():playWithIndex(self.weaponIndex)
end
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCHES_ENDED )
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
end
function TestArmatureNesting.create()
local layer = TestArmatureNesting.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:creatTitleAndSubTitle(armatureSceneIdx)
local function onNodeEvent(event)
if "enter" == event then
layer:onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
end
return layer
end
local Hero = class("Hero")
Hero.__index = Hero
Hero._mount = nil
Hero._layer = nil
function Hero.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, Hero)
return target
end
function Hero:changeMount(armature)
if nil == armature then
--note
self:retain()
self:playWithIndex(0)
self._mount:getBone("hero"):removeDisplay(0)
self._mount:stopAllActions()
self:setPosition(self._mount:getPosition())
self._layer:addChild(self)
self:release()
self._mount = armature
else
self._mount = armature
self:retain()
self:removeFromParent(false)
local bone = armature:getBone("hero")
bone:addDisplay(self, 0)
bone:changeDisplayWithIndex(0, true)
bone:setIgnoreMovementBoneData(true)
self:setPosition(cc.p(0,0))
self:playWithIndex(1)
self:setScale(1)
self:release()
end
end
function Hero:playWithIndex(index)
self:getAnimation():playWithIndex(index)
if nil ~= self._mount then
self._mount:getAnimation():playWithIndex(index)
end
end
function Hero.create(name)
local hero = Hero.extend(ccs.Armature:create(name))
return hero
end
local TestArmatureNesting2 = class("TestArmatureNesting",ArmatureTestLayer)
TestArmatureNesting2.__index = TestArmatureNesting2
TestArmatureNesting2._hero = nil
TestArmatureNesting2._horse = nil
TestArmatureNesting2._horse2 = nil
TestArmatureNesting2._bear = nil
TestArmatureNesting2._touchedMenu = nil
function TestArmatureNesting2.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestArmatureNesting2)
return target
end
function TestArmatureNesting2:onEnter()
-- handling touch events
local function onTouchEnded(touches, event)
local location = touches[1]:getLocation()
local armature = self._hero._mount and self._hero._mount or self._hero
if location.x < armature:getPositionX() then
armature:setScaleX(-1)
else
armature:setScaleX(1)
end
local move = cc.MoveTo:create(2, location)
armature:stopAllActions()
armature:runAction(cc.Sequence:create(move))
end
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCHES_ENDED )
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
local function changeMountCallback(sender)
self._hero:stopAllActions()
if nil ~= self._hero._mount then
self._hero:changeMount(nil)
else
if cc.pGetDistance(cc.p(self._hero:getPosition()),cc.p(self._horse:getPosition())) < 20 then
self._hero:changeMount(self._horse)
elseif cc.pGetDistance(cc.p(self._hero:getPosition()),cc.p(self._horse2:getPosition())) < 20 then
self._hero:changeMount(self._horse2)
elseif cc.pGetDistance(cc.p(self._hero:getPosition()),cc.p(self._bear:getPosition())) < 30 then
self._hero:changeMount(self._bear)
end
end
end
self._touchedMenu = false
local label = cc.Label:createWithTTF("Change Mount", s_arialPath, 20)
label:setAnchorPoint(cc.p(0.5, 0.5))
local menuItem = cc.MenuItemLabel:create(label)
menuItem:registerScriptTapHandler(changeMountCallback)
local menu = cc.Menu:create(menuItem)
menu:setPosition(cc.p(0,0))
menuItem:setPosition( cc.p( VisibleRect:right().x - 67, VisibleRect:bottom().y + 50) )
self:addChild(menu, 2)
self._hero = Hero.create("hero")
self._hero._layer = self
self._hero:playWithIndex(0)
self._hero:setPosition(cc.p(VisibleRect:left().x + 20, VisibleRect:left().y))
self:addChild(self._hero)
self._horse = self:createMount("horse", VisibleRect:center())
self._horse2 = self:createMount("horse", cc.p(120, 200))
self._horse2:setOpacity(200)
self._bear = self:createMount("bear", cc.p(300,70))
end
function TestArmatureNesting2:createMount(name,pt)
local armature = ccs.Armature:create(name)
armature:getAnimation():playWithIndex(0)
armature:setPosition(pt)
self:addChild(armature)
return armature
end
function TestArmatureNesting2.create()
local layer = TestArmatureNesting2.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:creatTitleAndSubTitle(armatureSceneIdx)
local function onNodeEvent(event)
if "enter" == event then
layer:onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
end
return layer
end
local armatureSceneArr =
{
TestAsynchronousLoading.create,
TestDirectLoading.create,
TestCSWithSkeleton.create,
TestDragonBones20.create,
TestPerformance.create,
--TestPerformanceBatchNode.create,
TestChangeZorder.create,
TestAnimationEvent.create,
TestFrameEvent.create,
TestParticleDisplay.create,
TestUseMutiplePicture.create,
TestAnchorPoint.create,
TestArmatureNesting.create,
TestArmatureNesting2.create,
}
function nextArmatureTest()
armatureSceneIdx = armatureSceneIdx + 1
armatureSceneIdx = armatureSceneIdx % table.getn(armatureSceneArr)
if 0 == armatureSceneIdx then
armatureSceneIdx = table.getn(armatureSceneArr)
end
return armatureSceneArr[armatureSceneIdx]()
end
function backArmatureTest()
armatureSceneIdx = armatureSceneIdx - 1
if armatureSceneIdx <= 0 then
armatureSceneIdx = armatureSceneIdx + table.getn(armatureSceneArr)
end
return armatureSceneArr[armatureSceneIdx]()
end
function restartArmatureTest()
return armatureSceneArr[armatureSceneIdx]()
end
local function addFileInfo()
end
function runArmatureTestScene()
local scene = ArmatureTestScene.create()
scene:runThisTest()
cc.Director:getInstance():replaceScene(scene)
end
| mit |
rderimay/Focus-Points | focuspoints.lrdevplugin/CanonDelegates.lua | 5 | 5145 | --[[
Copyright 2016 Whizzbang Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
--[[
A collection of delegate functions to be passed into the DefaultPointRenderer when
the camera is Canon
--]]
local LrStringUtils = import "LrStringUtils"
require "Utils"
CanonDelegates = {}
--[[
-- metaData - the metadata as read by exiftool
--]]
function CanonDelegates.getAfPoints(photo, metaData)
local cameraModel = string.lower(photo:getFormattedMetadata("cameraModel"))
local imageWidth
local imageHeight
if cameraModel == "canon eos 5d" then -- For some reason for this camera, the AF Image Width/Height has to be replaced by Canon Image Width/Height
imageWidth = ExifUtils.findFirstMatchingValue(metaData, { "Canon Image Width", "Exif Image Width" })
imageHeight = ExifUtils.findFirstMatchingValue(metaData, { "Canon Image Height", "Exif Image Height" })
else
imageWidth = ExifUtils.findFirstMatchingValue(metaData, { "AF Image Width", "Exif Image Width" })
imageHeight = ExifUtils.findFirstMatchingValue(metaData, { "AF Image Height", "Exif Image Height" })
end
if imageWidth == nil or imageHeight == nil then
return nil
end
local orgPhotoWidth, orgPhotoHeight = DefaultPointRenderer.getNormalizedDimensions(photo)
local xScale = orgPhotoWidth / imageWidth
local yScale = orgPhotoHeight / imageHeight
local afPointWidth = ExifUtils.findFirstMatchingValue(metaData, { "AF Area Width" })
local afPointHeight = ExifUtils.findFirstMatchingValue(metaData, { "AF Area Height" })
local afPointWidths = ExifUtils.findFirstMatchingValue(metaData, { "AF Area Widths" })
local afPointHeights = ExifUtils.findFirstMatchingValue(metaData, { "AF Area Heights" })
if (afPointWidth == nil and afPointWidths == nil) or (afPointHeight == nil and afPointHeights == nil) then
return nil
end
if afPointWidths == nil then
afPointWidths = {}
else
afPointWidths = split(afPointWidths, " ")
end
if afPointHeights == nil then
afPointHeights = {}
else
afPointHeights = split(afPointHeights, " ")
end
local afAreaXPositions = ExifUtils.findFirstMatchingValue(metaData, { "AF Area X Positions" })
local afAreaYPositions = ExifUtils.findFirstMatchingValue(metaData, { "AF Area Y Positions" })
if afAreaXPositions == nil or afAreaYPositions == nil then
return nil
end
afAreaXPositions = split(afAreaXPositions, " ")
afAreaYPositions = split(afAreaYPositions, " ")
local afPointsSelected = ExifUtils.findFirstMatchingValue(metaData, { "AF Points Selected", "AF Points In Focus" })
if afPointsSelected == nil then
afPointsSelected = {}
else
afPointsSelected = split(afPointsSelected, ",")
end
local afPointsInFocus = ExifUtils.findFirstMatchingValue(metaData, { "AF Points In Focus" })
if afPointsInFocus == nil then
afPointsInFocus = {}
else
afPointsInFocus = split(afPointsInFocus, ",")
end
local result = {
pointTemplates = DefaultDelegates.pointTemplates,
points = {
}
}
-- it seems Canon Point and Shoot cameras are reversed on the y-axis
local exifCameraType = ExifUtils.findFirstMatchingValue(metaData, { "Camera Type" })
if (exifCameraType == nil) then
exifCameraType = ""
end
local yDirection = -1
if string.lower(exifCameraType) == "compact" then
yDirection = 1
end
for key,value in pairs(afAreaXPositions) do
local x = (imageWidth/2 + afAreaXPositions[key]) * xScale -- On Canon, everithing is referenced from the center,
local y = (imageHeight/2 + (afAreaYPositions[key] * yDirection)) * yScale
local width = 0
local height = 0
if afPointWidths[key] == nil then
width = afPointWidth * xScale
else
width = afPointWidths[key] * xScale
end
if afPointHeights[key] == nil then
height = afPointHeight * xScale
else
height = afPointHeights[key] * xScale
end
local pointType = DefaultDelegates.POINTTYPE_AF_INACTIVE
local isInFocus = arrayKeyOf(afPointsInFocus, tostring(key - 1)) ~= nil -- 0 index based array by Canon
local isSelected = arrayKeyOf(afPointsSelected, tostring(key - 1)) ~= nil
if isInFocus and isSelected then
pointType = DefaultDelegates.POINTTYPE_AF_SELECTED_INFOCUS
elseif isInFocus then
pointType = DefaultDelegates.POINTTYPE_AF_INFOCUS
elseif isSelected then
pointType = DefaultDelegates.POINTTYPE_AF_SELECTED
end
if width > 0 and height > 0 then
table.insert(result.points, {
pointType = pointType,
x = x,
y = y,
width = width,
height = height
})
end
end
return result
end
| apache-2.0 |
patrikrm13/X_Y | plugins/inrealm.lua | 7 | 25539 | -- 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 'گروهی بانام [ '..string.gsub(group_name, '_', ' ')..' ] @RM13790115bot :)ساخته شد.'
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 'گپ مادر بانام [ '..string.gsub(group_name, '_', ' ')..' ] ساخته شد.'
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 'به گروپ هیچ خاصیتی ندارد.'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'گپ چت یافت نشد.'
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 "فقط ادمین رباتا"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'قوانین گروه:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin(msg) then
return "فقط ادمین"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'قوانین گروه:\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 "فقط ادمین!"
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 == 'غیرفعال' then
return 'اسم گروه قفل است.'
else
data[tostring(target)]['settings']['lock_name'] = 'فعال'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'اسم گروه قفل است.'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin(msg) then
return "فقط ادمین"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'غیرفعال' then
return 'اسم گروه آزاد شد.'
else
data[tostring(target)]['settings']['lock_name'] = 'غیر فعال'
save_data(_config.moderation.data, data)
return 'اسم گروه آزاد شد.'
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 "فقط ادمین"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'فعال' then
return 'قفل ادد ممبر فعال'
else
data[tostring(target)]['settings']['lock_member'] = 'فعال'
save_data(_config.moderation.data, data)
end
return 'قفل اددممبر فعال'
end
local function unlock_group_member(msg, data, target)
if not is_admin(msg) then
return "فقط ادمین"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'غیرفعال' then
return 'اددممبر قفل نیست'
else
data[tostring(target)]['settings']['lock_member'] = 'غیر فعال'
save_data(_config.moderation.data, data)
return 'قفل ادد ممبر فعال نیست'
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 "فقط ادمین"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'فعال' then
return 'قفل عکس فعال'
else
data[tostring(target)]['settings']['set_photo'] = 'صبرکنید'
save_data(_config.moderation.data, data)
end
return 'هرعکسی که بفرستی میزارم روی پروفایل گروه'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "فقط ادمین"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'غیرفعال' then
return 'عکس گروه قفل نیست'
else
data[tostring(target)]['settings']['lock_photo'] = 'غیرفعال'
save_data(_config.moderation.data, data)
return 'قفل عکس گروه غیرفعال شد'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "فقط ادمین"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'فعال' then
return 'اسپم قفل شد'
else
data[tostring(target)]['settings']['flood'] = 'فعال'
save_data(_config.moderation.data, data)
return 'اسپم فعال'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin(msg) then
return "فقط ادمین"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'فعال' then
return 'قفل اسپم غیرفعال'
else
data[tostring(target)]['settings']['flood'] = 'غیرفعال'
save_data(_config.moderation.data, data)
return 'قفل اسپم غیرفعال'
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 "فقط ادمین"
end
local settings = data[tostring(target)]['settings']
local text = "تنظیمات گروه:\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.."لیست افراداینگروه.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.."لیست افزاد این گروه.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..' ادمین بود'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..'ادمین شد'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "از ادمینی در اومد"
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..' ادمین نیست'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' از ادمینی در اومد'
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 = "اونری وجود ندارد"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_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 = "اونرندارد"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_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..' ادمین بود')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' ادمین شد')
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..' ادمین نیست')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' دراومد')
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 = 'شخص @'..member..' درگپ نیست'
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.."] لیست ممبر ها ")
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.."] فایل لیست ممبر")
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 |
jithumon/Kochu | plugins/backup.lua | 6 | 5574 | local config = require 'config'
local u = require 'utilities'
local api = require 'methods'
local JSON = require 'dkjson'
local plugin = {}
local function save_data(filename, data)
local s = JSON.encode(data, {indent = true})
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
local function load_data(filename)
local f = io.open(filename)
if f then
local s = f:read('*all')
f:close()
return JSON.decode(s)
else
return {}
end
end
local function gen_backup(chat_id)
chat_id = tostring(chat_id)
local file_path = '/tmp/snap'..chat_id..'.gbb'
local t = {
[chat_id] = {
hashes = {},
sets = {}
}
}
local hash
for i=1, #config.chat_hashes do
hash = ('chat:%s:%s'):format(chat_id, config.chat_hashes[i])
local content = db:hgetall(hash)
if next(content) then
t[chat_id].hashes[config.chat_hashes[i]] = {}
for key, val in pairs(content) do
t[chat_id].hashes[config.chat_hashes[i]][key] = val
end
end
end
for i=1, #config.chat_sets do
if config.chat_sets[i] ~= 'mods' then --do not backup the modlist
set = ('chat:%s:%s'):format(chat_id, config.chat_sets[i])
local content = db:smembers(set)
if next(content) then
t[chat_id].sets[config.chat_sets[i]] = content
end
end
end
save_data(file_path, t)
return file_path
end
local function get_time_remaining(seconds)
local final = ''
local hours = math.floor(seconds/3600)
seconds = seconds - (hours*60*60)
local min = math.floor(seconds/60)
seconds = seconds - (min*60)
if hours and hours > 0 then
final = final..hours..'h '
end
if min and min > 0 then
final = final..min..'m '
end
if seconds and seconds > 0 then
final = final..seconds..'s'
end
return final
end
local imported_text = [['Done.
*Important*:
- #extra commands which are associated with a media must be set again if the bot you are using now is different from the bot that originated the backup.
- moderators have been restored too (if there were some moderators when the file has been created)
]]
function plugin.onTextMessage(msg, blocks)
if msg.from.admin then
if blocks[1] == 'snap' then
local key = 'chat:'..msg.chat.id..':lastsnap'
local last_user = db:get(key)
if last_user then
local ttl = db:ttl(key)
local time_remaining = get_time_remaining(ttl)
local text = _("<i>I'm sorry, this command has been used for the last time less then 3 days ago by</i> %s (ask him for the file).\nWait [<code>%s</code>] to use it again"):format(last_user, time_remaining)
api.sendReply(msg, text, 'html')
else
local name = u.getname_final(msg.from)
db:setex(key, 259200, name) --3 days
local file_path = gen_backup(msg.chat.id)
api.sendReply(msg, _('*Sent in private*'), true)
api.sendDocument(msg.from.id, file_path, nil, ('#snap\n%s'):format(msg.chat.title))
end
end
if blocks[1] == 'import' then
local text
if msg.reply then
if msg.reply.document then
if msg.reply.document.file_name == 'snap'..msg.chat.id..'.gbb' then
local res = api.getFile(msg.reply.document.file_id)
local download_link = u.telegram_file_link(res)
local file_path, code = u.download_to_file(download_link, '/tmp/'..msg.chat.id..'.json')
if not file_path then
text = _('Download of the file failed with code %s'):format(tostring(code))
else
local data = load_data(file_path)
for chat_id, group_data in pairs(data) do
chat_id = tonumber(chat_id)
if tonumber(chat_id) ~= msg.chat.id then
text = _('Chat IDs don\'t match (%s and %s)'):format(tostring(chat_id), tostring(msg.chat.id))
else
--restoring sets
if group_data.sets and next(group_data.sets) then
for set, content in pairs(group_data.sets) do
db:sadd(('chat:%d:%s'):format(chat_id, set), table.unpack(content))
end
end
--restoring hashes
if group_data.hashes and next(group_data.hashes) then
for hash, content in pairs(group_data.hashes) do
if next(content) then
--[[for key, val in pairs(content) do
print('\tkey:', key)
db:hset(('chat:%d:%s'):format(chat_id, hash), key, val)
end]]
db:hmset(('chat:%d:%s'):format(chat_id, hash), content)
end
end
end
text = _(imported_text)
end
end
end
else
text = _('This is not a valid backup file.\nReason: invalid name (%s)'):format(tostring(msg.reply_to_message.document.file_name))
end
else
text = _('Invalid input. Please reply to a document')
end
else
text = _('Invalid input. Please reply to the backup file (/snap command to get it)')
end
api.sendMessage(msg.chat.id, text)
end
end
end
plugin.triggers = {
onTextMessage = {
config.cmd..'(snap)$',
config.cmd..'(import)$'
}
}
return plugin | gpl-2.0 |
JarnoVgr/Mr.Green-MTA-Resources | resources/[web]/irc/scripts/utility.lua | 3 | 6094 | ---------------------------------------------------------------------
-- Project: irc
-- Author: MCvarial
-- Contact: mcvarial@gmail.com
-- Version: 1.0.0
-- Date: 31.10.2010
---------------------------------------------------------------------
------------------------------------
-- Utility
------------------------------------
function getAdminMessage (time,author)
outputServerLog("Time: "..time..", Author: "..author)
return "Hello, world!"
end
function getNickFromRaw (raw)
return string.sub(gettok(raw,1,33),2)
end
function getMessageFromRaw (raw)
local t = split(string.sub(raw,2,-2),58)
table.remove(t,1)
return table.concat(t,":")
end
local chars = {"+","%","@","&","~"}
function getNickAndLevel (nick)
for i,char in ipairs (chars) do
if string.sub(nick,1,1) == char then
nick = string.sub(nick,2)
return nick,i
end
end
return nick,0
end
function toletters (string)
local t = {}
for i=1,string.len(string) do
table.insert(t,string.sub(string,1,1))
string = string.sub(string,2)
end
return t
end
function getPlayerFromPartialName (name)
local matches = {}
for i,player in ipairs (getElementsByType("player")) do
if getPlayerName(player) == name then
return player
end
if string.find(string.lower(getPlayerName(player):gsub('#%x%x%x%x%x%x', '')),string.lower(name),0,false) then
table.insert(matches,player)
end
end
if #matches == 1 then
return matches[1]
end
return false
end
function getResourceFromPartialName (name)
local matches = {}
for i,resource in ipairs (getResources()) do
if getResourceName(resource) == name then
return resource
end
if string.find(string.lower(getResourceName(resource)),string.lower(name),0,false) then
table.insert(matches,resource)
end
end
if #matches == 1 then
return matches[1]
end
return false
end
function getTimeStamp ()
local time = getRealTime()
return "["..(time.year + 1900).."-"..(time.month+1).."-"..time.monthday.." "..time.hour..":"..time.minute..":"..time.second.."]"
end
local mutes = {}
function muteSerial (serial,reason,time)
mutes[serial] = reason
setTimer(unmuteSerial,time,1,serial)
return true
end
function unmuteSerial (serial)
for i,player in ipairs (getElementsByType("player")) do
if getPlayerSerial(player) == serial then
setPlayerMuted(player,false)
outputChatBox("* "..getPlayerName(player).." was unmuted",root,0,0,255)
outputIRC("12* "..getPlayerName(player).." was unmuted")
end
end
mutes[serial] = nil
end
addEventHandler("onPlayerJoin",root,
function ()
local reason = mutes[(getPlayerSerial(source))]
if reason then
setPlayerMuted(source,true)
outputChatBox("* "..getPlayerName(source).." was muted ("..reason..")",root,0,0,255)
end
end
)
addEventHandler("onResourceStop",resourceRoot,
function ()
for serial,reason in pairs (mutes) do
unmuteSerial(serial)
end
end
)
local times = {}
times["ms"] = 1
times["sec"] = 1000
times["secs"] = 1000
times["second"] = 1000
times["seconds"] = 1000
times["min"] = 60000
times["mins"] = 60000
times["minute"] = 60000
times["minutes"] = 60000
times["hour"] = 3600000
times["hours"] = 3600000
times["day"] = 86400000
times["days"] = 86400000
times["week"] = 604800000
times["weeks"] = 604800000
times["month"] = 2592000000
times["months"] = 2592000000
function toMs (time)
time = string.sub(time,2,-2)
local t = split(time,32)
local factor = 0
local ms = 0
for i,v in ipairs (t) do
if tonumber(v) then
factor = tonumber(v)
elseif times[v] then
ms = ms + (factor * times[v])
end
end
return ms
end
function msToTimeStr(ms)
if not ms then
return ''
end
local centiseconds = tostring(math.floor(math.fmod(ms, 1000)/10))
if #centiseconds == 1 then
centiseconds = '0' .. centiseconds
end
local s = math.floor(ms / 1000)
local seconds = tostring(math.fmod(s, 60))
if #seconds == 1 then
seconds = '0' .. seconds
end
local minutes = tostring(math.floor(s / 60))
return minutes .. ':' .. seconds .. ':' .. centiseconds
end
function getTimeString (timeMs)
local weeks = math.floor(timeMs/604800000)
timeMs = timeMs - weeks * 604800000
local days = math.floor(timeMs/86400000)
timeMs = timeMs - days * 86400000
local hours = math.floor(timeMs/3600000)
timeMs = timeMs - hours * 3600000
local minutes = math.floor(timeMs/60000)
timeMs = timeMs - minutes * 60000
local seconds = math.floor(timeMs/1000)
return string.format("%dwks %ddays %dhrs %dmins %dsecs ",weeks,days,hours,minutes,seconds)
end
function getNumberFromVersion (version)
local p1,p2,p3 = unpack(split(version,46))
return tonumber((100*tonumber(p1))+(10*tonumber(p2))+(tonumber(p3)))
end
_addBan = addBan
function addBan (...)
if getVersion().number < 260 then
local t = {...}
t[4] = nil
return _addBan(unpack(t))
else
return _addBan(...)
end
end
function outputServerLog() end
| mit |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/ParticleFlower.lua | 11 | 1380 |
--------------------------------
-- @module ParticleFlower
-- @extend ParticleSystemQuad
-- @parent_module cc
--------------------------------
--
-- @function [parent=#ParticleFlower] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#ParticleFlower] initWithTotalParticles
-- @param self
-- @param #int numberOfParticles
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Create a flower particle system.<br>
-- return An autoreleased ParticleFlower object.
-- @function [parent=#ParticleFlower] create
-- @param self
-- @return ParticleFlower#ParticleFlower ret (return value: cc.ParticleFlower)
--------------------------------
-- Create a flower particle system withe a fixed number of particles.<br>
-- param numberOfParticles A given number of particles.<br>
-- return An autoreleased ParticleFlower object.<br>
-- js NA
-- @function [parent=#ParticleFlower] createWithTotalParticles
-- @param self
-- @param #int numberOfParticles
-- @return ParticleFlower#ParticleFlower ret (return value: cc.ParticleFlower)
--------------------------------
-- js ctor
-- @function [parent=#ParticleFlower] ParticleFlower
-- @param self
-- @return ParticleFlower#ParticleFlower self (return value: cc.ParticleFlower)
return nil
| mit |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/TransitionSlideInB.lua | 11 | 1044 |
--------------------------------
-- @module TransitionSlideInB
-- @extend TransitionSlideInL
-- @parent_module cc
--------------------------------
-- Creates a transition with duration and incoming scene.<br>
-- param t Duration time, in seconds.<br>
-- param scene A given scene.<br>
-- return A autoreleased TransitionSlideInB object.
-- @function [parent=#TransitionSlideInB] create
-- @param self
-- @param #float t
-- @param #cc.Scene scene
-- @return TransitionSlideInB#TransitionSlideInB ret (return value: cc.TransitionSlideInB)
--------------------------------
-- returns the action that will be performed by the incoming and outgoing scene
-- @function [parent=#TransitionSlideInB] action
-- @param self
-- @return ActionInterval#ActionInterval ret (return value: cc.ActionInterval)
--------------------------------
--
-- @function [parent=#TransitionSlideInB] TransitionSlideInB
-- @param self
-- @return TransitionSlideInB#TransitionSlideInB self (return value: cc.TransitionSlideInB)
return nil
| mit |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/tests/lua-tests/src/LightTest/LightTest.lua | 11 | 8467 | local LightTest = class("LightTest",function()
return cc.Layer:create()
end)
function LightTest:ctor()
local function onNodeEvent(event)
if event == "enter" then
self:init()
elseif event == "exit" then
self:unscheduleUpdate()
end
end
self:registerScriptHandler(onNodeEvent)
end
function LightTest:init()
self:addSprite()
self:addLights()
local s = cc.Director:getInstance():getWinSize()
local camera = cc.Camera:createPerspective(60, s.width/s.height, 1.0, 1000.0)
camera:setCameraFlag(cc.CameraFlag.USER1)
camera:setPosition3D(cc.vec3(0.0, 100, 100))
camera:lookAt(cc.vec3(0.0, 0.0, 0.0), cc.vec3(0.0, 1.0, 0.0))
self:addChild(camera)
local ttfConfig = {}
ttfConfig.fontFilePath = "fonts/arial.ttf"
ttfConfig.fontSize = 15
local ambientLightLabel = cc.Label:createWithTTF(ttfConfig,"Ambient Light ON")
local menuItem0 = cc.MenuItemLabel:create(ambientLightLabel)
menuItem0:registerScriptTapHandler(function (tag, sender)
local str = nil
local isON = not self._ambientLight:isEnabled()
if isON then
str = "Ambient Light ON"
else
str = "Ambient Light OFF"
end
self._ambientLight:setEnabled(isON)
menuItem0:setString(str)
end)
local directionalLightLabel = cc.Label:createWithTTF(ttfConfig,"Directional Light OFF")
local menuItem1 = cc.MenuItemLabel:create(directionalLightLabel)
menuItem1:registerScriptTapHandler(function (tag, sender)
local str = nil
local isON = not self._directionalLight:isEnabled()
if isON then
str = "Directional Light ON"
else
str = "Directional Light OFF"
end
self._directionalLight:setEnabled(isON)
menuItem1:setString(str)
end)
local pointLightLabel = cc.Label:createWithTTF(ttfConfig,"Point Light OFF")
local menuItem2 = cc.MenuItemLabel:create(pointLightLabel)
menuItem2:registerScriptTapHandler(function (tag, sender)
local str = nil
local isON = not self._pointLight:isEnabled()
if isON then
str = "Point Light ON"
else
str = "Point Light OFF"
end
self._pointLight:setEnabled(isON)
menuItem2:setString(str)
end)
local spotLightLabel = cc.Label:createWithTTF(ttfConfig,"Spot Light OFF")
local menuItem3 = cc.MenuItemLabel:create(spotLightLabel)
menuItem3:registerScriptTapHandler(function (tag, sender)
local str = nil
local isON = not self._spotLight:isEnabled()
if isON then
str = "Spot Light ON"
else
str = "Spot Light OFF"
end
self._spotLight:setEnabled(isON)
menuItem3:setString(str)
end)
local menu = cc.Menu:create(menuItem0, menuItem1, menuItem2, menuItem3)
menu:setPosition(cc.p(0, 0))
menuItem0:setAnchorPoint(cc.p(0.0 ,1.0))
menuItem0:setPosition( cc.p(VisibleRect:left().x, VisibleRect:top().y-50) )
menuItem1:setAnchorPoint(cc.p(0.0, 1.0))
menuItem1:setPosition( cc.p(VisibleRect:left().x, VisibleRect:top().y-100) )
menuItem2:setAnchorPoint(cc.p(0.0, 1.0))
menuItem2:setPosition( cc.p(VisibleRect:left().x, VisibleRect:top().y -150))
menuItem3:setAnchorPoint(cc.p(0.0, 1.0))
menuItem3:setPosition( cc.p(VisibleRect:left().x, VisibleRect:top().y -200))
self:addChild(menu)
local angleDelta = 0.0
local function update(delta)
if nil ~= self._directionalLight then
self._directionalLight:setRotation3D(cc.vec3(-45.0, -angleDelta * 57.29577951, 0.0))
end
if nil ~= self._pointLight then
self._pointLight:setPositionX(100.0 * math.cos(angleDelta + 2.0 * delta))
self._pointLight:setPositionY(100.0)
self._pointLight:setPositionZ(100.0 * math.sin(angleDelta + 2.0 * delta))
end
if nil ~= self._spotLight then
self._spotLight:setPositionX(100.0 * math.cos(angleDelta + 4.0 * delta))
self._spotLight:setPositionY(100.0)
self._spotLight:setPositionZ(100.0 * math.sin(angleDelta + 4.0 * delta))
self._spotLight:setDirection(cc.vec3(-math.cos(angleDelta + 4.0 * delta), -1.0, -math.sin(angleDelta + 4.0 * delta)))
end
angleDelta = angleDelta + delta
end
self:scheduleUpdateWithPriorityLua(update,0)
end
function LightTest:addSprite()
local s = cc.Director:getInstance():getWinSize()
local fileName = "Sprite3DTest/orc.c3b"
local sprite1 = cc.Sprite3D:create(fileName)
sprite1:setRotation3D(cc.vec3(0.0, 180.0, 0.0))
sprite1:setPosition(cc.p(0.0, 0.0))
sprite1:setScale(2.0)
local sp = cc.Sprite3D:create("Sprite3DTest/axe.c3b")
sprite1:getAttachNode("Bip001 R Hand"):addChild(sp)
local animation = cc.Animation3D:create(fileName)
if nil ~=animation then
local animate = cc.Animate3D:create(animation)
sprite1:runAction(cc.RepeatForever:create(animate))
end
self:addChild(sprite1)
sprite1:setCameraMask(2)
local fileName = "Sprite3DTest/sphere.c3b"
local sprite2 = cc.Sprite3D:create(fileName)
sprite2:setPosition(cc.p(30.0, 0.0))
self:addChild(sprite2)
sprite2:setCameraMask(2)
local fileName = "Sprite3DTest/sphere.c3b"
local sprite3 = cc.Sprite3D:create(fileName)
sprite3:setScale(0.5)
sprite3:setPosition(cc.p(-50.0, 0.0))
self:addChild(sprite3)
sprite3:setCameraMask(2)
local fileName = "Sprite3DTest/sphere.c3b"
local sprite4 = cc.Sprite3D:create(fileName)
sprite4:setScale(0.5)
sprite4:setPosition(cc.p(-30.0, 10.0))
self:addChild(sprite4)
sprite4:setCameraMask(2)
end
function LightTest:addLights()
local s = cc.Director:getInstance():getWinSize()
self._ambientLight = cc.AmbientLight:create(cc.c3b(200, 200, 200))
self._ambientLight:setEnabled(true)
self:addChild(self._ambientLight)
self._ambientLight:setCameraMask(2)
self._directionalLight = cc.DirectionLight:create(cc.vec3(-1.0, -1.0, 0.0), cc.c3b(200, 200, 200))
self._directionalLight:setEnabled(false)
self:addChild(self._directionalLight)
self._directionalLight:setCameraMask(2)
self._pointLight = cc.PointLight:create(cc.vec3(0.0, 0.0, 0.0), cc.c3b(200, 200, 200), 10000.0)
self._pointLight:setEnabled(false)
self:addChild(self._pointLight)
self._pointLight:setCameraMask(2)
self._spotLight = cc.SpotLight:create(cc.vec3(-1.0, -1.0, 0.0), cc.vec3(0.0, 0.0, 0.0), cc.c3b(200, 200, 200), 0.0, 0.5, 10000.0)
self._spotLight:setEnabled(false)
self:addChild(self._spotLight)
self._spotLight:setCameraMask(2)
local tintto1 = cc.TintTo:create(4, 0, 0, 255)
local tintto2 = cc.TintTo:create(4, 0, 255, 0)
local tintto3 = cc.TintTo:create(4, 255, 0, 0)
local tintto4 = cc.TintTo:create(4, 255, 255, 255)
local seq = cc.Sequence:create(tintto1,tintto2, tintto3, tintto4)
self._ambientLight:runAction(cc.RepeatForever:create(seq))
tintto1 = cc.TintTo:create(4, 255, 0, 0)
tintto2 = cc.TintTo:create(4, 0, 255, 0)
tintto3 = cc.TintTo:create(4, 0, 0, 255)
tintto4 = cc.TintTo:create(4, 255, 255, 255)
seq = cc.Sequence:create(tintto1,tintto2, tintto3, tintto4)
self._directionalLight:runAction(cc.RepeatForever:create(seq))
tintto1 = cc.TintTo:create(4, 255, 0, 0)
tintto2 = cc.TintTo:create(4, 0, 255, 0)
tintto3 = cc.TintTo:create(4, 0, 0, 255)
tintto4 = cc.TintTo:create(4, 255, 255, 255)
seq = cc.Sequence:create(tintto2, tintto1, tintto3, tintto4)
self._pointLight:runAction(cc.RepeatForever:create(seq))
tintto1 = cc.TintTo:create(4, 255, 0, 0)
tintto2 = cc.TintTo:create(4, 0, 255, 0)
tintto3 = cc.TintTo:create(4, 0, 0, 255)
tintto4 = cc.TintTo:create(4, 255, 255, 255)
seq = cc.Sequence:create(tintto3, tintto2, tintto1, tintto4)
self._spotLight:runAction(cc.RepeatForever:create(seq))
end
function LightTest.create( ... )
local layer = LightTest.new()
Helper.initWithLayer(layer)
Helper.titleLabel:setString("Light Test")
return layer
end
function LightTestMain()
cclog("LightTestMain")
local scene = cc.Scene:create()
Helper.createFunctionTable =
{
LightTest.create,
}
scene:addChild(LightTest.create(), 0)
scene:addChild(CreateBackMenuItem())
return scene
end
| mit |
uonline/debut | src/day2/act3/regimenstrasse.room.lua | 1 | 14423 | -- Переменные локации
_girl_has_gotten_help = false
-- Переходы
regimenstrasse_to_berlinstrasse = vroom('Главная улица', 'berlinstrasse')
regimenstrasse_to_berlinstrasse:disable()
-- Локация
regimenstrasse = room {
nam = 'Площадь Режима';
dsc = [[
Ты стоишь на небольшой площади, которую окружает кольцо трёхэтажных зданий. Судя
по относительно свежей краске и качеству строительства, здания были возведены
после войны. Режим великодушно отстраивал те города, где сажал своих наместников
с богоизбранными и размещал своих солдат. В каждом городе появлялась площадь Режима,
на которой воздвигали соответствующий монумент -- массивную раскрытую книгу, а рядом
сажали знаменитое каменное древо. Этот город не стал исключением.
^
Хотя солнце только встало, горожане уже заполнили площадь.
]];
obj = {
'regimenstrasse_staff';
'regimenstrasse_monument';
'regimenstrasse_salers';
'regimenstrasse_crowd';
'regimenstrasse_propagandist';
'regimenstrasse_singer';
'regimenstrasse_girl';
};
way = {
regimenstrasse_to_berlinstrasse;
};
entered = function()
end;
}
-- События
-- Прогоняем глашатая
on_event('regimenstrasse belongs to singer', function()
-- Удаляем старые описания глашатая и менестреля, разгоняем толпу
objs('regimenstrasse'):del('regimenstrasse_propagandist')
objs('regimenstrasse'):del('regimenstrasse_singer')
objs('regimenstrasse'):del('regimenstrasse_crowd')
-- Если мы не помогли девочке, то удаляем её вместе с толпой
if not _girl_has_gotten_help then
objs('regimenstrasse'):del('regimenstrasse_girl')
end;
-- Добавляем обновлённого менестреля
objs('regimenstrasse'):add('regimenstrasse_singer_silent')
regimenstrasse_to_berlinstrasse:enable()
end)
-- Прогоняем менестреля
on_event('regimenstrasse belongs to propagandist', function()
-- Удаляем старые описания глашатая и менестреля, разгоняем толпу
objs('regimenstrasse'):del('regimenstrasse_propagandist')
objs('regimenstrasse'):del('regimenstrasse_singer')
objs('regimenstrasse'):del('regimenstrasse_crowd')
-- Если мы не помогли девочке, то удаляем её вместе с толпой
if not _girl_has_gotten_help then
objs('regimenstrasse'):del('regimenstrasse_girl')
end;
-- Добавляем обновлённого глашатая
objs('regimenstrasse'):add('regimenstrasse_propagandist_silent')
regimenstrasse_to_berlinstrasse:enable()
end)
-- Помогаем девочке
on_event('help to child', function()
objs('regimenstrasse'):del('regimenstrasse_girl')
end)
-- Объекты
-- Штаб
regimenstrasse_staff = obj {
nam = 'Штаб Режима';
dsc = [[
Мрачной глыбой среди новостроек на площади темнеет {штаб Режима}. В его узких
окнах-бойницах ещё можно разглядеть свет факелов. Ты замечаешь, что местные
предпочитают обходить это здание стороной.
]];
act = function()
return [[
Ты осматриваешь каменную кладку крепости штаба. Снаружи здание выглядит куда
более грозно, чем изнутри с его храпящими во всю глотку солдатами и запахом
кислого пива.
]];
end;
}
-- Монумент
regimenstrasse_monument = obj {
nam = 'Монумент';
dsc = [[
^
На площади перед штабом, напротив, многолюдно. {Монумент Режима} окружён палатками
торговцев.
]];
act = function()
return [[
Ты осматриваешь громоздкую гранитную книгу, покоящуюся на огромном плоском булыжнике.
Внутри книги вырезана небольшая ниша, засыпанная землёй, на которую неуверенно роняет
листву саженец каменного древа. Ты слышал, что деревья для городов Приграничья
привозили прямиком из Каменных садов Тантикула -- столицы Режима.
]];
end;
}
-- Торгаши
regimenstrasse_salers = obj {
nam = 'Торговцы';
dsc = [[
Бодрясь утренней свежестью, {торгаши} разминают голоса, зазывая покупателей.
]];
act = function()
return [[
Ты осматриваешь палатки и их владельцев. Судя по нарядам, на площади Режима торгуют
преимущественно заезжие купцы. Ты решаешь, что пользы от них тебе не будет.
]];
end;
}
--- Толпа зевак
regimenstrasse_crowd = obj {
nam = 'Толпа зевак';
dsc = [[
Впрочем, их усилия пропадают даром, и большая часть людей окружает вовсе не лотки
с товарами. {Толпа} обступила пару препирающихся, крики которых
заглушают зазывания торговцев.
]];
act = function()
return [[
Ты осматриваешь толпу зевак. В движениях некоторых читается определённый азарт.
Похоже, люди ждут драки. Некоторые с опаской посматривают в твою сторону.
Ты вспоминаешь, что облачён в доспех Режима и люди могут ожидать, что ты
вмешаешься в перепалку.
]];
end;
}
-- Глашатай
regimenstrasse_propagandist = obj {
nam = 'Глашатай Благих';
dsc = [[
Один из них, {бритоголовый детина} в нелепого вида робе, визгливо изрекает молитву,
перемежающуюся проклятьями. Причём молитвы он умудряется адресовать
толпе, а проклятия -- второму крикуну.
]];
act = function()
walk 'regimenstrasse_conflict'
end;
}
-- Глашатай оставшийся
regimenstrasse_propagandist_silent = obj {
nam = 'Глашатай Благих';
dsc = [[
Рядом {глашатай Благих} воспевает спасение души, последующее за пламенем гнева Благих.
Находятся и те, кто бросают ему в таз монетки, шепча молитвы о спасении.
]];
act = [[
Ты внимательно смотришь на глашатая. Хотя его речи и выдают в нём душевнобольного,
взгляд холодных глаз заставляет в этом усомниться.
]];
}
-- Менестрель
regimenstrasse_singer = obj {
nam = 'Менестрель';
dsc = [[
{Тот} одет приличней, но вещает не менее громогласно, потрясая свирелью.
]];
act = function()
walk 'regimenstrasse_conflict'
end;
}
-- Менестрель оставшийся
regimenstrasse_singer_silent = obj {
nam = 'Менестрель';
dsc = [[
Рядом {менестрель} подыгрывает им на своей свирели.
]];
act = [[
Ты внимательно смотришь на менестреля. Его пальцы ловко бегают по
незатейливому инструменту, а взгляд хитрых глаз провожает прохожих,
что подкидывают медяки в его шляпу.
]];
}
-- Девочка
regimenstrasse_girl = obj {
nam = 'Потерявшаяся девочка';
dsc = [[
Среди толпы тебе удаётся разглядеть маленькую {девочку}, потирающую глаза.
]];
act = function()
event 'help to child'
_girl_has_gotten_help = true
return
[[
Ты протискиваешься между людей и протягиваешь девочке руку. Ребёнок с опаской
изучает тебя взглядом снизу вверх, пока не натыкается на герб Режима на твоём
потёртом панцире. Её маленькое личико проясняется и она послушно цепляется
за твою ладонь. Выдохнув, ты выводишь девочку из толпы.
^
Не успел ты со своей новой приятельницей ступить пару шагов в сторону от монумента,
как откуда-то послышались взволнованные крики.
^
Прямо тобой стоит запыхавшаяся женщина. Из-под её платка выпадают пряди растрёпанных
волос. С радостным криком девочка бросается к матери и оказывается у той на руках.
^
-- Ох, я так благодарна вам! Я не спала всю ночь, вот и зазевалась, не заметила,
как Дайан отстала. В этом возрасте её привлекает любой шум,
-- стыдливо объясняется женщина.
-- Нам с ней повезло, что страж Режима оказался рядом. В округе сейчас неспокойно,
а в городе полно разных проходимцев, -- она с неприязнью бросает взгляд на двух
спорщиков у постамента.
^
-- Неспокойно? -- ты сам ещё не понял, что тебя заинтересовало больше,
беспокойная округа или проходимцы.
^
-- Мы с Дайан проходили рядом с городскими воротами сегодня, как раз когда туда
вошёл патруль. Краем уха мне удалось услышать, что несколько дней назад они
наткнулись в лесу на разорённый караван. Просто ужас! Лошади, люди, все перебиты,
повозки разграблены. Никто не понимает, зачем караванщиков понесло так далеко в чащу.
^
-- А проходимцы? Видели кого-то подозрительного? -- спрашиваешь ты женщину. В голове
у тебя путаются мысли о подполье.
^
-- Прошу, не спрашивайте меня о таком! Я простая швея, которая пытается
прокормить себя и малолетнюю дочь. У нас с Дайан больше и нет никого, --
её голос стал еле слышимым, --
её отец был солдатом, мечтающим о славе, но война сделала его калекой.
Рождение дочери не вернуло ему желания жить, и он утопился в реке.
^
Она опускает ребёнка на землю и торопливо поправляет простенький наряд.
^
-- Да вы и сами знаете, половину города можно назвать подозрительной,
-- продолжает женщина. В её голосе слышится досада.
-- Далеко не все признают, что Режим защищает нас. Да, возможно сейчас среди
вас не всех людей можно назвать достойными, но если орки объявятся снова,
Режим не даст городу сгинуть. Больше и надеяться не на кого. Наших лордов
заботят только земли и богатства, это они развязали войну. А когда банды
разоряли деревни и города, им и дела до того не было. Если бы Режим не
вмешался, кто знает, уцелели ли бы мы? -- ты улавливаешь в её словах
твёрдую уверенность. -- Сейчас об этом уже не вспоминают.
Коротка же людская память! Хотя простите меня, я заболталась, у вас же
служба. Прошу, будьте осторожней! Недоброжелателей у вас хватает.
Да хранят нас Благие!
^
Она берёт дочь за руку и дарит тебе прощальную улыбку. Ты не знаешь, что
и сказать после этого душевного порыва, и не находишь ничего лучше,
чем улыбнуться в ответ. Поборов детскую стеснительность, девочка машет тебе ручкой.
^
Ты снова остаёшься наедине со своими поисками.
]]
end;
}
| gpl-3.0 |
vipteam1/VIP_TEAM_EN11 | plugins/newgroup.lua | 2 | 36340 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Team name : ( 🌐 VIP_TEAM 🌐 )▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ File name : ( اسم الملف ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Guenat team: ( @VIP_TEAM1 ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄
—]]
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_admin1(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'المجموعة 👥 [ '..string.gsub(group_name, '_', ' ')..' ] تم ✅ صناعتها بنجاح 😚👋🏿'
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_admin1(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.peer_id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.peer_id, result.peer_id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.peer_id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.peer_id, result.peer_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
if msg.to.type == 'chat' and not is_realm(msg) then
data[tostring(msg.to.id)]['group_type'] = 'Group'
save_data(_config.moderation.data, data)
elseif msg.to.type == 'channel' then
data[tostring(msg.to.id)]['group_type'] = 'SuperGroup'
save_data(_config.moderation.data, data)
end
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.peer_id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
local channel = 'channel#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
send_large_msg(channel, user..'\n'..name)
return user
end
local function set_description(msg, data, target, about)
if not is_admin1(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_admin1(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_admin1(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_admin1(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_admin1(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_admin1(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_admin1(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_admin1(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_admin1(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_admin1(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
local function lock_group_arabic(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic/Persian is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic/Persian has been unlocked'
end
end
local function lock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'yes' then
return 'RTL char. in names is already locked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'yes'
save_data(_config.moderation.data, data)
return 'RTL char. in names has been locked'
end
end
local function unlock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'no' then
return 'RTL char. in names is already unlocked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'no'
save_data(_config.moderation.data, data)
return 'RTL char. in names has been unlocked'
end
end
local function lock_group_links(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'yes' then
return 'Link posting is already locked'
else
data[tostring(target)]['settings']['lock_link'] = 'yes'
save_data(_config.moderation.data, data)
return 'Link posting has been locked'
end
end
local function unlock_group_links(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'no' then
return 'Link posting is not locked'
else
data[tostring(target)]['settings']['lock_link'] = 'no'
save_data(_config.moderation.data, data)
return 'Link posting has been unlocked'
end
end
local function lock_group_spam(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'yes' then
return 'SuperGroup spam is already locked'
else
data[tostring(target)]['settings']['lock_spam'] = 'yes'
save_data(_config.moderation.data, data)
return 'SuperGroup spam has been locked'
end
end
local function unlock_group_spam(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'no' then
return 'SuperGroup spam is not locked'
else
data[tostring(target)]['settings']['lock_spam'] = 'no'
save_data(_config.moderation.data, data)
return 'SuperGroup spam has been unlocked'
end
end
local function lock_group_rtl(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'yes' then
return 'RTL char. in names is already locked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'yes'
save_data(_config.moderation.data, data)
return 'RTL char. in names has been locked'
end
end
local function unlock_group_rtl(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'no' then
return 'RTL char. in names is already unlocked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'no'
save_data(_config.moderation.data, data)
return 'RTL char. in names has been unlocked'
end
end
local function lock_group_sticker(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'yes' then
return 'Sticker posting is already locked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'yes'
save_data(_config.moderation.data, data)
return 'Sticker posting has been locked'
end
end
local function unlock_group_sticker(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'no' then
return 'Sticker posting is already unlocked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'no'
save_data(_config.moderation.data, data)
return 'Sticker posting has been unlocked'
end
end
local function set_public_membermod(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_public_lock = data[tostring(target)]['settings']['public']
if group_public_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'SuperGroup is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_public_lock = data[tostring(target)]['settings']['public']
if group_public_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'SuperGroup is now: not public'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin1(msg) then
return "For admins only!"
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['public'] then
data[tostring(target)]['settings']['public'] = 'no'
end
end
local settings = data[tostring(target)]['settings']
local text = "Group settings for "..target..":\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nPublic: "..settings.public
end
-- show SuperGroup settings
local function show_super_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin1(msg) then
return "For admins only!"
end
if data[tostring(msg.to.id)]['settings'] then
if not data[tostring(msg.to.id)]['settings']['public'] then
data[tostring(msg.to.id)]['settings']['public'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_rtl'] then
data[tostring(target)]['settings']['lock_rtl'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_member'] then
data[tostring(target)]['settings']['lock_member'] = 'no'
end
end
local settings = data[tostring(target)]['settings']
local text = "SuperGroup settings for "..target..":\nLock links : "..settings.lock_link.."\nLock flood: "..settings.flood.."\nLock spam: "..settings.lock_spam.."\nLock Arabic: "..settings.lock_arabic.."\nLock Member: "..settings.lock_member.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public.."\nStrict settings: "..settings.strict
return text
end
local function returnids(cb_extra, success, result)
local i = 1
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.peer_id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' (ID: '..result.peer_id..'):\n\n'
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text ..i..' - '.. string.gsub(v.print_name,"_"," ") .. " [" .. v.peer_id .. "] \n\n"
i = i + 1
end
end
local file = io.open("./groups/lists/"..result.peer_id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function cb_user_info(cb_extra, success, result)
local receiver = cb_extra.receiver
if result.first_name then
first_name = result.first_name:gsub("_", " ")
else
first_name = "None"
end
if result.last_name then
last_name = result.last_name:gsub("_", " ")
else
last_name = "None"
end
if result.username then
username = "@"..result.username
else
username = "@[none]"
end
text = "User Info:\n\nID: "..result.peer_id.."\nFirst: "..first_name.."\nLast: "..last_name.."\nUsername: "..username
send_large_msg(receiver, text)
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_id..' 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 of global 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
if data[tostring(v)] then
if data[tostring(v)]['settings'] then
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
end
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 an 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
send_large_msg(receiver, "@"..member_username..' is not an admin.')
return
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
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.peer_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 res_user_support(cb_extra, success, result)
local receiver = cb_extra.receiver
local get_cmd = cb_extra.get_cmd
local support_id = result.peer_id
if get_cmd == 'addsupport' then
support_add(support_id)
send_large_msg(receiver, "User ["..support_id.."] has been added to the support team")
elseif get_cmd == 'removesupport' then
support_remove(support_id)
send_large_msg(receiver, "User ["..support_id.."] has been removed from the support team")
end
end
local function set_log_group(target, data)
if not is_admin1(msg) then
return
end
local log_group = data[tostring(target)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(target)]['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_admin1(msg) then
return
end
local log_group = data[tostring(target)]['log_group']
if log_group == 'no' then
return 'Log group is not set'
else
data[tostring(target)]['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)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
local receiver = get_receiver(msg)
savelog(msg.to.id, "log file created by owner/support/admin")
send_document(receiver,"./groups/logs/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and msg.to.type == 'chat' 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, returnids, {receiver=receiver})
local file = io.open("./groups/lists/"..msg.to.id.."memberlist.txt", "r")
text = file:read("*a")
send_large_msg(receiver,text)
file:close()
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})
send_document("chat#id"..msg.to.id,"./groups/lists/"..msg.to.id.."memberlist.txt", ok_cb, false)
end
if matches[1] == 'whois' and is_momod(msg) then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
user_info(user_id, cb_user_info, {receiver = receiver})
end
if not is_sudo(msg) then
if is_realm(msg) and is_admin1(msg) then
print("Admin detected")
else
return
end
end
if matches[1] == 'CR' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
--[[ Experimental
if matches[1] == 'createsuper' and matches[2] then
if not is_sudo(msg) or is_admin1(msg) and is_realm(msg) then
return "You cant create groups!"
end
group_name = matches[2]
group_type = 'super_group'
return create_group(msg)
end]]
if matches[1] == 'createrealm' and matches[2] then
if not is_sudo(msg) then
return "Sudo users only !"
end
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[1] == 'setabout' and matches[2] == 'group' and is_realm(msg) then
local target = matches[3]
local about = matches[4]
return set_description(msg, data, target, about)
end
if matches[1] == 'setabout' and matches[2] == 'sgroup'and is_realm(msg) then
local channel = 'channel#id'..matches[3]
local about_text = matches[4]
local data_cat = 'description'
local target = matches[3]
channel_set_about(channel, about_text, ok_cb, false)
data[tostring(target)][data_cat] = about_text
save_data(_config.moderation.data, data)
return "Description has been set for ["..matches[2]..']'
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
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
if matches[2] == 'arabic' then
return lock_group_arabic(msg, data, target)
end
if matches[3] == 'links' then
return lock_group_links(msg, data, target)
end
if matches[3] == 'spam' then
return lock_group_spam(msg, data, target)
end
if matches[3] == 'rtl' then
return unlock_group_rtl(msg, data, target)
end
if matches[3] == 'sticker' then
return lock_group_sticker(msg, data, target)
end
end
if matches[1] == 'unlock' then
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
if matches[3] == 'arabic' then
return unlock_group_arabic(msg, data, target)
end
if matches[3] == 'links' then
return unlock_group_links(msg, data, target)
end
if matches[3] == 'spam' then
return unlock_group_spam(msg, data, target)
end
if matches[3] == 'rtl' then
return unlock_group_rtl(msg, data, target)
end
if matches[3] == 'sticker' then
return unlock_group_sticker(msg, data, target)
end
end
if matches[1] == 'settings' and matches[2] == 'group' and data[tostring(matches[3])]['settings'] then
local target = matches[3]
text = show_group_settingsmod(msg, target)
return text.."\nID: "..target.."\n"
end
if matches[1] == 'settings' and matches[2] == 'sgroup' and data[tostring(matches[3])]['settings'] then
local target = matches[3]
text = show_supergroup_settingsmod(msg, target)
return text.."\nID: "..target.."\n"
end
if matches[1] == 'setname' and is_realm(msg) then
local settings = data[tostring(matches[2])]['settings']
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_admin1(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 chat_to_rename = 'chat#id'..matches[2]
local channel_to_rename = 'channel#id'..matches[2]
rename_chat(to_rename, group_name_set, ok_cb, false)
rename_channel(channel_to_rename, group_name_set, ok_cb, false)
savelog(matches[3], "Group { "..group_name_set.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
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' and is_sudo(msg) then
local target = msg.to.peer_id
savelog(msg.to.peer_id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(target, data)
end
end
if matches[1] == 'rem' then
if matches[2] == 'loggroup' and is_sudo(msg) then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return unset_log_group(target, data)
end
end]]
if matches[1] == 'kill' and matches[2] == 'chat' and matches[3] then
if not is_admin1(msg) then
return
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' and matches[3] then
if not is_admin1(msg) then
return
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] == 'rem' and matches[2] then
-- Group configuration removal
data[tostring(matches[2])] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(matches[2])] = nil
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Chat '..matches[2]..' removed')
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if not is_admin1(msg) and is_realm(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if not is_sudo(msg) then-- Sudo only
return
end
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 not is_sudo(msg) then-- Sudo only
return
end
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] == 'support' and matches[2] then
if string.match(matches[2], '^%d+$') then
local support_id = matches[2]
print("User "..support_id.." has been added to the support team")
support_add(support_id)
return "User ["..support_id.."] has been added to the support team"
else
local member = string.gsub(matches[2], "@", "")
local receiver = get_receiver(msg)
local get_cmd = "addsupport"
resolve_username(member, res_user_support, {get_cmd = get_cmd, receiver = receiver})
end
end
if matches[1] == '-support' then
if string.match(matches[2], '^%d+$') then
local support_id = matches[2]
print("User "..support_id.." has been removed from the support team")
support_remove(support_id)
return "User ["..support_id.."] has been removed from the support team"
else
local member = string.gsub(matches[2], "@", "")
local receiver = get_receiver(msg)
local get_cmd = "removesupport"
resolve_username(member, res_user_support, {get_cmd = get_cmd, receiver = receiver})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' then
if matches[2] == 'admins' then
return admin_list(msg)
end
-- if matches[2] == 'support' and not matches[2] then
-- return support_list()
-- end
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' or msg.to.type == 'channel' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
send_document("channel#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' or msg.to.type == 'channel' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
send_document("channel#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 resolve_username(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^(CR) (.*)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/Skybox.lua | 9 | 1866 |
--------------------------------
-- @module Skybox
-- @extend Node
-- @parent_module cc
--------------------------------
-- reload sky box after GLESContext reconstructed.
-- @function [parent=#Skybox] reload
-- @param self
-- @return Skybox#Skybox self (return value: cc.Skybox)
--------------------------------
-- initialize with texture path
-- @function [parent=#Skybox] init
-- @param self
-- @param #string positive_x
-- @param #string negative_x
-- @param #string positive_y
-- @param #string negative_y
-- @param #string positive_z
-- @param #string negative_z
-- @return bool#bool ret (return value: bool)
--------------------------------
-- texture getter and setter
-- @function [parent=#Skybox] setTexture
-- @param self
-- @param #cc.TextureCube
-- @return Skybox#Skybox self (return value: cc.Skybox)
--------------------------------
-- @overload self, string, string, string, string, string, string
-- @overload self
-- @function [parent=#Skybox] create
-- @param self
-- @param #string positive_x
-- @param #string negative_x
-- @param #string positive_y
-- @param #string negative_y
-- @param #string positive_z
-- @param #string negative_z
-- @return Skybox#Skybox ret (return value: cc.Skybox)
--------------------------------
-- draw Skybox object
-- @function [parent=#Skybox] draw
-- @param self
-- @param #cc.Renderer renderer
-- @param #mat4_table transform
-- @param #unsigned int flags
-- @return Skybox#Skybox self (return value: cc.Skybox)
--------------------------------
-- init Skybox.
-- @function [parent=#Skybox] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Constructor.
-- @function [parent=#Skybox] Skybox
-- @param self
-- @return Skybox#Skybox self (return value: cc.Skybox)
return nil
| mit |
cyanskies/OpenRA | mods/ra/maps/soviet-04b/soviet04b-AI.lua | 19 | 3108 | IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end
IdlingUnits = function()
local lazyUnits = Greece.GetGroundAttackers()
Utils.Do(lazyUnits, function(unit)
Trigger.OnDamaged(unit, function()
Trigger.ClearAll(unit)
Trigger.AfterDelay(0, function() IdleHunt(unit) end)
end)
end)
end
BasePower = { type = "powr", pos = CVec.New(-4, -2), cost = 300, exists = true }
BaseBarracks = { type = "tent", pos = CVec.New(-8, 1), cost = 400, exists = true }
BaseProc = { type = "proc", pos = CVec.New(-5, 1), cost = 1400, exists = true }
BaseWeaponsFactory = { type = "weap", pos = CVec.New(-12, -1), cost = 2000, exists = true }
BaseBuildings = { BasePower, BaseBarracks, BaseProc, BaseWeaponsFactory }
BuildBase = function()
for i,v in ipairs(BaseBuildings) do
if not v.exists then
BuildBuilding(v)
return
end
end
Trigger.AfterDelay(DateTime.Seconds(10), BuildBase)
end
BuildBuilding = function(building)
Trigger.AfterDelay(Actor.BuildTime(building.type), function()
if CYard.IsDead or CYard.Owner ~= Greece then
return
elseif Harvester.IsDead and Greece.Resources <= 299 then
return
end
local actor = Actor.Create(building.type, true, { Owner = Greece, Location = GreeceCYard.Location + building.pos })
Greece.Cash = Greece.Cash - building.cost
building.exists = true
Trigger.OnKilled(actor, function() building.exists = false end)
Trigger.OnDamaged(actor, function(building)
if building.Owner == Greece and building.Health < building.MaxHealth * 3/4 then
building.StartBuildingRepairs()
end
end)
Trigger.AfterDelay(DateTime.Seconds(10), BuildBase)
end)
end
ProduceInfantry = function()
if not BaseBarracks.exists then
return
elseif Harvester.IsDead and Greece.Resources <= 299 then
return
end
local delay = Utils.RandomInteger(DateTime.Seconds(3), DateTime.Seconds(9))
local toBuild = { Utils.Random(AlliedInfantryTypes) }
local Path = Utils.Random(AttackPaths)
Greece.Build(toBuild, function(unit)
InfAttack[#InfAttack + 1] = unit[1]
if #InfAttack >= 10 then
SendUnits(InfAttack, Path)
InfAttack = { }
Trigger.AfterDelay(DateTime.Minutes(2), ProduceInfantry)
else
Trigger.AfterDelay(delay, ProduceInfantry)
end
end)
end
ProduceArmor = function()
if not BaseWeaponsFactory.exists then
return
elseif Harvester.IsDead and Greece.Resources <= 599 then
return
end
local delay = Utils.RandomInteger(DateTime.Seconds(12), DateTime.Seconds(17))
local toBuild = { Utils.Random(AlliedArmorTypes) }
local Path = Utils.Random(AttackPaths)
Greece.Build(toBuild, function(unit)
ArmorAttack[#ArmorAttack + 1] = unit[1]
if #ArmorAttack >= 6 then
SendUnits(ArmorAttack, Path)
ArmorAttack = { }
Trigger.AfterDelay(DateTime.Minutes(3), ProduceArmor)
else
Trigger.AfterDelay(delay, ProduceArmor)
end
end)
end
SendUnits = function(units, waypoints)
Utils.Do(units, function(unit)
if not unit.IsDead then
Utils.Do(waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
unit.Hunt()
end
end)
end
| gpl-3.0 |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/Terrain.lua | 6 | 6015 |
--------------------------------
-- @module Terrain
-- @extend Node
-- @parent_module cc
--------------------------------
-- initialize heightMap data
-- @function [parent=#Terrain] initHeightMap
-- @param self
-- @param #string heightMap
-- @return bool#bool ret (return value: bool)
--------------------------------
-- set the MaxDetailAmount.
-- @function [parent=#Terrain] setMaxDetailMapAmount
-- @param self
-- @param #int maxValue
-- @return Terrain#Terrain self (return value: cc.Terrain)
--------------------------------
-- show the wireline instead of the surface,Debug Use only.<br>
-- Note only support desktop platform
-- @function [parent=#Terrain] setDrawWire
-- @param self
-- @param #bool boolValue
-- @return Terrain#Terrain self (return value: cc.Terrain)
--------------------------------
-- get the terrain's height data
-- @function [parent=#Terrain] getHeightData
-- @param self
-- @return array_table#array_table ret (return value: array_table)
--------------------------------
-- set the Detail Map
-- @function [parent=#Terrain] setDetailMap
-- @param self
-- @param #unsigned int index
-- @param #cc.Terrain::DetailMap detailMap
-- @return Terrain#Terrain self (return value: cc.Terrain)
--------------------------------
-- reset the heightmap data.
-- @function [parent=#Terrain] resetHeightMap
-- @param self
-- @param #string heightMap
-- @return Terrain#Terrain self (return value: cc.Terrain)
--------------------------------
-- set directional light for the terrain<br>
-- param lightDir The direction of directional light, Note that lightDir is in the terrain's local space. Most of the time terrain is placed at (0,0,0) and without rotation, so lightDir is also in the world space.
-- @function [parent=#Terrain] setLightDir
-- @param self
-- @param #vec3_table lightDir
-- @return Terrain#Terrain self (return value: cc.Terrain)
--------------------------------
-- set the alpha map
-- @function [parent=#Terrain] setAlphaMap
-- @param self
-- @param #cc.Texture2D newAlphaMapTexture
-- @return Terrain#Terrain self (return value: cc.Terrain)
--------------------------------
-- set the skirt height ratio
-- @function [parent=#Terrain] setSkirtHeightRatio
-- @param self
-- @param #float ratio
-- @return Terrain#Terrain self (return value: cc.Terrain)
--------------------------------
-- Convert a world Space position (X,Z) to terrain space position (X,Z)
-- @function [parent=#Terrain] convertToTerrainSpace
-- @param self
-- @param #vec2_table worldSpace
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
-- initialize alphaMap ,detailMaps textures
-- @function [parent=#Terrain] initTextures
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- initialize all Properties which terrain need
-- @function [parent=#Terrain] initProperties
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Terrain] initWithTerrainData
-- @param self
-- @param #cc.Terrain::TerrainData parameter
-- @param #int fixedType
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Set threshold distance of each LOD level,must equal or greater than the chunk size<br>
-- Note when invoke initHeightMap, the LOD distance will be automatic calculated.
-- @function [parent=#Terrain] setLODDistance
-- @param self
-- @param #float lod1
-- @param #float lod2
-- @param #float lod3
-- @return Terrain#Terrain self (return value: cc.Terrain)
--------------------------------
-- get the terrain's size
-- @function [parent=#Terrain] getTerrainSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- get the normal of the specified position in terrain<br>
-- return the normal vector of the specified position of the terrain.<br>
-- note the fast normal calculation may not get precise normal vector.
-- @function [parent=#Terrain] getNormal
-- @param self
-- @param #int pixelX
-- @param #int pixelY
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
--
-- @function [parent=#Terrain] reload
-- @param self
-- @return Terrain#Terrain self (return value: cc.Terrain)
--------------------------------
-- get height from the raw height filed
-- @function [parent=#Terrain] getImageHeight
-- @param self
-- @param #int pixelX
-- @param #int pixelY
-- @return float#float ret (return value: float)
--------------------------------
-- set light map texture
-- @function [parent=#Terrain] setLightMap
-- @param self
-- @param #string fileName
-- @return Terrain#Terrain self (return value: cc.Terrain)
--------------------------------
-- Switch frustum Culling Flag<br>
-- Note frustum culling will remarkable improve your terrain rendering performance.
-- @function [parent=#Terrain] setIsEnableFrustumCull
-- @param self
-- @param #bool boolValue
-- @return Terrain#Terrain self (return value: cc.Terrain)
--------------------------------
-- get the terrain's minimal height.
-- @function [parent=#Terrain] getMinHeight
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- get the terrain's maximal height.
-- @function [parent=#Terrain] getMaxHeight
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
--
-- @function [parent=#Terrain] draw
-- @param self
-- @param #cc.Renderer renderer
-- @param #mat4_table transform
-- @param #unsigned int flags
-- @return Terrain#Terrain self (return value: cc.Terrain)
--------------------------------
--
-- @function [parent=#Terrain] Terrain
-- @param self
-- @return Terrain#Terrain self (return value: cc.Terrain)
return nil
| mit |
osa1/language-lua | lua-5.3.1-tests/gc.lua | 4 | 15856 | -- $Id: gc.lua,v 1.70 2015/03/04 13:09:38 roberto Exp $
print('testing garbage collection')
local debug = require"debug"
collectgarbage()
assert(collectgarbage("isrunning"))
local function gcinfo () return collectgarbage"count" * 1024 end
-- test weird parameters
do
-- save original parameters
local a = collectgarbage("setpause", 200)
local b = collectgarbage("setstepmul", 200)
local t = {0, 2, 10, 90, 500, 5000, 30000, 0x7ffffffe}
for i = 1, #t do
local p = t[i]
for j = 1, #t do
local m = t[j]
collectgarbage("setpause", p)
collectgarbage("setstepmul", m)
collectgarbage("step", 0)
collectgarbage("step", 10000)
end
end
-- restore original parameters
collectgarbage("setpause", a)
collectgarbage("setstepmul", b)
collectgarbage()
end
_G["while"] = 234
limit = 5000
local function GC1 ()
local u
local b -- must be declared after 'u' (to be above it in the stack)
local finish = false
u = setmetatable({}, {__gc = function () finish = true end})
b = {34}
repeat u = {} until finish
assert(b[1] == 34) -- 'u' was collected, but 'b' was not
finish = false; local i = 1
u = setmetatable({}, {__gc = function () finish = true end})
repeat i = i + 1; u = tostring(i) .. tostring(i) until finish
assert(b[1] == 34) -- 'u' was collected, but 'b' was not
finish = false
u = setmetatable({}, {__gc = function () finish = true end})
repeat local i; u = function () return i end until finish
assert(b[1] == 34) -- 'u' was collected, but 'b' was not
end
local function GC2 ()
local u
local finish = false
u = {setmetatable({}, {__gc = function () finish = true end})}
b = {34}
repeat u = {{}} until finish
assert(b[1] == 34) -- 'u' was collected, but 'b' was not
finish = false; local i = 1
u = {setmetatable({}, {__gc = function () finish = true end})}
repeat i = i + 1; u = {tostring(i) .. tostring(i)} until finish
assert(b[1] == 34) -- 'u' was collected, but 'b' was not
finish = false
u = {setmetatable({}, {__gc = function () finish = true end})}
repeat local i; u = {function () return i end} until finish
assert(b[1] == 34) -- 'u' was collected, but 'b' was not
end
local function GC() GC1(); GC2() end
contCreate = 0
print('tables')
while contCreate <= limit do
local a = {}; a = nil
contCreate = contCreate+1
end
a = "a"
contCreate = 0
print('strings')
while contCreate <= limit do
a = contCreate .. "b";
a = string.gsub(a, '(%d%d*)', string.upper)
a = "a"
contCreate = contCreate+1
end
contCreate = 0
a = {}
print('functions')
function a:test ()
while contCreate <= limit do
load(string.format("function temp(a) return 'a%d' end", contCreate), "")()
assert(temp() == string.format('a%d', contCreate))
contCreate = contCreate+1
end
end
a:test()
-- collection of functions without locals, globals, etc.
do local f = function () end end
print("functions with errors")
prog = [[
do
a = 10;
function foo(x,y)
a = sin(a+0.456-0.23e-12);
return function (z) return sin(%x+z) end
end
local x = function (w) a=a+w; end
end
]]
do
local step = 1
if _soft then step = 13 end
for i=1, string.len(prog), step do
for j=i, string.len(prog), step do
pcall(load(string.sub(prog, i, j), ""))
end
end
end
foo = nil
print('long strings')
x = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"
assert(string.len(x)==80)
s = ''
n = 0
k = math.min(300, (math.maxinteger // 80) // 2)
while n < k do s = s..x; n=n+1; j=tostring(n) end
assert(string.len(s) == k*80)
s = string.sub(s, 1, 10000)
s, i = string.gsub(s, '(%d%d%d%d)', '')
assert(i==10000 // 4)
s = nil
x = nil
assert(_G["while"] == 234)
print("steps")
print("steps (2)")
local function dosteps (siz)
assert(not collectgarbage("isrunning"))
collectgarbage()
assert(not collectgarbage("isrunning"))
local a = {}
for i=1,100 do a[i] = {{}}; local b = {} end
local x = gcinfo()
local i = 0
repeat -- do steps until it completes a collection cycle
i = i+1
until collectgarbage("step", siz)
assert(gcinfo() < x)
return i
end
collectgarbage"stop"
if not _port then
-- test the "size" of basic GC steps (whatever they mean...)
assert(dosteps(0) > 10)
assert(dosteps(10) < dosteps(2))
end
-- collector should do a full collection with so many steps
assert(dosteps(20000) == 1)
assert(collectgarbage("step", 20000) == true)
assert(collectgarbage("step", 20000) == true)
assert(not collectgarbage("isrunning"))
collectgarbage"restart"
assert(collectgarbage("isrunning"))
if not _port then
-- test the pace of the collector
collectgarbage(); collectgarbage()
local x = gcinfo()
collectgarbage"stop"
assert(not collectgarbage("isrunning"))
repeat
local a = {}
until gcinfo() > 3 * x
collectgarbage"restart"
assert(collectgarbage("isrunning"))
repeat
local a = {}
until gcinfo() <= x * 2
end
print("clearing tables")
lim = 15
a = {}
-- fill a with `collectable' indices
for i=1,lim do a[{}] = i end
b = {}
for k,v in pairs(a) do b[k]=v end
-- remove all indices and collect them
for n in pairs(b) do
a[n] = nil
assert(type(n) == 'table' and next(n) == nil)
collectgarbage()
end
b = nil
collectgarbage()
for n in pairs(a) do error'cannot be here' end
for i=1,lim do a[i] = i end
for i=1,lim do assert(a[i] == i) end
print('weak tables')
a = {}; setmetatable(a, {__mode = 'k'});
-- fill a with some `collectable' indices
for i=1,lim do a[{}] = i end
-- and some non-collectable ones
for i=1,lim do a[i] = i end
for i=1,lim do local s=string.rep('@', i); a[s] = s..'#' end
collectgarbage()
local i = 0
for k,v in pairs(a) do assert(k==v or k..'#'==v); i=i+1 end
assert(i == 2*lim)
a = {}; setmetatable(a, {__mode = 'v'});
a[1] = string.rep('b', 21)
collectgarbage()
assert(a[1]) -- strings are *values*
a[1] = nil
-- fill a with some `collectable' values (in both parts of the table)
for i=1,lim do a[i] = {} end
for i=1,lim do a[i..'x'] = {} end
-- and some non-collectable ones
for i=1,lim do local t={}; a[t]=t end
for i=1,lim do a[i+lim]=i..'x' end
collectgarbage()
local i = 0
for k,v in pairs(a) do assert(k==v or k-lim..'x' == v); i=i+1 end
assert(i == 2*lim)
a = {}; setmetatable(a, {__mode = 'vk'});
local x, y, z = {}, {}, {}
-- keep only some items
a[1], a[2], a[3] = x, y, z
a[string.rep('$', 11)] = string.rep('$', 11)
-- fill a with some `collectable' values
for i=4,lim do a[i] = {} end
for i=1,lim do a[{}] = i end
for i=1,lim do local t={}; a[t]=t end
collectgarbage()
assert(next(a) ~= nil)
local i = 0
for k,v in pairs(a) do
assert((k == 1 and v == x) or
(k == 2 and v == y) or
(k == 3 and v == z) or k==v);
i = i+1
end
assert(i == 4)
x,y,z=nil
collectgarbage()
assert(next(a) == string.rep('$', 11))
-- 'bug' in 5.1
a = {}
local t = {x = 10}
local C = setmetatable({key = t}, {__mode = 'v'})
local C1 = setmetatable({[t] = 1}, {__mode = 'k'})
a.x = t -- this should not prevent 't' from being removed from
-- weak table 'C' by the time 'a' is finalized
setmetatable(a, {__gc = function (u)
assert(C.key == nil)
assert(type(next(C1)) == 'table')
end})
a, t = nil
collectgarbage()
collectgarbage()
assert(next(C) == nil and next(C1) == nil)
C, C1 = nil
-- ephemerons
local mt = {__mode = 'k'}
a = {{10},{20},{30},{40}}; setmetatable(a, mt)
x = nil
for i = 1, 100 do local n = {}; a[n] = {k = {x}}; x = n end
GC()
local n = x
local i = 0
while n do n = a[n].k[1]; i = i + 1 end
assert(i == 100)
x = nil
GC()
for i = 1, 4 do assert(a[i][1] == i * 10); a[i] = nil end
assert(next(a) == nil)
local K = {}
a[K] = {}
for i=1,10 do a[K][i] = {}; a[a[K][i]] = setmetatable({}, mt) end
x = nil
local k = 1
for j = 1,100 do
local n = {}; local nk = k%10 + 1
a[a[K][nk]][n] = {x, k = k}; x = n; k = nk
end
GC()
local n = x
local i = 0
while n do local t = a[a[K][k]][n]; n = t[1]; k = t.k; i = i + 1 end
assert(i == 100)
K = nil
GC()
-- assert(next(a) == nil)
-- testing errors during GC
do
collectgarbage("stop") -- stop collection
local u = {}
local s = {}; setmetatable(s, {__mode = 'k'})
setmetatable(u, {__gc = function (o)
local i = s[o]
s[i] = true
assert(not s[i - 1]) -- check proper finalization order
if i == 8 then error("here") end -- error during GC
end})
for i = 6, 10 do
local n = setmetatable({}, getmetatable(u))
s[n] = i
end
assert(not pcall(collectgarbage))
for i = 8, 10 do assert(s[i]) end
for i = 1, 5 do
local n = setmetatable({}, getmetatable(u))
s[n] = i
end
collectgarbage()
for i = 1, 10 do assert(s[i]) end
getmetatable(u).__gc = false
-- __gc errors with non-string messages
setmetatable({}, {__gc = function () error{} end})
local a, b = pcall(collectgarbage)
assert(not a and type(b) == "string" and string.find(b, "error in __gc"))
end
print '+'
-- testing userdata
if T==nil then
(Message or print)('\n >>> testC not active: skipping userdata GC tests <<<\n')
else
local function newproxy(u)
return debug.setmetatable(T.newuserdata(0), debug.getmetatable(u))
end
collectgarbage("stop") -- stop collection
local u = newproxy(nil)
debug.setmetatable(u, {__gc = true})
local s = 0
local a = {[u] = 0}; setmetatable(a, {__mode = 'vk'})
for i=1,10 do a[newproxy(u)] = i end
for k in pairs(a) do assert(getmetatable(k) == getmetatable(u)) end
local a1 = {}; for k,v in pairs(a) do a1[k] = v end
for k,v in pairs(a1) do a[v] = k end
for i =1,10 do assert(a[i]) end
getmetatable(u).a = a1
getmetatable(u).u = u
do
local u = u
getmetatable(u).__gc = function (o)
assert(a[o] == 10-s)
assert(a[10-s] == nil) -- udata already removed from weak table
assert(getmetatable(o) == getmetatable(u))
assert(getmetatable(o).a[o] == 10-s)
s=s+1
end
end
a1, u = nil
assert(next(a) ~= nil)
collectgarbage()
assert(s==11)
collectgarbage()
assert(next(a) == nil) -- finalized keys are removed in two cycles
end
-- __gc x weak tables
local u = setmetatable({}, {__gc = true})
-- __gc metamethod should be collected before running
setmetatable(getmetatable(u), {__mode = "v"})
getmetatable(u).__gc = function (o) os.exit(1) end -- cannot happen
u = nil
collectgarbage()
local u = setmetatable({}, {__gc = true})
local m = getmetatable(u)
m.x = {[{0}] = 1; [0] = {1}}; setmetatable(m.x, {__mode = "kv"});
m.__gc = function (o)
assert(next(getmetatable(o).x) == nil)
m = 10
end
u, m = nil
collectgarbage()
assert(m==10)
-- errors during collection
u = setmetatable({}, {__gc = function () error "!!!" end})
u = nil
assert(not pcall(collectgarbage))
if not _soft then
print("deep structures")
local a = {}
for i = 1,200000 do
a = {next = a}
end
collectgarbage()
end
-- create many threads with self-references and open upvalues
print("self-referenced threads")
local thread_id = 0
local threads = {}
local function fn (thread)
local x = {}
threads[thread_id] = function()
thread = x
end
coroutine.yield()
end
while thread_id < 1000 do
local thread = coroutine.create(fn)
coroutine.resume(thread, thread)
thread_id = thread_id + 1
end
-- Create a closure (function inside 'f') with an upvalue ('param') that
-- points (through a table) to the closure itself and to the thread
-- ('co' and the initial value of 'param') where closure is running.
-- Then, assert that table (and therefore everything else) will be
-- collected.
do
local collected = false -- to detect collection
collectgarbage(); collectgarbage("stop")
do
local function f (param)
;(function ()
assert(type(f) == 'function' and type(param) == 'thread')
param = {param, f}
setmetatable(param, {__gc = function () collected = true end})
coroutine.yield(100)
end)()
end
local co = coroutine.create(f)
assert(coroutine.resume(co, co))
end
-- Now, thread and closure are not reacheable any more;
-- two collections are needed to break cycle
collectgarbage()
assert(not collected)
collectgarbage()
assert(collected)
collectgarbage("restart")
end
do
collectgarbage()
collectgarbage"stop"
local x = gcinfo()
repeat
for i=1,1000 do _ENV.a = {} end
collectgarbage("step", 0) -- steps should not unblock the collector
until gcinfo() > 2 * x
collectgarbage"restart"
end
if T then -- tests for weird cases collecting upvalues
local function foo ()
local a = {x = 20}
coroutine.yield(function () return a.x end) -- will run collector
assert(a.x == 20) -- 'a' is 'ok'
a = {x = 30} -- create a new object
assert(T.gccolor(a) == "white") -- of course it is new...
coroutine.yield(100) -- 'a' is still local to this thread
end
local t = setmetatable({}, {__mode = "kv"})
collectgarbage(); collectgarbage('stop')
-- create coroutine in a weak table, so it will never be marked
t.co = coroutine.wrap(foo)
local f = t.co() -- create function to access local 'a'
T.gcstate("atomic") -- ensure all objects are traversed
assert(T.gcstate() == "atomic")
assert(t.co() == 100) -- resume coroutine, creating new table for 'a'
assert(T.gccolor(t.co) == "white") -- thread was not traversed
T.gcstate("pause") -- collect thread, but should mark 'a' before that
assert(t.co == nil and f() == 30) -- ensure correct access to 'a'
collectgarbage("restart")
-- test barrier in sweep phase (advance cleaning of upvalue to white)
local u = T.newuserdata(0) -- create a userdata
collectgarbage()
collectgarbage"stop"
T.gcstate"atomic"
local x = {}
T.gcstate"sweepallgc"
assert(T.gccolor(u) == "black") -- upvalue is "old" (black)
assert(T.gccolor(x) == "white") -- table is "new" (white)
debug.setuservalue(u, x) -- trigger barrier
assert(T.gccolor(u) == "white") -- upvalue changed to white
collectgarbage"restart"
print"+"
end
if T then
local debug = require "debug"
collectgarbage("stop")
local x = T.newuserdata(0)
local y = T.newuserdata(0)
debug.setmetatable(y, {__gc = true}) -- bless the new udata before...
debug.setmetatable(x, {__gc = true}) -- ...the old one
assert(T.gccolor(y) == "white")
T.checkmemory()
collectgarbage("restart")
end
if T then
print("emergency collections")
collectgarbage()
collectgarbage()
T.totalmem(T.totalmem() + 200)
for i=1,200 do local a = {} end
T.totalmem(0)
collectgarbage()
local t = T.totalmem("table")
local a = {{}, {}, {}} -- create 4 new tables
assert(T.totalmem("table") == t + 4)
t = T.totalmem("function")
a = function () end -- create 1 new closure
assert(T.totalmem("function") == t + 1)
t = T.totalmem("thread")
a = coroutine.create(function () end) -- create 1 new coroutine
assert(T.totalmem("thread") == t + 1)
end
-- create an object to be collected when state is closed
do
local setmetatable,assert,type,print,getmetatable =
setmetatable,assert,type,print,getmetatable
local tt = {}
tt.__gc = function (o)
assert(getmetatable(o) == tt)
-- create new objects during GC
local a = 'xuxu'..(10+3)..'joao', {}
___Glob = o -- ressurect object!
setmetatable({}, tt) -- creates a new one with same metatable
print(">>> closing state " .. "<<<\n")
end
local u = setmetatable({}, tt)
___Glob = {u} -- avoid object being collected before program end
end
-- create several objects to raise errors when collected while closing state
do
local mt = {__gc = function (o) return o + 1 end}
for i = 1,10 do
-- create object and preserve it until the end
table.insert(___Glob, setmetatable({}, mt))
end
end
-- just to make sure
assert(collectgarbage'isrunning')
print('OK')
| bsd-3-clause |
JarnoVgr/Mr.Green-MTA-Resources | resources/[admin]/anti/colstate_c.lua | 4 | 1240 | local theCollisionlessTable = {}
addEventHandler("onClientResourceStart",resourceRoot,function() triggerServerEvent("onClientRequestCollisionlessTable",resourceRoot) end)
addEvent("onClientReceiveCollisionlessTable",true)
addEventHandler("onClientReceiveCollisionlessTable",root,function(t)
theCollisionlessTable = t
for _, p in ipairs(getElementsByType'player') do
setElementData(p, 'markedlagger', t[p] or nil, false)
end
setCollision("refresh")
end)
-- addEvent("onPlayerVehicleIDChange",true)
function setCollision()
local mode = getResourceFromName'race' and getResourceState(getResourceFromName'race')=='running' and exports.race:getRaceMode()
if not mode or mode == "Shooter" then return end
for p,_ in pairs(theCollisionlessTable) do
if p ~= localPlayer then
local vehMe = getPedOccupiedVehicle(localPlayer)
local vehCollLess = getPedOccupiedVehicle(p)
if vehMe and vehCollLess then
setElementCollidableWith(vehMe, vehCollLess, false)
setElementAlpha(vehCollLess, 140)
end
end
end
end
setTimer(setCollision,50,0)
-- addEventHandler("onPlayerVehicleIDChange",root,setCollision)
addEventHandler("onClientExplosion",root,function() if theCollisionlessTable[source] then cancelEvent() end end) | mit |
MmxBoy/newbot | plugins/groupmanager.lua | 12 | 16925 | -- data saved to data/moderation.json
do
local function export_chat_link_cb(extra, success, result)
local msg = extra.msg
local data = extra.data
if success == 0 then
return send_large_msg(get_receiver(msg), 'Cannot generate invite link for this group.\nMake sure you are an admin or a sudoer.')
end
data[tostring(msg.to.id)]['link'] = result
save_data(_config.moderation.data, data)
return send_large_msg(get_receiver(msg),'Newest generated invite link for '..msg.to.title..' is:\n'..result)
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (get_receiver(msg), file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(get_receiver(msg), 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(get_receiver(msg), 'Failed, please try again!', ok_cb, false)
end
end
local function get_description(msg, data)
local about = data[tostring(msg.to.id)]['description']
if not about then
return 'No description available.'
end
return string.gsub(msg.to.print_name, '_', ' ')..':\n\n'..about
end
-- media handler. needed by group_photo_lock
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '['..msg.media.type..']'
end
return msg
end
function run(msg, matches)
if is_chat_msg(msg) then
local data = load_data(_config.moderation.data)
-- create a group
if matches[1] == 'cgroup' and matches[2] and is_mod(msg) then
create_group_chat (msg.from.print_name, matches[2], ok_cb, false)
return 'Group '..string.gsub(matches[2], '_', ' ')..' has been created.'
-- add a group to be moderated
elseif matches[1] == 'addgp' and is_admin(msg) then
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
-- create data array in moderation.json
data[tostring(msg.to.id)] = {
moderators ={},
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_bots = 'no',
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
anti_flood = 'ban',
welcome = 'group',
sticker = 'ok',
}
}
save_data(_config.moderation.data, data)
return 'Group has been added.'
-- remove group from moderation
elseif matches[1] == 'remgp' and is_admin(msg) then
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return 'Group has been removed'
end
if msg.media and is_chat_msg(msg) and is_mod(msg) then
if msg.media.type == 'photo' and data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then
load_photo(msg.id, set_group_photo, msg)
end
end
end
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'setabout' and matches[2] and is_mod(msg) then
data[tostring(msg.to.id)]['description'] = matches[2]
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..matches[2]
elseif matches[1] == 'about' then
return get_description(msg, data)
elseif matches[1] == 'setrules' and is_mod(msg) then
data[tostring(msg.to.id)]['rules'] = matches[2]
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..matches[2]
elseif matches[1] == 'rules' then
if not data[tostring(msg.to.id)]['rules'] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)]['rules']
local rules = string.gsub(msg.to.print_name, '_', ' ')..' rules:\n\n'..rules
return rules
-- group link {get|set}
elseif matches[1] == 'link' then
if matches[2] == 'get' then
if data[tostring(msg.to.id)]['link'] then
local about = get_description(msg, data)
local link = data[tostring(msg.to.id)]['link']
return about..'\n\n'..link
else
return 'Invite link does not exist.\nTry !link set to generate.'
end
elseif matches[2] == 'set' and is_mod(msg) then
msgr = export_chat_link(get_receiver(msg), export_chat_link_cb, {data=data, msg=msg})
end
elseif matches[1] == 'group' then
-- lock {bot|name|member|photo|sticker}
if matches[2] == 'lock' then
if matches[3] == 'bot' and is_mod(msg) then
if settings.lock_bots == 'yes' then
return 'Group is already locked from bots.'
else
settings.lock_bots = 'yes'
save_data(_config.moderation.data, data)
return 'Group is locked from bots.'
end
elseif matches[3] == 'name' and is_mod(msg) then
if settings.lock_name == 'yes' then
return 'Group name is already locked'
else
settings.lock_name = 'yes'
save_data(_config.moderation.data, data)
settings.set_name = string.gsub(msg.to.print_name, '_', ' ')
save_data(_config.moderation.data, data)
return 'Group name has been locked'
end
elseif matches[3] == 'member' and is_mod(msg) then
if settings.lock_member == 'yes' then
return 'Group members are already locked'
else
settings.lock_member = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
elseif matches[3] == 'photo' and is_mod(msg) then
if settings.lock_photo == 'yes' then
return 'Group photo is already locked'
else
settings.set_photo = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
-- unlock {bot|name|member|photo|sticker}
elseif matches[2] == 'unlock' then
if matches[3] == 'bot' and is_mod(msg) then
if settings.lock_bots == 'no' then
return 'Bots are allowed to enter group.'
else
settings.lock_bots = 'no'
save_data(_config.moderation.data, data)
return 'Group is open for bots.'
end
elseif matches[3] == 'name' and is_mod(msg) then
if settings.lock_name == 'no' then
return 'Group name is already unlocked'
else
settings.lock_name = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
elseif matches[3] == 'member' and is_mod(msg) then
if settings.lock_member == 'no' then
return 'Group members are not locked'
else
settings.lock_member = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
elseif matches[3] == 'photo' and is_mod(msg) then
if settings.lock_photo == 'no' then
return 'Group photo is not locked'
else
settings.lock_photo = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
-- view group settings
elseif matches[2] == 'settings' and is_mod(msg) then
if settings.lock_bots == 'yes' then
lock_bots_state = '🔒'
elseif settings.lock_bots == 'no' then
lock_bots_state = '🔓'
end
if settings.lock_name == 'yes' then
lock_name_state = '🔒'
elseif settings.lock_name == 'no' then
lock_name_state = '🔓'
end
if settings.lock_photo == 'yes' then
lock_photo_state = '🔒'
elseif settings.lock_photo == 'no' then
lock_photo_state = '🔓'
end
if settings.lock_member == 'yes' then
lock_member_state = '🔒'
elseif settings.lock_member == 'no' then
lock_member_state = '🔓'
end
if settings.anti_flood ~= 'no' then
antispam_state = '🔒'
elseif settings.anti_flood == 'no' then
antispam_state = '🔓'
end
if settings.welcome ~= 'no' then
greeting_state = '🔒'
elseif settings.welcome == 'no' then
greeting_state = '🔓'
end
if settings.sticker ~= 'ok' then
sticker_state = '🔒'
elseif settings.sticker == 'ok' then
sticker_state = '🔓'
end
local text = 'Group settings:\n'
..'\n'..lock_bots_state..' Lock group from bot : '..settings.lock_bots
..'\n'..lock_name_state..' Lock group name : '..settings.lock_name
..'\n'..lock_photo_state..' Lock group photo : '..settings.lock_photo
..'\n'..lock_member_state..' Lock group member : '..settings.lock_member
..'\n'..antispam_state..' Spam and Flood protection : '..settings.anti_flood
..'\n'..sticker_state..' Sticker policy : '..settings.sticker
..'\n'..greeting_state..' Welcome message : '..settings.welcome
return text
end
elseif matches[1] == 'sticker' then
if matches[2] == 'warn' then
if settings.sticker ~= 'warn' then
settings.sticker = 'warn'
save_data(_config.moderation.data, data)
end
return 'Stickers already prohibited.\n'
..'Sender will be warned first, then kicked for second violation.'
elseif matches[2] == 'kick' then
if settings.sticker ~= 'kick' then
settings.sticker = 'kick'
save_data(_config.moderation.data, data)
end
return 'Stickers already prohibited.\nSender will be kicked!'
elseif matches[2] == 'ok' then
if settings.sticker == 'ok' then
return 'Sticker restriction is not enabled.'
else
settings.sticker = 'ok'
save_data(_config.moderation.data, data)
return 'Sticker restriction has been disabled.'
end
end
-- if group name is renamed
elseif matches[1] == 'chat_rename' then
if not msg.service then
return 'Are you trying to troll me?'
end
if settings.lock_name == 'yes' then
if settings.set_name ~= tostring(msg.to.print_name) then
rename_chat(get_receiver(msg), settings.set_name, ok_cb, false)
end
elseif settings.lock_name == 'no' then
return nil
end
-- set group name
elseif matches[1] == 'setname' and is_mod(msg) then
settings.set_name = string.gsub(matches[2], '_', ' ')
save_data(_config.moderation.data, data)
rename_chat(get_receiver(msg), settings.set_name, ok_cb, false)
-- set group photo
elseif matches[1] == 'setphoto' and is_mod(msg) then
settings.set_photo = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
-- if a user is added to group
elseif 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
if settings.lock_member == 'yes' then
chat_del_user(get_receiver(msg), user, ok_cb, true)
-- no APIs bot are allowed to enter chat group, except invited by mods.
elseif settings.lock_bots == 'yes' and msg.action.user.flags == 4352 and not is_mod(msg) then
chat_del_user(get_receiver(msg), user, ok_cb, true)
elseif settings.lock_bots == 'no' or settings.lock_member == 'no' then
return nil
end
-- if sticker is sent
elseif msg.media and msg.media.caption == 'sticker.webp' and not is_sudo(msg) then
local user_id = msg.from.id
local chat_id = msg.to.id
local sticker_hash = 'mer_sticker:'..chat_id..':'..user_id
local is_sticker_offender = redis:get(sticker_hash)
if settings.sticker == 'warn' then
if is_sticker_offender then
chat_del_user(get_receiver(msg), 'user#id'..user_id, ok_cb, true)
redis:del(sticker_hash)
return 'You have been warned to not sending sticker into this group!'
elseif not is_sticker_offender then
redis:set(sticker_hash, true)
return 'DO NOT send sticker into this group!\nThis is a WARNING, next time you will be kicked!'
end
elseif settings.sticker == 'kick' then
chat_del_user(get_receiver(msg), 'user#id'..user_id, ok_cb, true)
return 'DO NOT send sticker into this group!'
elseif settings.sticker == 'ok' then
return nil
end
-- if group photo is deleted
elseif matches[1] == 'chat_delete_photo' then
if not msg.service then
return 'Are you trying to troll me?'
end
if settings.lock_photo == 'yes' then
chat_set_photo (get_receiver(msg), settings.set_photo, ok_cb, false)
elseif settings.lock_photo == 'no' then
return nil
end
-- if group photo is changed
elseif matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return 'Are you trying to troll me?'
end
if settings.lock_photo == 'yes' then
chat_set_photo (get_receiver(msg), settings.set_photo, ok_cb, false)
elseif settings.lock_photo == 'no' then
return nil
end
end
end
else
print '>>> This is not a chat group.'
end
end
return {
description = 'Plugin to manage group chat.',
usage = {
admin = {
'!mkgroup <group_name> : Make/create a new group.',
'!addgroup : Add group to moderation list.',
'!remgroup : Remove group from moderation list.'
},
moderator = {
'!group <lock|unlock> bot : {Dis}allow APIs bots.',
'!group <lock|unlock> member : Lock/unlock group member.',
'!group <lock|unlock> name : Lock/unlock group name.',
'!group <lock|unlock> photo : Lock/unlock group photo.',
'!group settings : Show group settings.',
'!link <set> : Generate/revoke invite link.',
'!setabout <description> : Set group description.',
'!setname <new_name> : Set group name.',
'!setphoto : Set group photo.',
'!setrules <rules> : Set group rules.',
'!sticker warn : Sticker restriction, sender will be warned for the first violation.',
'!sticker kick : Sticker restriction, sender will be kick.',
'!sticker ok : Disable sticker restriction.'
},
user = {
'!about : Read group description',
'!rules : Read group rules',
'!link <get> : Print invite link'
},
},
patterns = {
'^!(about)$',
'^!(addgp)$',
'%[(audio)%]',
'%[(document)%]',
'^!(group) (lock) (.*)$',
'^!(group) (settings)$',
'^!(group) (unlock) (.*)$',
'^!(link) (.*)$',
'^!(cgroup) (.*)$',
'%[(photo)%]',
'^!(remgp)$',
'^!(rules)$',
'^!(setabout) (.*)$',
'^!(setname) (.*)$',
'^!(setphoto)$',
'^!(setrules) (.*)$',
'^!(sticker) (.*)$',
'^!!tgservice (.+)$',
'%[(video)%]'
},
run = run,
pre_process = pre_process
}
end
| gpl-2.0 |
opentechinstitute/luci | modules/base/luasrc/model/ipkg.lua | 82 | 5778 | --[[
LuCI - Lua Configuration Interface
(c) 2008-2011 Jo-Philipp Wich <xm@subsignal.org>
(c) 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local os = require "os"
local io = require "io"
local fs = require "nixio.fs"
local util = require "luci.util"
local type = type
local pairs = pairs
local error = error
local table = table
local ipkg = "opkg --force-removal-of-dependent-packages --force-overwrite --nocase"
local icfg = "/etc/opkg.conf"
--- LuCI OPKG call abstraction library
module "luci.model.ipkg"
-- Internal action function
local function _action(cmd, ...)
local pkg = ""
for k, v in pairs({...}) do
pkg = pkg .. " '" .. v:gsub("'", "") .. "'"
end
local c = "%s %s %s >/tmp/opkg.stdout 2>/tmp/opkg.stderr" %{ ipkg, cmd, pkg }
local r = os.execute(c)
local e = fs.readfile("/tmp/opkg.stderr")
local o = fs.readfile("/tmp/opkg.stdout")
fs.unlink("/tmp/opkg.stderr")
fs.unlink("/tmp/opkg.stdout")
return r, o or "", e or ""
end
-- Internal parser function
local function _parselist(rawdata)
if type(rawdata) ~= "function" then
error("OPKG: Invalid rawdata given")
end
local data = {}
local c = {}
local l = nil
for line in rawdata do
if line:sub(1, 1) ~= " " then
local key, val = line:match("(.-): ?(.*)%s*")
if key and val then
if key == "Package" then
c = {Package = val}
data[val] = c
elseif key == "Status" then
c.Status = {}
for j in val:gmatch("([^ ]+)") do
c.Status[j] = true
end
else
c[key] = val
end
l = key
end
else
-- Multi-line field
c[l] = c[l] .. "\n" .. line
end
end
return data
end
-- Internal lookup function
local function _lookup(act, pkg)
local cmd = ipkg .. " " .. act
if pkg then
cmd = cmd .. " '" .. pkg:gsub("'", "") .. "'"
end
-- OPKG sometimes kills the whole machine because it sucks
-- Therefore we have to use a sucky approach too and use
-- tmpfiles instead of directly reading the output
local tmpfile = os.tmpname()
os.execute(cmd .. (" >%s 2>/dev/null" % tmpfile))
local data = _parselist(io.lines(tmpfile))
os.remove(tmpfile)
return data
end
--- Return information about installed and available packages.
-- @param pkg Limit output to a (set of) packages
-- @return Table containing package information
function info(pkg)
return _lookup("info", pkg)
end
--- Return the package status of one or more packages.
-- @param pkg Limit output to a (set of) packages
-- @return Table containing package status information
function status(pkg)
return _lookup("status", pkg)
end
--- Install one or more packages.
-- @param ... List of packages to install
-- @return Boolean indicating the status of the action
-- @return OPKG return code, STDOUT and STDERR
function install(...)
return _action("install", ...)
end
--- Determine whether a given package is installed.
-- @param pkg Package
-- @return Boolean
function installed(pkg)
local p = status(pkg)[pkg]
return (p and p.Status and p.Status.installed)
end
--- Remove one or more packages.
-- @param ... List of packages to install
-- @return Boolean indicating the status of the action
-- @return OPKG return code, STDOUT and STDERR
function remove(...)
return _action("remove", ...)
end
--- Update package lists.
-- @return Boolean indicating the status of the action
-- @return OPKG return code, STDOUT and STDERR
function update()
return _action("update")
end
--- Upgrades all installed packages.
-- @return Boolean indicating the status of the action
-- @return OPKG return code, STDOUT and STDERR
function upgrade()
return _action("upgrade")
end
-- List helper
function _list(action, pat, cb)
local fd = io.popen(ipkg .. " " .. action ..
(pat and (" '%s'" % pat:gsub("'", "")) or ""))
if fd then
local name, version, desc
while true do
local line = fd:read("*l")
if not line then break end
name, version, desc = line:match("^(.-) %- (.-) %- (.+)")
if not name then
name, version = line:match("^(.-) %- (.+)")
desc = ""
end
cb(name, version, desc)
name = nil
version = nil
desc = nil
end
fd:close()
end
end
--- List all packages known to opkg.
-- @param pat Only find packages matching this pattern, nil lists all packages
-- @param cb Callback function invoked for each package, receives name, version and description as arguments
-- @return nothing
function list_all(pat, cb)
_list("list", pat, cb)
end
--- List installed packages.
-- @param pat Only find packages matching this pattern, nil lists all packages
-- @param cb Callback function invoked for each package, receives name, version and description as arguments
-- @return nothing
function list_installed(pat, cb)
_list("list_installed", pat, cb)
end
--- Find packages that match the given pattern.
-- @param pat Find packages whose names or descriptions match this pattern, nil results in zero results
-- @param cb Callback function invoked for each patckage, receives name, version and description as arguments
-- @return nothing
function find(pat, cb)
_list("find", pat, cb)
end
--- Determines the overlay root used by opkg.
-- @return String containing the directory path of the overlay root.
function overlay_root()
local od = "/"
local fd = io.open(icfg, "r")
if fd then
local ln
repeat
ln = fd:read("*l")
if ln and ln:match("^%s*option%s+overlay_root%s+") then
od = ln:match("^%s*option%s+overlay_root%s+(%S+)")
local s = fs.stat(od)
if not s or s.type ~= "dir" then
od = "/"
end
break
end
until not ln
fd:close()
end
return od
end
| apache-2.0 |
darkdukey/sdkbox-facebook-sample-v2 | samples/Lua/TestLua/Resources/luaScript/SceneTest/SceneTest.lua | 8 | 5995 | local MID_PUSHSCENE = 100
local MID_PUSHSCENETRAN = 101
local MID_QUIT = 102
local MID_REPLACESCENE = 103
local MID_REPLACESCENETRAN = 104
local MID_GOBACK = 105
local SceneTestLayer1 = nil
local SceneTestLayer2 = nil
local SceneTestLayer3 = nil
--------------------------------------------------------------------
--
-- SceneTestLayer1
--
--------------------------------------------------------------------
SceneTestLayer1 = function()
local ret = CCLayer:create()
local function onPushScene(tag, pSender)
local scene = CCScene:create()
local layer = SceneTestLayer2()
scene:addChild(layer, 0)
scene:addChild(CreateBackMenuItem())
CCDirector:sharedDirector():pushScene( scene )
end
local function onPushSceneTran(tag, pSender)
local scene = CCScene:create()
local layer = SceneTestLayer2()
scene:addChild(layer, 0)
scene:addChild(CreateBackMenuItem())
CCDirector:sharedDirector():pushScene( CCTransitionSlideInT:create(1, scene) )
end
local function onQuit(tag, pSender)
cclog("onQuit")
end
local item1 = CCMenuItemFont:create( "Test pushScene")
item1:registerScriptTapHandler(onPushScene)
local item2 = CCMenuItemFont:create( "Test pushScene w/transition")
item2:registerScriptTapHandler(onPushSceneTran)
local item3 = CCMenuItemFont:create( "Quit")
item3:registerScriptTapHandler(onQuit)
local arr = CCArray:create()
arr:addObject(item1)
arr:addObject(item2)
arr:addObject(item3)
local menu = CCMenu:createWithArray(arr)
menu:alignItemsVertically()
ret:addChild( menu )
local s = CCDirector:sharedDirector():getWinSize()
local sprite = CCSprite:create(s_pPathGrossini)
ret:addChild(sprite)
sprite:setPosition( ccp(s.width-40, s.height/2) )
local rotate = CCRotateBy:create(2, 360)
local repeatAction = CCRepeatForever:create(rotate)
sprite:runAction(repeatAction)
local function onNodeEvent(event)
if event == "enter" then
cclog("SceneTestLayer1#onEnter")
elseif event == "enterTransitionFinish" then
cclog("SceneTestLayer1#onEnterTransitionDidFinish")
end
end
ret:registerScriptHandler(onNodeEvent)
return ret
end
--------------------------------------------------------------------
--
-- SceneTestLayer2
--
--------------------------------------------------------------------
SceneTestLayer2 = function()
local ret = CCLayer:create()
local m_timeCounter = 0
local function onGoBack(tag, pSender)
CCDirector:sharedDirector():popScene()
end
local function onReplaceScene(tag, pSender)
local scene = CCScene:create()
local layer = SceneTestLayer3()
scene:addChild(layer, 0)
scene:addChild(CreateBackMenuItem())
CCDirector:sharedDirector():replaceScene( scene )
end
local function onReplaceSceneTran(tag, pSender)
local scene = CCScene:create()
local layer = SceneTestLayer3()
scene:addChild(layer, 0)
scene:addChild(CreateBackMenuItem())
CCDirector:sharedDirector():replaceScene( CCTransitionFlipX:create(2, scene) )
end
local item1 = CCMenuItemFont:create( "replaceScene")
item1:registerScriptTapHandler(onReplaceScene)
local item2 = CCMenuItemFont:create( "replaceScene w/transition")
item2:registerScriptTapHandler(onReplaceSceneTran)
local item3 = CCMenuItemFont:create( "Go Back")
item3:registerScriptTapHandler(onGoBack)
local arr = CCArray:create()
arr:addObject(item1)
arr:addObject(item2)
arr:addObject(item3)
local menu = CCMenu:createWithArray(arr)
menu:alignItemsVertically()
ret:addChild( menu )
local s = CCDirector:sharedDirector():getWinSize()
local sprite = CCSprite:create(s_pPathGrossini)
ret:addChild(sprite)
sprite:setPosition( ccp(s.width-40, s.height/2) )
local rotate = CCRotateBy:create(2, 360)
local repeat_action = CCRepeatForever:create(rotate)
sprite:runAction(repeat_action)
return ret
end
--------------------------------------------------------------------
--
-- SceneTestLayer3
--
--------------------------------------------------------------------
SceneTestLayer3 = function()
local ret = CCLayerColor:create(ccc4(0,0,255,255))
local s = CCDirector:sharedDirector():getWinSize()
local function item0Clicked(tag, pSender)
local newScene = CCScene:create()
newScene:addChild(SceneTestLayer3())
CCDirector:sharedDirector():pushScene(CCTransitionFade:create(0.5, newScene, ccc3(0,255,255)))
end
local function item1Clicked(tag, pSender)
CCDirector:sharedDirector():popScene()
end
local function item2Clicked(tag, pSender)
CCDirector:sharedDirector():popToRootScene()
end
local item0 = CCMenuItemFont:create("Touch to pushScene (self)")
item0:registerScriptTapHandler(item0Clicked)
local item1 = CCMenuItemFont:create("Touch to popScene")
item1:registerScriptTapHandler(item1Clicked)
local item2 = CCMenuItemFont:create("Touch to popToRootScene")
item2:registerScriptTapHandler(item2Clicked)
local arr = CCArray:create()
arr:addObject(item0)
arr:addObject(item1)
arr:addObject(item2)
local menu = CCMenu:createWithArray(arr)
ret:addChild(menu)
menu:alignItemsVertically()
local sprite = CCSprite:create(s_pPathGrossini)
ret:addChild(sprite)
sprite:setPosition( ccp(s.width/2, 40) )
local rotate = CCRotateBy:create(2, 360)
local repeatAction = CCRepeatForever:create(rotate)
sprite:runAction(repeatAction)
return ret
end
function SceneTestMain()
cclog("SceneTestMain")
local scene = CCScene:create()
local layer = SceneTestLayer1()
scene:addChild(layer, 0)
scene:addChild(CreateBackMenuItem())
return scene
end
| mit |
snowplow/snowplow-lua-tracker | spec/mocks/mock_os.lua | 1 | 1105 | --- mock_os.lua
--
-- Copyright (c) 2013 - 2022 Snowplow Analytics Ltd. All rights reserved.
--
-- This program is licensed to you under the Apache License Version 2.0,
-- and you may not use this file except in compliance with the Apache License Version 2.0.
-- You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the Apache License Version 2.0 is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
local mock_os = {}
-- --------------------------------------------------------------
-- Gives our mock all the same methods as the real 'os' module
setmetatable(mock_os, os)
-- Mock os.time with a known value
-- @return number: a known mock time
mock_os.time = function()
return 1000000000000
end
-- --------------------------------------------------------------
return mock_os
| apache-2.0 |
cyberz-eu/octopus | extensions/orm/src/db/driver/postgres.lua | 1 | 11147 | -- Copyright (C) 2013 Azure Wang(azure1st@gmail.com)
local string = string
local table = table
local bit = bit
local ngx = ngx
local tonumber = tonumber
local type = type
local tostring = tostring
local setmetatable = setmetatable
local error = error
local _M = { _VERSION = '0.3' }
-- constants
local STATE_CONNECTED = 1
local STATE_COMMAND_SENT = 2
local AUTH_REQ_OK = "\00\00\00\00"
local mt = { __index = _M }
local converters = {}
-- INT8OID
converters[20] = tonumber
-- INT2OID
converters[21] = tonumber
-- INT2VECTOROID
converters[22] = tonumber
-- INT4OID
converters[23] = tonumber
-- FLOAT4OID
converters[700] = tonumber
-- FLOAT8OID
converters[701] = tonumber
-- NUMERICOID
converters[1700] = tonumber
function _M.new(self)
local sock, err = ngx.socket.tcp()
if not sock then
return nil, err
end
-- only new connection have env info
return setmetatable({ sock = sock, env = {}}, mt)
end
function _M.set_timeout(self, timeout)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:settimeout(timeout)
end
local function _get_byte4(data, i)
local a, b, c, d = string.byte(data, i, i+3)
return bit.bor(bit.lshift(a, 24), bit.lshift(b, 16), bit.lshift(c, 8), d), i+4
end
local function _get_byte2(data, i)
local a, b = string.byte(data, i, i+1)
return bit.bor(bit.lshift(a, 8), b), i+2
end
local function _get_data_n(data, len, i)
local d = string.sub(data, i, i+len-1)
return d, i+len
end
local function _set_byte2(n)
return string.char(bit.band(bit.rshift(n, 8), 0xff), bit.band(n, 0xff))
end
local function _set_byte4(n)
return string.char(bit.band(bit.rshift(n, 24), 0xff), bit.band(bit.rshift(n, 16), 0xff),
bit.band(bit.rshift(n, 8), 0xff), bit.band(n, 0xff))
end
local function _from_cstring(data, i)
local last = string.find(data, "\0", i, true)
if not last then
return nil, nil
end
return string.sub(data, i, last - 1), last + 1
end
local function _to_cstring(data)
return {data, "\0"}
end
function _send_packet(self, data, len, typ)
local sock = self.sock
local packet
if typ then
packet = {
typ,
_set_byte4(len),
data
}
else
packet = {
_set_byte4(len),
data
}
end
return sock:send(packet)
end
function _parse_error_packet(packet)
local pos = 1
local flg, value, msg
msg = {}
while true do
flg = string.sub(packet, pos, pos)
if not flg then
return nil, "parse error packet fail"
end
pos = pos + 1
if flg == '\0' then
break
end
-- all flg S/C/M/P/F/L/R
value, pos = _from_cstring(packet, pos)
if not value then
return nil, "parse error packet fail"
end
msg[flg] = value
end
return msg
end
function _recv_packet(self)
-- receive type
local sock = self.sock
local typ, err = sock:receive(1)
if not typ then
return nil, nil, "failed to receive packet type: " .. err
end
-- receive length
local data, err = sock:receive(4)
if not data then
return nil, nil , "failed to read packet length: " .. err
end
local len = _get_byte4(data, 1)
if len <= 4 then
return nil, typ, "empty packet"
end
-- receive data
data, err = sock:receive(len - 4)
if not data then
return nil, nil, "failed to read packet content: " .. err
end
return data, typ
end
function _compute_token(self, user, password, salt)
local token1 = ngx.md5(password .. user)
local token2 = ngx.md5(token1 .. salt)
return "md5" .. token2
end
function _M.connect(self, opts)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
local ok, err
self.compact = opts.compact
local host = opts.host
local database = opts.database or ""
local user = opts.user or ""
local host = opts.host
local pool = opts.pool
local password = opts.password
if host then
local port = opts.port or 5432
if not pool then
pool = table.concat({user, database, host, port}, ":")
end
ok, err = sock:connect(host, port, { pool = pool })
else
local path = opts.path
if not path then
return nil, 'neither "host" nor "path" options are specified'
end
if not pool then
pool = table.concat({user, database, path}, ":")
end
ok, err = sock:connect("unix:" .. path, { pool = pool })
end
if not ok then
return nil, 'failed to connect: ' .. err
end
local reused = sock:getreusedtimes()
-- use pool connection
if reused and reused > 0 then
self.state = STATE_CONNECTED
return 1
end
-- new connection
-- send first packet
local req, req_len
req = {}
-- PG_PROTOCOL 3.0
table.insert(req, {"\00\03","\00\00"})
table.insert(req, _to_cstring("user"))
table.insert(req, _to_cstring(user))
table.insert(req, _to_cstring("database"))
table.insert(req, _to_cstring(database))
table.insert(req, "\00")
-- packet_len + PG_PROTOCOL + user + database + end
-- req_len = 4 + 4 + string.len(user) + 6 + string.len(database) + 10 + 1
req_len = string.len(user) + string.len(database) + 25
local bytes, err = _send_packet(self, req, req_len)
if not bytes then
return nil, "failed to send client authentication packet1: " .. err
end
-- receive salt packet (len + data) no type
local packet, typ
packet, typ, err = _recv_packet(self)
if not packet then
return nil, "handshake error:" .. err
end
if typ ~= 'R' then
return nil, "handshake error, got packet type:" .. typ
end
local auth_type = string.sub(packet, 1, 4)
local salt = string.sub(packet, 5, 8)
-- send passsowrd
req = {_to_cstring(_compute_token(self, user, password, salt))}
req_len = 40
local bytes, err = _send_packet(self, req, req_len, 'p')
if not bytes then
return nil, "failed to send client authentication packet2: " .. err
end
-- receive response
packet, typ, err = _recv_packet(self)
if typ ~= 'R' then
return nil, "auth return type not support"
end
if packet ~= AUTH_REQ_OK then
return nil, "authentication failed"
end
while true do
packet, typ, err = _recv_packet(self)
if not packet then
return nil, "read packet error:" .. err
end
-- env
if typ == 'S' then
local pos = 1
local k, pos = _from_cstring(packet, pos)
local v, pos = _from_cstring(packet, pos)
self.env[k] = v
end
-- secret key
if typ == 'K' then
local pid = _get_byte4(packet, 1)
local secret_key = string.sub(packet, 5, 8)
self.env.secret_key = secret_key
self.env.pid = pid
end
-- error
if typ == 'E' then
local msg = _parse_error_packet(packet)
return nil, "Get error packet:" .. msg.M
end
-- ready for new query
if typ == 'Z' then
self.state = STATE_CONNECTED
return 1
end
end
end
function _M.set_keepalive(self, ...)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
if self.state ~= STATE_CONNECTED then
return nil, "cannot be reused in the current connection state: "
.. (self.state or "nil")
end
self.state = nil
return sock:setkeepalive(...)
end
function _M.get_reused_times(self)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:getreusedtimes()
end
function _M.close(self)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
self.state = nil
return sock:close()
end
function send_query(self, query)
if self.state ~= STATE_CONNECTED then
return nil, "cannot send query in the current context: "
.. (self.state or "nil")
end
local sock = self.sock
if not sock then
return nil, "not initialized"
end
local typ = 'Q'
local data = _to_cstring(query)
-- packet_len + cstring end(\0) = 5
local len = string.len(query) + 5
local bytes, err = _send_packet(self, data, len, typ)
self.state = STATE_COMMAND_SENT
return bytes, err
end
_M.send_query = send_query
function read_result(self)
if self.state ~= STATE_COMMAND_SENT then
return nil, "cannot read result in the current context: " .. self.state
end
local sock = self.sock
if not sock then
return nil, "not initialized"
end
-- read data
local res = {}
local fields = {}
local field_ok = false
local packet, typ, err
while true do
packet, typ, err = _recv_packet(self)
if not packet then
return nil, "read result packet error:" .. err
end
-- packet of fields
if typ == 'T' then
local field_num, pos = _get_byte2(packet, 1)
for i=1, field_num do
local field = {}
field.name, pos = _from_cstring(packet, pos)
field.table_id, pos = _get_byte4(packet, pos)
field.field_id, pos = _get_byte2(packet, pos)
field.type_id, pos = _get_byte4(packet, pos)
field.type_len, pos = _get_byte2(packet, pos)
-- pass atttypmod, format
pos = pos + 6
table.insert(fields, field)
end
field_ok = true
end
-- packet of data row
if typ == 'D' then
if not field_ok then
return nil, "not receive fields packet"
end
local row = {}
local row_num, pos = _get_byte2(packet, 1)
-- get row
for i=1, row_num do
local data, len
len, pos = _get_byte4(packet, pos)
if len == -1 then
data = ngx.null
else
data, pos = _get_data_n(packet, len, pos)
end
local field = fields[i]
local conv = converters[field.type_id]
if conv and data ~= ngx.null then
data = conv(data)
end
----------------------------------
-- convert null userdata to nil --
-- convert bool data to boolean --
----------------------------------
--ngx.log(ngx.ERR, field.type_id .. ":" .. field.name)
--ngx.log(ngx.ERR, data)
if type(data) == "userdata" and tostring(data) == "userdata: NULL" then
data = nil
elseif field.type_id == 16 then
-- t == true
-- f == false
if data == "t" then data = true else data = false end
end
----------------------------------
if self.compact then
table.insert(row, data)
else
local name = field.name
row[name] = data
end
end
table.insert(res, row)
end
if typ == 'E' then
-- error packet
local msg = _parse_error_packet(packet)
err = msg.M
res = nil
break
end
if typ == 'C' then
-- read complete
local sql_type = _from_cstring(packet, 1)
self.env.sql_type = sql_type
err = nil
end
if typ == 'Z' then
self.state = STATE_CONNECTED
break
end
end
return res, err
end
_M.read_result = read_result
function _M.query(self, query)
local bytes, err = send_query(self, query)
if not bytes then
return nil, "failed to send query: " .. err
end
return read_result(self)
end
function escape_string(str)
local new = string.gsub(str, "['\\]", "%0%0")
return new
end
local class_mt = {
-- to prevent use of casual module global variables
__newindex = function (table, key, val)
error('attempt to write to undeclared variable "' .. key .. '"')
end
}
setmetatable(_M, class_mt)
return _M | bsd-2-clause |
JarnoVgr/Mr.Green-MTA-Resources | resources/[gameplay]/webbrowser/WebBrowserGUI.lua | 3 | 5267 | WebBrowserGUI = {}
WebBrowserGUI.instance = nil
function WebBrowserGUI:new(url) local o=setmetatable({},{__index=WebBrowserGUI}) o:constructor(url) return o end
function WebBrowserGUI:constructor(url)
local sizeX, sizeY = screenWidth * 0.9, screenHeight * 0.9
self.m_Window = GuiWindow(screenWidth * 0.05, screenHeight * 0.05, sizeX, sizeY, "Web browser", false)
self.m_Window:setSizable(false)
self.m_BackButton = GuiButton(5, 25, 32, 32, "<", false, self.m_Window)
self.m_BackButton:setEnabled(false)
self.m_ForwardButton = GuiButton(42, 25, 32, 32, ">", false, self.m_Window)
self.m_ForwardButton:setEnabled(false)
self.m_EditAddress = GuiEdit(77, 25, sizeX - 192, 32, "Please enter an address", false, self.m_Window)
self.m_DevButton = GuiButton(sizeX - 110, 25, 32, 32, "✎", false, self.m_Window)
self.m_LoadButton = GuiButton(sizeX - 75, 25, 32, 32, "➽", false, self.m_Window)
self.m_ButtonClose = GuiButton(sizeX - 38, 25, 24, 24, "✖", false, self.m_Window)
self.m_ButtonClose:setProperty("NormalTextColour", "FFFF2929")
self.m_ButtonClose:setProperty("HoverTextColour", "FF990909")
self.m_ButtonClose:setFont("default-bold-small")
self.m_Browser = GuiBrowser(5, 62, sizeX - 10, sizeY - 67, false, false, false, self.m_Window)
if not self.m_Browser then
outputChatBox( "Can't create browser. Check Settings->Web Browser" )
self.m_Window:destroy()
return
end
local browser = self.m_Browser:getBrowser()
addEventHandler("onClientBrowserCreated", browser, function(...) self:Browser_Created(...) end)
addEventHandler("onClientBrowserNavigate", browser, function(...) self:Browser_Navigate(...) end)
addEventHandler("onClientBrowserWhitelistChange", root, function(...) self:Browser_WhitelistChange(...) end)
addEventHandler("onClientBrowserDocumentReady", browser, function(...) self:Browser_DocumentReady(...) end)
self.m_RequestedURL = url
showCursor(true)
GuiElement.setInputMode("no_binds_when_editing")
end
function WebBrowserGUI:Browser_Created()
addEventHandler("onClientGUIClick", self.m_LoadButton, function(...) self:LoadButton_Click(...) end, false)
addEventHandler("onClientGUIAccepted", self.m_EditAddress, function(...) self:LoadButton_Click(...) end, false)
addEventHandler("onClientGUIClick", self.m_BackButton, function(...) self:BackButton_Click(...) end, false)
addEventHandler("onClientGUIClick", self.m_ForwardButton, function(...) self:ForwardButton_Click(...) end, false)
addEventHandler("onClientGUIClick", self.m_ButtonClose, function(...) self:CloseButton_Click(...) end, false)
addEventHandler("onClientGUIClick", self.m_DevButton, function(...) self:DevButton_Click(...) end, false)
self:loadURL(self.m_RequestedURL or "https://mtasa.com/")
end
function WebBrowserGUI:Browser_Navigate(targetURL, isBlocked)
if isBlocked then
self.m_RequestedURL = targetURL
Browser.requestDomains({targetURL}, true)
return
end
end
function WebBrowserGUI:Browser_WhitelistChange(whitelistedURLs)
for i, v in pairs(whitelistedURLs) do
if self.m_RequestedURL:find(v) then
self.m_Browser:getBrowser():loadURL(self.m_RequestedURL)
self.m_RequestedURL = ""
end
end
end
function WebBrowserGUI:Browser_DocumentReady()
self.m_Window:setText("Web browser: " .. tostring(self.m_Browser:getBrowser():getTitle()))
self.m_EditAddress:setText(tostring(self.m_Browser:getBrowser():getURL()))
self.m_BackButton:setEnabled(self.m_Browser:getBrowser():canNavigateBack())
self.m_ForwardButton:setEnabled(self.m_Browser:getBrowser():canNavigateForward())
end
-- // GUI Navigation
function WebBrowserGUI:LoadButton_Click(param1, state)
if isElement(param1) or (param1 == "left" and state == "up") then
self:loadURL(self.m_EditAddress:getText())
end
end
function WebBrowserGUI:BackButton_Click(button, state)
if button == "left" and state == "up" then
self.m_Browser:getBrowser():navigateBack()
end
end
function WebBrowserGUI:ForwardButton_Click(button, state)
if button == "left" and state == "up" then
self.m_Browser:getBrowser():navigateForward()
end
end
function WebBrowserGUI:CloseButton_Click(button, state)
if button == "left" and state == "up" then
self.m_Window:destroy()
showCursor(false)
--GuiElement.setInputMode("no_binds_when_editing")
WebBrowserGUI.instance = nil
end
end
function WebBrowserGUI:DevButton_Click(button, state)
if button == "left" and state == "up" then
if not getDevelopmentMode() then
exports.msgbox:guiShowMessageBox("You have to enable the development using setDevelopmentMode", "error", "Development mode required", false)
return
end
self.m_Browser:getBrowser():toggleDevTools(true)
end
end
-- \\ GUI Navigation
function WebBrowserGUI:loadURL(url)
if url == "" then
self.m_EditAddress:setText("about:blank")
self.m_Browser:getBrowser():loadURL("about:blank")
return
elseif url:sub(0, 6) == "about:" then
self.m_EditAddress:setText(url)
self.m_Browser:getBrowser():loadURL(url)
return
elseif url:sub(0, 7) ~= "http://" and url:sub(0, 8) ~= "https://" then
url = "http://"..url
end
if Browser.isDomainBlocked(url, true) then
self.m_RequestedURL = url
Browser.requestDomains({url}, true)
return
end
self.m_EditAddress:setText(url)
self.m_Browser:getBrowser():loadURL(url)
end
| mit |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/TextureData.lua | 19 | 1044 |
--------------------------------
-- @module TextureData
-- @extend Ref
-- @parent_module ccs
--------------------------------
--
-- @function [parent=#TextureData] getContourData
-- @param self
-- @param #int index
-- @return ContourData#ContourData ret (return value: ccs.ContourData)
--------------------------------
--
-- @function [parent=#TextureData] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#TextureData] addContourData
-- @param self
-- @param #ccs.ContourData contourData
-- @return TextureData#TextureData self (return value: ccs.TextureData)
--------------------------------
--
-- @function [parent=#TextureData] create
-- @param self
-- @return TextureData#TextureData ret (return value: ccs.TextureData)
--------------------------------
-- js ctor
-- @function [parent=#TextureData] TextureData
-- @param self
-- @return TextureData#TextureData self (return value: ccs.TextureData)
return nil
| mit |
opentechinstitute/luci | applications/luci-openvpn/luasrc/model/cbi/openvpn.lua | 65 | 3316 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
local sys = require "luci.sys"
local uci = require "luci.model.uci".cursor()
local m = Map("openvpn", translate("OpenVPN"))
local s = m:section( TypedSection, "openvpn", translate("OpenVPN instances"), translate("Below is a list of configured OpenVPN instances and their current state") )
s.template = "cbi/tblsection"
s.template_addremove = "openvpn/cbi-select-input-add"
s.addremove = true
s.add_select_options = { }
s.extedit = luci.dispatcher.build_url(
"admin", "services", "openvpn", "basic", "%s"
)
uci:load("openvpn_recipes")
uci:foreach( "openvpn_recipes", "openvpn_recipe",
function(section)
s.add_select_options[section['.name']] =
section['_description'] or section['.name']
end
)
function s.parse(self, section)
local recipe = luci.http.formvalue(
luci.cbi.CREATE_PREFIX .. self.config .. "." ..
self.sectiontype .. ".select"
)
if recipe and not s.add_select_options[recipe] then
self.invalid_cts = true
else
TypedSection.parse( self, section )
end
end
function s.create(self, name)
local recipe = luci.http.formvalue(
luci.cbi.CREATE_PREFIX .. self.config .. "." ..
self.sectiontype .. ".select"
)
if name and not name:match("[^a-zA-Z0-9_]") then
uci:section(
"openvpn", "openvpn", name,
uci:get_all( "openvpn_recipes", recipe )
)
uci:delete("openvpn", name, "_role")
uci:delete("openvpn", name, "_description")
uci:save("openvpn")
luci.http.redirect( self.extedit:format(name) )
else
self.invalid_cts = true
end
end
s:option( Flag, "enabled", translate("Enabled") )
local active = s:option( DummyValue, "_active", translate("Started") )
function active.cfgvalue(self, section)
local pid = fs.readfile("/var/run/openvpn-%s.pid" % section)
if pid and #pid > 0 and tonumber(pid) ~= nil then
return (sys.process.signal(pid, 0))
and translatef("yes (%i)", pid)
or translate("no")
end
return translate("no")
end
local updown = s:option( Button, "_updown", translate("Start/Stop") )
updown._state = false
function updown.cbid(self, section)
local pid = fs.readfile("/var/run/openvpn-%s.pid" % section)
self._state = pid and #pid > 0 and sys.process.signal(pid, 0)
self.option = self._state and "stop" or "start"
return AbstractValue.cbid(self, section)
end
function updown.cfgvalue(self, section)
self.title = self._state and "stop" or "start"
self.inputstyle = self._state and "reset" or "reload"
end
function updown.write(self, section, value)
if self.option == "stop" then
luci.sys.call("/etc/init.d/openvpn down %s" % section)
else
luci.sys.call("/etc/init.d/openvpn up %s" % section)
end
end
local port = s:option( DummyValue, "port", translate("Port") )
function port.cfgvalue(self, section)
local val = AbstractValue.cfgvalue(self, section)
return val or "1194"
end
local proto = s:option( DummyValue, "proto", translate("Protocol") )
function proto.cfgvalue(self, section)
local val = AbstractValue.cfgvalue(self, section)
return val or "udp"
end
return m
| apache-2.0 |
JustAPerson/MODS | docs/CURRENT.lua | 1 | 1098 | --[[
Maximum OverDrive System v2.2.0-pre-alpha
MODS
I've yet to write the documentation, I'll do so when I finish the assembler.
Though I will keep a change log here.
Change Log:
Alpha Stage:
v2.2.0:
- General work on the assembler
- Finished Macros
- Added a ".const" directive finally.
v2.1.0:
- Finished Identifiers
- Finished most of the basic identifiers
- Finished instruction and expression parsing
- Removed Lua based assembler macros in favor of NASM style macros.
- Assembler now in a working state.
Pre-Alpha Stage:
v2.0.1:
- More work on Identifiers
- Stared directives, yet to fully implement .local
- Laying the base for Instructions so we can finally finish
- Finished labels I think
- Oh yeah, Macros are cool
v2.0.0:
- Finally realesed MODS in my place so it can be right next to my bio
- renaming the old Assemble and Disassemble functions to Link and Delink respectively
- Stole some MORE of xLEGOx's wonderful code, this time it is the Lexer/Tokenizer thing that is used extensively in the Assembler
]] | mit |
lizh06/premake-core | modules/self-test/test_assertions.lua | 6 | 4787 | ---
-- test_assertions.lua
--
-- Assertion functions for unit tests.
--
-- Author Jason Perkins
-- Copyright (c) 2008-2016 Jason Perkins and the Premake project.
---
local p = premake
local m = p.modules.self_test
local _ = {}
function m.capture(expected)
local actual = premake.captured() .. premake.eol()
-- create line-by-line iterators for both values
local ait = actual:gmatch("(.-)" .. premake.eol())
local eit = expected:gmatch("(.-)\n")
-- compare each value line by line
local linenum = 1
local atxt = ait()
local etxt = eit()
while etxt do
if (etxt ~= atxt) then
m.fail("(%d) expected:\n%s\n...but was:\n%s\nfulltext:\n%s", linenum, etxt, atxt, actual)
end
linenum = linenum + 1
atxt = ait()
etxt = eit()
end
end
function m.closedfile(expected)
if expected and not m.value_closedfile then
m.fail("expected file to be closed")
elseif not expected and m.value_closedfile then
m.fail("expected file to remain open")
end
end
function m.contains(expected, actual)
if type(expected) == "table" then
for i, v in ipairs(expected) do
m.contains(v, actual)
end
elseif not table.contains(actual, expected) then
m.fail("expected value %s not found", expected)
end
end
function m.excludes(expected, actual)
if type(expected) == "table" then
for i, v in ipairs(expected) do
m.excludes(v, actual)
end
elseif table.contains(actual, expected) then
m.fail("excluded value %s found", expected)
end
end
function m.fail(format, ...)
-- if format is a number then it is the stack depth
local depth = 3
local arg = {...}
if type(format) == "number" then
depth = depth + format
format = table.remove(arg, 1)
end
-- convert nils into something more usefuls
for i = 1, #arg do
if (arg[i] == nil) then
arg[i] = "(nil)"
elseif (type(arg[i]) == "table") then
arg[i] = "{" .. table.concat(arg[i], ", ") .. "}"
end
end
local msg = string.format(format, unpack(arg))
error(debug.traceback(msg, depth), depth)
end
function m.filecontains(expected, fn)
local f = io.open(fn)
local actual = f:read("*a")
f:close()
if (expected ~= actual) then
m.fail("expected %s but was %s", expected, actual)
end
end
function m.hasoutput()
local actual = premake.captured()
if actual == "" then
m.fail("expected output, received none");
end
end
function m.isemptycapture()
local actual = premake.captured()
if actual ~= "" then
m.fail("expected empty capture, but was %s", actual);
end
end
function m.isequal(expected, actual, depth)
depth = depth or 0
if type(expected) == "table" then
if expected and not actual then
m.fail(depth, "expected table, got nil")
end
if #expected < #actual then
m.fail(depth, "expected %d items, got %d", #expected, #actual)
end
for k,v in pairs(expected) do
m.isequal(expected[k], actual[k], depth + 1)
end
else
if (expected ~= actual) then
m.fail(depth, "expected %s but was %s", expected, actual)
end
end
return true
end
function m.isfalse(value)
if (value) then
m.fail("expected false but was true")
end
end
function m.isnil(value)
if (value ~= nil) then
m.fail("expected nil but was " .. tostring(value))
end
end
function m.isnotnil(value)
if (value == nil) then
m.fail("expected not nil")
end
end
function m.issame(expected, action)
if expected ~= action then
m.fail("expected same value")
end
end
function m.istrue(value)
if (not value) then
m.fail("expected true but was false")
end
end
function m.missing(value, actual)
if table.contains(actual, value) then
m.fail("unexpected value %s found", value)
end
end
function m.openedfile(fname)
if fname ~= m.value_openedfilename then
local msg = "expected to open file '" .. fname .. "'"
if m.value_openedfilename then
msg = msg .. ", got '" .. m.value_openedfilename .. "'"
end
m.fail(msg)
end
end
function m.success(fn, ...)
local ok, err = pcall(fn, ...)
if not ok then
m.fail("call failed: " .. err)
end
end
function m.stderr(expected)
if not expected and m.stderr_capture then
m.fail("Unexpected: " .. m.stderr_capture)
elseif expected then
if not m.stderr_capture or not m.stderr_capture:find(expected) then
m.fail(string.format("expected '%s'; got %s", expected, m.stderr_capture or "(nil)"))
end
end
end
function m.notstderr(expected)
if not expected and not m.stderr_capture then
m.fail("Expected output on stderr; none received")
elseif expected then
if m.stderr_capture and m.stderr_capture:find(expected) then
m.fail(string.format("stderr contains '%s'; was %s", expected, m.stderr_capture))
end
end
end
| bsd-3-clause |
lizh06/premake-core | src/base/globals.lua | 14 | 2408 | --
-- globals.lua
-- Replacements and extensions to Lua's global functions.
-- Copyright (c) 2002-2014 Jason Perkins and the Premake project
--
--
-- Find and execute a Lua source file present on the filesystem, but
-- continue without error if the file is not present. This is used to
-- handle optional files such as the premake-system.lua script.
--
-- @param fname
-- The name of the file to load. This may be specified as a single
-- file path or an array of file paths, in which case the first
-- file found is run.
-- @return
-- True if a file was found and executed, nil otherwise.
--
function dofileopt(fname)
if type(fname) == "string" then fname = {fname} end
for i = 1, #fname do
local found = os.locate(fname[i])
if not found then
found = os.locate(fname[i] .. ".lua")
end
if found then
dofile(found)
return true
end
end
end
---
-- Load and run an external script file, with a bit of extra logic to make
-- including projects easier. if "path" is a directory, will look for
-- path/premake5.lua. And each file is tracked, and loaded only once.
--
-- @param fname
-- The name of the directory or file to include. If a directory, will
-- automatically include the contained premake5.lua or premake4.lua
-- script at that lcoation.
---
io._includedFiles = {}
function include(fname)
local fullPath = premake.findProjectScript(fname)
fname = fullPath or fname
if not io._includedFiles[fname] then
io._includedFiles[fname] = true
return dofile(fname)
end
end
---
-- Extend require() with a second argument to specify the expected
-- version of the loaded module. Raises an error if the version criteria
-- are not met.
--
-- @param modname
-- The name of the module to load.
-- @param versions
-- An optional version criteria string; see premake.checkVersion()
-- for more information on the format.
-- @return
-- If successful, the loaded module, which is also stored into the
-- global package.loaded table.
---
premake.override(_G, "require", function(base, modname, versions)
local result, mod = pcall(base,modname)
if not result then
error( mod, 3 )
end
if mod and versions and not premake.checkVersion(mod._VERSION, versions) then
error(string.format("module %s %s does not meet version criteria %s",
modname, mod._VERSION or "(none)", versions), 3)
end
return mod
end)
| bsd-3-clause |
hussian1997/bot_Iraq1997 | tg/test.lua | 210 | 2571 | started = 0
our_id = 0
function vardump(value, depth, key)
local linePrefix = ""
local spaces = ""
if key ~= nil then
linePrefix = "["..key.."] = "
end
if depth == nil then
depth = 0
else
depth = depth + 1
for i=1, depth do spaces = spaces .. " " end
end
if type(value) == 'table' then
mTable = getmetatable(value)
if mTable == nil then
print(spaces ..linePrefix.."(table) ")
else
print(spaces .."(metatable) ")
value = mTable
end
for tableKey, tableValue in pairs(value) do
vardump(tableValue, depth, tableKey)
end
elseif type(value) == 'function' or
type(value) == 'thread' or
type(value) == 'userdata' or
value == nil
then
print(spaces..tostring(value))
else
print(spaces..linePrefix.."("..type(value)..") "..tostring(value))
end
end
print ("HI, this is lua script")
function ok_cb(extra, success, result)
end
-- Notification code {{{
function get_title (P, Q)
if (Q.type == 'user') then
return P.first_name .. " " .. P.last_name
elseif (Q.type == 'chat') then
return Q.title
elseif (Q.type == 'encr_chat') then
return 'Secret chat with ' .. P.first_name .. ' ' .. P.last_name
else
return ''
end
end
local lgi = require ('lgi')
local notify = lgi.require('Notify')
notify.init ("Telegram updates")
local icon = os.getenv("HOME") .. "/.telegram-cli/telegram-pics/telegram_64.png"
function do_notify (user, msg)
local n = notify.Notification.new(user, msg, icon)
n:show ()
end
-- }}}
function on_msg_receive (msg)
if started == 0 then
return
end
if msg.out then
return
end
do_notify (get_title (msg.from, msg.to), msg.text)
if (msg.text == 'ping') then
if (msg.to.id == our_id) then
send_msg (msg.from.print_name, 'pong', ok_cb, false)
else
send_msg (msg.to.print_name, 'pong', ok_cb, false)
end
return
end
if (msg.text == 'PING') then
if (msg.to.id == our_id) then
fwd_msg (msg.from.print_name, msg.id, ok_cb, false)
else
fwd_msg (msg.to.print_name, msg.id, ok_cb, false)
end
return
end
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
--vardump (chat)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
function cron()
-- do something
postpone (cron, false, 1.0)
end
function on_binlog_replay_end ()
started = 1
postpone (cron, false, 1.0)
end
| gpl-2.0 |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/lua_cocos2dx_physics3d_auto_api.lua | 11 | 2391 | --------------------------------
-- @module cc
--------------------------------------------------------
-- the cc Physics3DShape
-- @field [parent=#cc] Physics3DShape#Physics3DShape Physics3DShape preloaded module
--------------------------------------------------------
-- the cc Physics3DObject
-- @field [parent=#cc] Physics3DObject#Physics3DObject Physics3DObject preloaded module
--------------------------------------------------------
-- the cc Physics3DRigidBody
-- @field [parent=#cc] Physics3DRigidBody#Physics3DRigidBody Physics3DRigidBody preloaded module
--------------------------------------------------------
-- the cc Physics3DComponent
-- @field [parent=#cc] Physics3DComponent#Physics3DComponent Physics3DComponent preloaded module
--------------------------------------------------------
-- the cc PhysicsSprite3D
-- @field [parent=#cc] PhysicsSprite3D#PhysicsSprite3D PhysicsSprite3D preloaded module
--------------------------------------------------------
-- the cc Physics3DWorld
-- @field [parent=#cc] Physics3DWorld#Physics3DWorld Physics3DWorld preloaded module
--------------------------------------------------------
-- the cc Physics3DConstraint
-- @field [parent=#cc] Physics3DConstraint#Physics3DConstraint Physics3DConstraint preloaded module
--------------------------------------------------------
-- the cc Physics3DPointToPointConstraint
-- @field [parent=#cc] Physics3DPointToPointConstraint#Physics3DPointToPointConstraint Physics3DPointToPointConstraint preloaded module
--------------------------------------------------------
-- the cc Physics3DHingeConstraint
-- @field [parent=#cc] Physics3DHingeConstraint#Physics3DHingeConstraint Physics3DHingeConstraint preloaded module
--------------------------------------------------------
-- the cc Physics3DSliderConstraint
-- @field [parent=#cc] Physics3DSliderConstraint#Physics3DSliderConstraint Physics3DSliderConstraint preloaded module
--------------------------------------------------------
-- the cc Physics3DConeTwistConstraint
-- @field [parent=#cc] Physics3DConeTwistConstraint#Physics3DConeTwistConstraint Physics3DConeTwistConstraint preloaded module
--------------------------------------------------------
-- the cc Physics3D6DofConstraint
-- @field [parent=#cc] Physics3D6DofConstraint#Physics3D6DofConstraint Physics3D6DofConstraint preloaded module
return nil
| mit |
JarnoVgr/Mr.Green-MTA-Resources | resources/[admin]/admin/server/admin_ACL.lua | 7 | 2730 | --[[**********************************
*
* Multi Theft Auto - Admin Panel
*
* admin_ACL.lua
*
* Original File by lil_Toady
*
**************************************]]
function aSetupACL ()
local temp_acl_nodes = {}
local node = xmlLoadFile ( "conf\\ACL.xml" )
if ( node ) then
--Get ACLs
local acls = 0
while ( xmlFindChild ( node, "acl", acls ) ~= false ) do
local aclNode = xmlFindChild ( node, "acl", acls )
local aclName = xmlNodeGetAttribute ( aclNode, "name" )
if ( ( aclNode ) and ( aclName ) ) then
temp_acl_nodes[aclName] = aclNode
end
acls = acls + 1
end
-- Add missing rights
local totalAdded = 0
for id, acl in ipairs ( aclList () ) do
local aclName = aclGetName ( acl )
if string.sub(aclName,1,8) ~= "autoACL_" then
local node = temp_acl_nodes[aclName] or temp_acl_nodes["Default"]
if node then
totalAdded = totalAdded + aACLLoad ( acl, node )
end
end
end
if totalAdded > 0 then
outputServerLog ( "Admin access list successfully updated " )
outputConsole ( "Admin access list successfully updated " )
outputDebugString ( "Admin added " .. totalAdded .. " missing rights" )
end
xmlUnloadFile ( node )
else
outputServerLog ( "Failed to install admin access list - File missing" )
outputConsole ( "Failed to install admin access list - File missing" )
end
end
function aACLLoad ( acl, node )
local added = 0
local rights = 0
while ( xmlFindChild ( node, "right", rights ) ~= false ) do
local rightNode = xmlFindChild ( node, "right", rights )
local rightName = xmlNodeGetAttribute ( rightNode, "name" )
local rightAccess = xmlNodeGetAttribute ( rightNode, "access" )
if ( ( rightName ) and ( rightAccess ) ) then
-- Add if missing from this acl
if not aclRightExists ( acl, rightName ) then
aclSetRight ( acl, rightName, rightAccess == "true" )
added = added + 1
end
end
rights = rights + 1
end
return added
end
function aclGetAccount ( player )
local account = getPlayerAccount ( player )
if ( isGuestAccount ( account ) ) then return false
else return "user."..getAccountName ( account ) end
end
function aclGetAccountGroups ( account )
local acc = getAccountName ( account )
if ( not acc ) then return false end
local res = {}
acc = "user."..acc
local all = "user.*"
for ig, group in ipairs ( aclGroupList() ) do
for io, object in ipairs ( aclGroupListObjects ( group ) ) do
if ( ( acc == object ) or ( all == object ) ) then
table.insert ( res, aclGroupGetName ( group ) )
break
end
end
end
return res
end
function aclRightExists( acl, right )
for _,name in ipairs( aclListRights( acl ) ) do
if name == right then
return true
end
end
return false
end
| mit |
ioiasff/khp | bot/bot.lua | 1 | 6661 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
local f = assert(io.popen('/usr/bin/git describe --tags', 'r'))
VERSION = assert(f:read('*a'))
f:close()
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
-- vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
-- See plugins/isup.lua as an example for cron
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
print('\27[36mNot valid: Telegram message\27[39m')
return false
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"9gag",
"eur",
"echo",
"btc",
"get",
"giphy",
"google",
"gps",
"help",
"id",
"images",
"img_google",
"location",
"media",
"plugins",
"channels",
"set",
"stats",
"time",
"version",
"weather",
"xkcd",
"youtube" },
sudo_users = {152485254,152350938},
disabled_channels = {}
}
serialize_to_file(config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
--vardump (chat)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 5 mins
postpone (cron_plugins, false, 5*60.0)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
12-South-Studios/realmmud | Data/setup/terrain.lua | 1 | 5741 | -- TERRAIN.LUA
-- This is the terrain data file
-- Revised: 2012.03.24
-- Author: Jason Murdick
f = loadfile(GetAppSetting("dataPath") .. "\\modules\\module_base.lua")();
systemLog("=================== REALMMUD SETUP - TERRAIN ===================");
newTerrain = createTerrain("Void");
terrain.this = newTerrain;
terrain.this.Cost = 0;
terrain.this.IsLitBySun = false;
terrain.this.Description = "Nothingness, empty";
-- Town terrains
newTerrain = createTerrain("Dirt Path");
terrain.this = newTerrain;
terrain.this.Cost = 2;
terrain.this.Skill = "streetwise";
terrain.this.IsLitBySun = true;
terrain.this.Description = "A rough path of beaten dirt";
terrain.this:AddRestrictedMovementMode(MovementMode.Swimming);
terrain.this:AddRestrictedMovementMode(MovementMode.Climbing);
newTerrain = createTerrain("Cobblestone Road");
terrain.this = newTerrain;
terrain.this.Cost = 1;
terrain.this.Skill = "streetwise";
terrain.this.IsLitBySun = true;
terrain.this.Description = "A road of carefully placed cobblestones";
terrain.this:AddRestrictedMovementMode(MovementMode.Swimming);
terrain.this:AddRestrictedMovementMode(MovementMode.Climbing);
newTerrain = createTerrain("Interior");
terrain.this = newTerrain;
terrain.this.Cost = 1;
terrain.this.Skill = "streetwise";
terrain.this.IsLitBySun = false;
terrain.this.Description = "The interior of a structure";
terrain.this:AddRestrictedMovementMode(MovementMode.Swimming);
terrain.this:AddRestrictedMovementMode(MovementMode.Climbing);
newTerrain = createTerrain("Stone Wall");
terrain.this = newTerrain;
terrain.this.Cost = 5;
terrain.this.Skill = "climbing";
terrain.this.IsLitBySun = true;
terrain.this.Description = "A wall of stacked stone.";
terrain.this:AddRestrictedMovementMode(MovementMode.Climbing);
-- Wilderness Terrain
newTerrain = createTerrain("Grassland");
terrain.this = newTerrain;
terrain.this.Cost = 2;
terrain.this.Skill = "pathfinding";
terrain.this.IsLitBySun = true;
terrain.this.Description = "Flowing knee-high grass";
terrain.this:AddRestrictedMovementMode(MovementMode.Swimming);
terrain.this:AddRestrictedMovementMode(MovementMode.Climbing);
newTerrain = createTerrain("Light Forest");
terrain.this = newTerrain;
terrain.this.Cost = 5;
terrain.this.Skill = "pathfinding";
terrain.this.IsLitBySun = true;
terrain.this.Description = "A forest of smaller, younger trees";
terrain.this:AddRestrictedMovementMode(MovementMode.Swimming);
terrain.this:AddRestrictedMovementMode(MovementMode.Climbing);
newTerrain = createTerrain("Heavy Forest");
terrain.this = newTerrain;
terrain.this.Cost = 10;
terrain.this.Skill = "nature";
terrain.this.IsLitBySun = true;
terrain.this.Description = "A forest of older larger trees";
terrain.this:AddRestrictedMovementMode(MovementMode.Flying);
terrain.this:AddRestrictedMovementMode(MovementMode.Swimming);
terrain.this:AddRestrictedMovementMode(MovementMode.Climbing);
newTerrain = createTerrain("Primeval Forest");
terrain.this = newTerrain;
terrain.this.Cost = 20;
terrain.this.Skill = "nature";
terrain.this.IsLitBySun = true;
terrain.this.Description = "An ancient forest of huge, primeval trees";
terrain.this:AddRestrictedMovementMode(MovementMode.Flying);
terrain.this:AddRestrictedMovementMode(MovementMode.Swimming);
terrain.this:AddRestrictedMovementMode(MovementMode.Climbing);
newTerrain = createTerrain("Massive Tree");
terrain.this = newTerrain;
terrain.this.Cost = 20;
terrain.this.Skill = "climbing";
terrain.this.IsLitBySun = true;
terrain.this.Description = "The trunk or branch of a massive tree.";
terrain.this:AddRestrictedMovementMode(MovementMode.Climbing);
-- Water Terrain
-- Underground Terrain
newTerrain = createTerrain("Smooth Cave");
terrain.this = newTerrain;
terrain.this.Cost = 2;
terrain.this.Skill = "dungeoneering";
terrain.this.IsLitBySun = false;
terrain.this.Description = "The interior of a worn cave";
terrain.this:AddRestrictedMovementMode(MovementMode.Flying);
terrain.this:AddRestrictedMovementMode(MovementMode.Swimming);
terrain.this:AddRestrictedMovementMode(MovementMode.Climbing);
newTerrain = createTerrain("Rough Cave");
terrain.this = newTerrain;
terrain.this.Cost = 5;
terrain.this.Skill = "spelunking";
terrain.this.IsLitBySun = false;
terrain.this.Description = "The interior of a rough cave";
terrain.this:AddRestrictedMovementMode(MovementMode.Flying);
terrain.this:AddRestrictedMovementMode(MovementMode.Swimming);
terrain.this:AddRestrictedMovementMode(MovementMode.Climbing);
-- Desert Terrain
newTerrain = createTerrain("Desert");
terrain.this = newTerrain;
terrain.this.Cost = 5;
terrain.this.Skill = "desert survival";
terrain.this.IsLitBySun = true;
terrain.this.Description = "Sandy desert";
terrain.this:AddRestrictedMovementMode(MovementMode.Flying);
terrain.this:AddRestrictedMovementMode(MovementMode.Swimming);
terrain.this:AddRestrictedMovementMode(MovementMode.Climbing);
-- Swamp Terrain
newTerrain = createTerrain("Marsh");
terrain.this = newTerrain;
terrain.this.Cost = 6;
terrain.this.Skill = "pathfinding";
terrain.this.IsLitBySun = true;
terrain.this.Description = "Wet, sodden ground.";
terrain.this:AddRestrictedMovementMode(MovementMode.Flying);
terrain.this:AddRestrictedMovementMode(MovementMode.Swimming);
terrain.this:AddRestrictedMovementMode(MovementMode.Climbing);
newTerrain = createTerrain("Swamp");
terrain.this = newTerrain;
terrain.this.Cost = 10;
terrain.this.Skill = "nature";
terrain.this.IsLitBySun = true;
terrain.this.Description = "Knee-deep water and muck-filled bogs.";
terrain.this:AddRestrictedMovementMode(MovementMode.Flying);
terrain.this:AddRestrictedMovementMode(MovementMode.Swimming);
terrain.this:AddRestrictedMovementMode(MovementMode.Climbing);
-- Snow Terrain
-- Sky Terrain
-- Cliff Terrain
-- EOF | gpl-2.0 |
moodlIMyIl/DEVTSHAKE | plugins/lock_join.lua | 10 | 1121 | --[[
_____ _ _ _ _____ Dev @lIMyIl
|_ _|__| |__ / \ | | _| ____| Dev @li_XxX_il
| |/ __| '_ \ / _ \ | |/ / _| Dev @h_k_a
| |\__ \ | | |/ ___ \| <| |___ Dev @Aram_omar22
|_||___/_| |_/_/ \_\_|\_\_____| Dev @IXX_I_XXI
CH > @lTSHAKEl_CH
--]]
local function run (msg, matches)
local data = load_data(_config.moderation.data)
if matches[1] == 'chat_add_user_link' then
local user_id = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['join'] == 'yes' then
kick_user(user_id, msg.to.id)
end
end
end
end
end
return {
patterns = {
"^!!tgservice (chat_add_user_link)$"
},
run = run
}
--[[
_____ _ _ _ _____ Dev @lIMyIl
|_ _|__| |__ / \ | | _| ____| Dev @li_XxX_il
| |/ __| '_ \ / _ \ | |/ / _| Dev @h_k_a
| |\__ \ | | |/ ___ \| <| |___ Dev @Aram_omar22
|_||___/_| |_/_/ \_\_|\_\_____| Dev @IXX_I_XXI
CH > @lTSHAKEl_CH
--]]
| gpl-2.0 |
sumefsp/zile | lib/zz/commands/window.lua | 1 | 4277 | -- Window handling commands.
--
-- Copyright (c) 2010-2014 Free Software Foundation, Inc.
--
-- This file is part of GNU Zile.
--
-- 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 3, or (at your option)
-- any later version.
--
-- This program is distributed in the hope that it will be useful, but
-- WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
local eval = require "zz.eval"
local Defun = eval.Defun
Defun ("delete_window",
[[
Remove the current window from the screen.
]],
true,
function ()
if #windows == 1 then
minibuf_error ('Attempt to delete sole ordinary window')
return false
end
delete_window (cur_wp)
end
)
Defun ("enlarge_window",
[[
Make current window one line bigger.
]],
true,
function ()
if #windows == 1 then
return false
end
local wp = cur_wp.next
if not wp or wp.fheight < 3 then
for _, wp in ipairs (windows) do
if wp.next == cur_wp then
if wp.fheight < 3 then
return false
end
break
end
end
if cur_wp == windows[#windows] and cur_wp.next.fheight < 3 then
return false
end
wp.fheight = wp.fheight - 1
wp.eheight = wp.eheight - 1
if wp.topdelta >= wp.eheight then
recenter (wp)
end
cur_wp.fheight = cur_wp.fheight + 1
cur_wp.eheight = cur_wp.eheight + 1
end
end
)
Defun ("shrink_window",
[[
Make current window one line smaller.
]],
true,
function ()
if #windows == 1 or cur_wp.fheight < 3 then
return false
end
local next_wp = window_next (cur_wp)
next_wp.fheight = next_wp.fheight + 1
next_wp.eheight = next_wp.eheight + 1
cur_wp.fheight = cur_wp.fheight - 1
cur_wp.eheight = cur_wp.eheight - 1
if cur_wp.topdelta >= cur_wp.eheight then
recenter (next_wp)
end
end
)
Defun ("delete_other_windows",
[[
Make the selected window fill the screen.
]],
true,
function ()
for _, wp in ipairs (table.clone (windows)) do
if wp ~= cur_wp then
delete_window (wp)
end
end
end
)
Defun ("other_window",
[[
Select the first different window on the screen.
All windows are arranged in a cyclic order.
This command selects the window one step away in that order.
]],
true,
function ()
set_current_window (window_next (cur_wp))
end
)
Defun ("split_window",
[[
Split current window into two windows, one above the other.
Both windows display the same buffer now current.
]],
true,
split_window
)
Defun ("recenter",
[[
Center point in selected window and redisplay frame.
]],
true,
interactive_recenter
)
Defun ("screen_height",
[[
The total number of lines available for display on the screen.
]],
true,
function ()
minibuf_write (tostring (term_height ()))
end
)
Defun ("screen_width",
[[
The total number of lines available for display on the screen.
]],
true,
function ()
minibuf_write (tostring (term_width ()))
end
)
Defun ("set_screen_height",
[[
Set the usable number of lines for display on the screen.
]],
true,
function (lines)
local ok, errmsg = term_resize (lines or term_height (), term_width ())
if not ok then
minibuf_error (errmsg)
end
return ok
end
)
Defun ("set_screen_size",
[[
Set the number of usable lines and columns for display on the screen.
]],
true,
function (lines, cols)
local ok, errmsg = term_resize (lines or term_height (),
cols or term_width ())
if not ok then
minibuf_error (errmsg)
end
return ok
end
)
Defun ("set_screen_width",
[[
Set the usable number of columns for display on the screen.
]],
true,
function (cols)
local ok, errmsg = term_resize (term_height (), cols or term_width ())
if not ok then
minibuf_error (errmsg)
end
return ok
end
)
| gpl-3.0 |
mrmhxx82/JokerBot | bot/seedbot.lua | 1 | 10365 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '2'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
if redis:get("bot:markread") then
if redis:get("bot:markread") == "on" then
mark_read(receiver, ok_cb, false)
end
end
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"onservice",
"inrealm",
"ingroup",
"inpm",
"banhammer",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"broadcast",
"download_media",
"invite",
"all",
"leave_ban",
"admin"
"texttosticker";
"tophoto";
"sticker";
},
sudo_users = {110626080,103649648,143723991,111020322,0,tonumber(our_id)},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
about_text = [[Teleseed v2 - Open Source
An advance Administration bot based on yagop/telegram-bot
https://github.com/SEEDTEAM/TeleSeed
Our team!
Alphonse (@Iwals)
I M /-\ N (@Imandaneshi)
Siyanew (@Siyanew)
Rondoozle (@Potus)
Seyedan (@Seyedan25)
Special thanks to:
Juan Potato
Siyanew
Topkecleon
Vamptacus
Our channels:
English: @TeleSeedCH
Persian: @IranSeed
]],
help_text_realm = [[
Realm Commands:
!creategroup [name]
Create a group
!createrealm [name]
Create a realm
!setname [name]
Set realm name
!setabout [group_id] [text]
Set a group's about text
!setrules [grupo_id] [text]
Set a group's rules
!lock [grupo_id] [setting]
Lock a group's setting
!unlock [grupo_id] [setting]
Unock a group's setting
!wholist
Get a list of members in group/realm
!who
Get a file of members in group/realm
!type
Get group type
!kill chat [grupo_id]
Kick all memebers and delete group
!kill realm [realm_id]
Kick all members and delete realm
!addadmin [id|username]
Promote an admin by id OR username *Sudo only
!removeadmin [id|username]
Demote an admin by id OR username *Sudo only
!list groups
Get a list of all groups
!list realms
Get a list of all realms
!log
Get a logfile of current group or realm
!broadcast [text]
!broadcast Hello !
Send text to all groups
» Only sudo users can run this command
!bc [group_id] [text]
!bc 123456789 Hello !
This command will send text to [group_id]
» U can use both "/" and "!"
» Only mods, owner and admin can add bots in group
» Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
» Only owner can use res,setowner,promote,demote and log commands
]],
help_text = [[
Commands list :
!kick [username|id]
You can also do it by reply
!ban [ username|id]
You can also do it by reply
!unban [id]
You can also do it by reply
!who
Members list
!modlist
Moderators list
!promote [username]
Promote someone
!demote [username]
Demote someone
!kickme
Will kick user
!about
Group description
!setphoto
Set and locks group photo
!setname [name]
Set group name
!rules
Group rules
!id
Return group id or user id
!help
Get commands list
!lock [member|name|bots|leave]
Locks [member|name|bots|leaveing]
!unlock [member|name|bots|leave]
Unlocks [member|name|bots|leaving]
!set rules [text]
Set [text] as rules
!set about [text]
Set [text] as about
!settings
Returns group settings
!newlink
Create/revoke your group link
!link
Returns group link
!owner
Returns group owner id
!setowner [id]
Will set id as owner
!setflood [value]
Set [value] as flood sensitivity
!stats
Simple message statistics
!save [value] [text]
Save [text] as [value]
!get [value]
Returns text of [value]
!clean [modlist|rules|about]
Will clear [modlist|rules|about] and set it to nil
!res [username]
Returns user id
!log
Will return group logs
!banlist
Will return group ban list
» U can use both "/" and "!"
» Only mods, owner and admin can add bots in group
» Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
» Only owner can use res,setowner,promote,demote and log commands
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all')))
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
AliKhodadad/zed-spam | plugins/plugins.lua | 325 | 6164 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'. '..v..' '..status..'\n'
end
end
local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled'
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..v..' '..status..'\n'
end
end
local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return 'Plugin '..plugin_name..' is enabled'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return 'Plugin '..plugin_name..' does not exists'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return 'Plugin '..name..' does not exists'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return 'Plugin '..name..' not enabled'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "Plugin doesn't exists"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return 'Plugin '..plugin..' disabled on this chat'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'This plugin is not disabled'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return 'Plugin '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == 'enable' and matches[3] == 'chat' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == 'disable' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plugins disable [plugin] chat : disable plugin only this chat.",
"!plugins enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plugins : list all plugins.",
"!plugins enable [plugin] : enable plugin.",
"!plugins disable [plugin] : disable plugin.",
"!plugins reload : reloads all plugins." },
},
patterns = {
"^!plugins$",
"^!plugins? (enable) ([%w_%.%-]+)$",
"^!plugins? (disable) ([%w_%.%-]+)$",
"^!plugins? (enable) ([%w_%.%-]+) (chat)",
"^!plugins? (disable) ([%w_%.%-]+) (chat)",
"^!plugins? (reload)$" },
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end | gpl-2.0 |
ashkanpj/fire | plugins/plugins.lua | 325 | 6164 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'. '..v..' '..status..'\n'
end
end
local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled'
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..v..' '..status..'\n'
end
end
local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return 'Plugin '..plugin_name..' is enabled'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return 'Plugin '..plugin_name..' does not exists'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return 'Plugin '..name..' does not exists'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return 'Plugin '..name..' not enabled'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "Plugin doesn't exists"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return 'Plugin '..plugin..' disabled on this chat'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'This plugin is not disabled'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return 'Plugin '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == 'enable' and matches[3] == 'chat' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == 'disable' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plugins disable [plugin] chat : disable plugin only this chat.",
"!plugins enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plugins : list all plugins.",
"!plugins enable [plugin] : enable plugin.",
"!plugins disable [plugin] : disable plugin.",
"!plugins reload : reloads all plugins." },
},
patterns = {
"^!plugins$",
"^!plugins? (enable) ([%w_%.%-]+)$",
"^!plugins? (disable) ([%w_%.%-]+)$",
"^!plugins? (enable) ([%w_%.%-]+) (chat)",
"^!plugins? (disable) ([%w_%.%-]+) (chat)",
"^!plugins? (reload)$" },
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end | gpl-2.0 |
hfjgjfg/amir2 | plugins/plugins.lua | 325 | 6164 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'. '..v..' '..status..'\n'
end
end
local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled'
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..v..' '..status..'\n'
end
end
local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return 'Plugin '..plugin_name..' is enabled'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return 'Plugin '..plugin_name..' does not exists'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return 'Plugin '..name..' does not exists'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return 'Plugin '..name..' not enabled'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "Plugin doesn't exists"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return 'Plugin '..plugin..' disabled on this chat'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'This plugin is not disabled'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return 'Plugin '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == 'enable' and matches[3] == 'chat' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == 'disable' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plugins disable [plugin] chat : disable plugin only this chat.",
"!plugins enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plugins : list all plugins.",
"!plugins enable [plugin] : enable plugin.",
"!plugins disable [plugin] : disable plugin.",
"!plugins reload : reloads all plugins." },
},
patterns = {
"^!plugins$",
"^!plugins? (enable) ([%w_%.%-]+)$",
"^!plugins? (disable) ([%w_%.%-]+)$",
"^!plugins? (enable) ([%w_%.%-]+) (chat)",
"^!plugins? (disable) ([%w_%.%-]+) (chat)",
"^!plugins? (reload)$" },
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end | gpl-2.0 |
lipp/tinker | tinker/current_12.lua | 1 | 2122 | return {
methods = {
get_current = {
funcid = 1,
outs = 'h'
},
calibrate = {
funcid = 2
},
is_over_current = {
funcid = 3,
outs = 'b',
format_outs =
function(over)
return over > 0
end
},
get_analog_value = {
funcid = 4,
outs = 'H'
},
set_current_callback_period = {
funcid = 5,
ins = 'I'
},
get_current_callback_period = {
funcid = 6,
outs = 'I'
},
set_analog_value_callback_period = {
funcid = 7,
ins = 'I'
},
get_analog_value_callback_period = {
funcid = 8,
outs = 'I'
},
set_current_callback_threshold = {
funcid = 9,
ins = 'Ahh',
format_ins =
function(option,min,max)
if #option ~= 1 then
error('invalid option value')
end
return option,min,max
end
},
get_current_callback_threshold = {
funcid = 10,
outs = 'A1hh'
},
set_analog_value_callback_threshold = {
funcid = 11,
ins = 'AHH',
format_ins =
function(option,min,max)
if #option ~= 1 then
error('invalid option value')
end
return option,min,max
end
},
get_analog_value_callback_threshold = {
funcid = 12,
outs = 'A1HH'
},
set_debounce_period = {
funcid = 13,
ins = 'I'
},
get_debounce_period = {
funcid = 14,
outs = 'I'
}
},
callbacks = {
current = {
funcid = 15,
ins = 'h'
},
analog_value = {
funcid = 16,
ins = 'H'
},
current_reached = {
funcid = 17,
ins = 'h'
},
analog_value_reached = {
funcid = 18,
ins = 'H'
},
over_current = {
funcid = 19
}
}
}
| mit |
FarGroup/FarManager | plugins/emenu/Hotkey.lua | 3 | 1677 | -- Hotkeys [Shift-]Apps, Alt-[Shift-]Apps and Ctrl-Apps to show context menu
Macro {
area="Shell"; key="Apps"; flags=""; action = function()
Keys("F11 x Enter") if Menu.Id == "5099B83C-4222-4325-95A6-F6FC4635DED6" then Keys("2") end
end;
}
Macro {
area="Shell"; key="ShiftApps"; flags=""; action = function()
Keys("F11 x Enter") if Menu.Id == "5099B83C-4222-4325-95A6-F6FC4635DED6" then Keys("2") end
end;
}
Macro {
area="Shell"; key="AltApps"; flags=""; action = function()
Keys("F11 x Enter") if Menu.Id == "5099B83C-4222-4325-95A6-F6FC4635DED6" then Keys("1") end
end;
}
Macro {
area="Shell"; key="AltShiftApps"; flags=""; action = function()
Keys("F11 x Enter") if Menu.Id == "5099B83C-4222-4325-95A6-F6FC4635DED6" then Keys("1") end
end;
}
Macro {
area="Shell"; key="CtrlApps"; flags=""; action = function()
Keys("F11 x Enter")
end;
}
Macro {
area="Tree"; key="Apps"; flags=""; action = function()
Keys("F11 x Enter") if Menu.Id == "5099B83C-4222-4325-95A6-F6FC4635DED6" then Keys("2") end
end;
}
Macro {
area="Tree"; key="ShiftApps"; flags=""; action = function()
Keys("F11 x Enter") if Menu.Id == "5099B83C-4222-4325-95A6-F6FC4635DED6" then Keys("2") end
end;
}
Macro {
area="Tree"; key="AltApps"; flags=""; action = function()
Keys("F11 x Enter") if Menu.Id == "5099B83C-4222-4325-95A6-F6FC4635DED6" then Keys("1") end
end;
}
Macro {
area="Tree"; key="AltShiftApps"; flags=""; action = function()
Keys("F11 x Enter") if Menu.Id == "5099B83C-4222-4325-95A6-F6FC4635DED6" then Keys("1") end
end;
}
Macro {
area="Tree"; key="CtrlApps"; flags=""; action = function()
Keys("F11 x Enter")
end;
}
| bsd-3-clause |
lizh06/premake-core | modules/xcode/xcode_project.lua | 5 | 6212 | ---
-- xcode/xcode4_project.lua
-- Generate an Xcode project file.
-- Author Jason Perkins
-- Modified by Mihai Sebea
-- Copyright (c) 2009-2015 Jason Perkins and the Premake project
---
local p = premake
local m = p.modules.xcode
local xcode = p.modules.xcode
local project = p.project
local config = p.config
local fileconfig = p.fileconfig
local tree = p.tree
--
-- Create a tree corresponding to what is shown in the Xcode project browser
-- pane, with nodes for files and folders, resources, frameworks, and products.
--
-- @param prj
-- The project being generated.
-- @returns
-- A tree, loaded with metadata, which mirrors Xcode's view of the project.
--
function xcode.buildprjtree(prj)
local tr = project.getsourcetree(prj, nil , false)
tr.project = prj
-- create a list of build configurations and assign IDs
tr.configs = {}
for cfg in project.eachconfig(prj) do
cfg.xcode = {}
cfg.xcode.targetid = xcode.newid(prj.xcode.projectnode.name, cfg.buildcfg, "target")
cfg.xcode.projectid = xcode.newid(tr.name, cfg.buildcfg)
table.insert(tr.configs, cfg)
end
-- convert localized resources from their filesystem layout (English.lproj/MainMenu.xib)
-- to Xcode's display layout (MainMenu.xib/English).
tree.traverse(tr, {
onbranch = function(node)
if path.getextension(node.name) == ".lproj" then
local lang = path.getbasename(node.name) -- "English", "French", etc.
-- create a new language group for each file it contains
for _, filenode in ipairs(node.children) do
local grpnode = node.parent.children[filenode.name]
if not grpnode then
grpnode = tree.insert(node.parent, tree.new(filenode.name))
grpnode.kind = "vgroup"
end
-- convert the file node to a language node and add to the group
filenode.name = path.getbasename(lang)
tree.insert(grpnode, filenode)
end
-- remove this directory from the tree
tree.remove(node)
end
end
})
-- the special folder "Frameworks" lists all linked frameworks
tr.frameworks = tree.new("Frameworks")
for cfg in project.eachconfig(prj) do
for _, link in ipairs(config.getlinks(cfg, "system", "fullpath")) do
local name = path.getname(link)
if xcode.isframework(name) and not tr.frameworks.children[name] then
node = tree.insert(tr.frameworks, tree.new(name))
node.path = link
end
end
end
-- only add it to the tree if there are frameworks to link
if #tr.frameworks.children > 0 then
tree.insert(tr, tr.frameworks)
end
-- the special folder "Products" holds the target produced by the project; this
-- is populated below
tr.products = tree.insert(tr, tree.new("Products"))
-- the special folder "Projects" lists sibling project dependencies
tr.projects = tree.new("Projects")
for _, dep in ipairs(project.getdependencies(prj, "sibling", "object")) do
-- create a child node for the dependency's xcodeproj
local xcpath = xcode.getxcodeprojname(dep)
local xcnode = tree.insert(tr.projects, tree.new(path.getname(xcpath)))
xcnode.path = xcpath
xcnode.project = dep
xcnode.productgroupid = xcode.newid(xcnode.name, "prodgrp")
xcnode.productproxyid = xcode.newid(xcnode.name, "prodprox")
xcnode.targetproxyid = xcode.newid(xcnode.name, "targprox")
xcnode.targetdependid = xcode.newid(xcnode.name, "targdep")
-- create a grandchild node for the dependency's link target
local lprj = premake.workspace.findproject(prj.workspace, dep.name)
local cfg = project.findClosestMatch(lprj, prj.configurations[1])
node = tree.insert(xcnode, tree.new(cfg.linktarget.name))
node.path = cfg.linktarget.fullpath
node.cfg = cfg
end
if #tr.projects.children > 0 then
tree.insert(tr, tr.projects)
end
-- Final setup
tree.traverse(tr, {
onnode = function(node)
-- assign IDs to every node in the tree
node.id = xcode.newid(node.name, nil, node.path)
node.isResource = xcode.isItemResource(prj, node)
-- assign build IDs to buildable files
if xcode.getbuildcategory(node) then
node.buildid = xcode.newid(node.name, "build", node.path)
end
-- remember key files that are needed elsewhere
if string.endswith(node.name, "Info.plist") then
tr.infoplist = node
end
end
}, true)
-- Plug in the product node into the Products folder in the tree. The node
-- was built in xcode.prepareWorkspace() in xcode_common.lua; it contains IDs
-- that are necessary for inter-project dependencies
node = tree.insert(tr.products, prj.xcode.projectnode)
node.kind = "product"
node.path = node.cfg.buildtarget.fullpath
node.cfgsection = xcode.newid(node.name, "cfg")
node.resstageid = xcode.newid(node.name, "rez")
node.sourcesid = xcode.newid(node.name, "src")
node.fxstageid = xcode.newid(node.name, "fxs")
return tr
end
---
-- Generate an Xcode .xcodeproj for a Premake project.
---
m.elements.project = function(prj)
return {
m.header,
}
end
function m.generateProject(prj)
local tr = xcode.buildprjtree(prj)
p.callArray(m.elements.project, prj)
xcode.PBXBuildFile(tr)
xcode.PBXContainerItemProxy(tr)
xcode.PBXFileReference(tr)
xcode.PBXFrameworksBuildPhase(tr)
xcode.PBXGroup(tr)
xcode.PBXNativeTarget(tr)
xcode.PBXProject(tr)
xcode.PBXReferenceProxy(tr)
xcode.PBXResourcesBuildPhase(tr)
xcode.PBXShellScriptBuildPhase(tr)
xcode.PBXSourcesBuildPhase(tr)
xcode.PBXTargetDependency(tr)
xcode.PBXVariantGroup(tr)
xcode.XCBuildConfiguration(tr)
xcode.XCBuildConfigurationList(tr)
xcode.footer(prj)
end
function m.header(prj)
p.w('// !$*UTF8*$!')
p.push('{')
p.w('archiveVersion = 1;')
p.w('classes = {')
p.w('};')
p.w('objectVersion = 46;')
p.push('objects = {')
p.w()
end
function xcode.footer(prj)
p.pop('};')
p.w('rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;')
p.pop('}')
end
| bsd-3-clause |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/tests/lua-tests/src/ComponentTest/projectile.lua | 3 | 1606 |
local projectile = {
sceneLua = nil,
onEnter = function(self)
local sceneScriptComponent = tolua.cast(self:getOwner():getParent():getComponent("sceneLuaComponent"), "cc.ComponentLua")
self.sceneLua = sceneScriptComponent:getScriptObject()
end,
update = function(self, dt)
-- if there is any enemy collides with this projectile, then
-- remove this projectile and all collided enemies
local owner = self:getOwner()
local projectileX, projectileY = owner:getPosition()
local projectileContentSize = owner:getContentSize()
local projectileRect = cc.rect(projectileX, projectileY,
projectileContentSize.width, projectileContentSize.height)
local scene = owner:getParent()
local enemies = self.sceneLua.enemies
--local enemies = self:getEnemies()
local removeOwner = false
for i = #enemies, 1, -1 do
local enemy = enemies[i]
local enemyX, enemyY = enemy:getPosition()
local enemyContentSize = enemy:getContentSize()
local enemyRect = cc.rect(enemyX, enemyY,
enemyContentSize.width, enemyContentSize.height)
if cc.rectIntersectsRect(projectileRect, enemyRect) then
table.remove(enemies, i)
scene:removeChild(enemy, true)
self.sceneLua:inscreaseCount()
removeOwner = true
end
end
if removeOwner == true then
scene:removeChild(owner, true)
end
end,
}
return projectile
| mit |
ioiasff/khp | plugins/btc.lua | 289 | 1375 | -- See https://bitcoinaverage.com/api
local function getBTCX(amount,currency)
local base_url = 'https://api.bitcoinaverage.com/ticker/global/'
-- Do request on bitcoinaverage, the final / is critical!
local res,code = https.request(base_url..currency.."/")
if code ~= 200 then return nil end
local data = json:decode(res)
-- Easy, it's right there
text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid
-- If we have a number as second parameter, calculate the bitcoin amount
if amount~=nil then
btc = tonumber(amount) / tonumber(data.ask)
text = text.."\n "..currency .." "..amount.." = BTC "..btc
end
return text
end
local function run(msg, matches)
local cur = 'EUR'
local amt = nil
-- Get the global match out of the way
if matches[1] == "!btc" then
return getBTCX(amt,cur)
end
if matches[2] ~= nil then
-- There is a second match
amt = matches[2]
cur = string.upper(matches[1])
else
-- Just a EUR or USD param
cur = string.upper(matches[1])
end
return getBTCX(amt,cur)
end
return {
description = "Bitcoin global average market value (in EUR or USD)",
usage = "!btc [EUR|USD] [amount]",
patterns = {
"^!btc$",
"^!btc ([Ee][Uu][Rr])$",
"^!btc ([Uu][Ss][Dd])$",
"^!btc (EUR) (%d+[%d%.]*)$",
"^!btc (USD) (%d+[%d%.]*)$"
},
run = run
}
| gpl-2.0 |
minecraftgame-andrd/minecraftgame | plugins/info_en.lua | 3 | 8021 | do
local Arian = 112392827 --put your id here(BOT OWNER ID)
local function setrank(msg, name, value) -- setrank function
local hash = nil
if msg.to.type == 'chat' then
hash = 'rank:'..msg.to.id..':variables'
end
if hash then
redis:hset(hash, name, value)
return send_msg('chat#id'..msg.to.id, 'set Rank for ('..name..') To : '..value, ok_cb, true)
end
end
local function res_user_callback(extra, success, result) -- /info <username> function
if success == 1 then
if result.username then
Username = '@'..result.username
else
Username = '----'
end
local text = 'Full name : '..(result.first_name or '')..' '..(result.last_name or '')..'\n'
..'User name: '..Username..'\n'
..'ID : '..result.id..'\n\n'
local hash = 'rank:'..extra.chat2..':variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == tonumber(Arian) then
text = text..'Rank : Executive Admin \n\n'
elseif is_admin2(result.id) then
text = text..'Rank : Admin \n\n'
elseif is_owner2(result.id, extra.chat2) then
text = text..'Rank : Owner \n\n'
elseif is_momod2(result.id, extra.chat2) then
text = text..'Rank : Moderator \n\n'
else
text = text..'Rank : Member \n\n'
end
else
text = text..'Rank : '..value..'\n\n'
end
local uhash = 'user:'..result.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.id..':'..extra.chat2
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n\n'
text = text..'@QuickGuardTEAM'
send_msg(extra.receiver, text, ok_cb, true)
else
send_msg(extra.receiver, ' Username not found.', ok_cb, false)
end
end
local function action_by_id(extra, success, result) -- /info <ID> function
if success == 1 then
if result.username then
Username = '@'..result.username
else
Username = '----'
end
local text = 'Full name : '..(result.first_name or '')..' '..(result.last_name or '')..'\n'
..'Username: '..Username..'\n'
..'ID : '..result.id..'\n\n'
local hash = 'rank:'..extra.chat2..':variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == tonumber(Arian) then
text = text..'Rank : Executive Admin \n\n'
elseif is_admin2(result.id) then
text = text..'Rank : Admin \n\n'
elseif is_owner2(result.id, extra.chat2) then
text = text..'Rank : Owner \n\n'
elseif is_momod2(result.id, extra.chat2) then
text = text..'Rank : Moderator \n\n'
else
text = text..'Rank : Member \n\n'
end
else
text = text..'Rank : '..value..'\n\n'
end
local uhash = 'user:'..result.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.id..':'..extra.chat2
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n\n'
text = text..'@QuickGuardTEAM'
send_msg(extra.receiver, text, ok_cb, true)
else
send_msg(extra.receiver, 'id not found.\nuse : /info @username', ok_cb, false)
end
end
local function action_by_reply(extra, success, result)-- (reply) /info function
if result.from.username then
Username = '@'..result.from.username
else
Username = '----'
end
local text = 'Full name : '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n'
..'Username : '..Username..'\n'
..'ID : '..result.from.id..'\n\n'
local hash = 'rank:'..result.to.id..':variables'
local value = redis:hget(hash, result.from.id)
if not value then
if result.from.id == tonumber(Arian) then
text = text..'Rank :Executive Admin \n\n'
elseif is_admin2(result.from.id) then
text = text..'Rank : Admin \n\n'
elseif is_owner2(result.from.id, result.to.id) then
text = text..'Rank : Owner \n\n'
elseif is_momod2(result.from.id, result.to.id) then
text = text..'Rank : Moderator \n\n'
else
text = text..'Rank : Member \n\n'
end
else
text = text..'Rank : '..value..'\n\n'
end
local user_info = {}
local uhash = 'user:'..result.from.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.from.id..':'..result.to.id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n\n'
text = text..'@QuickGuardTEAM'
send_msg(extra.receiver, text, ok_cb, true)
end
local function action_by_reply2(extra, success, result)
local value = extra.value
setrank(result, result.from.id, value)
end
local function run(msg, matches)
if matches[1]:lower() == 'setrank' then
local hash = 'usecommands:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
if not is_sudo(msg) then
return "کونده مگه تو بابامی؟"
end
local receiver = get_receiver(msg)
local Reply = msg.reply_id
if msg.reply_id then
local value = string.sub(matches[2], 1, 1000)
msgr = get_message(msg.reply_id, action_by_reply2, {receiver=receiver, Reply=Reply, value=value})
else
local name = string.sub(matches[2], 1, 50)
local value = string.sub(matches[3], 1, 1000)
local text = setrank(msg, name, value)
return text
end
end
if matches[1]:lower() == 'info' and not matches[2] then
local receiver = get_receiver(msg)
local Reply = msg.reply_id
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {receiver=receiver, Reply=Reply})
else
if msg.from.username then
Username = '@'..msg.from.username
else
Username = '----'
end
local text = 'First name : '..(msg.from.first_name or '----')..'\n'
local text = text..'Last name : '..(msg.from.last_name or '----')..'\n'
local text = text..'Username : '..Username..'\n'
local text = text..'ID : '..msg.from.id..'\n\n'
local hash = 'rank:'..msg.to.id..':variables'
if hash then
local value = redis:hget(hash, msg.from.id)
if not value then
if msg.from.id == tonumber(Arian) then
text = text..'Rank : Executive Admin \n\n'
elseif is_sudo(msg) then
text = text..'Rank : Admin \n\n'
elseif is_owner(msg) then
text = text..'Rank : Owner \n\n'
elseif is_momod(msg) then
text = text..'Rank :Moderator \n\n'
else
text = text..'Rank : Member \n\n'
end
else
text = text..'Rank : '..value..'\n'
end
end
local uhash = 'user:'..msg.from.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..msg.from.id..':'..msg.to.id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n\n'
if msg.to.type == 'chat' then
text = text..'Group name : '..msg.to.title..'\n'
text = text..'Group ID : '..msg.to.id
end
text = text..'\n\n@QuickGuardTEAM'
return send_msg(receiver, text, ok_cb, true)
end
end
if matches[1]:lower() == 'info' and matches[2] then
local user = matches[2]
local chat2 = msg.to.id
local receiver = get_receiver(msg)
if string.match(user, '^%d+$') then
user_info('user#id'..user, action_by_id, {receiver=receiver, user=user, text=text, chat2=chat2})
elseif string.match(user, '^@.+$') then
username = string.gsub(user, '@', '')
msgr = res_user(username, res_user_callback, {receiver=receiver, user=user, text=text, chat2=chat2})
end
end
end
return {
description = 'Know your information or the info of a chat members.',
usage = {
'!info: Return your info and the chat info if you are in one.',
'(Reply)!info: Return info of replied user if used by reply.',
'!info <id>: Return the info\'s of the <id>.',
'!info @<user_name>: Return the member @<user_name> information from the current chat.',
'!setrank <userid> <rank>: change members rank.',
'(Reply)!setrank <rank>: change members rank.',
},
patterns = {
"^([Ii][Nn][Ff][Oo])$",
"^([Ii][Nn][Ff][Oo]) (.*)$",
"^[#!/](info)$",
"^[#!/](info)(.*)$",
"^([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (%d+) (.*)$",
"^([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (.*)$"
},
run = run
}
end
| gpl-2.0 |
shadoalzupedy/shadow | plugins/q.lua | 1 | 1508 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄
#CODS CREATED BT @iq_plus
please join to Channel Oscar Team @OSCARBOTv2
▀▄ ▄▀ ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
do
local function oscar(extra, success, result) -- function result
local oscar_id = result.from.peer_id
local r = extra.r
if result.from then
if result.from.username then
username = result.from.username
else
username = "nil"
end --@iq_plus
end
local msg = result
local reply = msg['id']
local a = "مــــــــواح😘💋لسق😍عل شفة ☺️💋"
reply_msg(reply, a, ok_cb, true)
end
local function run(msg, matches)
local r = get_receiver(msg)
local e = msg['id']
local f = "تدلل استاذي 😻❣ هسه ابوسه الك 🌝❤️"
--by oscarteam
if matches[1] == "بوسه" and msg.reply_id then
msgr = get_message(msg.reply_id, oscar, {r=r, })
reply_msg(e, f, ok_cb, true)
end
if msg.text == "cods" then
send_large_msg(r, "by @iq_plus")
end
end
return {
patterns = {
"(احصره)$",
"(.*)"
},
run = run,
}
end
--By OscarTeam 👾 | gpl-2.0 |
osa1/language-lua | lua-5.3.1-tests/closure.lua | 6 | 5430 | -- $Id: closure.lua,v 1.58 2014/12/26 17:20:53 roberto Exp $
print "testing closures"
local A,B = 0,{g=10}
function f(x)
local a = {}
for i=1,1000 do
local y = 0
do
a[i] = function () B.g = B.g+1; y = y+x; return y+A end
end
end
local dummy = function () return a[A] end
collectgarbage()
A = 1; assert(dummy() == a[1]); A = 0;
assert(a[1]() == x)
assert(a[3]() == x)
collectgarbage()
assert(B.g == 12)
return a
end
local a = f(10)
-- force a GC in this level
local x = {[1] = {}} -- to detect a GC
setmetatable(x, {__mode = 'kv'})
while x[1] do -- repeat until GC
local a = A..A..A..A -- create garbage
A = A+1
end
assert(a[1]() == 20+A)
assert(a[1]() == 30+A)
assert(a[2]() == 10+A)
collectgarbage()
assert(a[2]() == 20+A)
assert(a[2]() == 30+A)
assert(a[3]() == 20+A)
assert(a[8]() == 10+A)
assert(getmetatable(x).__mode == 'kv')
assert(B.g == 19)
-- testing equality
a = {}
for i = 1, 5 do a[i] = function (x) return x + a + _ENV end end
assert(a[3] == a[4] and a[4] == a[5])
for i = 1, 5 do a[i] = function (x) return i + a + _ENV end end
assert(a[3] ~= a[4] and a[4] ~= a[5])
local function f()
return function (x) return math.sin(_ENV[x]) end
end
assert(f() == f())
-- testing closures with 'for' control variable
a = {}
for i=1,10 do
a[i] = {set = function(x) i=x end, get = function () return i end}
if i == 3 then break end
end
assert(a[4] == nil)
a[1].set(10)
assert(a[2].get() == 2)
a[2].set('a')
assert(a[3].get() == 3)
assert(a[2].get() == 'a')
a = {}
local t = {"a", "b"}
for i = 1, #t do
local k = t[i]
a[i] = {set = function(x, y) i=x; k=y end,
get = function () return i, k end}
if i == 2 then break end
end
a[1].set(10, 20)
local r,s = a[2].get()
assert(r == 2 and s == 'b')
r,s = a[1].get()
assert(r == 10 and s == 20)
a[2].set('a', 'b')
r,s = a[2].get()
assert(r == "a" and s == "b")
-- testing closures with 'for' control variable x break
for i=1,3 do
f = function () return i end
break
end
assert(f() == 1)
for k = 1, #t do
local v = t[k]
f = function () return k, v end
break
end
assert(({f()})[1] == 1)
assert(({f()})[2] == "a")
-- testing closure x break x return x errors
local b
function f(x)
local first = 1
while 1 do
if x == 3 and not first then return end
local a = 'xuxu'
b = function (op, y)
if op == 'set' then
a = x+y
else
return a
end
end
if x == 1 then do break end
elseif x == 2 then return
else if x ~= 3 then error() end
end
first = nil
end
end
for i=1,3 do
f(i)
assert(b('get') == 'xuxu')
b('set', 10); assert(b('get') == 10+i)
b = nil
end
pcall(f, 4);
assert(b('get') == 'xuxu')
b('set', 10); assert(b('get') == 14)
local w
-- testing multi-level closure
function f(x)
return function (y)
return function (z) return w+x+y+z end
end
end
y = f(10)
w = 1.345
assert(y(20)(30) == 60+w)
-- testing closures x repeat-until
local a = {}
local i = 1
repeat
local x = i
a[i] = function () i = x+1; return x end
until i > 10 or a[i]() ~= x
assert(i == 11 and a[1]() == 1 and a[3]() == 3 and i == 4)
-- testing closures created in 'then' and 'else' parts of 'if's
a = {}
for i = 1, 10 do
if i % 3 == 0 then
local y = 0
a[i] = function (x) local t = y; y = x; return t end
elseif i % 3 == 1 then
goto L1
error'not here'
::L1::
local y = 1
a[i] = function (x) local t = y; y = x; return t end
elseif i % 3 == 2 then
local t
goto l4
::l4a:: a[i] = t; goto l4b
error("should never be here!")
::l4::
local y = 2
t = function (x) local t = y; y = x; return t end
goto l4a
error("should never be here!")
::l4b::
end
end
for i = 1, 10 do
assert(a[i](i * 10) == i % 3 and a[i]() == i * 10)
end
print'+'
-- test for correctly closing upvalues in tail calls of vararg functions
local function t ()
local function c(a,b) assert(a=="test" and b=="OK") end
local function v(f, ...) c("test", f() ~= 1 and "FAILED" or "OK") end
local x = 1
return v(function() return x end)
end
t()
-- test for debug manipulation of upvalues
local debug = require'debug'
do
local a , b, c = 3, 5, 7
foo1 = function () return a+b end;
foo2 = function () return b+a end;
do
local a = 10
foo3 = function () return a+b end;
end
end
assert(debug.upvalueid(foo1, 1))
assert(debug.upvalueid(foo1, 2))
assert(not pcall(debug.upvalueid, foo1, 3))
assert(debug.upvalueid(foo1, 1) == debug.upvalueid(foo2, 2))
assert(debug.upvalueid(foo1, 2) == debug.upvalueid(foo2, 1))
assert(debug.upvalueid(foo3, 1))
assert(debug.upvalueid(foo1, 1) ~= debug.upvalueid(foo3, 1))
assert(debug.upvalueid(foo1, 2) == debug.upvalueid(foo3, 2))
assert(debug.upvalueid(string.gmatch("x", "x"), 1) ~= nil)
assert(foo1() == 3 + 5 and foo2() == 5 + 3)
debug.upvaluejoin(foo1, 2, foo2, 2)
assert(foo1() == 3 + 3 and foo2() == 5 + 3)
assert(foo3() == 10 + 5)
debug.upvaluejoin(foo3, 2, foo2, 1)
assert(foo3() == 10 + 5)
debug.upvaluejoin(foo3, 2, foo2, 2)
assert(foo3() == 10 + 3)
assert(not pcall(debug.upvaluejoin, foo1, 3, foo2, 1))
assert(not pcall(debug.upvaluejoin, foo1, 1, foo2, 3))
assert(not pcall(debug.upvaluejoin, foo1, 0, foo2, 1))
assert(not pcall(debug.upvaluejoin, print, 1, foo2, 1))
assert(not pcall(debug.upvaluejoin, {}, 1, foo2, 1))
assert(not pcall(debug.upvaluejoin, foo1, 1, print, 1))
print'OK'
| bsd-3-clause |
tinydanbo/Impoverished-Starfighter | game/enemies/stage1boss.lua | 1 | 10127 | Class = require "lib.hump.class"
Enemy = require "entities.enemy"
vector = require "lib.hump.vector"
EnemyBullet = require "entities.enemyBullet"
Explosion = require "game.particles.explosion"
EntityTypes = require "entities.types"
Stage1Boss = Class{__includes = Enemy,
init = function(self, x, y, state)
Enemy.init(self, x, y, state)
self.health = 6000
self.image = love.graphics.newImage("data/img/enemy/stage1boss/stage1boss.png")
self.energyBarFront = love.graphics.newImage("data/img/hud/energy-front.png")
self.energyBar = love.graphics.newImage("data/img/hud/boss-bar.png")
self.energyBarBack = love.graphics.newImage("data/img/hud/energy-back.png")
self.phase = 1
self.tick = 0
self.desiredPosition = vector(240, 160)
self.hitbox = {
x1 = x - 120,
x2 = x + 120,
y1 = y - 100,
y2 = y + 80
}
self.phaseTick = 0
self.schedule = {}
self:startPhase1()
end,
}
function Stage1Boss:update(dt)
self.tick = self.tick + dt
self.phaseTick = self.phaseTick + dt
local i = 1
for i,v in ipairs(self.schedule) do
local callback = self.schedule[i]
if callback[1] < self.phaseTick and callback[3] == false then
callback[3] = true
self[callback[2]](self)
else
i = i + 1
end
end
-- move to desired position
local difference = self.desiredPosition - self.position
if difference:len() > 10 then
local movement = difference:normalized() * 160
self:move(movement * dt)
end
end
function Stage1Boss:fireClumpCircle()
local player = self.state.player
local difference = player.position - self.position
local aimAt = difference:normalized()
local x,y = self.position:unpack()
for i=-5,5,1 do
local phi = (36*i) * (math.pi / 180)
for j=-2,2,1 do
local spreadAimAt = aimAt:rotated(phi+(j*0.05))
local bulletVel = spreadAimAt * 130
local newBullet = EnemyBullet(x+(spreadAimAt.x * 50), y+(spreadAimAt.y * 50), bulletVel.x, bulletVel.y, self.state)
self.state.manager:addEntity(newBullet, EntityTypes.ENEMY_BULLET)
end
end
end
function Stage1Boss:fireAimedSpread()
local player = self.state.player
local difference = player.position - self.position
local aimAt = difference:normalized()
local x,y = self.position:unpack()
for i=-1,1,2 do
local phi = (5*i) * (math.pi / 180)
local spreadAimAt = aimAt:rotated(phi)
local bulletVel = spreadAimAt * 460
local newBullet = EnemyBullet(x, y, bulletVel.x, bulletVel.y, self.state)
self.state.manager:addEntity(newBullet, EntityTypes.ENEMY_BULLET)
end
end
function Stage1Boss:fireAimedArc()
local player = self.state.player
local difference = player.position - self.position
local aimAt = difference:normalized()
local x,y = self.position:unpack()
local offset = math.random(-3, 3)
for i=-3+offset,3+offset,1 do
local phi = (i) * (math.pi / 180)
local spreadAimAt = aimAt:rotated(phi)
local bulletVel = spreadAimAt * 260
local newBullet = EnemyBullet(x, y, bulletVel.x, bulletVel.y, self.state)
self.state.manager:addEntity(newBullet, EntityTypes.ENEMY_BULLET)
end
end
function Stage1Boss:fireEnclosingBullets()
local player = self.state.player
local difference = player.position - self.position
local aimAt = difference:normalized()
local x,y = self.position:unpack()
for i=-1,1,2 do
local phi = (20*i) * (math.pi / 180)
local spreadAimAt = aimAt:rotated(phi)
local bulletVel = spreadAimAt * 360
local newBullet = EnemyBullet(x, y, bulletVel.x, bulletVel.y, self.state)
self.state.manager:addEntity(newBullet, EntityTypes.ENEMY_BULLET)
end
end
function Stage1Boss:fireRandom()
local x,y = self.position:unpack()
for i=1,4,1 do
local newBullet = EnemyBullet(x, y, math.random(-400, 400), 220+math.random(140), self.state)
self.state.manager:addEntity(newBullet, EntityTypes.ENEMY_BULLET)
end
end
function Stage1Boss:moveToNeutral()
self.desiredPosition.x = 240
self.desiredPosition.y = 160
end
function Stage1Boss:moveToLowerNeutral()
self.desiredPosition.x = 240
self.desiredPosition.y = 280
end
function Stage1Boss:explode()
local expl = Explosion(self.position.x + math.random(-113, 113), self.position.y + math.random(-104, 104), 0, 0, 1.4)
self.state.manager:addEntity(expl, EntityTypes.PARTICLE)
end
function Stage1Boss:die()
self:onDestroy()
self.isDestroyed = true
for i=1,20 do
local expl = Explosion(self.position.x + math.random(-113, 113), self.position.y + math.random(-104, 104), 0, 0, 1.4)
self.state.manager:addEntity(expl, EntityTypes.PARTICLE)
end
self.state:stageComplete()
end
function Stage1Boss:moveToTopLeft()
self.desiredPosition.x = 60
self.desiredPosition.y = 60
end
function Stage1Boss:moveToTopRight()
self.desiredPosition.x = 480-60
self.desiredPosition.y = 60
end
function Stage1Boss:startPhase1()
self.schedule = {
{0, "moveToNeutral", false},
{1, "startPhase2", false}
}
self.phaseTick = 0
end
function Stage1Boss:startPhase2()
self.schedule = {
{0.5, "fireClumpCircle", false},
{1.5, "fireClumpCircle", false},
{1.80, "fireAimedSpread", false},
{1.81, "fireAimedSpread", false},
{1.82, "fireAimedSpread", false},
{1.83, "fireAimedSpread", false},
{1.84, "fireAimedSpread", false},
{1.85, "fireAimedSpread", false},
{1.86, "fireAimedSpread", false},
{1.87, "fireAimedSpread", false},
{1.88, "fireAimedSpread", false},
{1.89, "fireAimedSpread", false},
{2, "fireClumpCircle", false},
{3, "checkPhase2", false}
}
self.phaseTick = 0
end
function Stage1Boss:startPhase3()
self.schedule = {
{0.05, "moveToTopLeft", false},
{0.1, "fireRandom", false},
{0.2, "fireRandom", false},
{0.3, "fireRandom", false},
{0.4, "fireRandom", false},
{0.5, "fireRandom", false},
{0.6, "fireRandom", false},
{0.7, "fireRandom", false},
{0.8, "fireRandom", false},
{0.9, "fireRandom", false},
{1.0, "fireRandom", false},
{1.1, "fireRandom", false},
{1.2, "fireRandom", false},
{1.3, "fireRandom", false},
{1.4, "fireRandom", false},
{1.5, "fireRandom", false},
{1.6, "fireRandom", false},
{1.7, "fireRandom", false},
{1.8, "fireRandom", false},
{1.9, "fireRandom", false},
{2.0, "fireRandom", false},
{2.1, "moveToTopRight", false},
{2.1, "fireRandom", false},
{2.2, "fireRandom", false},
{2.3, "fireRandom", false},
{2.4, "fireRandom", false},
{2.5, "fireRandom", false},
{2.6, "fireRandom", false},
{2.7, "fireRandom", false},
{2.8, "fireRandom", false},
{2.9, "fireRandom", false},
{3.0, "fireRandom", false},
{3.1, "fireRandom", false},
{3.2, "fireRandom", false},
{3.3, "fireRandom", false},
{3.4, "fireRandom", false},
{3.5, "fireRandom", false},
{3.6, "fireRandom", false},
{3.7, "fireRandom", false},
{3.8, "fireRandom", false},
{3.9, "fireRandom", false},
{4.0, "fireRandom", false},
{4.1, "checkPhase3", false},
}
self.phaseTick = 0
end
function Stage1Boss:startPhase4()
self.schedule = {
{0, "fireEnclosingBullets", false},
{0, "fireRandom", false},
{0.05, "moveToNeutral", false},
{0.05, "fireEnclosingBullets", false},
{0.10, "fireEnclosingBullets", false},
{0.10, "fireAimedArc", false},
{0.15, "fireEnclosingBullets", false},
{0.20, "fireEnclosingBullets", false},
{0.20, "fireRandom", false},
{0.25, "fireEnclosingBullets", false},
{0.30, "fireEnclosingBullets", false},
{0.35, "fireEnclosingBullets", false},
{0.40, "fireEnclosingBullets", false},
{0.40, "fireRandom", false},
{0.45, "fireEnclosingBullets", false},
{0.50, "fireEnclosingBullets", false},
{0.55, "fireEnclosingBullets", false},
{0.60, "fireEnclosingBullets", false},
{0.60, "fireRandom", false},
{0.65, "fireEnclosingBullets", false},
{0.70, "fireEnclosingBullets", false},
{0.75, "fireEnclosingBullets", false},
{0.80, "fireEnclosingBullets", false},
{0.80, "fireRandom", false},
{0.85, "fireEnclosingBullets", false},
{0.90, "fireEnclosingBullets", false},
{0.95, "fireEnclosingBullets", false},
{1.00, "fireEnclosingBullets", false},
{1.00, "fireRandom", false},
{1.05, "fireEnclosingBullets", false},
{1.10, "fireEnclosingBullets", false},
{1.15, "fireEnclosingBullets", false},
{1.20, "fireEnclosingBullets", false},
{1.20, "fireRandom", false},
{1.35, "fireEnclosingBullets", false},
{1.40, "fireEnclosingBullets", false},
{1.45, "fireEnclosingBullets", false},
{1.50, "fireEnclosingBullets", false},
{1.50, "fireRandom", false},
{1.55, "fireEnclosingBullets", false},
{1.60, "fireEnclosingBullets", false},
{1.65, "fireEnclosingBullets", false},
{1.70, "fireEnclosingBullets", false},
{1.70, "fireRandom", false},
{1.75, "fireEnclosingBullets", false},
{1.8, "resetCurrentPhase", false}
}
self.phaseTick = 0
end
function Stage1Boss:startPhase5()
self.schedule = {
{0, "moveToLowerNeutral", false},
{0, "explode", false},
{0.1, "explode", false},
{0.2, "explode", false},
{0.3, "explode", false},
{0.4, "explode", false},
{0.5, "explode", false},
{0.6, "explode", false},
{0.7, "explode", false},
{0.8, "explode", false},
{0.9, "explode", false},
{1.0, "die", false}
}
self.phaseTick = 0
end
function Stage1Boss:checkPhase2()
if self.health > 4000 then
self:resetCurrentPhase()
else
self:startPhase3()
end
end
function Stage1Boss:checkPhase3()
if self.health > 2000 then
self:resetCurrentPhase()
else
self:startPhase4()
end
end
function Stage1Boss:resetCurrentPhase()
for i,v in ipairs(self.schedule) do
v[3] = false
end
self.phaseTick = 0
end
function Stage1Boss:onHit(entity)
if entity.damageOnHit then
self.health = self.health - entity.damageOnHit
if self.health <= 0 then
self:startPhase5()
self.state:fadeBossMusic()
self.state.manager:clearBullets()
self.health = 0
end
end
end
function Stage1Boss:draw()
local x,y = self.position:unpack()
love.graphics.setColor(255, 255, 255)
love.graphics.draw(self.image, x, y, self.rotation, 1, 1, 113, 104)
Entity.draw(self)
if self.state.player.viewBossHealth then
love.graphics.draw(self.energyBarBack, 120, 10)
love.graphics.draw(self.energyBar, 120, 10, 0, (self.health / 6000), 1)
love.graphics.draw(self.energyBarFront, 120, 10)
end
end
return Stage1Boss | mit |
JarnoVgr/Mr.Green-MTA-Resources | resources/[race]/custom_coronas/c_exported_functions.lua | 4 | 5663 | --
-- c_exported_functions.lua
--
function createCorona(posX,posY,posZ,size,colorR,colorG,colorB,colorA,...)
local reqParam = {posX,posY,posZ,size,colorR,colorG,colorB,colorA}
local isThisValid = true
local countParam = 0
for m, param in ipairs(reqParam) do
countParam = countParam + 1
isThisValid = isThisValid and param~=nil and (type(param) == "number")
end
local optParam = {...}
if not isThisValid or (#optParam > 1 or #reqParam ~= 8 ) or (countParam ~= 8) then
outputDebugString('createCorona fail!')
return false
end
if (type(optParam[1]) ~= "boolean") then
optParam[1] = false
end
local isDepthEffect = optParam[1]
if isDepthEffect then isDepthEffect = 2 else isDepthEffect = 1 end
local SHCelementID = funcTable.createCorona(isDepthEffect,posX,posY,posZ,size,colorR,colorG,colorB,colorA)
return createElement("SHCustomCorona",tostring(SHCelementID))
end
function createMaterialCorona(texImage,posX,posY,posZ,size,colorR,colorG,colorB,colorA,...)
local reqParam = {posX,posY,posZ,size,colorR,colorG,colorB,colorA}
local isThisValid = true
local countParam = 0
for m, param in ipairs(reqParam) do
countParam = countParam + 1
isThisValid = isThisValid and param~=nil and (type(param) == "number")
end
local optParam = {...}
if not isThisValid or (#optParam > 1 or #reqParam ~= 8 ) or (countParam ~= 8) or not isElement(texImage) then
outputDebugString('createMaterialCorona fail!')
return false
end
if (type(optParam[1]) ~= "boolean") then
optParam[1] = false
end
local isDepthEffect = optParam[1]
if isDepthEffect then isDepthEffect = 2 else isDepthEffect = 1 end
local SHCelementID = funcTable.createMaterialCorona(texImage,isDepthEffect,posX,posY,posZ,size,colorR,colorG,colorB,colorA)
return createElement("SHCustomCorona",tostring(SHCelementID))
end
function destroyCorona(w)
if not isElement(w) then
return false
end
local SHCelementID = tonumber(getElementID(w))
if type(SHCelementID) == "number" then
return destroyElement(w) and funcTable.destroy(SHCelementID)
else
outputDebugString('destroyCorona fail!')
return false
end
end
function setCoronaMaterial(w,texImage)
if not isElement(w) then
return false
end
local SHCelementID = tonumber(getElementID(w))
if coronaTable.inputCoronas[SHCelementID] and isElement(texImage) then
coronaTable.isInValChanged = true
return funcTable.setMaterial(SHCelementID,texImage)
else
outputDebugString('setCoronaMaterial fail!')
return false
end
end
function setCoronaPosition(w,posX,posY,posZ)
if not isElement(w) then
return false
end
local SHCelementID = tonumber(getElementID(w))
local reqParam = {SHCelementID,posX,posY,posZ}
local isThisValid = true
local countParam = 0
for m, param in ipairs(reqParam) do
countParam = countParam + 1
isThisValid = isThisValid and param and (type(param) == "number")
end
if coronaTable.inputCoronas[SHCelementID] and isThisValid and (countParam == 4) then
coronaTable.inputCoronas[SHCelementID].pos = {posX,posY,posZ}
coronaTable.isInValChanged = true
return true
else
outputDebugString('setCoronaPosition fail!')
return false
end
end
function setCoronaColor(w,colorR,colorG,colorB,colorA)
if not isElement(w) then
return false
end
local SHCelementID = tonumber(getElementID(w))
local reqParam = {SHCelementID,colorR,colorG,colorB,colorA}
local isThisValid = true
local countParam = 0
for m, param in ipairs(reqParam) do
countParam = countParam + 1
isThisValid = isThisValid and param and (type(param) == "number")
end
if coronaTable.inputCoronas[SHCelementID] and isThisValid and (countParam == 5) then
coronaTable.inputCoronas[SHCelementID].color = {colorR,colorG,colorB,colorA}
coronaTable.isInValChanged = true
return true
else
outputDebugString('setCoronaColor fail!')
return false
end
end
function setCoronaSize(w,size)
if not isElement(w) then
return false
end
local SHCelementID = tonumber(getElementID(w))
if coronaTable.inputCoronas[SHCelementID] and (type(size) == "number") then
coronaTable.inputCoronas[SHCelementID].size = {size,size}
coronaTable.inputCoronas[SHCelementID].dBias = math.min(size,1)
coronaTable.isInValChanged = true
return true
else
outputDebugString('setCoronaSize fail!')
return false
end
end
function setCoronaDepthBias(w,depthBias)
if not isElement(w) then
return false
end
local SHCelementID = tonumber(getElementID(w))
if coronaTable.inputCoronas[SHCelementID] and (type(depthBias) == "number") then
coronaTable.inputCoronas[SHCelementID].dBias = depthBias
coronaTable.isInValChanged = true
return true
else
outputDebugString('setCoronaDepthBias fail!')
return false
end
end
function setCoronaSizeXY(w,sizeX,sizeY)
if not isElement(w) then
return false
end
local SHCelementID = tonumber(getElementID(w))
if coronaTable.inputCoronas[SHCelementID] and (type(sizeX) == "number") and (type(sizeY) == "number") then
coronaTable.inputCoronas[SHCelementID].size = {sizeX,sizeY}
coronaTable.inputCoronas[SHCelementID].dBias = math.min((sizeX + sizeY)/2,1)
coronaTable.isInValChanged = true
return true
else
outputDebugString('setCoronaSizeXY fail!')
return false
end
end
function setCoronasDistFade(dist1,dist2)
if (type(dist1) == "number") and (type(dist2) == "number") then
return funcTable.setDistFade(dist1,dist2)
else
outputDebugString('setCoronasDistFade fail!')
return false
end
end
function enableDepthBiasScale(depthBiasEnable)
if type(depthBiasEnable) == "boolean" then
coronaTable.depthBias = depthBiasEnable
return true
else
outputDebugString('enableDepthBiasScale fail!')
return false
end
end | mit |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/tests/lua-tests/src/ExtensionTest/WebProxyTest.lua | 11 | 7485 | local function WebSocketTestLayer()
local layer = cc.Layer:create()
local winSize = cc.Director:getInstance():getWinSize()
local MARGIN = 40
local SPACE = 35
local wsSendText = nil
local wsSendBinary = nil
local wsError = nil
local sendTextStatus = nil
local sendBinaryStatus = nil
local errorStatus = nil
local receiveTextTimes = 0
local receiveBinaryTimes = 0
local label = cc.Label:createWithTTF("WebSocket Test", s_arialPath, 28)
label:setAnchorPoint(cc.p(0.5, 0.5))
label:setPosition(cc.p( winSize.width / 2, winSize.height - MARGIN))
layer:addChild(label, 0)
local menuRequest = cc.Menu:create()
menuRequest:setPosition(cc.p(0, 0))
layer:addChild(menuRequest)
--Send Text
local function onMenuSendTextClicked()
if nil ~= wsSendText then
if cc.WEBSOCKET_STATE_OPEN == wsSendText:getReadyState() then
sendTextStatus:setString("Send Text WS is waiting...")
wsSendText:sendString("Hello WebSocket中文, I'm a text message.")
else
local warningStr = "send text websocket instance wasn't ready..."
print(warningStr)
sendTextStatus:setString(warningStr)
end
end
end
local labelSendText = cc.Label:createWithTTF("Send Text", s_arialPath, 22)
labelSendText:setAnchorPoint(0.5, 0.5)
local itemSendText = cc.MenuItemLabel:create(labelSendText)
itemSendText:registerScriptTapHandler(onMenuSendTextClicked)
itemSendText:setPosition(cc.p(winSize.width / 2, winSize.height - MARGIN - SPACE))
menuRequest:addChild(itemSendText)
--Send Binary
local function onMenuSendBinaryClicked()
if nil ~= wsSendBinary then
if cc.WEBSOCKET_STATE_OPEN == wsSendBinary:getReadyState() then
sendBinaryStatus:setString("Send Binary WS is waiting...")
wsSendBinary:sendString("Hello WebSocket中文--,\0 I'm\0 a\0 binary\0 message\0.")
else
local warningStr = "send binary websocket instance wasn't ready..."
sendBinaryStatus:setString(warningStr)
end
end
end
local labelSendBinary = cc.Label:createWithTTF("Send Binary", s_arialPath, 22)
labelSendBinary:setAnchorPoint(cc.p(0.5, 0.5))
local itemSendBinary = cc.MenuItemLabel:create(labelSendBinary)
itemSendBinary:registerScriptTapHandler(onMenuSendBinaryClicked)
itemSendBinary:setPosition(cc.p(winSize.width / 2, winSize.height - MARGIN - 2 * SPACE))
menuRequest:addChild(itemSendBinary)
--Send Text Status Label
sendTextStatus = cc.Label:createWithTTF("Send Text WS is waiting...", s_arialPath, 14,cc.size(160, 100),cc.VERTICAL_TEXT_ALIGNMENT_CENTER,cc.VERTICAL_TEXT_ALIGNMENT_TOP)
sendTextStatus:setAnchorPoint(cc.p(0, 0))
sendTextStatus:setPosition(cc.p(0, 25))
layer:addChild(sendTextStatus)
--Send Binary Status Label
sendBinaryStatus = cc.Label:createWithTTF("Send Binary WS is waiting...", s_arialPath, 14, cc.size(160, 100), cc.VERTICAL_TEXT_ALIGNMENT_CENTER, cc.VERTICAL_TEXT_ALIGNMENT_TOP)
sendBinaryStatus:setAnchorPoint(cc.p(0, 0))
sendBinaryStatus:setPosition(cc.p(160, 25))
layer:addChild(sendBinaryStatus)
--Error Label
errorStatus = cc.Label:createWithTTF("Error WS is waiting...", s_arialPath, 14, cc.size(160, 100), cc.VERTICAL_TEXT_ALIGNMENT_CENTER, cc.VERTICAL_TEXT_ALIGNMENT_TOP)
errorStatus:setAnchorPoint(cc.p(0, 0))
errorStatus:setPosition(cc.p(320, 25))
layer:addChild(errorStatus)
local toMainMenu = cc.Menu:create()
CreateExtensionsBasicLayerMenu(toMainMenu)
toMainMenu:setPosition(cc.p(0, 0))
layer:addChild(toMainMenu,10)
wsSendText = cc.WebSocket:create("ws://echo.websocket.org")
wsSendBinary = cc.WebSocket:create("ws://echo.websocket.org")
wsError = cc.WebSocket:create("ws://invalid.url.com")
local function wsSendTextOpen(strData)
sendTextStatus:setString("Send Text WS was opened.")
end
local function wsSendTextMessage(strData)
receiveTextTimes= receiveTextTimes + 1
local strInfo= "response text msg: "..strData..", "..receiveTextTimes
sendTextStatus:setString(strInfo)
end
local function wsSendTextClose(strData)
print("_wsiSendText websocket instance closed.")
sendTextStatus = nil
wsSendText = nil
end
local function wsSendTextError(strData)
print("sendText Error was fired")
end
local function wsSendBinaryOpen(strData)
sendBinaryStatus:setString("Send Binary WS was opened.")
end
local function wsSendBinaryMessage(paramTable)
local length = table.getn(paramTable)
local i = 1
local strInfo = "response bin msg: "
for i = 1,length do
if 0 == paramTable[i] then
strInfo = strInfo.."\'\\0\'"
else
strInfo = strInfo..string.char(paramTable[i])
end
end
receiveBinaryTimes = receiveBinaryTimes + 1
strInfo = strInfo..receiveBinaryTimes
sendBinaryStatus:setString(strInfo)
end
local function wsSendBinaryClose(strData)
print("_wsiSendBinary websocket instance closed.")
sendBinaryStatus = nil
wsSendBinary = nil
end
local function wsSendBinaryError(strData)
print("sendBinary Error was fired")
end
local function wsErrorOpen(strData)
end
local function wsErrorMessage(strData)
end
local function wsErrorError(strData)
print("Error was fired")
errorStatus:setString("an error was fired")
end
local function wsErrorClose(strData)
print("_wsiError websocket instance closed.")
errorStatus= nil
wsError = nil
end
if nil ~= wsSendText then
wsSendText:registerScriptHandler(wsSendTextOpen,cc.WEBSOCKET_OPEN)
wsSendText:registerScriptHandler(wsSendTextMessage,cc.WEBSOCKET_MESSAGE)
wsSendText:registerScriptHandler(wsSendTextClose,cc.WEBSOCKET_CLOSE)
wsSendText:registerScriptHandler(wsSendTextError,cc.WEBSOCKET_ERROR)
end
if nil ~= wsSendBinary then
wsSendBinary:registerScriptHandler(wsSendBinaryOpen,cc.WEBSOCKET_OPEN)
wsSendBinary:registerScriptHandler(wsSendBinaryMessage,cc.WEBSOCKET_MESSAGE)
wsSendBinary:registerScriptHandler(wsSendBinaryClose,cc.WEBSOCKET_CLOSE)
wsSendBinary:registerScriptHandler(wsSendBinaryError,cc.WEBSOCKET_ERROR)
end
if nil ~= wsError then
wsError:registerScriptHandler(wsErrorOpen,cc.WEBSOCKET_OPEN)
wsError:registerScriptHandler(wsErrorMessage,cc.WEBSOCKET_MESSAGE)
wsError:registerScriptHandler(wsErrorClose,cc.WEBSOCKET_CLOSE)
wsError:registerScriptHandler(wsErrorError,cc.WEBSOCKET_ERROR)
end
local function OnExit(strEventName)
if "exit" == strEventName then
if nil ~= wsSendText then
wsSendText:close()
end
if nil ~= wsSendBinary then
wsSendBinary:close()
end
if nil ~= wsError then
wsError:close()
end
end
end
layer:registerScriptHandler(OnExit)
return layer
end
function runWebSocketTest()
local scene = cc.Scene:create()
scene:addChild(WebSocketTestLayer())
return scene
end
| mit |
mowoe/diemaschine | demos/vis-outputs.lua | 11 | 2580 | #!/usr/bin/env th
--
-- Copyright 2015-2016 Carnegie Mellon University
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
require 'torch'
require 'nn'
require 'dpnn'
require 'image'
require 'paths'
torch.setdefaulttensortype('torch.FloatTensor')
local cmd = torch.CmdLine()
cmd:text()
cmd:text('Visualize OpenFace outputs.')
cmd:text()
cmd:text('Options:')
cmd:option('-imgPath', 'images/examples-aligned/lennon-1.png',
'Path to aligned image.')
cmd:option('-filterOutput',
'images/examples-aligned/lennon-1',
'Output directory.')
cmd:option('-model', './models/openface/nn4.small2.v1.t7', 'Path to model.')
cmd:option('-imgDim', 96, 'Image dimension. nn1=224, nn4=96')
cmd:option('-numPreview', 39, 'Number of images to preview')
cmd:text()
opt = cmd:parse(arg or {})
-- print(opt)
os.execute('mkdir -p ' .. opt.filterOutput)
if not paths.filep(opt.imgPath) then
print("Unable to find: " .. opt.imgPath)
os.exit(-1)
end
net = torch.load(opt.model)
net:evaluate()
print(net)
local img = torch.Tensor(1, 3, opt.imgDim, opt.imgDim)
local img_orig = image.load(opt.imgPath, 3)
img[1] = image.scale(img_orig, opt.imgDim, opt.imgDim)
net:forward(img)
local fName = opt.filterOutput .. '/preview.html'
print("Outputting filter preview to '" .. fName .. "'")
f, err = io.open(fName, 'w')
if err then
print("Error: Unable to open preview.html");
os.exit(-1)
end
torch.IntTensor({3, 7, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21}):apply(function (i)
os.execute(string.format('mkdir -p %s/%s',
opt.filterOutput, i))
out = net.modules[i].output[1]
f:write(string.format("<h1>Layer %s</h1>\n", i))
for j = 1,out:size(1) do
imgName = string.format('%s/%d/%d.png',
opt.filterOutput, i, j)
image.save(imgName, out[j])
if j <= opt.numPreview then
f:write(string.format("<img src='%d/%d.png' width='96px'></img>\n",
i, j))
end
end
end)
| gpl-3.0 |
darkdukey/sdkbox-facebook-sample-v2 | samples/Lua/TestLua/Resources/luaScript/ParticleTest/ParticleTest.lua | 7 | 43201 |
local SceneIdx = -1
local MAX_LAYER = 42
local emitter = nil
local background = nil
local labelAtlas = nil
local titleLabel = nil
local subtitleLabel = nil
local baseLayer_entry = nil
local s = CCDirector:sharedDirector():getWinSize()
local function backAction()
SceneIdx = SceneIdx - 1
if SceneIdx < 0 then
SceneIdx = SceneIdx + MAX_LAYER
end
return CreateParticleLayer()
end
local function restartAction()
return CreateParticleLayer()
end
local function nextAction()
SceneIdx = SceneIdx + 1
SceneIdx = math.mod(SceneIdx, MAX_LAYER)
return CreateParticleLayer()
end
local function backCallback(sender)
local scene = CCScene:create()
scene:addChild(backAction())
scene:addChild(CreateBackMenuItem())
CCDirector:sharedDirector():replaceScene(scene)
end
local function restartCallback(sender)
local scene = CCScene:create()
scene:addChild(restartAction())
scene:addChild(CreateBackMenuItem())
CCDirector:sharedDirector():replaceScene(scene)
end
local function nextCallback(sender)
local scene = CCScene:create()
scene:addChild(nextAction())
scene:addChild(CreateBackMenuItem())
CCDirector:sharedDirector():replaceScene(scene)
end
local function toggleCallback(sender)
if emitter ~= nil then
if emitter:getPositionType() == kCCPositionTypeGrouped then
emitter:setPositionType(kCCPositionTypeFree)
elseif emitter:getPositionType() == kCCPositionTypeFree then
emitter:setPositionType(kCCPositionTypeRelative)
elseif emitter:getPositionType() == kCCPositionTypeRelative then
emitter:setPositionType(kCCPositionTypeGrouped)
end
end
end
local function setEmitterPosition()
if emitter ~= nil then
emitter:setPosition(s.width / 2, s.height / 2)
end
end
local function update(dt)
if emitter ~= nil then
local str = "" .. emitter:getParticleCount()
-- labelAtlas:setString("" .. str)
end
end
local function baseLayer_onEnterOrExit(tag)
local scheduler = CCDirector:sharedDirector():getScheduler()
if tag == "enter" then
baseLayer_entry = scheduler:scheduleScriptFunc(update, 0, false)
elseif tag == "exit" then
scheduler:unscheduleScriptEntry(baseLayer_entry)
end
end
local function getBaseLayer()
local layer = CCLayerColor:create(ccc4(127,127,127,255))
emitter = nil
titleLabel = CCLabelTTF:create("", "Arial", 28)
layer:addChild(titleLabel, 100, 1000)
titleLabel:setPosition(s.width / 2, s.height - 50)
subtitleLabel = CCLabelTTF:create("", "Arial", 16)
layer:addChild(subtitleLabel, 100)
subtitleLabel:setPosition(s.width / 2, s.height - 80)
local item1 = CCMenuItemImage:create(s_pPathB1, s_pPathB2)
local item2 = CCMenuItemImage:create(s_pPathR1, s_pPathR2)
local item3 = CCMenuItemImage:create(s_pPathF1, s_pPathF2)
local item4 = CCMenuItemToggle:create(CCMenuItemFont:create("Free Movement"))
item4:addSubItem(CCMenuItemFont:create("Relative Movement"))
item4:addSubItem(CCMenuItemFont:create("Grouped Movement"))
item1:registerScriptTapHandler(backCallback)
item2:registerScriptTapHandler(restartCallback)
item3:registerScriptTapHandler(nextCallback)
item4:registerScriptTapHandler(toggleCallback)
local menu = CCMenu:create()
menu:addChild(item1)
menu:addChild(item2)
menu:addChild(item3)
menu:addChild(item4)
menu:setPosition(CCPointMake(0, 0))
item1:setPosition(CCPointMake(s.width/2 - item2:getContentSize().width * 2, item2:getContentSize().height / 2))
item2:setPosition(CCPointMake(s.width/2, item2:getContentSize().height / 2))
item3:setPosition(CCPointMake(s.width/2 + item2:getContentSize().width * 2, item2:getContentSize().height / 2))
item4:setPosition(ccp(0, 100))
item4:setAnchorPoint(ccp(0, 0))
layer:addChild(menu, 100)
labelAtlas = CCLabelAtlas:create("0000", "fps_images.png", 12, 32, string.byte('.'))
layer:addChild(labelAtlas, 100)
labelAtlas:setPosition(ccp(s.width - 66, 50))
-- moving background
background = CCSprite:create(s_back3)
layer:addChild(background, 5)
background:setPosition(ccp(s.width / 2, s.height - 180))
local move = CCMoveBy:create(4, ccp(300, 0))
local move_back = move:reverse()
local seq = CCSequence:createWithTwoActions(move, move_back)
background:runAction(CCRepeatForever:create(seq))
local function onTouchEnded(x, y)
local pos = CCPointMake(0, 0)
if background ~= nil then
pos = background:convertToWorldSpace(CCPointMake(0, 0))
end
if emitter ~= nil then
local newPos = ccpSub(CCPointMake(x, y), pos)
emitter:setPosition(newPos.x, newPos.y)
end
end
local function onTouch(eventType, x, y)
if eventType == "began" then
return true
else
return onTouchEnded(x, y)
end
end
layer:setTouchEnabled(true)
layer:registerScriptTouchHandler(onTouch)
layer:registerScriptHandler(baseLayer_onEnterOrExit)
return layer
end
---------------------------------
-- ParticleReorder
---------------------------------
local ParticleReorder_Order = nil
local ParticleReorder_entry = nil
local ParticleReorder_layer = nil
local function reorderParticles(dt)
update(dt)
for i = 0, 1 do
local parent = ParticleReorder_layer:getChildByTag(1000 + i)
local child1 = parent:getChildByTag(1)
local child2 = parent:getChildByTag(2)
local child3 = parent:getChildByTag(3)
if math.mod(ParticleReorder_Order, 3) == 0 then
parent:reorderChild(child1, 1)
parent:reorderChild(child2, 2)
parent:reorderChild(child3, 3)
elseif math.mod(ParticleReorder_Order, 3) == 1 then
parent:reorderChild(child1, 3)
parent:reorderChild(child2, 1)
parent:reorderChild(child3, 2)
elseif math.mod(ParticleReorder_Order, 3) == 2 then
parent:reorderChild(child1, 2)
parent:reorderChild(child2, 3)
parent:reorderChild(child3, 1)
end
end
ParticleReorder_Order = ParticleReorder_Order + 1
end
local function ParticleReorder_onEnterOrExit(tag)
local scheduler = CCDirector:sharedDirector():getScheduler()
if tag == "enter" then
ParticleReorder_entry = scheduler:scheduleScriptFunc(reorderParticles, 1.0, false)
elseif tag == "exit" then
scheduler:unscheduleScriptEntry(ParticleReorder_entry)
end
end
local function ParticleReorder()
ParticleReorder_layer = getBaseLayer()
ParticleReorder_Order = 0
ParticleReorder_layer:setColor(ccc3(0, 0, 0))
ParticleReorder_layer:removeChild(background, true)
background = nil
local ignore = CCParticleSystemQuad:create("Particles/SmallSun.plist")
local parent1 = CCNode:create()
local parent2 = CCParticleBatchNode:createWithTexture(ignore:getTexture())
ignore:unscheduleUpdate()
for i = 0, 1 do
local parent = nil
if i == 0 then
parent = parent1
else
parent = parent2
end
local emitter1 = CCParticleSystemQuad:create("Particles/SmallSun.plist")
emitter1:setStartColor(ccc4f(1,0,0,1))
emitter1:setBlendAdditive(false)
local emitter2 = CCParticleSystemQuad:create("Particles/SmallSun.plist")
emitter2:setStartColor(ccc4f(0,1,0,1))
emitter2:setBlendAdditive(false)
local emitter3 = CCParticleSystemQuad:create("Particles/SmallSun.plist")
emitter3:setStartColor(ccc4f(0,0,1,1))
emitter3:setBlendAdditive(false)
local neg = nil
if i == 0 then
neg = 1
else
neg = -1
end
emitter1:setPosition(ccp( s.width / 2 - 30, s.height / 2 + 60 * neg))
emitter2:setPosition(ccp( s.width / 2, s.height / 2 + 60 * neg))
emitter3:setPosition(ccp( s.width / 2 + 30, s.height / 2 + 60 * neg))
parent:addChild(emitter1, 0, 1)
parent:addChild(emitter2, 0, 2)
parent:addChild(emitter3, 0, 3)
ParticleReorder_layer:addChild(parent, 10, 1000 + i)
end
ParticleReorder_layer:registerScriptHandler(ParticleReorder_onEnterOrExit)
titleLabel:setString("Reordering particles")
subtitleLabel:setString("Reordering particles with and without batches batches")
return ParticleReorder_layer
end
---------------------------------
-- ParticleBatchHybrid
---------------------------------
local ParticleBatchHybrid_entry = nil
local ParticleBatchHybrid_parent1 = nil
local ParticleBatchHybrid_parent2 = nil
local function switchRender(dt)
update(dt)
local cond = (emitter:getBatchNode() ~= nil)
emitter:removeFromParentAndCleanup(false)
local str = "Particle: Using new parent: "
local newParent = nil
if cond == true then
newParent = ParticleBatchHybrid_parent2
str = str .. "CCNode"
else
newParent = ParticleBatchHybrid_parent1
str = str .. "CCParticleBatchNode"
end
newParent:addChild(emitter)
cclog(str)
end
local function ParticleBatchHybrid_onEnterOrExit(tag)
local scheduler = CCDirector:sharedDirector():getScheduler()
if tag == "enter" then
ParticleBatchHybrid_entry = scheduler:scheduleScriptFunc(switchRender, 2.0, false)
elseif tag == "exit" then
scheduler:unscheduleScriptEntry(ParticleBatchHybrid_entry)
--emitter:release()
end
end
local function ParticleBatchHybrid()
local layer = getBaseLayer()
layer:setColor(ccc3(0, 0, 0))
layer:removeChild(background, true)
background = nil
emitter = CCParticleSystemQuad:create("Particles/LavaFlow.plist")
---- emitter:retain()
local batch = CCParticleBatchNode:createWithTexture(emitter:getTexture())
batch:addChild(emitter)
layer:addChild(batch, 10)
local node = CCNode:create()
layer:addChild(node)
ParticleBatchHybrid_parent1 = batch
ParticleBatchHybrid_parent2 = node
layer:registerScriptHandler(ParticleBatchHybrid_onEnterOrExit)
titleLabel:setString("Paticle Batch")
subtitleLabel:setString("Hybrid: batched and non batched every 2 seconds")
return layer
end
---------------------------------
-- ParticleBatchMultipleEmitters
---------------------------------
local function ParticleBatchMultipleEmitters()
local layer = getBaseLayer()
layer:setColor(ccc3(0, 0, 0))
layer:removeChild(background, true)
background = nil
local emitter1 = CCParticleSystemQuad:create("Particles/LavaFlow.plist")
emitter1:setStartColor(ccc4f(1,0,0,1))
local emitter2 = CCParticleSystemQuad:create("Particles/LavaFlow.plist")
emitter2:setStartColor(ccc4f(0,1,0,1))
local emitter3 = CCParticleSystemQuad:create("Particles/LavaFlow.plist")
emitter3:setStartColor(ccc4f(0,0,1,1))
emitter1:setPosition(ccp(s.width / 1.25, s.height / 1.25))
emitter2:setPosition(ccp(s.width / 2, s.height / 2))
emitter3:setPosition(ccp(s.width / 4, s.height / 4))
local batch = CCParticleBatchNode:createWithTexture(emitter1:getTexture())
batch:addChild(emitter1, 0)
batch:addChild(emitter2, 0)
batch:addChild(emitter3, 0)
layer:addChild(batch, 10)
titleLabel:setString("Paticle Batch")
subtitleLabel:setString("Multiple emitters. One Batch")
return layer
end
---------------------------------
-- DemoFlower
---------------------------------
local function DemoFlower()
local layer = getBaseLayer()
emitter = CCParticleFlower:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_stars1))
setEmitterPosition()
titleLabel:setString("ParticleFlower")
return layer
end
---------------------------------
-- DemoGalaxy
---------------------------------
local function DemoGalaxy()
local layer = getBaseLayer()
emitter = CCParticleGalaxy:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire))
setEmitterPosition()
titleLabel:setString("ParticleGalaxy")
return layer
end
---------------------------------
-- DemoFirework
---------------------------------
local function DemoFirework()
local layer = getBaseLayer()
emitter = CCParticleFireworks:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_stars1))
setEmitterPosition()
titleLabel:setString("ParticleFireworks")
return layer
end
---------------------------------
-- DemoSpiral
---------------------------------
local function DemoSpiral()
local layer = getBaseLayer()
emitter = CCParticleSpiral:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire))
setEmitterPosition()
titleLabel:setString("ParticleSpiral")
return layer
end
---------------------------------
-- DemoSun
---------------------------------
local function DemoSun()
local layer = getBaseLayer()
emitter = CCParticleSun:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire))
setEmitterPosition()
titleLabel:setString("ParticleSun")
return layer
end
---------------------------------
-- DemoMeteor
---------------------------------
local function DemoMeteor()
local layer = getBaseLayer()
emitter = CCParticleMeteor:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire))
setEmitterPosition()
titleLabel:setString("ParticleMeteor")
return layer
end
---------------------------------
-- DemoFire
---------------------------------
local function DemoFire()
local layer = getBaseLayer()
emitter = CCParticleFire:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire))
local pos_x, pos_y = emitter:getPosition()
emitter:setPosition(pos_x, 100)
titleLabel:setString("ParticleFire")
return layer
end
---------------------------------
-- DemoSmoke
---------------------------------
local function DemoSmoke()
local layer = getBaseLayer()
emitter = CCParticleSmoke:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire))
local pos_x, pos_y = emitter:getPosition()
emitter:setPosition(pos_x, 100)
setEmitterPosition()
titleLabel:setString("ParticleSmoke")
return layer
end
---------------------------------
-- DemoExplosion
---------------------------------
local function DemoExplosion()
local layer = getBaseLayer()
emitter = CCParticleExplosion:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_stars1))
emitter:setAutoRemoveOnFinish(true)
setEmitterPosition()
titleLabel:setString("ParticleExplosion")
return layer
end
---------------------------------
-- DemoSnow
---------------------------------
local function DemoSnow()
local layer = getBaseLayer()
emitter = CCParticleSnow:create()
-- emitter:retain()
background:addChild(emitter, 10)
local pos_x, pos_y = emitter:getPosition()
emitter:setPosition(pos_x, pos_y - 110)
emitter:setLife(3)
emitter:setLifeVar(1)
-- gravity
emitter:setGravity(CCPointMake(0, -10))
-- speed of particles
emitter:setSpeed(130)
emitter:setSpeedVar(30)
local startColor = emitter:getStartColor()
startColor.r = 0.9
startColor.g = 0.9
startColor.b = 0.9
emitter:setStartColor(startColor)
local startColorVar = emitter:getStartColorVar()
startColorVar.b = 0.1
emitter:setStartColorVar(startColorVar)
emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife())
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_snow))
setEmitterPosition()
titleLabel:setString("ParticleSnow")
return layer
end
---------------------------------
-- DemoRain
---------------------------------
local function DemoRain()
local layer = getBaseLayer()
emitter = CCParticleRain:create()
-- emitter:retain()
background:addChild(emitter, 10)
local pos_x, pos_y = emitter:getPosition()
emitter:setPosition(pos_x, pos_y - 100)
emitter:setLife(4)
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire))
setEmitterPosition()
titleLabel:setString("ParticleRain")
return layer
end
---------------------------------
-- DemoBigFlower
---------------------------------
local function DemoBigFlower()
local layer = getBaseLayer()
emitter = CCParticleSystemQuad:new()
emitter:initWithTotalParticles(50)
emitter:autorelease()
background:addChild(emitter, 10)
----emitter:release() -- win32 : use this line or remove this line and use autorelease()
emitter:setTexture( CCTextureCache:sharedTextureCache():addImage(s_stars1) )
emitter:setDuration(-1)
-- gravity
emitter:setGravity(CCPointMake(0, 0))
-- angle
emitter:setAngle(90)
emitter:setAngleVar(360)
-- speed of particles
emitter:setSpeed(160)
emitter:setSpeedVar(20)
-- radial
emitter:setRadialAccel(-120)
emitter:setRadialAccelVar(0)
-- tagential
emitter:setTangentialAccel(30)
emitter:setTangentialAccelVar(0)
-- emitter position
emitter:setPosition(160, 240)
emitter:setPosVar(ccp(0, 0))
-- life of particles
emitter:setLife(4)
emitter:setLifeVar(1)
-- spin of particles
emitter:setStartSpin(0)
emitter:setStartSizeVar(0)
emitter:setEndSpin(0)
emitter:setEndSpinVar(0)
-- color of particles
emitter:setStartColor(ccc4f(0.5, 0.5, 0.5, 1.0))
emitter:setStartColorVar(ccc4f(0.5, 0.5, 0.5, 1.0))
emitter:setEndColor(ccc4f(0.1, 0.1, 0.1, 0.2))
emitter:setEndColorVar(ccc4f(0.1, 0.1, 0.1, 0.2))
-- size, in pixels
emitter:setStartSize(80.0)
emitter:setStartSizeVar(40.0)
emitter:setEndSize(kParticleStartSizeEqualToEndSize)
-- emits per second
emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife())
-- additive
emitter:setBlendAdditive(true)
setEmitterPosition()
titleLabel:setString("ParticleBigFlower")
return layer
end
---------------------------------
-- DemoRotFlower
---------------------------------
local function DemoRotFlower()
local layer = getBaseLayer()
emitter = CCParticleSystemQuad:new()
emitter:initWithTotalParticles(300)
emitter:autorelease()
background:addChild(emitter, 10)
----emitter:release() -- win32 : Remove this line
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_stars2))
-- duration
emitter:setDuration(-1)
-- gravity
emitter:setGravity(ccp(0, 0))
-- angle
emitter:setAngle(90)
emitter:setAngleVar(360)
-- speed of particles
emitter:setSpeed(160)
emitter:setSpeedVar(20)
-- radial
emitter:setRadialAccel(-120)
emitter:setRadialAccelVar(0)
-- tagential
emitter:setTangentialAccel(30)
emitter:setTangentialAccelVar(0)
-- emitter position
emitter:setPosition(160, 240)
emitter:setPosVar(ccp(0, 0))
-- life of particles
emitter:setLife(3)
emitter:setLifeVar(1)
-- spin of particles
emitter:setStartSpin(0)
emitter:setStartSpinVar(0)
emitter:setEndSpin(0)
emitter:setEndSpinVar(2000)
-- color of particles
emitter:setStartColor(ccc4f(0.5, 0.5, 0.5, 1.0))
emitter:setStartColorVar(ccc4f(0.5, 0.5, 0.5, 1.0))
emitter:setEndColor(ccc4f(0.1, 0.1, 0.1, 0.2))
emitter:setEndColorVar(ccc4f(0.1, 0.1, 0.1, 0.2))
-- size, in pixels
emitter:setStartSize(30.0)
emitter:setStartSizeVar(0)
emitter:setEndSize(kParticleStartSizeEqualToEndSize)
-- emits per second
emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife())
-- additive
emitter:setBlendAdditive(false)
setEmitterPosition()
titleLabel:setString("ParticleRotFlower")
return layer
end
---------------------------------
-- DemoModernArt
---------------------------------
local function DemoModernArt()
local layer = getBaseLayer()
emitter = CCParticleSystemQuad:new()
emitter:initWithTotalParticles(1000)
emitter:autorelease()
background:addChild(emitter, 10)
----emitter:release()
-- duration
emitter:setDuration(-1)
-- gravity
emitter:setGravity(CCPointMake(0,0))
-- angle
emitter:setAngle(0)
emitter:setAngleVar(360)
-- radial
emitter:setRadialAccel(70)
emitter:setRadialAccelVar(10)
-- tagential
emitter:setTangentialAccel(80)
emitter:setTangentialAccelVar(0)
-- speed of particles
emitter:setSpeed(50)
emitter:setSpeedVar(10)
-- emitter position
emitter:setPosition(s.width / 2, s.height / 2)
emitter:setPosVar(ccp(0, 0))
-- life of particles
emitter:setLife(2.0)
emitter:setLifeVar(0.3)
-- emits per frame
emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife())
-- color of particles
emitter:setStartColor(ccc4f(0.5, 0.5, 0.5, 1.0))
emitter:setStartColorVar(ccc4f(0.5, 0.5, 0.5, 1.0))
emitter:setEndColor(ccc4f(0.1, 0.1, 0.1, 0.2))
emitter:setEndColorVar(ccc4f(0.1, 0.1, 0.1, 0.2))
-- size, in pixels
emitter:setStartSize(1.0)
emitter:setStartSizeVar(1.0)
emitter:setEndSize(32.0)
emitter:setEndSizeVar(8.0)
-- texture
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire))
-- additive
emitter:setBlendAdditive(false)
setEmitterPosition()
titleLabel:setString("Varying size")
return layer
end
---------------------------------
-- DemoRing
---------------------------------
local function DemoRing()
local layer = getBaseLayer()
emitter = CCParticleFlower:create()
-- emitter:retain()
background:addChild(emitter, 10)
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_stars1))
emitter:setLifeVar(0)
emitter:setLife(10)
emitter:setSpeed(100)
emitter:setSpeedVar(0)
emitter:setEmissionRate(10000)
setEmitterPosition()
titleLabel:setString("Ring Demo")
return layer
end
---------------------------------
-- ParallaxParticle
---------------------------------
local function ParallaxParticle()
local layer = getBaseLayer()
background:getParent():removeChild(background, true)
background = nil
local p = CCParallaxNode:create()
layer:addChild(p, 5)
local p1 = CCSprite:create(s_back3)
local p2 = CCSprite:create(s_back3)
p:addChild(p1, 1, CCPointMake(0.5, 1), CCPointMake(0, 250))
p:addChild(p2, 2, CCPointMake(1.5, 1), CCPointMake(0, 50))
emitter = CCParticleFlower:create()
-- emitter:retain()
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire))
p1:addChild(emitter, 10)
emitter:setPosition(250, 200)
local par = CCParticleSun:create()
p2:addChild(par, 10)
par:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire))
local move = CCMoveBy:create(4, CCPointMake(300,0))
local move_back = move:reverse()
local seq = CCSequence:createWithTwoActions(move, move_back)
p:runAction(CCRepeatForever:create(seq))
titleLabel:setString("Parallax + Particles")
return layer
end
---------------------------------
-- DemoParticleFromFile
---------------------------------
local function DemoParticleFromFile(name)
local layer = getBaseLayer()
layer:setColor(ccc3(0, 0, 0))
layer:removeChild(background, true)
background = nil
emitter = CCParticleSystemQuad:new()
emitter:autorelease()
local filename = "Particles/" .. name .. ".plist"
emitter:initWithFile(filename)
layer:addChild(emitter, 10)
setEmitterPosition()
titleLabel:setString(name)
return layer
end
---------------------------------
-- RadiusMode1
---------------------------------
local function RadiusMode1()
local layer = getBaseLayer()
layer:setColor(ccc3(0, 0, 0))
layer:removeChild(background, true)
background = nil
emitter = CCParticleSystemQuad:new()
emitter:initWithTotalParticles(200)
layer:addChild(emitter, 10)
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage("Images/stars-grayscale.png"))
-- duration
emitter:setDuration(kCCParticleDurationInfinity)
-- radius mode
emitter:setEmitterMode(kCCParticleModeRadius)
-- radius mode: start and end radius in pixels
emitter:setStartRadius(0)
emitter:setStartRadiusVar(0)
emitter:setEndRadius(160)
emitter:setEndRadiusVar(0)
-- radius mode: degrees per second
emitter:setRotatePerSecond(180)
emitter:setRotatePerSecondVar(0)
-- angle
emitter:setAngle(90)
emitter:setAngleVar(0)
-- emitter position
emitter:setPosition(s.width / 2, s.height / 2)
emitter:setPosVar(ccp(0, 0))
-- life of particles
emitter:setLife(5)
emitter:setLifeVar(0)
-- spin of particles
emitter:setStartSpin(0)
emitter:setStartSpinVar(0)
emitter:setEndSpin(0)
emitter:setEndSpinVar(0)
-- color of particles
emitter:setStartColor(ccc4f(0.5, 0.5, 0.5, 1.0))
emitter:setStartColorVar(ccc4f(0.5, 0.5, 0.5, 1.0))
emitter:setEndColor(ccc4f(0.1, 0.1, 0.1, 0.2))
emitter:setEndColorVar(ccc4f(0.1, 0.1, 0.1, 0.2))
-- size, in pixels
emitter:setStartSize(32)
emitter:setStartSizeVar(0)
emitter:setEndSize(kCCParticleStartSizeEqualToEndSize)
-- emits per second
emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife())
-- additive
emitter:setBlendAdditive(false)
titleLabel:setString("Radius Mode: Spiral")
return layer
end
---------------------------------
-- RadiusMode2
---------------------------------
local function RadiusMode2()
local layer = getBaseLayer()
layer:setColor(ccc3(0, 0, 0))
layer:removeChild(background, true)
background = nil
emitter = CCParticleSystemQuad:new()
emitter:initWithTotalParticles(200)
layer:addChild(emitter, 10)
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage("Images/stars-grayscale.png"))
-- duration
emitter:setDuration(kCCParticleDurationInfinity)
-- radius mode
emitter:setEmitterMode(kCCParticleModeRadius)
-- radius mode: start and end radius in pixels
emitter:setStartRadius(100)
emitter:setStartRadiusVar(0)
emitter:setEndRadius(kCCParticleStartRadiusEqualToEndRadius)
emitter:setEndRadiusVar(0)
-- radius mode: degrees per second
emitter:setRotatePerSecond(45)
emitter:setRotatePerSecondVar(0)
-- angle
emitter:setAngle(90)
emitter:setAngleVar(0)
-- emitter position
emitter:setPosition(s.width / 2, s.height / 2)
emitter:setPosVar(ccp(0, 0))
-- life of particles
emitter:setLife(4)
emitter:setLifeVar(0)
-- spin of particles
emitter:setStartSpin(0)
emitter:setStartSpinVar(0)
emitter:setEndSpin(0)
emitter:setEndSpinVar(0)
-- color of particles
emitter:setStartColor(ccc4f(0.5, 0.5, 0.5, 1.0))
emitter:setStartColorVar(ccc4f(0.5, 0.5, 0.5, 1.0))
emitter:setEndColor(ccc4f(0.1, 0.1, 0.1, 0.2))
emitter:setEndColorVar(ccc4f(0.1, 0.1, 0.1, 0.2))
-- size, in pixels
emitter:setStartSize(32)
emitter:setStartSizeVar(0)
emitter:setEndSize(kCCParticleStartSizeEqualToEndSize)
-- emits per second
emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife())
-- additive
emitter:setBlendAdditive(false)
titleLabel:setString("Radius Mode: Semi Circle")
return layer
end
---------------------------------
-- Issue704
---------------------------------
local function Issue704()
local layer = getBaseLayer()
layer:setColor(ccc3(0, 0, 0))
layer:removeChild(background, true)
background = nil
emitter = CCParticleSystemQuad:new()
emitter:initWithTotalParticles(100)
layer:addChild(emitter, 10)
emitter:setTexture(CCTextureCache:sharedTextureCache():addImage("Images/fire.png"))
-- duration
emitter:setDuration(kCCParticleDurationInfinity)
-- radius mode
emitter:setEmitterMode(kCCParticleModeRadius)
-- radius mode: start and end radius in pixels
emitter:setStartRadius(50)
emitter:setStartRadiusVar(0)
emitter:setEndRadius(kCCParticleStartRadiusEqualToEndRadius)
emitter:setEndRadiusVar(0)
-- radius mode: degrees per second
emitter:setRotatePerSecond(0)
emitter:setRotatePerSecondVar(0)
-- angle
emitter:setAngle(90)
emitter:setAngleVar(0)
-- emitter position
emitter:setPosition(s.width / 2, s.height / 2)
emitter:setPosVar(ccp(0, 0))
-- life of particles
emitter:setLife(5)
emitter:setLifeVar(0)
-- spin of particles
emitter:setStartSpin(0)
emitter:setStartSpinVar(0)
emitter:setEndSpin(0)
emitter:setEndSpinVar(0)
-- color of particles
emitter:setStartColor(ccc4f(0.5, 0.5, 0.5, 1.0))
emitter:setStartColorVar(ccc4f(0.5, 0.5, 0.5, 1.0))
emitter:setEndColor(ccc4f(0.1, 0.1, 0.1, 0.2))
emitter:setEndColorVar(ccc4f(0.1, 0.1, 0.1, 0.2))
-- size, in pixels
emitter:setStartSize(16)
emitter:setStartSizeVar(0)
emitter:setEndSize(kCCParticleStartSizeEqualToEndSize)
-- emits per second
emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife())
-- additive
emitter:setBlendAdditive(false)
local rot = CCRotateBy:create(16, 360)
emitter:runAction(CCRepeatForever:create(rot))
titleLabel:setString("Issue 704. Free + Rot")
subtitleLabel:setString("Emitted particles should not rotate")
return layer
end
---------------------------------
-- Issue870
---------------------------------
local Issue870_index = nil
local Issue870_entry = nil
local function updateQuads(dt)
update(dt)
Issue870_index = math.mod(Issue870_index + 1, 4)
local rect = CCRectMake(Issue870_index * 32, 0, 32, 32)
emitter:setTextureWithRect(emitter:getTexture(), rect)
end
local function Issue870_onEnterOrExit(tag)
local scheduler = CCDirector:sharedDirector():getScheduler()
if tag == "enter" then
Issue870_entry = scheduler:scheduleScriptFunc(updateQuads, 2.0, false)
elseif tag == "exit" then
scheduler:unscheduleScriptEntry(Issue870_entry)
end
end
local function Issue870()
local layer = getBaseLayer()
layer:setColor(ccc3(0, 0, 0))
layer:removeChild(background, true)
background = nil
local system = CCParticleSystemQuad:new()
system:initWithFile("Particles/SpinningPeas.plist")
system:setTextureWithRect(CCTextureCache:sharedTextureCache():addImage("Images/particles.png"), CCRectMake(0,0,32,32))
layer:addChild(system, 10)
emitter = system
Issue870_index = 0
layer:registerScriptHandler(Issue870_onEnterOrExit)
titleLabel:setString("Issue 870. SubRect")
subtitleLabel:setString("Every 2 seconds the particle should change")
return layer
end
---------------------------------
-- MultipleParticleSystems
---------------------------------
local function MultipleParticleSystems()
local layer = getBaseLayer()
layer:setColor(ccc3(0, 0, 0))
layer:removeChild(background, true)
background = nil
CCTextureCache:sharedTextureCache():addImage("Images/particles.png")
for i = 0, 4 do
local particleSystem = CCParticleSystemQuad:create("Particles/SpinningPeas.plist")
particleSystem:setPosition(i * 50, i * 50)
particleSystem:setPositionType(kCCPositionTypeGrouped)
layer:addChild(particleSystem)
end
emitter = nil
titleLabel:setString("Multiple particle systems")
subtitleLabel:setString("v1.1 test: FPS should be lower than next test")
return layer
end
---------------------------------
-- MultipleParticleSystemsBatched
---------------------------------
local function MultipleParticleSystemsBatched()
local layer = getBaseLayer()
layer:setColor(ccc3(0, 0, 0))
layer:removeChild(background, true)
background = nil
local batchNode = CCParticleBatchNode:createWithTexture(nil, 3000)
layer:addChild(batchNode, 1, 2)
for i = 0, 4 do
local particleSystem = CCParticleSystemQuad:create("Particles/SpinningPeas.plist")
particleSystem:setPositionType(kCCPositionTypeGrouped)
particleSystem:setPosition(i * 50, i * 50)
batchNode:setTexture(particleSystem:getTexture())
batchNode:addChild(particleSystem)
end
emitter = nil
titleLabel:setString("Multiple particle systems batched")
subtitleLabel:setString("v1.1 test: should perform better than previous test")
return layer
end
---------------------------------
-- AddAndDeleteParticleSystems
---------------------------------
local AddAndDeleteParticleSystems_entry = nil
local AddAndDeleteParticleSystems_batchNode = nil
local function removeSystem(dt)
update(dt)
local ChildrenCount = AddAndDeleteParticleSystems_batchNode:getChildren():count()
if ChildrenCount > 0 then
cclog("remove random system")
local rand = math.mod(math.random(1, 999999), ChildrenCount - 1)
AddAndDeleteParticleSystems_batchNode:removeChild(AddAndDeleteParticleSystems_batchNode:getChildren():objectAtIndex(rand), true)
--add new
local particleSystem = CCParticleSystemQuad:create("Particles/Spiral.plist")
particleSystem:setPositionType(kCCPositionTypeGrouped)
particleSystem:setTotalParticles(200)
particleSystem:setPosition(math.mod(math.random(1, 999999), 300) ,math.mod(math.random(1, 999999), 400))
cclog("add a new system")
local randZ = math.floor(math.random() * 100)
AddAndDeleteParticleSystems_batchNode:addChild(particleSystem, randZ, -1)
end
end
local function AddAndDeleteParticleSystems_onEnterOrExit(tag)
local scheduler = CCDirector:sharedDirector():getScheduler()
if tag == "enter" then
AddAndDeleteParticleSystems_entry = scheduler:scheduleScriptFunc(removeSystem, 2.0, false)
elseif tag == "exit" then
scheduler:unscheduleScriptEntry(AddAndDeleteParticleSystems_entry)
end
end
local function AddAndDeleteParticleSystems()
local layer = getBaseLayer()
layer:setColor(ccc3(0, 0, 0))
layer:removeChild(background, true)
background = nil
--adds the texture inside the plist to the texture cache
AddAndDeleteParticleSystems_batchNode = CCParticleBatchNode:createWithTexture(nil, 16000)
layer:addChild(AddAndDeleteParticleSystems_batchNode, 1, 2)
for i = 0, 5 do
local particleSystem = CCParticleSystemQuad:create("Particles/Spiral.plist")
AddAndDeleteParticleSystems_batchNode:setTexture(particleSystem:getTexture())
particleSystem:setPositionType(kCCPositionTypeGrouped)
particleSystem:setTotalParticles(200)
particleSystem:setPosition(i * 15 + 100, i * 15 + 100)
local randZ = math.floor(math.random() * 100)
AddAndDeleteParticleSystems_batchNode:addChild(particleSystem, randZ, -1)
end
layer:registerScriptHandler(AddAndDeleteParticleSystems_onEnterOrExit)
emitter = nil
titleLabel:setString("Add and remove Particle System")
subtitleLabel:setString("v1.1 test: every 2 sec 1 system disappear, 1 appears")
return layer
end
---------------------------------
-- ReorderParticleSystems *
-- problem
---------------------------------
local ReorderParticleSystems_entry = nil
local ReorderParticleSystems_batchNode = nil
local function reorderSystem(dt)
update(dt)
local child = ReorderParticleSystems_batchNode:getChildren():randomObject()
-- problem: there's no getZOrder() for CCObject
-- ReorderParticleSystems_batchNode:reorderChild(child, child:getZOrder() - 1)
ReorderParticleSystems_batchNode:reorderChild(child, math.random(0, 99999))
end
local function ReorderParticleSystems_onEnterOrExit(tag)
local scheduler = CCDirector:sharedDirector():getScheduler()
if tag == "enter" then
ReorderParticleSystems_entry = scheduler:scheduleScriptFunc(reorderSystem, 2.0, false)
elseif tag == "exit" then
scheduler:unscheduleScriptEntry(ReorderParticleSystems_entry)
end
end
local function ReorderParticleSystems()
local layer = getBaseLayer()
layer:setColor(ccc3(0, 0, 0))
layer:removeChild(background ,true)
background = nil
ReorderParticleSystems_batchNode = CCParticleBatchNode:create("Images/stars-grayscale.png", 3000)
layer:addChild(ReorderParticleSystems_batchNode, 1, 2)
for i = 0, 2 do
local particleSystem = CCParticleSystemQuad:new()
particleSystem:initWithTotalParticles(200)
particleSystem:setTexture(ReorderParticleSystems_batchNode:getTexture())
-- duration
particleSystem:setDuration(kCCParticleDurationInfinity)
-- radius mode
particleSystem:setEmitterMode(kCCParticleModeRadius)
-- radius mode: 100 pixels from center
particleSystem:setStartRadius(100)
particleSystem:setStartRadiusVar(0)
particleSystem:setEndRadius(kCCParticleStartRadiusEqualToEndRadius)
particleSystem:setEndRadiusVar(0) -- not used when start == end
-- radius mode: degrees per second
-- 45 * 4 seconds of life = 180 degrees
particleSystem:setRotatePerSecond(45)
particleSystem:setRotatePerSecondVar(0)
-- angle
particleSystem:setAngle(90)
particleSystem:setAngleVar(0)
-- emitter position
particleSystem:setPosVar(ccp(0, 0))
-- life of particles
particleSystem:setLife(4)
particleSystem:setLifeVar(0)
-- spin of particles
particleSystem:setStartSpin(0)
particleSystem:setStartSpinVar(0)
particleSystem:setEndSpin(0)
particleSystem:setEndSpinVar(0)
-- color of particles
local startColor = ccColor4F:new()
startColor.r = 0
startColor.g = 0
startColor.b = 0
startColor.a = 1
if i == 0 then startColor.r = 1
elseif i == 1 then startColor.g = 1
elseif i == 2 then startColor.b = 1
end
particleSystem:setStartColor(startColor)
particleSystem:setStartColorVar(ccc4f(0, 0, 0, 0))
local endColor = startColor
particleSystem:setEndColor(endColor)
particleSystem:setEndColorVar(ccc4f(0, 0, 0, 0))
-- size, in pixels
particleSystem:setStartSize(32)
particleSystem:setStartSizeVar(0)
particleSystem:setEndSize(kCCParticleStartSizeEqualToEndSize)
-- emits per second
particleSystem:setEmissionRate(particleSystem:getTotalParticles() / particleSystem:getLife())
-- additive
particleSystem:setPosition(i * 10 + 120, 200)
ReorderParticleSystems_batchNode:addChild(particleSystem)
particleSystem:setPositionType(kCCPositionTypeFree)
particleSystem:release()
end
layer:registerScriptHandler(ReorderParticleSystems_onEnterOrExit)
emitter = nil
titleLabel:setString("reorder systems")
subtitleLabel:setString("changes every 2 seconds")
return layer
end
---------------------------------
-- PremultipliedAlphaTest
---------------------------------
local function PremultipliedAlphaTest()
local layer = getBaseLayer()
layer:setColor(ccc3(0, 0, 255))
layer:removeChild(background, true)
background = nil
emitter = CCParticleSystemQuad:create("Particles/BoilingFoam.plist")
local tBlendFunc = ccBlendFunc:new()
tBlendFunc.src = 1 --GL_ONE
tBlendFunc.dst = 0x0303 --GL_ONE_MINUS_SRC_ALPHA
emitter:setBlendFunc(tBlendFunc)
--assert(emitter:getOpacityModifyRGB(), "Particle texture does not have premultiplied alpha, test is useless")
emitter:setStartColor(ccc4f(1, 1, 1, 1))
emitter:setEndColor(ccc4f(1, 1, 1, 0))
emitter:setStartColorVar(ccc4f(0, 0, 0, 0))
emitter:setEndColorVar(ccc4f(0, 0, 0, 0))
layer:addChild(emitter, 10)
titleLabel:setString("premultiplied alpha")
subtitleLabel:setString("no black halo, particles should fade out")
return layer
end
---------------------------------
-- PremultipliedAlphaTest2
---------------------------------
local function PremultipliedAlphaTest2()
local layer = getBaseLayer()
layer:setColor(ccc3(0, 0, 0))
layer:removeChild(background, true)
background = nil
emitter = CCParticleSystemQuad:create("Particles/TestPremultipliedAlpha.plist")
layer:addChild(emitter ,10)
titleLabel:setString("premultiplied alpha 2")
subtitleLabel:setString("Arrows should be faded")
return layer
end
---------------------------------
-- Particle Test
---------------------------------
function CreateParticleLayer()
if SceneIdx == 0 then return ParticleReorder()
elseif SceneIdx == 1 then return ParticleBatchHybrid()
elseif SceneIdx == 2 then return ParticleBatchMultipleEmitters()
elseif SceneIdx == 3 then return DemoFlower()
elseif SceneIdx == 4 then return DemoGalaxy()
elseif SceneIdx == 5 then return DemoFirework()
elseif SceneIdx == 6 then return DemoSpiral()
elseif SceneIdx == 7 then return DemoSun()
elseif SceneIdx == 8 then return DemoMeteor()
elseif SceneIdx == 9 then return DemoFire()
elseif SceneIdx == 10 then return DemoSmoke()
elseif SceneIdx == 11 then return DemoExplosion()
elseif SceneIdx == 12 then return DemoSnow()
elseif SceneIdx == 13 then return DemoRain()
elseif SceneIdx == 14 then return DemoBigFlower()
elseif SceneIdx == 15 then return DemoRotFlower()
elseif SceneIdx == 16 then return DemoModernArt()
elseif SceneIdx == 17 then return DemoRing()
elseif SceneIdx == 18 then return ParallaxParticle()
elseif SceneIdx == 19 then return DemoParticleFromFile("BoilingFoam")
elseif SceneIdx == 20 then return DemoParticleFromFile("BurstPipe")
elseif SceneIdx == 21 then return DemoParticleFromFile("Comet")
elseif SceneIdx == 22 then return DemoParticleFromFile("debian")
elseif SceneIdx == 23 then return DemoParticleFromFile("ExplodingRing")
elseif SceneIdx == 24 then return DemoParticleFromFile("LavaFlow")
elseif SceneIdx == 25 then return DemoParticleFromFile("SpinningPeas")
elseif SceneIdx == 26 then return DemoParticleFromFile("SpookyPeas")
elseif SceneIdx == 27 then return DemoParticleFromFile("Upsidedown")
elseif SceneIdx == 28 then return DemoParticleFromFile("Flower")
elseif SceneIdx == 29 then return DemoParticleFromFile("Spiral")
elseif SceneIdx == 30 then return DemoParticleFromFile("Galaxy")
elseif SceneIdx == 31 then return DemoParticleFromFile("Phoenix")
elseif SceneIdx == 32 then return DemoParticleFromFile("lines")
elseif SceneIdx == 33 then return RadiusMode1()
elseif SceneIdx == 34 then return RadiusMode2()
elseif SceneIdx == 35 then return Issue704()
elseif SceneIdx == 36 then return Issue870()
--elseif SceneIdx == 36 then return Issue1201()
-- v1.1 tests
elseif SceneIdx == 37 then return MultipleParticleSystems()
elseif SceneIdx == 38 then return MultipleParticleSystemsBatched()
elseif SceneIdx == 39 then return AddAndDeleteParticleSystems()
elseif SceneIdx == 40 then return ReorderParticleSystems()
elseif SceneIdx == 41 then return PremultipliedAlphaTest()
elseif SceneIdx == 42 then return PremultipliedAlphaTest2()
end
end
function ParticleTest()
cclog("ParticleTest")
local scene = CCScene:create()
SceneIdx = -1
scene:addChild(nextAction())
scene:addChild(CreateBackMenuItem())
return scene
end
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.