repo_name stringlengths 6 78 | path stringlengths 4 206 | copies stringclasses 281
values | size stringlengths 4 7 | content stringlengths 625 1.05M | license stringclasses 15
values |
|---|---|---|---|---|---|
xdemolish/darkstar | scripts/zones/The_Eldieme_Necropolis/npcs/Sarcophagus.lua | 11 | 4269 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: Sarcophagus
-- Involved in Quest: The Requiem (BARD AF2)
-- @pos -420 8 500 195
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/zones/The_Eldieme_Necropolis/TextIDs");
-----------------------------------
-- sarcophagusNumber
-----------------------------------
function sarcophagusNumber(X,Z)
if(X <= -423 and X >= -426 and Z >= 494 and Z <= 499) then
return 1;
elseif(X <= -418 and X >= -423 and Z >= 500 and Z <= 505) then
return 2;
elseif(X <= -415 and X >= -418 and Z >= 500 and Z <= 505) then
return 3;
elseif(X <= -410 and X >= -415 and Z >= 500 and Z <= 505) then
return 4;
elseif(X <= -410 and X >= -415 and Z >= 494 and Z <= 499) then
return 5;
end
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getVar("TheRequiemCS") == 3 and trade:hasItemQty(4154,1) and trade:getItemCount() == 1) then
if(player:getVar("TheRequiemRandom") == 0) then
player:setVar("TheRequiemRandom",math.random(1,5));
end
if(sarcophagusNumber(npc:getXPos(),npc:getZPos()) == player:getVar("TheRequiemRandom") and player:getVar("TheRequiemYumKilled") == 0) then
player:tradeComplete();
player:messageSpecial(SENSE_OF_FOREBODING);
player:setVar("TheRequiemAlreadyPoped",1);
SpawnMob(17576264,300):updateEnmity(player); -- Spawn Yum Kimil NM @pos -414 8 499
SpawnMob(17576267,180):updateEnmity(player); -- Spawn Owl Guardian NM @pos -414 8 501
SpawnMob(17576266,180):updateEnmity(player); -- Spawn Dog Guardian NM @pos -414 8 497
else
player:messageSpecial(NOTHING_HAPPENED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local ANewDawn = player:getQuestStatus(JEUNO,A_NEW_DAWN);
local ANewDawnEvent = player:getVar("ANewDawn_Event");
-- BST AF3 Quest
if (sarcophagusNumber(npc:getXPos(),npc:getZPos()) == 4 and ANewDawn == QUEST_ACCEPTED) then
if (ANewDawnEvent == 4) then
for i = 17576267, 17576269 do
if (GetMobAction(i) == 0) then
SpawnMob(i,180):updateEnmity(player); -- Spawn Sturm, Taifun and Trombe.
end
end
elseif (ANewDawnEvent == 5) then
player:startEvent(0x002d);
end
-- BRD AF Quest
elseif(sarcophagusNumber(npc:getXPos(),npc:getZPos()) == player:getVar("TheRequiemRandom")) then
if(player:getVar("TheRequiemYumKilled") == 1) then
player:startEvent(0x002e);
elseif(player:getVar("TheRequiemAlreadyPoped") == 1) then
player:messageSpecial(SENSE_OF_FOREBODING);
SpawnMob(17576264):updateEnmity(player); -- Spawn Yum Kimil NM @pos -414 8 499
SpawnMob(17576267):updateEnmity(player); -- Spawn Owl Guardian NM @pos -414 8 501
SpawnMob(17576266):updateEnmity(player); -- Spawn Dog Guardian NM @pos -414 8 497
end
-- Standard Dialogue
else
player:messageSpecial(SARCOPHAGUS_CANNOT_BE_OPENED);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x002e) then
player:setVar("TheRequiemCS",0);
player:setVar("TheRequiemYumKilled",0);
player:setVar("TheRequiemRandom",0);
player:setVar("TheRequiemAlreadyPoped",0);
player:addKeyItem(STAR_RING1);
player:messageSpecial(KEYITEM_OBTAINED,STAR_RING1); -- Star Ring (Key Item).
elseif (csid == 0x002d) then
player:setVar("ANewDawn_Event",6);
player:delKeyItem(217);
player:addTitle(196);
player:addItem(14222,1);
player:messageSpecial(ITEM_OBTAINED,14222);
player:completeQuest(JEUNO,A_NEW_DAWN);
player:addFame(JEUNO, JEUNO_FAME*30);
end
end; | gpl-3.0 |
xdemolish/darkstar | scripts/zones/Cloister_of_Flames/Zone.lua | 32 | 1663 | -----------------------------------
--
-- Zone: Cloister_of_Flames (207)
--
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Flames/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Cloister_of_Flames/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-698.729,-1.045,-646.659,184);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
xdemolish/darkstar | scripts/zones/AlTaieu/npcs/_0x2.lua | 3 | 2389 | -----------------------------------
-- Area: Al'Taieu
-- NPC: Rubious Crystal (West Tower)
-- @pos -683.709 -6.250 -222.142 33
-----------------------------------
package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/AlTaieu/TextIDs");
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and (player:getVar("PromathiaStatus")==2 or player:getVar("PromathiaStatus")==4 or player:getVar("PromathiaStatus")==6)
and player:getVar("Ru_aern_2-1KILL")==0 or player:getVar("Ru_aern_2-2KILL")==0 or player:getVar("Ru_aern_2-3KILL")==0)then
player:messageSpecial(OMINOUS_SHADOW);
SpawnMob(16912832,180):updateEnmity(player);
SpawnMob(16912833,180):updateEnmity(player);
SpawnMob(16912834,180):updateEnmity(player);
elseif(player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and player:getVar("Ru_aern_2-1KILL")==1 and player:getVar("Ru_aern_2-2KILL")==1 and player:getVar("Ru_aern_2-3KILL")==1) then
if(player:getVar("PromathiaStatus")==3) then
player:startEvent(0x00A1);
elseif(player:getVar("PromathiaStatus")==5) then
player:startEvent(0x00A2);
elseif(player:getVar("PromathiaStatus")==7)then
player:startEvent(0x00A3);
else
player:messageSpecial(NOTHING_OF_INTEREST);
end
else
player:messageSpecial(NOTHING_OF_INTEREST);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if(csid == 0x00A1)then
player:setVar("PromathiaStatus",4);
elseif(csid == 0x00A2)then
player:setVar("PromathiaStatus",6);
elseif(csid == 0x00A3)then
player:setVar("PromathiaStatus",8);
end
end; | gpl-3.0 |
xdemolish/darkstar | scripts/zones/Mhaura/npcs/Vera.lua | 17 | 2846 | -----------------------------------
-- Area: Mhaura
-- NPC: Vera
-- Finishes Quest: The Old Lady
-- @pos -49 -5 20 249
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local questStatus = player:getQuestStatus(OTHER_AREAS,THE_OLD_LADY);
if(questStatus == QUEST_ACCEPTED and trade:getItemCount() == 1) then
local VeraOldLadyVar = player:getVar("VeraOldLadyVar");
if(VeraOldLadyVar == 1 and trade:hasItemQty(542,1)) then
player:startEvent(0x0087,541);
elseif(VeraOldLadyVar == 2 and trade:hasItemQty(541,1)) then
player:startEvent(0x0088,540);
elseif(VeraOldLadyVar == 3 and trade:hasItemQty(540,1)) then
player:startEvent(0x0089);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local questStatus = player:getQuestStatus(OTHER_AREAS, THE_OLD_LADY);
if(player:getQuestStatus(OTHER_AREAS, ELDER_MEMORIES) ~= QUEST_AVAILABLE) then
player:startEvent(0x0082);
elseif(questStatus == QUEST_COMPLETED) then
player:startEvent(0x008a);
elseif(questStatus == QUEST_ACCEPTED) then
VeraOldLadyVar = player:getVar("VeraOldLadyVar");
if(VeraOldLadyVar == 1) then
player:startEvent(0x0084,542);
elseif(VeraOldLadyVar == 2) then
player:startEvent(0x0084,541);
elseif(VeraOldLadyVar == 3) then
player:startEvent(0x0084,540);
end
else
if(player:getMainLvl() >= SUBJOB_QUEST_LEVEL) then
player:startEvent(0x0083,542);
else
player:startEvent(0x0085);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x0083 and option == 40) then
player:addQuest(OTHER_AREAS, THE_OLD_LADY);
player:setVar("VeraOldLadyVar", 1);
elseif(csid == 0x0087) then
player:tradeComplete();
player:setVar("VeraOldLadyVar", 2);
elseif(csid == 0x0088) then
player:tradeComplete();
player:setVar("VeraOldLadyVar", 3);
elseif(csid == 0x0089) then
player:tradeComplete();
player:unlockJob(0);
player:setVar("VeraOldLadyVar", 0);
player:messageSpecial(SUBJOB_UNLOCKED);
player:completeQuest(OTHER_AREAS,THE_OLD_LADY);
end
end; | gpl-3.0 |
xdemolish/darkstar | scripts/zones/Al_Zahbi/npcs/Ndego.lua | 19 | 1139 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Ndego
-- Guild Merchant NPC: Smithing Guild
-- @pos -37.192 0.000 -33.949 48
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Al_Zahbi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:sendGuild(60427,8,23,2)) then
player:showText(npc,NDEGO_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
xdemolish/darkstar | scripts/zones/Hall_of_the_Gods/Zone.lua | 32 | 1936 | -----------------------------------
--
-- Zone: Hall_of_the_Gods (251)
--
-----------------------------------
package.loaded["scripts/zones/Hall_of_the_Gods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Hall_of_the_Gods/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-0.011,-1.848,-176.133,192);
elseif (player:getCurrentMission(ACP) == REMEMBER_ME_IN_YOUR_DREAMS and prevZone == 122) then
cs = 0x0005;
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0005) then
player:completeMission(ACP,REMEMBER_ME_IN_YOUR_DREAMS);
player:addMission(ACP,BORN_OF_HER_NIGHTMARES);
end
end; | gpl-3.0 |
lukego/snabb | lib/ljsyscall/syscall/syscalls.lua | 13 | 33583 | -- choose correct syscalls for OS, plus shared calls
-- note that where functions are identical if present but may be missing they can also go here
-- note that OS specific calls are loaded at the end so they may override generic calls here
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
local abi = require "syscall.abi"
local ffi = require "ffi"
local bit = require "syscall.bit"
local h = require "syscall.helpers"
local err64 = h.err64
local errpointer = h.errpointer
local getfd, istype, mktype, reviter = h.getfd, h.istype, h.mktype, h.reviter
local function init(C, c, types)
-- this could be an arguments, fcntl syscall is a function of this
local fcntl = require("syscall." .. abi.os .. ".fcntl").init(types)
local errno = ffi.errno
local t, pt, s = types.t, types.pt, types.s
local S = {}
local function getdev(dev)
if type(dev) == "table" then return t.device(dev).dev end
if ffi.istype(t.device, dev) then dev = dev.dev end
return dev
end
-- return helpers.
-- 64 bit return helpers. Only use for lseek in fact; we use tonumber but remove if you need files over 56 bits long
-- TODO only luaffi needs the cast as wont compare to number; hopefully fixed in future with 5.3 or a later luaffi.
local function ret64(ret, err)
if ret == err64 then return nil, t.error(err or errno()) end
return tonumber(ret)
end
local function retnum(ret, err) -- return Lua number where double precision ok, eg file ops etc
ret = tonumber(ret)
if ret == -1 then return nil, t.error(err or errno()) end
return ret
end
local function retfd(ret, err)
if ret == -1 then return nil, t.error(err or errno()) end
return t.fd(ret)
end
-- used for no return value, return true for use of assert
local function retbool(ret, err)
if ret == -1 then return nil, t.error(err or errno()) end
return true
end
-- used for pointer returns, -1 is failure
local function retptr(ret, err)
if ret == errpointer then return nil, t.error(err or errno()) end
return ret
end
-- generic iterator; this counts down to 0 so need no closure
local function retiter(ret, err, array)
ret = tonumber(ret)
if ret == -1 then return nil, t.error(err or errno()) end
return reviter, array, ret
end
-- generic system calls
function S.close(fd) return retbool(C.close(getfd(fd))) end
function S.chdir(path) return retbool(C.chdir(path)) end
function S.fchdir(fd) return retbool(C.fchdir(getfd(fd))) end
function S.fchmod(fd, mode) return retbool(C.fchmod(getfd(fd), c.MODE[mode])) end
function S.fchown(fd, owner, group) return retbool(C.fchown(getfd(fd), owner or -1, group or -1)) end
function S.lchown(path, owner, group) return retbool(C.lchown(path, owner or -1, group or -1)) end
function S.chroot(path) return retbool(C.chroot(path)) end
function S.umask(mask) return C.umask(c.MODE[mask]) end
function S.sync() C.sync() end
function S.flock(fd, operation) return retbool(C.flock(getfd(fd), c.LOCK[operation])) end
-- TODO read should have consistent return type but then will differ from other calls.
function S.read(fd, buf, count)
if buf then return retnum(C.read(getfd(fd), buf, count or #buf or 4096)) end -- user supplied a buffer, standard usage
count = count or 4096
buf = t.buffer(count)
local ret, err = tonumber(C.read(getfd(fd), buf, count))
if ret == -1 then return nil, t.error(err or errno()) end
return ffi.string(buf, ret) -- user gets a string back, can get length from #string
end
function S.readv(fd, iov)
iov = mktype(t.iovecs, iov)
return retnum(C.readv(getfd(fd), iov.iov, #iov))
end
function S.write(fd, buf, count) return retnum(C.write(getfd(fd), buf, count or #buf)) end
function S.writev(fd, iov)
iov = mktype(t.iovecs, iov)
return retnum(C.writev(getfd(fd), iov.iov, #iov))
end
function S.pread(fd, buf, count, offset) return retnum(C.pread(getfd(fd), buf, count, offset)) end
function S.pwrite(fd, buf, count, offset) return retnum(C.pwrite(getfd(fd), buf, count or #buf, offset)) end
if C.preadv and C.pwritev then -- these are missing in eg OSX
function S.preadv(fd, iov, offset)
iov = mktype(t.iovecs, iov)
return retnum(C.preadv(getfd(fd), iov.iov, #iov, offset))
end
function S.pwritev(fd, iov, offset)
iov = mktype(t.iovecs, iov)
return retnum(C.pwritev(getfd(fd), iov.iov, #iov, offset))
end
end
function S.lseek(fd, offset, whence)
return ret64(C.lseek(getfd(fd), offset or 0, c.SEEK[whence or c.SEEK.SET]))
end
if C.readlink then
function S.readlink(path, buffer, size)
size = size or c.PATH_MAX
buffer = buffer or t.buffer(size)
local ret, err = tonumber(C.readlink(path, buffer, size))
if ret == -1 then return nil, t.error(err or errno()) end
return ffi.string(buffer, ret)
end
else
function S.readlink(path, buffer, size)
size = size or c.PATH_MAX
buffer = buffer or t.buffer(size)
local ret, err = tonumber(C.readlinkat(c.AT_FDCWD.FDCWD, path, buffer, size))
if ret == -1 then return nil, t.error(err or errno()) end
return ffi.string(buffer, ret)
end
end
function S.fsync(fd) return retbool(C.fsync(getfd(fd))) end
if C.stat then
function S.stat(path, buf)
if not buf then buf = t.stat() end
local ret = C.stat(path, buf)
if ret == -1 then return nil, t.error() end
return buf
end
else
function S.stat(path, buf)
if not buf then buf = t.stat() end
local ret = C.fstatat(c.AT_FDCWD.FDCWD, path, buf, 0)
if ret == -1 then return nil, t.error() end
return buf
end
end
if C.lstat then
function S.lstat(path, buf)
if not buf then buf = t.stat() end
local ret, err = C.lstat(path, buf)
if ret == -1 then return nil, t.error(err or errno()) end
return buf
end
else
function S.lstat(path, buf)
if not buf then buf = t.stat() end
local ret, err = C.fstatat(c.AT_FDCWD.FDCWD, path, buf, c.AT.SYMLINK_NOFOLLOW)
if ret == -1 then return nil, t.error(err or errno()) end
return buf
end
end
function S.fstat(fd, buf)
if not buf then buf = t.stat() end
local ret, err = C.fstat(getfd(fd), buf)
if ret == -1 then return nil, t.error(err or errno()) end
return buf
end
function S.truncate(path, length) return retbool(C.truncate(path, length)) end
function S.ftruncate(fd, length) return retbool(C.ftruncate(getfd(fd), length)) end
-- recent Linux does not have open, rmdir, unlink etc any more as syscalls
if C.open then
function S.open(pathname, flags, mode) return retfd(C.open(pathname, c.O[flags], c.MODE[mode])) end
else
function S.open(pathname, flags, mode) return retfd(C.openat(c.AT_FDCWD.FDCWD, pathname, c.O[flags], c.MODE[mode])) end
end
if C.rmdir then
function S.rmdir(path) return retbool(C.rmdir(path)) end
else
function S.rmdir(path) return retbool(C.unlinkat(c.AT_FDCWD.FDCWD, path, c.AT.REMOVEDIR)) end
end
if C.unlink then
function S.unlink(pathname) return retbool(C.unlink(pathname)) end
else
function S.unlink(path) return retbool(C.unlinkat(c.AT_FDCWD.FDCWD, path, 0)) end
end
if C.chmod then
function S.chmod(path, mode) return retbool(C.chmod(path, c.MODE[mode])) end
else
function S.chmod(path, mode) return retbool(C.fchmodat(c.AT_FDCWD.FDCWD, path, c.MODE[mode], 0)) end
end
if C.access then
function S.access(pathname, mode) return retbool(C.access(pathname, c.OK[mode])) end
else
function S.access(pathname, mode) return retbool(C.faccessat(c.AT_FDCWD.FDCWD, pathname, c.OK[mode], 0)) end
end
if C.chown then
function S.chown(path, owner, group) return retbool(C.chown(path, owner or -1, group or -1)) end
else
function S.chown(path, owner, group) return retbool(C.fchownat(c.AT_FDCWD.FDCWD, path, owner or -1, group or -1, 0)) end
end
if C.mkdir then
function S.mkdir(path, mode) return retbool(C.mkdir(path, c.MODE[mode])) end
else
function S.mkdir(path, mode) return retbool(C.mkdirat(c.AT_FDCWD.FDCWD, path, c.MODE[mode])) end
end
if C.symlink then
function S.symlink(oldpath, newpath) return retbool(C.symlink(oldpath, newpath)) end
else
function S.symlink(oldpath, newpath) return retbool(C.symlinkat(oldpath, c.AT_FDCWD.FDCWD, newpath)) end
end
if C.link then
function S.link(oldpath, newpath) return retbool(C.link(oldpath, newpath)) end
else
function S.link(oldpath, newpath) return retbool(C.linkat(c.AT_FDCWD.FDCWD, oldpath, c.AT_FDCWD.FDCWD, newpath, 0)) end
end
if C.rename then
function S.rename(oldpath, newpath) return retbool(C.rename(oldpath, newpath)) end
else
function S.rename(oldpath, newpath) return retbool(C.renameat(c.AT_FDCWD.FDCWD, oldpath, c.AT_FDCWD.FDCWD, newpath)) end
end
if C.mknod then
function S.mknod(pathname, mode, dev) return retbool(C.mknod(pathname, c.S_I[mode], getdev(dev) or 0)) end
else
function S.mknod(pathname, mode, dev) return retbool(C.mknodat(c.AT_FDCWD.FDCWD, pathname, c.S_I[mode], getdev(dev) or 0)) end
end
local function sproto(domain, protocol) -- helper function to lookup protocol type depending on domain TODO table?
protocol = protocol or 0
if domain == c.AF.NETLINK then return c.NETLINK[protocol] end
return c.IPPROTO[protocol]
end
function S.socket(domain, stype, protocol)
domain = c.AF[domain]
return retfd(C.socket(domain, c.SOCK[stype], sproto(domain, protocol)))
end
function S.socketpair(domain, stype, protocol, sv2)
domain = c.AF[domain]
sv2 = sv2 or t.int2()
local ret, err = C.socketpair(domain, c.SOCK[stype], sproto(domain, protocol), sv2)
if ret == -1 then return nil, t.error(err or errno()) end
return true, nil, t.fd(sv2[0]), t.fd(sv2[1])
end
function S.dup(oldfd) return retfd(C.dup(getfd(oldfd))) end
if C.dup2 then function S.dup2(oldfd, newfd) return retfd(C.dup2(getfd(oldfd), getfd(newfd))) end end
if C.dup3 then function S.dup3(oldfd, newfd, flags) return retfd(C.dup3(getfd(oldfd), getfd(newfd), flags or 0)) end end
function S.sendto(fd, buf, count, flags, addr, addrlen)
if not addr then addrlen = 0 end
local saddr = pt.sockaddr(addr)
return retnum(C.sendto(getfd(fd), buf, count or #buf, c.MSG[flags], saddr, addrlen or #addr))
end
function S.recvfrom(fd, buf, count, flags, addr, addrlen)
local saddr
if addr == false then
addr = nil
addrlen = nil
else
if addr then
addrlen = addrlen or #addr
else
addr = t.sockaddr_storage()
addrlen = addrlen or s.sockaddr_storage
end
if type(addrlen) == "number" then addrlen = t.socklen1(addrlen) end
saddr = pt.sockaddr(addr)
end
local ret, err = C.recvfrom(getfd(fd), buf, count or #buf, c.MSG[flags], saddr, addrlen) -- TODO addrlen 0 here???
ret = tonumber(ret)
if ret == -1 then return nil, t.error(err or errno()) end
if addr then return ret, nil, t.sa(addr, addrlen[0]) else return ret end
end
function S.sendmsg(fd, msg, flags)
if not msg then -- send a single byte message, eg enough to send credentials
local buf1 = t.buffer(1)
local io = t.iovecs{{buf1, 1}}
msg = t.msghdr{msg_iov = io.iov, msg_iovlen = #io}
end
return retnum(C.sendmsg(getfd(fd), msg, c.MSG[flags]))
end
function S.recvmsg(fd, msg, flags) return retnum(C.recvmsg(getfd(fd), msg, c.MSG[flags])) end
-- TODO better handling of msgvec, create one structure/table
if C.sendmmsg then
function S.sendmmsg(fd, msgvec, flags)
msgvec = mktype(t.mmsghdrs, msgvec)
return retbool(C.sendmmsg(getfd(fd), msgvec.msg, msgvec.count, c.MSG[flags]))
end
end
if C.recvmmsg then
function S.recvmmsg(fd, msgvec, flags, timeout)
if timeout then timeout = mktype(t.timespec, timeout) end
msgvec = mktype(t.mmsghdrs, msgvec)
return retbool(C.recvmmsg(getfd(fd), msgvec.msg, msgvec.count, c.MSG[flags], timeout))
end
end
-- TODO {get,set}sockopt may need better type handling see new unfinished sockopt file, plus not always c.SO[]
function S.setsockopt(fd, level, optname, optval, optlen)
-- allocate buffer for user, from Lua type if know how, int and bool so far
if not optlen and type(optval) == 'boolean' then optval = h.booltoc(optval) end
if not optlen and type(optval) == 'number' then
optval = t.int1(optval)
optlen = s.int
end
return retbool(C.setsockopt(getfd(fd), c.SOL[level], c.SO[optname], optval, optlen))
end
function S.getsockopt(fd, level, optname, optval, optlen)
if not optval then optval, optlen = t.int1(), s.int end
optlen = optlen or #optval
local len = t.socklen1(optlen)
local ret, err = C.getsockopt(getfd(fd), c.SOL[level], c.SO[optname], optval, len)
if ret == -1 then return nil, t.error(err or errno()) end
if len[0] ~= optlen then error("incorrect optlen for getsockopt: set " .. optlen .. " got " .. len[0]) end
return optval[0] -- TODO will not work if struct, eg see netfilter
end
function S.bind(sockfd, addr, addrlen)
local saddr = pt.sockaddr(addr)
return retbool(C.bind(getfd(sockfd), saddr, addrlen or #addr))
end
function S.listen(sockfd, backlog) return retbool(C.listen(getfd(sockfd), backlog or c.SOMAXCONN)) end
function S.connect(sockfd, addr, addrlen)
local saddr = pt.sockaddr(addr)
return retbool(C.connect(getfd(sockfd), saddr, addrlen or #addr))
end
function S.accept(sockfd, addr, addrlen)
local saddr = pt.sockaddr(addr)
if addr then addrlen = addrlen or t.socklen1() end
return retfd(C.accept(getfd(sockfd), saddr, addrlen))
end
function S.getsockname(sockfd, addr, addrlen)
addr = addr or t.sockaddr_storage()
addrlen = addrlen or t.socklen1(#addr)
local saddr = pt.sockaddr(addr)
local ret, err = C.getsockname(getfd(sockfd), saddr, addrlen)
if ret == -1 then return nil, t.error(err or errno()) end
return t.sa(addr, addrlen[0])
end
function S.getpeername(sockfd, addr, addrlen)
addr = addr or t.sockaddr_storage()
addrlen = addrlen or t.socklen1(#addr)
local saddr = pt.sockaddr(addr)
local ret, err = C.getpeername(getfd(sockfd), saddr, addrlen)
if ret == -1 then return nil, t.error(err or errno()) end
return t.sa(addr, addrlen[0])
end
function S.shutdown(sockfd, how) return retbool(C.shutdown(getfd(sockfd), c.SHUT[how])) end
if C.poll then
function S.poll(fds, timeout) return retnum(C.poll(fds.pfd, #fds, timeout or -1)) end
end
-- TODO rework fdset interface, see issue #71
-- fdset handlers
local function mkfdset(fds, nfds) -- should probably check fd is within range (1024), or just expand structure size
local set = t.fdset()
for i, v in ipairs(fds) do
local fd = tonumber(getfd(v))
if fd + 1 > nfds then nfds = fd + 1 end
local fdelt = bit.rshift(fd, 5) -- always 32 bits
set.fds_bits[fdelt] = bit.bor(set.fds_bits[fdelt], bit.lshift(1, fd % 32)) -- always 32 bit words
end
return set, nfds
end
local function fdisset(fds, set)
local f = {}
for i, v in ipairs(fds) do
local fd = tonumber(getfd(v))
local fdelt = bit.rshift(fd, 5) -- always 32 bits
if bit.band(set.fds_bits[fdelt], bit.lshift(1, fd % 32)) ~= 0 then table.insert(f, v) end -- careful not to duplicate fd objects
end
return f
end
-- TODO convert to metatype. Problem is how to deal with nfds
if C.select then
function S.select(sel, timeout) -- note same structure as returned
local r, w, e
local nfds = 0
if timeout then timeout = mktype(t.timeval, timeout) end
r, nfds = mkfdset(sel.readfds or {}, nfds or 0)
w, nfds = mkfdset(sel.writefds or {}, nfds)
e, nfds = mkfdset(sel.exceptfds or {}, nfds)
local ret, err = C.select(nfds, r, w, e, timeout)
if ret == -1 then return nil, t.error(err or errno()) end
return {readfds = fdisset(sel.readfds or {}, r), writefds = fdisset(sel.writefds or {}, w),
exceptfds = fdisset(sel.exceptfds or {}, e), count = tonumber(ret)}
end
else
function S.select(sel, timeout)
if timeout then timeout = mktype(t.timespec, timeout / 1000) end
return S.pselect(sel, timeout)
end
end
-- TODO note that in Linux syscall modifies timeout, which is non standard, like ppoll
function S.pselect(sel, timeout, set) -- note same structure as returned
local r, w, e
local nfds = 0
if timeout then timeout = mktype(t.timespec, timeout) end
if set then set = mktype(t.sigset, set) end
r, nfds = mkfdset(sel.readfds or {}, nfds or 0)
w, nfds = mkfdset(sel.writefds or {}, nfds)
e, nfds = mkfdset(sel.exceptfds or {}, nfds)
local ret, err = C.pselect(nfds, r, w, e, timeout, set)
if ret == -1 then return nil, t.error(err or errno()) end
return {readfds = fdisset(sel.readfds or {}, r), writefds = fdisset(sel.writefds or {}, w),
exceptfds = fdisset(sel.exceptfds or {}, e), count = tonumber(ret)}
end
function S.getuid() return C.getuid() end
function S.geteuid() return C.geteuid() end
function S.getpid() return C.getpid() end
function S.getppid() return C.getppid() end
function S.getgid() return C.getgid() end
function S.getegid() return C.getegid() end
function S.setuid(uid) return retbool(C.setuid(uid)) end
function S.setgid(gid) return retbool(C.setgid(gid)) end
function S.seteuid(uid) return retbool(C.seteuid(uid)) end
function S.setegid(gid) return retbool(C.setegid(gid)) end
function S.getsid(pid) return retnum(C.getsid(pid or 0)) end
function S.setsid() return retnum(C.setsid()) end
function S.setpgid(pid, pgid) return retbool(C.setpgid(pid or 0, pgid or 0)) end
function S.getpgid(pid) return retnum(C.getpgid(pid or 0)) end
if C.getpgrp then
function S.getpgrp() return retnum(C.getpgrp()) end
else
function S.getpgrp() return retnum(C.getpgid(0)) end
end
function S.getgroups()
local size = C.getgroups(0, nil) -- note for BSD could use NGROUPS_MAX instead
if size == -1 then return nil, t.error() end
local groups = t.groups(size)
local ret = C.getgroups(size, groups.list)
if ret == -1 then return nil, t.error() end
return groups
end
function S.setgroups(groups)
if type(groups) == "table" then groups = t.groups(groups) end
return retbool(C.setgroups(groups.count, groups.list))
end
function S.sigprocmask(how, set, oldset)
oldset = oldset or t.sigset()
if not set then how = c.SIGPM.SETMASK end -- value does not matter if set nil, just returns old set
local ret, err = C.sigprocmask(c.SIGPM[how], t.sigset(set), oldset)
if ret == -1 then return nil, t.error(err or errno()) end
return oldset
end
function S.sigpending()
local set = t.sigset()
local ret, err = C.sigpending(set)
if ret == -1 then return nil, t.error(err or errno()) end
return set
end
function S.sigsuspend(mask) return retbool(C.sigsuspend(t.sigset(mask))) end
function S.kill(pid, sig) return retbool(C.kill(pid, c.SIG[sig])) end
-- _exit is the real exit syscall, or whatever is suitable if overridden in c.lua; libc.lua may override
function S.exit(status) C._exit(c.EXIT[status or 0]) end
function S.fcntl(fd, cmd, arg)
cmd = c.F[cmd]
if fcntl.commands[cmd] then arg = fcntl.commands[cmd](arg) end
local ret, err = C.fcntl(getfd(fd), cmd, pt.void(arg or 0))
if ret == -1 then return nil, t.error(err or errno()) end
if fcntl.ret[cmd] then return fcntl.ret[cmd](ret, arg) end
return true
end
-- TODO return metatype that has length and can gc?
function S.mmap(addr, length, prot, flags, fd, offset)
return retptr(C.mmap(addr, length, c.PROT[prot], c.MAP[flags], getfd(fd or -1), offset or 0))
end
function S.munmap(addr, length)
return retbool(C.munmap(addr, length))
end
function S.msync(addr, length, flags) return retbool(C.msync(addr, length, c.MSYNC[flags])) end
function S.mlock(addr, len) return retbool(C.mlock(addr, len)) end
function S.munlock(addr, len) return retbool(C.munlock(addr, len)) end
function S.munlockall() return retbool(C.munlockall()) end
function S.madvise(addr, length, advice) return retbool(C.madvise(addr, length, c.MADV[advice])) end
function S.ioctl(d, request, argp)
local read, singleton = false, false
local name = request
if type(name) == "string" then
request = c.IOCTL[name]
end
if type(request) == "table" then
local write = request.write
local tp = request.type
read = request.read
singleton = request.singleton
request = request.number
if type(argp) ~= "string" and type(argp) ~= "cdata" and type ~= "userdata" then
if write then
if not argp then error("no argument supplied for ioctl " .. name) end
argp = mktype(tp, argp)
end
if read then
argp = argp or tp()
end
end
else -- some sane defaults if no info
if type(request) == "table" then request = request.number end
if type(argp) == "string" then argp = pt.char(argp) end
if type(argp) == "number" then argp = t.int1(argp) end
end
local ret, err = C.ioctl(getfd(d), request, argp)
if ret == -1 then return nil, t.error(err or errno()) end
if read and singleton then return argp[0] end
if read then return argp end
return true -- will need override for few linux ones that return numbers
end
if C.pipe then
function S.pipe(fd2)
fd2 = fd2 or t.int2()
local ret, err = C.pipe(fd2)
if ret == -1 then return nil, t.error(err or errno()) end
return true, nil, t.fd(fd2[0]), t.fd(fd2[1])
end
else
function S.pipe(fd2)
fd2 = fd2 or t.int2()
local ret, err = C.pipe2(fd2, 0)
if ret == -1 then return nil, t.error(err or errno()) end
return true, nil, t.fd(fd2[0]), t.fd(fd2[1])
end
end
if C.gettimeofday then
function S.gettimeofday(tv)
tv = tv or t.timeval() -- note it is faster to pass your own tv if you call a lot
local ret, err = C.gettimeofday(tv, nil)
if ret == -1 then return nil, t.error(err or errno()) end
return tv
end
end
if C.settimeofday then
function S.settimeofday(tv) return retbool(C.settimeofday(tv, nil)) end
end
function S.getrusage(who, ru)
ru = ru or t.rusage()
local ret, err = C.getrusage(c.RUSAGE[who], ru)
if ret == -1 then return nil, t.error(err or errno()) end
return ru
end
if C.fork then
function S.fork() return retnum(C.fork()) end
else
function S.fork() return retnum(C.clone(c.SIG.CHLD, 0)) end
end
function S.execve(filename, argv, envp)
local cargv = t.string_array(#argv + 1, argv or {})
cargv[#argv] = nil -- LuaJIT does not zero rest of a VLA
local cenvp = t.string_array(#envp + 1, envp or {})
cenvp[#envp] = nil
return retbool(C.execve(filename, cargv, cenvp))
end
-- man page says obsolete for Linux, but implemented and useful for compatibility
function S.wait4(pid, options, ru, status) -- note order of arguments changed as rarely supply status (as waitpid)
if ru == false then ru = nil else ru = ru or t.rusage() end -- false means no allocation
status = status or t.int1()
local ret, err = C.wait4(c.WAIT[pid], status, c.W[options], ru)
if ret == -1 then return nil, t.error(err or errno()) end
return ret, nil, t.waitstatus(status[0]), ru
end
if C.waitpid then
function S.waitpid(pid, options, status) -- note order of arguments changed as rarely supply status
status = status or t.int1()
local ret, err = C.waitpid(c.WAIT[pid], status, c.W[options])
if ret == -1 then return nil, t.error(err or errno()) end
return ret, nil, t.waitstatus(status[0])
end
end
if S.waitid then
function S.waitid(idtype, id, options, infop) -- note order of args, as usually dont supply infop
if not infop then infop = t.siginfo() end
local ret, err = C.waitid(c.P[idtype], id or 0, infop, c.W[options])
if ret == -1 then return nil, t.error(err or errno()) end
return infop
end
end
function S.setpriority(which, who, prio) return retbool(C.setpriority(c.PRIO[which], who or 0, prio)) end
-- Linux overrides getpriority as it offsets return values so that they are not negative
function S.getpriority(which, who)
errno(0)
local ret, err = C.getpriority(c.PRIO[which], who or 0)
if ret == -1 and (err or errno()) ~= 0 then return nil, t.error(err or errno()) end
return ret
end
-- these may not always exist, but where they do they have the same interface
if C.creat then
function S.creat(pathname, mode) return retfd(C.creat(pathname, c.MODE[mode])) end
end
if C.pipe2 then
function S.pipe2(flags, fd2)
fd2 = fd2 or t.int2()
local ret, err = C.pipe2(fd2, c.OPIPE[flags])
if ret == -1 then return nil, t.error(err or errno()) end
return true, nil, t.fd(fd2[0]), t.fd(fd2[1])
end
end
if C.mlockall then
function S.mlockall(flags) return retbool(C.mlockall(c.MCL[flags])) end
end
if C.linkat then
function S.linkat(olddirfd, oldpath, newdirfd, newpath, flags)
return retbool(C.linkat(c.AT_FDCWD[olddirfd], oldpath, c.AT_FDCWD[newdirfd], newpath, c.AT[flags]))
end
end
if C.symlinkat then
function S.symlinkat(oldpath, newdirfd, newpath) return retbool(C.symlinkat(oldpath, c.AT_FDCWD[newdirfd], newpath)) end
end
if C.unlinkat then
function S.unlinkat(dirfd, path, flags) return retbool(C.unlinkat(c.AT_FDCWD[dirfd], path, c.AT[flags])) end
end
if C.renameat then
function S.renameat(olddirfd, oldpath, newdirfd, newpath)
return retbool(C.renameat(c.AT_FDCWD[olddirfd], oldpath, c.AT_FDCWD[newdirfd], newpath))
end
end
if C.mkdirat then
function S.mkdirat(fd, path, mode) return retbool(C.mkdirat(c.AT_FDCWD[fd], path, c.MODE[mode])) end
end
if C.fchownat then
function S.fchownat(dirfd, path, owner, group, flags)
return retbool(C.fchownat(c.AT_FDCWD[dirfd], path, owner or -1, group or -1, c.AT[flags]))
end
end
if C.faccessat then
function S.faccessat(dirfd, pathname, mode, flags)
return retbool(C.faccessat(c.AT_FDCWD[dirfd], pathname, c.OK[mode], c.AT[flags]))
end
end
if C.readlinkat then
function S.readlinkat(dirfd, path, buffer, size)
size = size or c.PATH_MAX
buffer = buffer or t.buffer(size)
local ret, err = C.readlinkat(c.AT_FDCWD[dirfd], path, buffer, size)
ret = tonumber(ret)
if ret == -1 then return nil, t.error(err or errno()) end
return ffi.string(buffer, ret)
end
end
if C.mknodat then
function S.mknodat(fd, pathname, mode, dev)
return retbool(C.mknodat(c.AT_FDCWD[fd], pathname, c.S_I[mode], getdev(dev) or 0))
end
end
if C.utimensat then
function S.utimensat(dirfd, path, ts, flags)
if ts then ts = t.timespec2(ts) end -- TODO use mktype?
return retbool(C.utimensat(c.AT_FDCWD[dirfd], path, ts, c.AT[flags]))
end
end
if C.fstatat then
function S.fstatat(fd, path, buf, flags)
if not buf then buf = t.stat() end
local ret, err = C.fstatat(c.AT_FDCWD[fd], path, buf, c.AT[flags])
if ret == -1 then return nil, t.error(err or errno()) end
return buf
end
end
if C.fchmodat then
function S.fchmodat(dirfd, pathname, mode, flags)
return retbool(C.fchmodat(c.AT_FDCWD[dirfd], pathname, c.MODE[mode], c.AT[flags]))
end
end
if C.openat then
function S.openat(dirfd, pathname, flags, mode)
return retfd(C.openat(c.AT_FDCWD[dirfd], pathname, c.O[flags], c.MODE[mode]))
end
end
if C.fchroot then
function S.fchroot(fd) return retbool(C.fchroot(getfd(fd))) end
end
if C.lchmod then
function S.lchmod(path, mode) return retbool(C.lchmod(path, c.MODE[mode])) end
end
if C.fdatasync then
function S.fdatasync(fd) return retbool(C.fdatasync(getfd(fd))) end
end
-- Linux does not have mkfifo syscalls, emulated
if C.mkfifo then
function S.mkfifo(pathname, mode) return retbool(C.mkfifo(pathname, c.S_I[mode])) end
end
if C.mkfifoat then
function S.mkfifoat(dirfd, pathname, mode) return retbool(C.mkfifoat(c.AT_FDCWD[dirfd], pathname, c.S_I[mode])) end
end
if C.utimes then
function S.utimes(filename, ts)
if ts then ts = t.timeval2(ts) end
return retbool(C.utimes(filename, ts))
end
end
if C.lutimes then
function S.lutimes(filename, ts)
if ts then ts = t.timeval2(ts) end
return retbool(C.lutimes(filename, ts))
end
end
if C.futimes then
function S.futimes(fd, ts)
if ts then ts = t.timeval2(ts) end
return retbool(C.futimes(getfd(fd), ts))
end
end
if C.getdents then
function S.getdents(fd, buf, size)
size = size or 4096 -- may have to be equal to at least block size of fs
buf = buf or t.buffer(size)
local ret, err = C.getdents(getfd(fd), buf, size)
if ret == -1 then return nil, t.error(err or errno()) end
return t.dirents(buf, ret)
end
end
if C.futimens then
function S.futimens(fd, ts)
if ts then ts = t.timespec2(ts) end
return retbool(C.futimens(getfd(fd), ts))
end
end
if C.accept4 then
function S.accept4(sockfd, addr, addrlen, flags)
local saddr = pt.sockaddr(addr)
if addr then addrlen = addrlen or t.socklen1() end
return retfd(C.accept4(getfd(sockfd), saddr, addrlen, c.SOCK[flags]))
end
end
if C.sigaction then
function S.sigaction(signum, handler, oldact)
if type(handler) == "string" or type(handler) == "function" then
handler = {handler = handler, mask = "", flags = 0} -- simple case like signal
end
if handler then handler = mktype(t.sigaction, handler) end
return retbool(C.sigaction(c.SIG[signum], handler, oldact))
end
end
if C.getitimer then
function S.getitimer(which, value)
value = value or t.itimerval()
local ret, err = C.getitimer(c.ITIMER[which], value)
if ret == -1 then return nil, t.error(err or errno()) end
return value
end
end
if C.setitimer then
function S.setitimer(which, it, oldtime)
oldtime = oldtime or t.itimerval()
local ret, err = C.setitimer(c.ITIMER[which], mktype(t.itimerval, it), oldtime)
if ret == -1 then return nil, t.error(err or errno()) end
return oldtime
end
end
if C.clock_getres then
function S.clock_getres(clk_id, ts)
ts = ts or t.timespec()
local ret, err = C.clock_getres(c.CLOCK[clk_id], ts)
if ret == -1 then return nil, t.error(err or errno()) end
return ts
end
end
if C.clock_gettime then
function S.clock_gettime(clk_id, ts)
ts = ts or t.timespec()
local ret, err = C.clock_gettime(c.CLOCK[clk_id], ts)
if ret == -1 then return nil, t.error(err or errno()) end
return ts
end
end
if C.clock_settime then
function S.clock_settime(clk_id, ts)
ts = mktype(t.timespec, ts)
return retbool(C.clock_settime(c.CLOCK[clk_id], ts))
end
end
if C.clock_nanosleep then
function S.clock_nanosleep(clk_id, flags, req, rem)
rem = rem or t.timespec()
local ret, err = C.clock_nanosleep(c.CLOCK[clk_id], c.TIMER[flags or 0], mktype(t.timespec, req), rem)
if ret == -1 then
if (err or errno()) == c.E.INTR then return true, nil, rem else return nil, t.error(err or errno()) end
end
return true -- no time remaining
end
end
if C.timer_create then
function S.timer_create(clk_id, sigev, timerid)
timerid = timerid or t.timer()
if sigev then sigev = mktype(t.sigevent, sigev) end
local ret, err = C.timer_create(c.CLOCK[clk_id], sigev, timerid:gettimerp())
if ret == -1 then return nil, t.error(err or errno()) end
return timerid
end
function S.timer_delete(timerid) return retbool(C.timer_delete(timerid:gettimer())) end
function S.timer_settime(timerid, flags, new_value, old_value)
if old_value ~= false then old_value = old_value or t.itimerspec() else old_value = nil end
new_value = mktype(t.itimerspec, new_value)
local ret, err = C.timer_settime(timerid:gettimer(), c.TIMER[flags], new_value, old_value)
if ret == -1 then return nil, t.error(err or errno()) end
return true, nil, old_value
end
function S.timer_gettime(timerid, curr_value)
curr_value = curr_value or t.itimerspec()
local ret, err = C.timer_gettime(timerid:gettimer(), curr_value)
if ret == -1 then return nil, t.error(err or errno()) end
return curr_value
end
function S.timer_getoverrun(timerid) return retnum(C.timer_getoverrun(timerid:gettimer())) end
end
-- legacy in many OSs, implemented using recvfrom, sendto
if C.send then
function S.send(fd, buf, count, flags) return retnum(C.send(getfd(fd), buf, count, c.MSG[flags])) end
end
if C.recv then
function S.recv(fd, buf, count, flags) return retnum(C.recv(getfd(fd), buf, count, c.MSG[flags], false)) end
end
-- TODO not sure about this interface, maybe return rem as extra parameter see #103
if C.nanosleep then
function S.nanosleep(req, rem)
rem = rem or t.timespec()
local ret, err = C.nanosleep(mktype(t.timespec, req), rem)
if ret == -1 then
if (err or errno()) == c.E.INTR then return true, nil, rem else return nil, t.error(err or errno()) end
end
return true -- no time remaining
end
end
-- getpagesize might be a syscall, or in libc, or may not exist
if C.getpagesize then
function S.getpagesize() return retnum(C.getpagesize()) end
end
if C.syncfs then
function S.syncfs(fd) return retbool(C.syncfs(getfd(fd))) end
end
-- although the pty functions are not syscalls, we include here, like eg shm functions, as easier to provide as methods on fds
-- Freebsd has a syscall, other OSs use /dev/ptmx
if C.posix_openpt then
function S.posix_openpt(flags) return retfd(C.posix_openpt(c.O[flags])) end
else
function S.posix_openpt(flags) return S.open("/dev/ptmx", flags) end
end
S.openpt = S.posix_openpt
function S.isatty(fd)
local tc, err = S.tcgetattr(fd)
if tc then return true else return nil, err end
end
if c.IOCTL.TIOCGSID then -- OpenBSD only has in legacy ioctls
function S.tcgetsid(fd) return S.ioctl(fd, "TIOCGSID") end
end
-- now call OS specific for non-generic calls
local hh = {
ret64 = ret64, retnum = retnum, retfd = retfd, retbool = retbool, retptr = retptr, retiter = retiter
}
if (abi.rump and abi.types == "netbsd") or (not abi.rump and abi.bsd) then
S = require("syscall.bsd.syscalls")(S, hh, c, C, types)
end
S = require("syscall." .. abi.os .. ".syscalls")(S, hh, c, C, types)
return S
end
return {init = init}
| apache-2.0 |
czfshine/UpAndAway | wicker/kernel_extensions/dst_abstraction/componentactions.lua | 6 | 9531 | --[[
-- IMPORTANT:
-- The modinfo.id is being hacked in place of 'modname' for identification.
--]]
local Lambda = wickerrequire "paradigms.functional"
if IsWorldgen() then
init = Lambda.Nil
return _M
end
local Rest = pkgrequire "restriction"
---
if IsDST() then
require "entityscript"
local SHOULD_FAKE_SERVER_MODNAMES = false
_G.ModManager.GetServerModsNames = (function()
local GetServerModsNames = assert( _G.ModManager.GetServerModsNames )
local modname = assert( modenv.modname )
local id = assert( modinfo.id )
local function modname_mapper(name)
if name == modname then
return id
else
return name
end
end
return function(self, ...)
local modlist = GetServerModsNames(self, ...)
if SHOULD_FAKE_SERVER_MODNAMES then
return Lambda.CompactlyMap(modname_mapper, ipairs(modlist))
else
return modlist
end
end
end)()
_G.Entity.AddNetwork = (function()
local AddNetwork = _G.Entity.AddNetwork
return function(self)
SHOULD_FAKE_SERVER_MODNAMES = true
local ret = AddNetwork(self)
SHOULD_FAKE_SERVER_MODNAMES = false
return ret
end
end)()
end
---
-- Maps DST's action type IDs to DS's component method names.
local actiontype_map = {
EQUIPPED = "CollectEquippedActions",
INVENTORY = "CollectInventoryActions",
POINT = "CollectPointActions",
SCENE = "CollectSceneActions",
USEITEM = "CollectUseActions",
ISVALID = "IsActionValid",
}
local function ActionTypeToMethodName(actiontype)
local name = actiontype_map[actiontype]
if name == nil then
return error("Invalid action type '"..tostring(actiontype).."'.", 2)
end
return name
end
local GetComponentActions
if IsDST() then
GetComponentActions = memoize_0ary(function()
require "entityscript"
require "componentactions"
local Reflection = wickerrequire "game.reflection"
return assert(Reflection.RequireUpvalue(_G.EntityScript.CollectActions, "COMPONENT_ACTIONS"))
end)
else
GetComponentActions = Rest.ForbiddenFunction("GetComponentActions", "singleplayer")
end
local GetModComponentActions
if IsDST() then
GetModComponentActions = memoize_0ary(function()
require "entityscript"
require "componentactions"
local Reflection = wickerrequire "game.reflection"
return assert(Reflection.RequireUpvalue(_G.AddComponentAction, "MOD_COMPONENT_ACTIONS"))
end)
else
GetModComponentActions = Rest.ForbiddenFunction("GetModComponentActions", "singleplayer")
end
local GetActionComponentIDs
if IsDST() then
GetActionComponentIDs = memoize_0ary(function()
require "entityscript"
require "componentactions"
local Reflection = wickerrequire "game.reflection"
return Reflection.RequireUpvalue(_G.EntityScript.RegisterComponentActions, "ACTION_COMPONENT_IDS")
end)
else
GetActionComponentIDs = Rest.ForbiddenFunction("GetActionComponentIDs", "singleplayer")
end
local GetModActionComponentIDs
if IsDST() then
GetModActionComponentIDs = memoize_0ary(function()
require "entityscript"
require "componentactions"
local Reflection = wickerrequire "game.reflection"
return Reflection.RequireUpvalue(_G.AddComponentAction, "MOD_ACTION_COMPONENT_IDS")
end)
else
GetModActionComponentIDs = Rest.ForbiddenFunction("GetModActionComponentIDs", "singleplayer")
end
local GetActionComponentNames
if IsDST() then
GetActionComponentNames = memoize_0ary(function()
require "entityscript"
require "componentactions"
local Reflection = wickerrequire "game.reflection"
return Reflection.RequireUpvalue(_G.EntityScript.CollectActions, "ACTION_COMPONENT_NAMES")
end)
else
GetActionComponentNames = Rest.ForbiddenFunction("GetActionComponentNames", "singleplayer")
end
local GetModActionComponentNames
if IsDST() then
GetModActionComponentNames = memoize_0ary(function()
require "entityscript"
require "componentactions"
local Reflection = wickerrequire "game.reflection"
return Reflection.RequireUpvalue(_G.AddComponentAction, "MOD_ACTION_COMPONENT_NAMES")
end)
else
GetModActionComponentNames = Rest.ForbiddenFunction("GetModActionComponentNames", "singleplayer")
end
---
local AddComponentAction, PatchComponentAction
if IsDST() then
assert(modenv.AddComponentAction)
assert(TheMod.AddComponentAction)
AddComponentAction = function(actiontype, cmp_name, fn)
return _G.AddComponentAction(actiontype, cmp_name, fn, modinfo.id)
end
PatchComponentAction = function(actiontype, cmp_name, patcher)
local cas = GetComponentActions()
local subcas = cas[actiontype]
if not subcas then
return AddComponentAction(actiontype, cmp_name, patcher(nil, actiontype, cmp_name))
end
local fn = subcas[cmp_name]
subcas[cmp_name] = patcher(fn, actiontype, cmp_name)
end
else
local function wrapComponentActionFn(fn)
return function(self, ...)
return fn(self.inst, ...)
end
end
local function unwrapComponentActionFn(fn, cmp_name)
return function(inst, ...)
local cmp = inst.components[cmp_name]
if cmp then
return fn(cmp, ...)
end
end
end
AddComponentAction = function(actiontype, cmp_name, fn)
local cmp = require("components/"..cmp_name)
local method_name = actiontype_map[actiontype]
if method_name == nil then
return error("Attempt to add component action of invalid action type '"..tostring(actiontype).."' to component '"..cmp_name, 2)
end
cmp[method_name] = wrapComponentActionFn(fn)
end
PatchComponentAction = function(actiontype, cmp_name, patcher)
local cmp = require("components/"..cmp_name)
local method_name = actiontype_map[actiontype]
if method_name then
local fn = cmp[method_name]
if fn then
fn = unwrapComponentActionFn(fn, cmp_name)
end
cmp[method_name] = wrapComponentActionFn( patcher(fn, actiontype, cmp_name) )
end
end
end
TheMod:EmbedAdder("ComponentAction", AddComponentAction)
function TheMod:PatchComponentAction(...)
return PatchComponentAction(...)
end
-- Takes a table in the same format as COMPONENT_ACTIONS found in DST's componentactions.lua.
local function AddComponentsActions(data)
for actiontype, subdata in pairs(data) do
for cmp_name, fn in pairs(subdata) do
AddComponentAction(actiontype, cmp_name, fn)
end
end
end
TheMod:EmbedAdder("ComponentsActions", AddComponentsActions)
---
local HasActionComponent
if IsDST() then
local set_key = {}
local dirty_set_key = {}
---
local function genericUpdateActionComponentSet(set, id_list, id_map, value)
local current_ids = {}
for _, id in ipairs(id_list) do
current_ids[id] = true
end
for k, v in pairs(set) do
if v == value and not current_ids[id_map[k]] then
set[k] = nil
end
end
for id, k in pairs(id_map) do
if current_ids[id] and set[k] == nil then
set[k] = value
end
end
end
---
local function updateActionComponentSet(inst)
local set = assert( inst[set_key] )
local id_map = GetActionComponentIDs()
return genericUpdateActionComponentSet(set, inst.actioncomponents, id_map, true)
end
local function updateModActionComponentSet(inst, mod_name)
assert( mod_name )
local set = assert( inst[set_key] )
local id_list = inst.modactioncomponents[mod_name]
if id_list == nil then return end
local id_map = GetModActionComponentIDs()[mod_name]
if id_map == nil then return end
return genericUpdateActionComponentSet(set, id_list, id_map, mod_name)
end
local function cleanDirtySets(inst)
local set = inst[dirty_set_key]
if set == nil then return end
for k in pairs(set) do
if k == 1 then
updateActionComponentSet(inst)
else
updateModActionComponentSet(inst, k)
end
end
inst[dirty_set_key] = nil
end
local function flagDirtyActionComponentSet(inst)
local set = inst[dirty_set_key]
if set == nil then
set = {nil}
inst[dirty_set_key] = set
end
set[1] = true
end
local getDirtyModActionComponentSetFlagger = (function()
local cache = {}
return function(mod_name)
local ret = cache[mod_name]
if ret == nil then
ret = function(inst)
local set = inst[dirty_set_key]
if set == nil then
set = {_ = nil}
inst[dirty_set_key] = set
end
set[mod_name] = true
end
cache[mod_name] = ret
end
return ret
end
end)()
local function initializeActionComponentSet(inst)
if inst.actionreplica then
inst:ListenForEvent("actioncomponentsdirty", flagDirtyActionComponentSet)
for modname in pairs(inst.actionreplica.modactioncomponents) do
inst:ListenForEvent("modactioncomponentsdirty"..modname, getDirtyModActionComponentSetFlagger(modname))
end
end
updateActionComponentSet(inst)
if inst.modactioncomponents then
for modname in pairs(inst.modactioncomponents) do
updateModActionComponentSet(inst, modname)
end
end
end
HasActionComponent = function(inst, cmp_name)
local set = inst[set_key]
if set == nil then
set = {}
inst[set_key] = set
initializeActionComponentSet(inst)
else
cleanDirtySets(inst)
end
return set[cmp_name] and true or false
end
else
HasActionComponent = function(inst, cmp_name)
return inst.components[cmp_name] ~= nil
end
end
---
function init(kernel)
kernel.GetComponentActions = GetComponentActions
kernel.GetModComponentActions = GetModComponentActions
kernel.GetActionComponentIDs = GetActionComponentIDs
kernel.GetModActionComponentIDs = GetModActionComponentIDs
kernel.GetActionComponentNames = GetActionComponentNames
kernel.GetModActionComponentNames = GetModActionComponentNames
kernel.ActionTypeToMethodName = ActionTypeToMethodName
kernel.HasActionComponent = HasActionComponent
end
| gpl-2.0 |
nalidixic/OpenRA | mods/cnc/maps/funpark01/scj01ea.lua | 19 | 3521 | RifleReinforcments = { "e1", "e1", "e1", "bike" }
BazookaReinforcments = { "e3", "e3", "e3", "bike" }
BikeReinforcments = { "bike" }
ReinforceWithLandingCraft = function(units, transportStart, transportUnload, rallypoint)
local transport = Actor.Create("oldlst", true, { Owner = nod, Facing = 0, Location = transportStart })
local subcell = 0
Utils.Do(units, function(a)
transport.LoadPassenger(Actor.Create(a, false, { Owner = transport.Owner, Facing = transport.Facing, Location = transportUnload, SubCell = subcell }))
subcell = subcell + 1
end)
transport.ScriptedMove(transportUnload)
transport.CallFunc(function()
Utils.Do(units, function()
local a = transport.UnloadPassenger()
a.IsInWorld = true
a.MoveIntoWorld(transport.Location - CVec.New(0, 1))
if rallypoint ~= nil then
a.Move(rallypoint)
end
end)
end)
transport.Wait(5)
transport.ScriptedMove(transportStart)
transport.Destroy()
Media.PlaySpeechNotification(player, "Reinforce")
end
WorldLoaded = function()
nod = Player.GetPlayer("Nod")
dinosaur = Player.GetPlayer("Dinosaur")
civilian = Player.GetPlayer("Civilian")
InvestigateObj = nod.AddPrimaryObjective("Investigate the nearby village for reports of \nstrange activity.")
Trigger.OnObjectiveAdded(nod, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(nod, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(nod, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerWon(nod, function()
Media.PlaySpeechNotification(nod, "Win")
end)
Trigger.OnPlayerLost(nod, function()
Media.PlaySpeechNotification(nod, "Lose")
end)
ReachVillageObj = nod.AddPrimaryObjective("Reach the village.")
Trigger.OnPlayerDiscovered(civilian, function(_, discoverer)
if discoverer == nod and not nod.IsObjectiveCompleted(ReachVillageObj) then
if not dinosaur.HasNoRequiredUnits() then
KillDinos = nod.AddPrimaryObjective("Kill all creatures in the area.")
end
nod.MarkCompletedObjective(ReachVillageObj)
end
end)
DinoTric.Patrol({WP0.Location, WP1.Location}, true, 3)
DinoTrex.Patrol({WP2.Location, WP3.Location}, false)
Trigger.OnIdle(DinoTrex, DinoTrex.Hunt)
ReinforceWithLandingCraft(RifleReinforcments, SeaEntryA.Location, BeachReinforceA.Location, BeachReinforceA.Location)
Trigger.AfterDelay(DateTime.Seconds(1), function() InitialUnitsArrived = true end)
Trigger.AfterDelay(DateTime.Seconds(15), function() ReinforceWithLandingCraft(BazookaReinforcments, SeaEntryB.Location, BeachReinforceB.Location, BeachReinforceB.Location) end)
if Map.Difficulty == "Easy" then
Trigger.AfterDelay(DateTime.Seconds(25), function() ReinforceWithLandingCraft(BikeReinforcments, SeaEntryA.Location, BeachReinforceA.Location, BeachReinforceA.Location) end)
Trigger.AfterDelay(DateTime.Seconds(30), function() ReinforceWithLandingCraft(BikeReinforcments, SeaEntryB.Location, BeachReinforceB.Location, BeachReinforceB.Location) end)
end
Camera.Position = CameraStart.CenterPosition
end
Tick = function()
if InitialUnitsArrived then
if nod.HasNoRequiredUnits() then
nod.MarkFailedObjective(InvestigateObj)
end
if dinosaur.HasNoRequiredUnits() then
if KillDinos then nod.MarkCompletedObjective(KillDinos) end
nod.MarkCompletedObjective(InvestigateObj)
end
end
end
| gpl-3.0 |
LuaDist2/cqueues | regress/72-fill-hangs.lua | 5 | 1168 | #!/bin/sh
_=[[
. "${0%%/*}/regress.sh"
exec runlua "$0" "$@"
]]
require"regress".export".*"
--
-- lso_fill attempts to read more than requested, and returns EAGAIN even if
-- it fulfilled the request completely. socket:fill is the only API method
-- which triggers this bug because all the others do speculative reads and
-- test if the input buffer contains sufficient data to fulfill the request.
-- Only if it doesn't do they read or return the error from lso_fill.
-- socket:fill, however, unconditionally returns the error from lso_fill,
-- regardless if the input buffer contains the requested amount of data
-- after lso_fill returns.
--
check(cqueues.new():wrap(function ()
local a, b = check(socket.pair())
local send = "test"
info('writing "%s" (%d bytes)', send, #send)
check(a:write(send))
a:flush()
local n = a:stat().sent.count
check(n == #send, "only %d bytes flushed", n)
info("filling %d bytes", #send)
check(b:fill(#send))
info("%d bytes pending", (b:pending()))
info("reading %d bytes", #send)
local rcvd = check(b:read(4))
check(send == rcvd, "data doesn't match (send \"%s\" but got \"%s\")", send, rcvd)
end):loop())
say"OK"
| mit |
xdemolish/darkstar | scripts/globals/spells/poison_ii.lua | 2 | 1442 | -----------------------------------------
-- Spell: Poison
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local effect = EFFECT_POISON;
local duration = 120;
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
duration = duration * 2;
end
local pINT = caster:getStat(MOD_INT);
local mINT = target:getStat(MOD_INT);
local dINT = (pINT - mINT);
local power = caster:getSkillLevel(ENFEEBLING_MAGIC_SKILL) / 20 + 1;
if power > 10 then
power = 10;
end
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
power = power * 2;
end
caster:delStatusEffect(EFFECT_SABOTEUR);
--local bonus = AffinityBonus(caster, spell:getElement()); Removed: affinity bonus is added in applyResistance
local resist = applyResistanceEffect(caster,spell,target,dINT,ENFEEBLING_MAGIC_SKILL,0,effect);
if(resist == 1 or resist == 0.5) then -- effect taken
duration = duration * resist;
if(target:addStatusEffect(effect,power,3,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else -- resist entirely.
spell:setMsg(85);
end
return effect;
end; | gpl-3.0 |
londry/nodemcu-firmware | lua_modules/ds3231/ds3231.lua | 16 | 1865 | --------------------------------------------------------------------------------
-- DS3231 I2C module for NODEMCU
-- NODEMCU TEAM
-- LICENCE: http://opensource.org/licenses/MIT
-- Tobie Booth <tbooth@hindbra.in>
--------------------------------------------------------------------------------
local moduleName = ...
local M = {}
_G[moduleName] = M
-- Default value for i2c communication
local id = 0
--device address
local dev_addr = 0x68
local function decToBcd(val)
return((val/10*16) + (val%10))
end
local function bcdToDec(val)
return((val/16*10) + (val%16))
end
-- initialize i2c
--parameters:
--d: sda
--l: scl
function M.init(d, l)
if (d ~= nil) and (l ~= nil) and (d >= 0) and (d <= 11) and (l >= 0) and ( l <= 11) and (d ~= l) then
sda = d
scl = l
else
print("iic config failed!") return nil
end
print("init done")
i2c.setup(id, sda, scl, i2c.SLOW)
end
--get time from DS3231
function M.getTime()
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x00)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr, i2c.RECEIVER)
local c=i2c.read(id, 7)
i2c.stop(id)
return bcdToDec(tonumber(string.byte(c, 1))),
bcdToDec(tonumber(string.byte(c, 2))),
bcdToDec(tonumber(string.byte(c, 3))),
bcdToDec(tonumber(string.byte(c, 4))),
bcdToDec(tonumber(string.byte(c, 5))),
bcdToDec(tonumber(string.byte(c, 6))),
bcdToDec(tonumber(string.byte(c, 7)))
end
--set time for DS3231
function M.setTime(second, minute, hour, day, date, month, year)
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x00)
i2c.write(id, decToBcd(second))
i2c.write(id, decToBcd(minute))
i2c.write(id, decToBcd(hour))
i2c.write(id, decToBcd(day))
i2c.write(id, decToBcd(date))
i2c.write(id, decToBcd(month))
i2c.write(id, decToBcd(year))
i2c.stop(id)
end
return M
| mit |
lytedev/quick-td | lib/hump/vector.lua | 4 | 4887 | --[[
Copyright (c) 2010-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 assert = assert
local sqrt, cos, sin = math.sqrt, math.cos, math.sin
local vector = {}
vector.__index = vector
local function new(x,y)
return setmetatable({x = x or 0, y = y or 0}, vector)
end
local function isvector(v)
return getmetatable(v) == vector
end
function vector:clone()
return new(self.x, self.y)
end
function vector:unpack()
return self.x, self.y
end
function vector:__tostring()
return "("..tonumber(self.x)..","..tonumber(self.y)..")"
end
function vector.__unm(a)
return new(-a.x, -a.y)
end
function vector.__add(a,b)
assert(isvector(a) and isvector(b), "Add: wrong argument types (<vector> expected)")
return new(a.x+b.x, a.y+b.y)
end
function vector.__sub(a,b)
assert(isvector(a) and isvector(b), "Sub: wrong argument types (<vector> expected)")
return new(a.x-b.x, a.y-b.y)
end
function vector.__mul(a,b)
if type(a) == "number" then
return new(a*b.x, a*b.y)
elseif type(b) == "number" then
return new(b*a.x, b*a.y)
else
assert(isvector(a) and isvector(b), "Mul: wrong argument types (<vector> or <number> expected)")
return a.x*b.x + a.y*b.y
end
end
function vector.__div(a,b)
assert(isvector(a) and type(b) == "number", "wrong argument types (expected <vector> / <number>)")
return new(a.x / b, a.y / b)
end
function vector.__eq(a,b)
return a.x == b.x and a.y == b.y
end
function vector.__lt(a,b)
return a.x < b.x or (a.x == b.x and a.y < b.y)
end
function vector.__le(a,b)
return a.x <= b.x and a.y <= b.y
end
function vector.permul(a,b)
assert(isvector(a) and isvector(b), "permul: wrong argument types (<vector> expected)")
return new(a.x*b.x, a.y*b.y)
end
function vector:len2()
return self.x * self.x + self.y * self.y
end
function vector:len()
return sqrt(self.x * self.x + self.y * self.y)
end
function vector.dist(a, b)
assert(isvector(a) and isvector(b), "dist: wrong argument types (<vector> expected)")
local dx = a.x - b.x
local dy = a.y - b.y
return sqrt(dx * dx + dy * dy)
end
function vector:normalize_inplace()
local l = self:len()
if l > 0 then
self.x, self.y = self.x / l, self.y / l
end
return self
end
function vector:normalized()
return self:clone():normalize_inplace()
end
function vector:rotate_inplace(phi)
local c, s = cos(phi), sin(phi)
self.x, self.y = c * self.x - s * self.y, s * self.x + c * self.y
return self
end
function vector:rotated(phi)
local c, s = cos(phi), sin(phi)
return new(c * self.x - s * self.y, s * self.x + c * self.y)
end
function vector:perpendicular()
return new(-self.y, self.x)
end
function vector:projectOn(v)
assert(isvector(v), "invalid argument: cannot project vector on " .. type(v))
-- (self * v) * v / v:len2()
local s = (self.x * v.x + self.y * v.y) / (v.x * v.x + v.y * v.y)
return new(s * v.x, s * v.y)
end
function vector:mirrorOn(v)
assert(isvector(v), "invalid argument: cannot mirror vector on " .. type(v))
-- 2 * self:projectOn(v) - self
local s = 2 * (self.x * v.x + self.y * v.y) / (v.x * v.x + v.y * v.y)
return new(s * v.x - self.x, s * v.y - self.y)
end
function vector:cross(v)
assert(isvector(v), "cross: wrong argument types (<vector> expected)")
return self.x * v.y - self.y * v.x
end
-- ref.: http://blog.signalsondisplay.com/?p=336
function vector:trim_inplace(maxLen)
local s = maxLen * maxLen / self:len2()
s = s < 1 and 1 or math.sqrt(s)
self.x, self.y = self.x * s, self.y * s
return self
end
function vector:trimmed(maxLen)
return self:clone():trim_inplace(maxLen)
end
-- the module
return setmetatable({new = new, isvector = isvector},
{__call = function(_, ...) return new(...) end})
| apache-2.0 |
xdemolish/darkstar | scripts/zones/Spire_of_Dem/npcs/_0j2.lua | 3 | 1319 | -----------------------------------
-- Area: Spire_of_Dem
-- NPC: web of regret
-----------------------------------
package.loaded["scripts/zones/Spire_of_Dem/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/bcnm");
require("scripts/zones/Spire_of_Dem/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(TradeBCNM(player,player:getZone():getID(),trade,npc))then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(EventTriggerBCNM(player,npc))then
return 1;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdate CSID: %u",csid);
--printf("onUpdate RESULT: %u",option);
if(EventUpdateBCNM(player,csid,option))then
return;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if(EventFinishBCNM(player,csid,option))then
return;
end
end; | gpl-3.0 |
PlexChat/premake-core | src/base/container.lua | 6 | 8270 | ---
-- container.lua
-- Implementation of configuration containers.
-- Copyright (c) 2014 Jason Perkins and the Premake project
---
local p = premake
p.container = {}
local container = p.container
---
-- Keep a master dictionary of container class, so they can be easily looked
-- up by name (technically you could look at premake["name"] but that is just
-- a coding convention and I don't want to count on it)
---
container.classes = {}
---
-- Define a new class of containers.
--
-- @param name
-- The name of the new container class. Used wherever the class needs to
-- be shown to the end user in a readable way.
-- @param parent (optional)
-- If this class of container is intended to be contained within another,
-- the containing class object.
-- @param extraScopes (optional)
-- Each container can hold fields scoped to itself (by putting the container's
-- class name into its scope attribute), or any of the container's children.
-- If a container can hold scopes other than these (i.e. "config"), it can
-- provide a list of those scopes in this argument.
-- @return
-- If successful, the new class descriptor object (a table). Otherwise,
-- returns nil and an error message.
---
function container.newClass(name, parent, extraScopes)
local class = p.configset.new(parent)
class.name = name
class.pluralName = name:plural()
class.containedClasses = {}
class.extraScopes = extraScopes
if parent then
table.insert(parent.containedClasses, class)
end
container.classes[name] = class
return class
end
---
-- Create a new instance of a configuration container. This is just the
-- generic base implementation, each container class will define their
-- own version.
--
-- @param parent
-- The class of container being instantiated.
-- @param name
-- The name for the new container instance.
-- @return
-- A new container instance.
---
function container.new(class, name)
local self = p.configset.new()
setmetatable(self, p.configset.metatable(self))
self.class = class
self.name = name
self.filename = name
self.script = _SCRIPT
self.basedir = os.getcwd()
self.external = false
for childClass in container.eachChildClass(class) do
self[childClass.pluralName] = {}
end
return self
end
---
-- Add a new child to an existing container instance.
--
-- @param self
-- The container instance to hold the child.
-- @param child
-- The child container instance.
---
function container.addChild(self, child)
local children = self[child.class.pluralName]
table.insert(children, child)
children[child.name] = child
child.parent = self
child[self.class.name] = self
if self.class.alias then
child[self.class.alias] = self
end
end
---
-- Process the contents of a container, which were populated by the project
-- script, in preparation for doing work on the results, such as exporting
-- project files.
---
function container.bake(self)
if self._isBaked then
return self
end
self._isBaked = true
local ctx = p.context.new(self)
for key, value in pairs(self) do
ctx[key] = value
end
local parent = self.parent
ctx[parent.class.name] = parent
for class in container.eachChildClass(self.class) do
for child in container.eachChild(self, class) do
child.parent = ctx
child[self.class.name] = ctx
end
end
if type(self.class.bake) == "function" then
self.class.bake(ctx)
end
return ctx
end
function container.bakeChildren(self)
for class in container.eachChildClass(self.class) do
local children = self[class.pluralName]
-- sort children by name.
table.sort(children, function(a,b)
return a.name < b.name
end)
for i = 1, #children do
local ctx = container.bake(children[i])
children[i] = ctx
children[ctx.name] = ctx
end
end
end
---
-- Returns true if the container can hold any of the specified field scopes.
--
-- @param class
-- The container class to test.
-- @param scope
-- A scope string (e.g. "project", "config") or an array of scope strings.
-- @return
-- True if this container can hold any of the specified scopes.
---
function container.classCanContain(class, scope)
if type(scope) == "table" then
for i = 1, #scope do
if container.classCanContain(class, scope[i]) then
return true
end
end
return false
end
-- if I have child classes, check with them first, since scopes
-- are usually specified for leaf nodes in the hierarchy
for child in container.eachChildClass(class) do
if (container.classCanContain(child, scope)) then
return true
end
end
if class.name == scope or class.alias == scope then
return true
end
-- is it in my extra scopes list?
if class.extraScopes and table.contains(class.extraScopes, scope) then
return true
end
return false
end
---
-- Return true if a container class is or inherits from the
-- specified class.
--
-- @param class
-- The container class to be tested.
-- @param scope
-- The name of the class to be checked against. If the container
-- class matches this scope (i.e. class is a project and the
-- scope is "project"), or if it is a parent object of it (i.e.
-- class is a workspace and scope is "project"), then returns
-- true.
---
function container.classIsA(class, scope)
while class do
if class.name == scope or class.alias == scope then
return true
end
class = class.parent
end
return false
end
---
-- Enumerate all of the registered child classes of a specific container class.
--
-- @param class
-- The container class to be enumerated.
-- @return
-- An iterator function for the container's child classes.
---
function container.eachChildClass(class)
local children = class.containedClasses
local i = 0
return function ()
i = i + 1
if i <= #children then
return children[i]
end
end
end
---
-- Enumerate all of the registered child instances of a specific container.
--
-- @param self
-- The container to be queried.
-- @param class
-- The class of child containers to be enumerated.
-- @return
-- An iterator function for the container's child classes.
---
function container.eachChild(self, class)
local children = self[class.pluralName]
local i = 0
return function ()
i = i + 1
if i <= #children then
return children[i]
end
end
end
---
-- Retrieve the child container with the specified class and name.
--
-- @param self
-- The container instance to query.
-- @param class
-- The class of the child container to be fetched.
-- @param name
-- The name of the child container to be fetched.
-- @return
-- The child instance if it exists, nil otherwise.
---
function container.getChild(self, class, name)
local children = self[class.pluralName]
return children[name]
end
---
-- Retrieve a container class object.
--
-- @param name
-- The name of the container class to retrieve.
-- @return
-- The container class object if it exists, nil otherwise.
---
function container.getClass(name)
return container.classes[name]
end
---
-- Determine if the container contains a child of the specified class which
-- meets the criteria of a testing function.
--
-- @param self
-- The container to be queried.
-- @param class
-- The class of the child containers to be enumerated.
-- @param func
-- A function that takes a child container as its only argument, and
-- returns true if it meets the selection criteria for the call.
-- @return
-- True if the test function returns true for any child.
---
function container.hasChild(self, class, func)
for child in container.eachChild(self, class) do
if func(child) then
return true
end
end
end
---
-- Call out to the container validation to make sure everything
-- is as it should be before handing off to the actions.
---
function container.validate(self)
if type(self.class.validate) == "function" then
self.class.validate(self)
end
end
function container.validateChildren(self)
for class in container.eachChildClass(self.class) do
local children = self[class.pluralName]
for i = 1, #children do
container.validate(children[i])
end
end
end
| bsd-3-clause |
OlivierHamel/gHCM | premake5.lua | 1 | 1321 |
local bIsWindows = os.get() == "windows"
-- \todo Add OCL for NV? Then again, they don't give a damn about OCL support so why bother.
local strOclIncDir = bIsWindows and "$(AMDAPPSDKROOT)/include" or "$(HOME)/AMDAPPSDK/include"
local strOclLibDir = bIsWindows and "$(AMDAPPSDKROOT)/lib/x86_64" or "$(HOME)/AMDAPPSDK/lib/x86_64"
workspace "gHCM"
configurations { "debug", "release" }
project "gHCM"
architecture "x86_64"
kind "ConsoleApp"
language "C++"
targetdir ".build/%{cfg.buildcfg}"
objdir ".build/%{cfg.buildcfg}/obj"
includedirs { "lib", "src", strOclIncDir }
libdirs { strOclLibDir }
links { "OpenCL" } -- either a project's name, or the name of a sys lib w/o ext
--- \fixme Temporarily disabled PCH due to oddity in latest premake5 & Travis CI
--pchheader "pch.h"
--pchsource "src/pch.cpp"
forceincludes "pch.h"
files { "src/**.h", "src/**.cpp", "lib/docopt/docopt.cpp" }
flags { }
filter { "system:linux" }
buildoptions { "-std=c++14", "-stdlib=libc++" }
linkoptions { "-v", "-stdlib=libc++" }
links { "c++" }
filter "configurations:debug"
defines { "DEBUG" }
symbols "On"
filter "configurations:release"
defines { "NDEBUG" }
symbols "On"
optimize "On"
| bsd-3-clause |
nazrhyn/epgp-tep | LibJSON-1.0.lua | 10 | 21748 | --[[
Name: LibJSON-1.0
Author(s): ckknight (ckknight@gmail.com)
Website: http://www.wowace.com/projects/libjson-1-0/
Description: A library to convert between Lua objects and serialized JSON objects
License: MIT
]]
local LibJSON = LibStub:NewLibrary("LibJSON-1.0", 1)
if not LibJSON then
return
end
LibJSON.NULL = LibJSON.NULL or newproxy()
local NULL = LibJSON.NULL
--- Return a proxy object that will serialize to null.
-- @usage LibJSON.Serialize(LibJSON.Null()) == "null"
-- @usage LibJSON.Serialize({1, LibJSON.Null(), 3}) == "[1,null,3]"
-- @return a proxy object
function LibJSON.Null()
return NULL
end
local serialize
--- Serialize an object to LibJSON
-- This will error if a function, userdata, or thread is passed in.
-- This will also error if a non-UTF-8 string is passed in.
-- @param value a serialized JSON object
-- @usage LibJSON.Serialize(1234) == "1234"
-- @usage LibJSON.Serialize(1234e50) == "1.234e+53"
-- @usage LibJSON.Serialize("Hello, friend") == '"Hello, friend"'
-- @usage LibJSON.Serialize({ 1, 2, 3 }) == "[1,2,3]"
-- @usage LibJSON.Serialize({ one = 1, two = 2 }) == '{"one":1,"two":2}'
-- @usage LibJSON.Serialize("\195\156berfantastisch") == '"\u00DCberfantastisch"'
-- @usage LibJSON.Serialize(nil) == 'null'
-- @usage LibJSON.Serialize(true) == 'true'
-- @usage LibJSON.Serialize() == 'false'
-- @usage LibJSON.Serialize({[4] = "Hello"}) == '[null,null,null,"Hello"]'
-- @return a string with the serialized data in it
function LibJSON.Serialize(value)
local buffer = {}
serialize(value, buffer)
return table.concat(buffer)
end
local deserialize, skipWhitespace
--- Deserialize a JSON object into a lua object
-- This will error if the JSON object is malformed.
-- @param value a string, number, boolean, or nil (or LibJSON.Null()), or a table consisting of those
-- @usage LibJSON.Deserialize("1234") == 1234
-- @usage LibJSON.Deserialize("1.234e+53") == 1234e50
-- @usage LibJSON.Deserialize('"Hello, friend"') == "Hello, friend"
-- @usage LibJSON.Deserialize('[1, 2, 3]') => { 1, 2, 3 }
-- @usage LibJSON.Deserialize('[1, null, 3]') => { [1] = 1, [3] = 3 }
-- @usage LibJSON.Deserialize('{"one":"two"}') => { one = "two" }
-- @usage LibJSON.Deserialize('"\u00DCberfantastisch"') => "\195\156berfantastisch"
-- @usage LibJSON.Deserialize('[1, /* a comment */ 2]') => { 1, 2 }
-- @usage LibJSON.Deserialize('true') => true
-- @usage LibJSON.Deserialize('false') => false
-- @usage LibJSON.Deserialize('null') => nil
-- @return a lua object, either a table, string, number, boolean, or nil
function LibJSON.Deserialize(value)
if type(value) ~= "string" then
error("Cannot deserialize a non-string")
end
local result, position = deserialize(value, 1)
position = skipWhitespace(value, position)
if position <= value:len() then
error(("Unused trailing characters: %q"):format(value))
end
return result
end
do
local serializers = {}
-- serialize a value, appending to the given buffer
function serialize(value, buffer)
if value == NULL then
-- NULL is special, for embedding nils into lists
value = nil
end
local serializer = serializers[type(value)]
if not serializer then
error(("Serializing of type %s is unsupported"):format(type(value)))
end
serializer(value, buffer)
end
local backslashed_bytes = {
[('"'):byte()] = '\\"',
[('\\'):byte()] = '\\\\',
[('/'):byte()] = '\\/',
[('\b'):byte()] = '\\b',
[('\f'):byte()] = '\\f',
[('\n'):byte()] = '\\n',
[('\r'):byte()] = '\\r',
[('\t'):byte()] = '\\t',
}
function serializers:string(buffer)
buffer[#buffer+1] = '"'
local i = 1
local length = #self
while i <= length do
local byte = self:byte(i)
i = i + 1
if backslashed_bytes[byte] then
-- one of the standard backslashed characters
buffer[#buffer+1] = backslashed_bytes[byte]
elseif byte < 32 then
-- control character, not visible normally
buffer[#buffer+1] = "\\u00"
buffer[#buffer+1] = ("%02X"):format(byte)
elseif byte < 128 then
-- normal character
buffer[#buffer+1] = string.char(byte)
elseif byte < 194 or byte > 244 then
error("String is not proper UTF-8: %q"):format(self)
elseif byte < 224 then
-- unicode fun, this handles U+0080 to U+07FF
-- see http://en.wikipedia.org/wiki/UTF-8
local byte1, byte2 = self:byte(i), byte
i = i + 1
local nibble1 = byte1 % 16
local nibble2 = ((byte1 - nibble1) % 64) / 16 + (byte2 % 4) * 4
local nibble3 = math.floor(byte2 / 4) % 8
buffer[#buffer+1] = "\\u"
buffer[#buffer+1] = ("%04X"):format(nibble1 + nibble2 * 16 + nibble3 * 256)
elseif byte < 240 then
-- even more unicode fun, handles U+0800 to U+FFFF
local byte1, byte2, byte3 = self:byte(i+1), self:byte(i), byte
i = i + 2
local nibble1 = byte1 % 16
local nibble2 = ((byte1 - nibble1) % 64) / 16 + (byte2 % 4) * 4
local nibble3 = math.floor(byte2 / 4) % 16
local nibble4 = byte3 % 16
buffer[#buffer+1] = "\\u"
buffer[#buffer+1] = ("%04X"):format(nibble1 + nibble2 * 16 + nibble3 * 256 + nibble4 * 4096)
else
error("Cannot serialize unicode greater than U+FFFF: %q"):format(self)
end
end
buffer[#buffer+1] = '"'
end
function serializers:number(buffer)
-- lua's and LibJSON's numbers are the same
buffer[#buffer+1] = tostring(self)
end
function serializers:boolean(buffer)
-- lua's and LibJSON's booleans are the same
buffer[#buffer+1] = tostring(self)
end
-- see if the table provided is a list, if so, return the list's length
-- This does handle lists with embedded nils, e.g. {1, nil, 3}
-- This could theoretically be an issue if you pass in {[10000]="Hello"}
local function isList(list)
local length = 0
for k, v in pairs(list) do
if type(k) ~= "number" or k < 1 or math.floor(k) ~= k then
return false
end
if length < k then
length = k
end
end
return length
end
function serializers:table(buffer)
local listLength = isList(self)
if listLength then
buffer[#buffer+1] = "["
for i = 1, listLength do
if i > 1 then
buffer[#buffer+1] = ","
end
serialize(self[i], buffer)
end
buffer[#buffer+1] = "]"
else
buffer[#buffer+1] = "{"
local first = true
for k, v in pairs(self) do
if first then
first = false
else
buffer[#buffer+1] = ","
end
-- we're going to just coerce all keys to string
serialize(tostring(k), buffer)
buffer[#buffer+1] = ":"
serialize(v, buffer)
end
buffer[#buffer+1] = "}"
end
end
serializers['nil'] = function(self, buffer)
buffer[#buffer+1] = "null"
end
end
do
local solidus = ("/"):byte()
local reverseSolidus = ("\\"):byte()
local asterix = ("*"):byte()
local openBrace = ("{"):byte()
local closeBrace = ("}"):byte()
local openBracket = ("["):byte()
local closeBracket = ("]"):byte()
local comma = (","):byte()
local colon = (":"):byte()
local doubleQuote = ('"'):byte()
local minus = ("-"):byte()
local plus = ("+"):byte()
local letterT = ("t"):byte()
local letterF = ("f"):byte()
local letterN = ("n"):byte()
local letterU = ("u"):byte()
local digit0 = ("0"):byte()
local digit1 = ("1"):byte()
local digit9 = ("9"):byte()
local fullStop = ("."):byte()
local letterE = ("e"):byte()
local letterUpperE = ("E"):byte()
local whitespace = {
[(" "):byte()] = true,
[("\t"):byte()] = true,
[("\r"):byte()] = true,
[("\n"):byte()] = true,
}
local newlines = {
[("\r"):byte()] = true,
[("\n"):byte()] = true,
}
local numbers = {}
for i = 0, 9 do
numbers[i + ('0'):byte()] = i
end
local escapes = {
[('"'):byte()] = ('"'):byte(),
[('\\'):byte()] = ('\\'):byte(),
[('/'):byte()] = ('/'):byte(),
[('b'):byte()] = ('\b'):byte(),
[('f'):byte()] = ('\f'):byte(),
[('n'):byte()] = ('\n'):byte(),
[('r'):byte()] = ('\r'):byte(),
[('t'):byte()] = ('\t'):byte(),
}
-- this jumps the position ahead to past the first newline
local function skipCommentSingleLine(value, position)
local byte
repeat
byte = value:byte(position)
position = position + 1
until not byte or newlines[byte]
return skipWhitespace(value, position)
end
-- this searches for */ and stops
local function skipCommentBlock(value, position)
local lastByte, byte
repeat
lastByte, byte = byte, value:byte(position)
position = position + 1
if lastByte == solidus and byte == asterix then
-- /* blah /* */ is illegal
error(("Invalid comment found: %q"):format(value))
end
until not byte or (lastByte == asterix and byte == solidus)
if not byte then
-- ran out of text before finishing the comment
error(("Invalid comment found: %q"):format(value))
end
return skipWhitespace(value, position)
end
local function skipComment(value, position)
assert(value:byte(position) == solidus)
local byte = value:byte(position + 1)
if byte == solidus then
-- // text until newline
return skipCommentSingleLine(value, position+2)
elseif byte == asterix then
-- /* text until */
return skipCommentBlock(value, position+2)
else
-- can't have a random slash hanging around
error(("Invalid comment found: %q"):format(value))
end
end
-- skip all whitespace and comments
function skipWhitespace(value, position)
local byte = value:byte(position)
if whitespace[byte] then
return skipWhitespace(value, position+1)
end
if byte == solidus then
return skipComment(value, position)
end
return position
end
local tmp = {}
-- read in a string
local function readString(value, position)
assert(value:byte(position) == doubleQuote)
position = position + 1
for k in pairs(tmp) do
-- this is in case there was an error while figuring the string last time
tmp[k] = nil
end
while true do
local byte = value:byte(position)
position = position + 1
if not byte then
error(("String ended early: %q"):format(value))
elseif byte == doubleQuote then
-- end of the string
break
elseif byte == reverseSolidus then
byte = value:byte(position)
position = position + 1
if not byte then
error(("String ended early: %q"):format(value))
elseif byte == letterU then
-- unicode fun
-- see http://en.wikipedia.org/wiki/UTF-8
local hexDigits = value:sub(position, position+3)
if hexDigits:len() ~= 4 then
error(("String ended early: %q"):format(value))
end
position = position + 4
local codepoint = tonumber(hexDigits, 16)
if not codepoint then
error(("Invalid string found: %q"):format(value))
end
if codepoint < 0x0080 then
tmp[#tmp+1] = string.char(codepoint)
elseif codepoint < 0x0800 then
tmp[#tmp+1] = string.char(math.floor(codepoint / 0x0040) + 0xC0)
tmp[#tmp+1] = string.char((codepoint % 0x0040) + 0x80)
else
tmp[#tmp+1] = string.char(math.floor(codepoint / 0x1000) + 0xE0)
tmp[#tmp+1] = string.char(math.floor((codepoint % 0x1000) / 0x0040) + 0x80)
tmp[#tmp+1] = string.char((codepoint % 0x0040) + 0x80)
end
else
tmp[#tmp+1] = string.char(escapes[byte] or byte)
end
else
tmp[#tmp+1] = string.char(byte)
end
end
local result = table.concat(tmp)
for k in pairs(tmp) do
tmp[k] = nil
end
return result, position
end
-- read in a number
local function readNumber(value, position)
local start = position
local byte = value:byte(position)
position = position + 1
if byte == minus then
byte = value:byte(position)
position = position + 1
end
local number = numbers[byte]
if not number then
error(("Number ended early: %q"):format(value))
end
if number ~= 0 then
while true do
byte = value:byte(position)
position = position + 1
local digit = numbers[byte]
if not digit then
break
end
end
else
byte = value:byte(position)
position = position + 1
end
if byte == fullStop then
local first = true
local exponent = 0
while true do
byte = value:byte(position)
position = position + 1
if not numbers[byte] then
if first then
error(("Number ended early: %q"):format(value))
end
break
end
first = false
end
end
if byte == letterE or byte == letterUpperE then
byte = value:byte(position)
position = position + 1
if byte == plus then
-- nothing to do
elseif byte == minus then
-- also nothing to do
else
position = position - 1
end
byte = value:byte(position)
position = position + 1
if not numbers[byte] then
error(("Invalid number: %q"):format(value))
end
repeat
byte = value:byte(position)
position = position + 1
until not numbers[byte]
else
position = position - 1
end
-- we're gonna use number because it's typically faster and more accurate than adding and multiplying ourselves
local number = tonumber(value:sub(start, position-1))
assert(number)
return number, position
end
-- read in true
local function readTrue(value, position)
local string = value:sub(position, position+3)
if string ~= "true" then
error(("Error reading true: %q"):format(value))
end
return true, position+4
end
-- read in false
local function readFalse(value, position)
local string = value:sub(position, position+4)
if string ~= "false" then
error(("Error reading false: %q"):format(value))
end
return false, position+5
end
-- read in null (becomes nil)
local function readNull(value, position)
local string = value:sub(position, position+3)
if string ~= "null" then
error(("Error reading null: %q"):format(value))
end
return nil, position+4
end
-- read in a list
local function readList(value, position)
assert(value:byte(position) == openBracket)
position = position + 1
if value:byte(position) == closeBracket then
return {}, position+1
end
local list = {}
-- track list position rather than #list+1 because of embedded nulls
local listPosition = 1
while true do
-- when the great division comes, there will be no pain, no
-- suffering, for we shall be the mother and father to a million
-- civilizations
local atom
atom, position = deserialize(value, position)
list[listPosition] = atom
listPosition = listPosition + 1
position = skipWhitespace(value, position)
local byte = value:byte(position)
position = position + 1
if byte == closeBracket then
return list, position
elseif not byte then
error(("Invalid list: %q, ended early"):format(value))
elseif byte ~= comma then
error(("Invalid list: %q, because of %q"):format(value, string.char(byte)))
end
end
end
-- read in a dictionary
local function readDictionary(value, position)
assert(value:byte(position) == openBrace)
position = position + 1
if value:byte(position) == closeBrace then
return {}, position+1
end
local dictionary = {}
while true do
-- get the key first
local key
key, position = deserialize(value, position)
if type(key) ~= "string" then
error(("Found non-string dictionary key: %s"):format(tostring(key)))
end
position = skipWhitespace(value, position)
local byte = value:byte(position)
position = position+1
if not byte then
error(("Invalid dictionary: %q, ended early"):format(value))
elseif byte ~= colon then
error(("Invalid dictionary: %q, because of %q"):format(value, string.char(byte)))
end
position = skipWhitespace(value, position)
-- now the value
local val
val, position = deserialize(value, position)
dictionary[key] = val
position = skipWhitespace(value, position)
local byte = value:byte(position)
position = position + 1
if byte == closeBrace then
return dictionary, position
elseif not byte then
error(("Invalid dictionary: %q, ended early"):format(value))
elseif byte ~= comma then
error(("Invalid dictionary: %q, because of %q"):format(value, string.char(byte)))
end
end
end
-- deserialize the object for the given value at the given position
function deserialize(value, position)
position = skipWhitespace(value, position)
local nextByte = value:byte(position)
if not nextByte then
error(("Premature end: %q"):format(value))
end
if nextByte == openBrace then
return readDictionary(value, position)
elseif nextByte == openBracket then
return readList(value, position)
elseif nextByte == doubleQuote then
return readString(value, position)
elseif nextByte == solidus then
position = skipComment(value, position)
return deserialize(value, position)
elseif nextByte == minus or numbers[nextByte] then
return readNumber(value, position)
elseif nextByte == letterT then
return readTrue(value, position)
elseif nextByte == letterF then
return readFalse(value, position)
elseif nextByte == letterN then
return readNull(value, position)
else
error(("Invalid input: %q"):format(value))
end
end
end
| bsd-3-clause |
a20251313/wax | lib/stdlib/helpers/frame.lua | 19 | 2670 | -- This is weird code... I'm just playing with an idea
function wax.frame(object)
return wax.dimensions(object, "frame")
end
function wax.bounds(object)
return wax.dimensions(object, "bounds")
end
function wax.dimensions(object, varName)
return setmetatable({
object = object,
center = function(self)
local offset = (wax.dimensions(self.object:superview(), varName).width - self.width) / 2
self.x = offset
return self
end,
},
{
__index = function(self, key)
if key == "y" then key = "top"
elseif key == "x" then key = "left"
end
local dimensions = (varName == "frame") and object:frame() or object:bounds()
if key == "left" then return dimensions.x
elseif key == "right" then return dimensions.x + dimensions.width
elseif key == "top" then return dimensions.y
elseif key == "bottom" then return dimensions.y + dimensions.height
elseif key == "height" then return dimensions.height
elseif key == "width" then return dimensions.width
elseif key == "size" then return CGSize(dimensions.width, dimensions.height)
elseif key == "origin" then return CGPoint(dimensions.x, dimensions.y)
else
error("Unknown frame key: " .. key)
end
end,
__newindex = function(self, key, value)
if key == "y" then key = "top"
elseif key == "x" then key = "left"
end
local dimensions = (varName == "frame") and object:frame() or object:bounds()
if key == "left" then dimensions.x = value
elseif key == "right" then dimensions.x = value - dimensions.width
elseif key == "top" then dimensions.y = value
elseif key == "bottom" then dimensions.y = value - dimensions.height
elseif key == "height" then dimensions.height = value
elseif key == "width" then dimensions.width = value
elseif key == "size" then dimensions.width = value.width dimensions.height = value.height
elseif key == "origin" then dimensions.x = value.x dimensions.y = value.y
elseif key == "stretchTop" then
dimensions.height = dimensions.height - (value - dimensions.y)
dimensions.y = value
elseif key == "stretchBottom" then
dimensions.height = dimensions.height + (value - (dimensions.height + dimensions.y))
elseif key == "stretchRight" then
dimensions.width = dimensions.width + (value - (dimensions.width + dimensions.x))
else
error("Unknown frame key: " .. key)
end
if (varName == "frame") then
object:setFrame(dimensions)
else
object:setBounds(dimensions)
end
return self
end
})
end | mit |
PlexChat/premake-core | tests/testfx.lua | 9 | 10494 | --
-- tests/testfx.lua
-- Automated test framework for Premake.
-- Copyright (c) 2008-2015 Jason Perkins and the Premake project
--
local p = premake
--
-- Define a namespace for the testing functions
--
test = {}
test.suppressed = {}
--
-- Capture stderr for testing.
--
local stderr_capture = nil
local mt = getmetatable(io.stderr)
local builtin_write = mt.write
mt.write = function(...)
if select(1,...) == io.stderr then
stderr_capture = (stderr_capture or "") .. select(2,...)
else
return builtin_write(...)
end
end
--
-- Assertion functions
--
function test.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
test.fail("(%d) expected:\n%s\n...but was:\n%s", linenum, etxt, atxt)
end
linenum = linenum + 1
atxt = ait()
etxt = eit()
end
end
function test.closedfile(expected)
if expected and not test.value_closedfile then
test.fail("expected file to be closed")
elseif not expected and test.value_closedfile then
test.fail("expected file to remain open")
end
end
function test.contains(expected, actual)
if type(expected) == "table" then
for i, v in ipairs(expected) do
test.contains(v, actual)
end
elseif not table.contains(actual, expected) then
test.fail("expected value %s not found", expected)
end
end
function test.excludes(expected, actual)
if type(expected) == "table" then
for i, v in ipairs(expected) do
test.excludes(v, actual)
end
elseif table.contains(actual, expected) then
test.fail("excluded value %s found", expected)
end
end
function test.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 test.filecontains(expected, fn)
local f = io.open(fn)
local actual = f:read("*a")
f:close()
if (expected ~= actual) then
test.fail("expected %s but was %s", expected, actual)
end
end
function test.hasoutput()
local actual = premake.captured()
if actual == "" then
test.fail("expected output, received none");
end
end
function test.isemptycapture()
local actual = premake.captured()
if actual ~= "" then
test.fail("expected empty capture, but was %s", actual);
end
end
function test.isequal(expected, actual, depth)
depth = depth or 0
if type(expected) == "table" then
if expected and not actual then
test.fail(depth, "expected table, got nil")
end
if #expected < #actual then
test.fail(depth, "expected %d items, got %d", #expected, #actual)
end
for k,v in pairs(expected) do
test.isequal(expected[k], actual[k], depth + 1)
end
else
if (expected ~= actual) then
test.fail(depth, "expected %s but was %s", expected, actual)
end
end
return true
end
function test.isfalse(value)
if (value) then
test.fail("expected false but was true")
end
end
function test.isnil(value)
if (value ~= nil) then
test.fail("expected nil but was " .. tostring(value))
end
end
function test.isnotnil(value)
if (value == nil) then
test.fail("expected not nil")
end
end
function test.issame(expected, action)
if expected ~= action then
test.fail("expected same value")
end
end
function test.istrue(value)
if (not value) then
test.fail("expected true but was false")
end
end
function test.missing(value, actual)
if table.contains(actual, value) then
test.fail("unexpected value %s found", value)
end
end
function test.openedfile(fname)
if fname ~= test.value_openedfilename then
local msg = "expected to open file '" .. fname .. "'"
if test.value_openedfilename then
msg = msg .. ", got '" .. test.value_openedfilename .. "'"
end
test.fail(msg)
end
end
function test.success(fn, ...)
local ok, err = pcall(fn, ...)
if not ok then
test.fail("call failed: " .. err)
end
end
function test.stderr(expected)
if not expected and stderr_capture then
test.fail("Unexpected: " .. stderr_capture)
elseif expected then
if not stderr_capture or not stderr_capture:find(expected) then
test.fail(string.format("expected '%s'; got %s", expected, stderr_capture or "(nil)"))
end
end
end
function test.notstderr(expected)
if not expected and not stderr_capture then
test.fail("Expected output on stderr; none received")
elseif expected then
if stderr_capture and stderr_capture:find(expected) then
test.fail(string.format("stderr contains '%s'; was %s", expected, stderr_capture))
end
end
end
--
-- Some helper functions
--
function test.createWorkspace()
local wks = workspace("MyWorkspace")
configurations { "Debug", "Release" }
local prj = test.createproject(wks)
return wks, prj
end
-- Eventually we'll want to deprecate this one and move everyone
-- over to createWorkspace() instead (4 Sep 2015).
function test.createsolution()
local wks = workspace("MySolution")
configurations { "Debug", "Release" }
local prj = test.createproject(wks)
return wks, prj
end
function test.createproject(wks)
local n = #wks.projects + 1
if n == 1 then n = "" end
local prj = project ("MyProject" .. n)
language "C++"
kind "ConsoleApp"
return prj
end
function test.getWorkspace(wks)
p.oven.bake()
return p.global.getWorkspace(wks.name)
end
p.alias(test, "getWorkspace", "getsolution")
function test.getproject(wks, i)
wks = test.getWorkspace(wks)
return p.workspace.getproject(wks, i or 1)
end
function test.getconfig(prj, buildcfg, platform)
local wks = test.getWorkspace(prj.workspace)
prj = p.workspace.getproject(wks, prj.name)
return p.project.getconfig(prj, buildcfg, platform)
end
--
-- Test stubs
--
local function stub_io_open(fname, mode)
test.value_openedfilename = fname
test.value_openedfilemode = mode
return {
close = function()
test.value_closedfile = true
end
}
end
local function stub_io_output(f)
end
local function stub_print(s)
end
local function stub_utf8()
end
local function stub_os_writefile_ifnotequal(content, fname)
test.value_openedfilename = fname;
test.value_closedfile = true
return 0;
end
--
-- Define a collection for the test suites
--
T = {}
--
-- Test execution function
--
local _OS_host = _OS
local _OPTIONS_host = _OPTIONS
local function error_handler(err)
local msg = err
-- if the error doesn't include a stack trace, add one
if not msg:find("stack traceback:", 1, true) then
msg = debug.traceback(err, 2)
end
-- trim of the trailing context of the originating xpcall
local i = msg:find("[C]: in function 'xpcall'", 1, true)
if i then
msg = msg:sub(1, i - 3)
end
-- if the resulting stack trace is only one level deep, ignore it
local n = select(2, msg:gsub('\n', '\n'))
if n == 2 then
msg = msg:sub(1, msg:find('\n', 1, true) - 1)
end
return msg
end
local function test_setup(suite, fn)
_ACTION = "test"
_OS = _OS_host
_OPTIONS = {}
setmetatable(_OPTIONS, getmetatable(_OPTIONS_host))
stderr_capture = nil
premake.clearWarnings()
premake.eol("\n")
premake.escaper(nil)
premake.indent("\t")
premake.api.reset()
-- reset captured I/O values
test.value_openedfilename = nil
test.value_openedfilemode = nil
test.value_closedfile = false
if suite.setup then
return xpcall(suite.setup, error_handler)
else
return true
end
end
local function test_run(suite, fn)
local result, err
premake.capture(function()
result, err = xpcall(fn, error_handler)
end)
return result, err
end
local function test_teardown(suite, fn)
if suite.teardown then
return xpcall(suite.teardown, error_handler)
else
return true
end
end
function test.declare(id)
if T[id] then
error("Duplicate test suite " .. id)
end
T[id] = {
_TESTS_DIR = _TESTS_DIR,
_SCRIPT_DIR = _SCRIPT_DIR,
}
return T[id]
end
function test.suppress(id)
if type(id) == "table" then
for i = 1, #id do
test.suppress(id[i])
end
else
test.suppressed[id] = true
end
end
function test.runall(suitename, testname)
test.print = print
local real_print = print
local real_open = io.open
local real_output = io.output
print = stub_print
io.open = stub_io_open
io.output = stub_io_output
os.writefile_ifnotequal = stub_os_writefile_ifnotequal
premake.utf8 = stub_utf8
local numpassed = 0
local numfailed = 0
function runtest(suitename, suitetests, testname, testfunc)
if suitetests.setup ~= testfunc and
suitetests.teardown ~= testfunc and
not test.suppressed[suitename .. "." .. testname]
then
local ok, err = test_setup(suitetests, testfunc)
if ok then
ok, err = test_run(suitetests, testfunc)
end
local tok, terr = test_teardown(suitetests, testfunc)
ok = ok and tok
err = err or terr
if (not ok) then
test.print(string.format("%s.%s: %s", suitename, testname, err))
numfailed = numfailed + 1
else
numpassed = numpassed + 1
end
end
end
function runsuite(suitename, suitetests, testname)
if suitetests and not test.suppressed[suitename] then
_TESTS_DIR = suitetests._TESTS_DIR
_SCRIPT_DIR = suitetests._SCRIPT_DIR
if testname then
runtest(suitename, suitetests, testname, suitetests[testname])
else
for testname, testfunc in pairs(suitetests) do
if type(testfunc) == "function" then
runtest(suitename, suitetests, testname, testfunc)
end
end
end
end
end
if suitename then
runsuite(suitename, T[suitename], testname)
else
for suitename, suitetests in pairs(T) do
runsuite(suitename, suitetests, testname)
end
end
print = real_print
io.open = real_open
io.output = real_output
return numpassed, numfailed
end
| bsd-3-clause |
xdemolish/darkstar | scripts/zones/Dynamis-Windurst/Zone.lua | 4 | 2260 | -----------------------------------
--
-- Zone: Dynamis-Windurst
--
-----------------------------------
package.loaded["scripts/zones/Dynamis-Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Dynamis-Windurst/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaWindurst]UniqueID")) then
if(player:isBcnmsFull() == 1) then
if(player:hasStatusEffect(EFFECT_DYNAMIS, 0) == false) then
inst = player:addPlayerToDynamis(1282);
if(inst == 1)then
player:bcnmEnter(1282);
else
cs = 0;
end
else
player:bcnmEnter(1282);
end
else
inst = player:bcnmRegister(1282);
if(inst == 1)then
player:bcnmEnter(1282);
else
cs = 0;
end
end
else
cs = 0;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0) then
player:setPos(-217.000,1.000,-119.000,94,0xEF);
end
end; | gpl-3.0 |
mluds/blockulous | goo/objects/progressbar.lua | 2 | 1582 | -------------------------------------------------------------
------ PROGRESS BAR.
-------------------------------------------------------------
goo.progressbar = class('goo progressbar', goo.object)
function goo.progressbar:initialize( parent )
super.initialize(self,parent)
self.current_progress = 0
self.max_progress = 100
self.max_width = 100
self.scale = 100
self:setRange()
end
function goo.progressbar:draw( x, y )
love.graphics.setColor( unpack(self.style.backgroundColor) )
love.graphics.rectangle( self.style.fillMode, x, y, self.w, self.h )
end
function goo.progressbar:setProgress( progress )
self.current_progress = progress
local w = self.current_progress/self.range
end
function goo.progressbar:setPercentage( percentage )
local percentage = percentage or 0
self.w = self.max_width * (percentage/100)
end
function goo.progressbar:setRange( min, max )
local min = min or 0
local max = max or 100
self.range = (max-min)
return self.range
end
function goo.progressbar:setSize( w, h )
super.setSize( self, w, h )
self.max_width = w
self.scale = self.range / w
end
function goo.progressbar:updateSize( w, h )
local w = w or self.w or 0
local h = h or self.h or 20
self.w = w
self.h = h
end
function goo.progressbar:incrementProgress()
self.current_progress = self.current_progress + 1
self:updateSize( (self.current_progress / self.range) * self.max_width )
end
function goo.progressbar:getProgress()
return self.current_progress
end
function goo.progressbar:getPercentage()
return (self.w/self.max_width)*100
end
return goo.progressbar | mit |
lukego/snabb | lib/ljsyscall/test/bsd.lua | 18 | 16048 | -- General BSD tests
local function init(S)
local helpers = require "syscall.helpers"
local types = S.types
local c = S.c
local abi = S.abi
local bit = require "syscall.bit"
local ffi = require "ffi"
local t, pt, s = types.t, types.pt, types.s
local assert = helpers.assert
local function fork_assert(cond, err, ...) -- if we have forked we need to fail in main thread not fork
if not cond then
print(tostring(err))
print(debug.traceback())
S.exit("failure")
end
if cond == true then return ... end
return cond, ...
end
local function assert_equal(...)
collectgarbage("collect") -- force gc, to test for bugs
return assert_equals(...)
end
local teststring = "this is a test string"
local size = 512
local buf = t.buffer(size)
local tmpfile = "XXXXYYYYZZZ4521" .. S.getpid()
local tmpfile2 = "./666666DDDDDFFFF" .. S.getpid()
local tmpfile3 = "MMMMMTTTTGGG" .. S.getpid()
local longfile = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" .. S.getpid()
local efile = "./tmpexXXYYY" .. S.getpid() .. ".sh"
local largeval = math.pow(2, 33) -- larger than 2^32 for testing
local mqname = "ljsyscallXXYYZZ" .. S.getpid()
local clean = function()
S.rmdir(tmpfile)
S.unlink(tmpfile)
S.unlink(tmpfile2)
S.unlink(tmpfile3)
S.unlink(longfile)
S.unlink(efile)
end
local test = {}
test.bsd_misc = {
test_sysctl_all = function()
local all, err = S.sysctl()
assert(all and type(all) == "table", "expect a table from all sysctls got " .. type(all))
end,
}
test.bsd_ids = {
test_issetugid = function()
if not S.issetugid then error "skipped" end
local res = assert(S.issetugid())
assert(res == 0 or res == 1) -- some tests call setuid so might be tainted
end,
}
test.filesystem_bsd = {
test_revoke = function()
local fd = assert(S.posix_openpt("rdwr, noctty"))
assert(fd:grantpt())
assert(fd:unlockpt())
local pts_name = assert(fd:ptsname())
local pts = assert(S.open(pts_name, "rdwr, noctty"))
assert(S.revoke(pts_name))
local n, err = pts:read()
if n then -- correct behaviour according to man page
assert_equal(#n, 0) -- read returns EOF after revoke
else -- FreeBSD is NXIO Filed http://www.freebsd.org/cgi/query-pr.cgi?pr=188952
-- OSX is EIO
assert(not n and (err.IO or err.NXIO))
end
local n, err = pts:write("test") -- write fails after revoke
assert(not n and (err.IO or err.NXIO), "access should be revoked")
assert(pts:close()) -- close succeeds after revoke
assert(fd:close())
end,
test_chflags = function()
local fd = assert(S.creat(tmpfile, "RWXU"))
assert(fd:write("append"))
assert(S.chflags(tmpfile, "uf_append"))
assert(fd:write("append"))
assert(fd:seek(0, "set"))
local n, err = fd:write("not append")
if not (S.__rump or abi.xen) then assert(err and err.PERM, "non append write should fail") end -- TODO I think this is due to tmpfs mount??
assert(S.chflags(tmpfile)) -- clear flags
assert(S.unlink(tmpfile))
assert(fd:close())
end,
test_lchflags = function()
if not S.lchflags then error "skipped" end
local fd = assert(S.creat(tmpfile, "RWXU"))
assert(fd:write("append"))
assert(S.lchflags(tmpfile, "uf_append"))
assert(fd:write("append"))
assert(fd:seek(0, "set"))
local n, err = fd:write("not append")
if not (S.__rump or abi.xen) then assert(err and err.PERM, "non append write should fail") end -- TODO I think this is due to tmpfs mount??
assert(S.lchflags(tmpfile)) -- clear flags
assert(S.unlink(tmpfile))
assert(fd:close())
end,
test_fchflags = function()
local fd = assert(S.creat(tmpfile, "RWXU"))
assert(fd:write("append"))
assert(fd:chflags("uf_append"))
assert(fd:write("append"))
assert(fd:seek(0, "set"))
local n, err = fd:write("not append")
if not (S.__rump or abi.xen) then assert(err and err.PERM, "non append write should fail") end -- TODO I think this is due to tmpfs mount??
assert(fd:chflags()) -- clear flags
assert(S.unlink(tmpfile))
assert(fd:close())
end,
test_chflagsat = function()
if not S.chflagsat then error "skipped" end
local fd = assert(S.creat(tmpfile, "RWXU"))
assert(fd:write("append"))
assert(S.chflagsat("fdcwd", tmpfile, "uf_append", "symlink_nofollow"))
assert(fd:write("append"))
assert(fd:seek(0, "set"))
local n, err = fd:write("not append")
assert(err and err.PERM, "non append write should fail")
assert(S.chflagsat("fdcwd", tmpfile)) -- clear flags
assert(S.unlink(tmpfile))
assert(fd:close())
end,
test_lchmod = function()
if not S.lchmod then error "skipped" end
local fd = assert(S.creat(tmpfile, "RWXU"))
assert(S.lchmod(tmpfile, "RUSR, WUSR"))
assert(S.access(tmpfile, "rw"))
assert(S.unlink(tmpfile))
assert(fd:close())
end,
test_utimensat = function()
-- BSD utimensat as same specification as Linux, but some functionality missing, so test simpler
if not S.utimensat then error "skipped" end
local fd = assert(S.creat(tmpfile, "RWXU"))
local dfd = assert(S.open("."))
assert(S.utimensat(nil, tmpfile))
local st1 = fd:stat()
assert(S.utimensat("fdcwd", tmpfile, {"omit", "omit"}))
local st2 = fd:stat()
assert(st1.mtime == st2.mtime, "mtime unchanged") -- cannot test atime as stat touches it
assert(S.unlink(tmpfile))
assert(fd:close())
assert(dfd:close())
end,
}
test.kqueue = {
test_kqueue_vnode = function()
local kfd = assert(S.kqueue())
local fd = assert(S.creat(tmpfile, "rwxu"))
local kevs = t.kevents{{fd = fd, filter = "vnode",
flags = "add, enable, clear", fflags = "delete, write, extend, attrib, link, rename, revoke"}}
assert(kfd:kevent(kevs, nil))
local _, _, n = assert(kfd:kevent(nil, kevs, 0))
assert_equal(n, 0) -- no events yet
assert(S.unlink(tmpfile))
local count = 0
for k, v in assert(kfd:kevent(nil, kevs, 1)) do
assert(v.DELETE, "expect delete event")
count = count + 1
end
assert_equal(count, 1)
assert(fd:write("something"))
local count = 0
for k, v in assert(kfd:kevent(nil, kevs, 1)) do
assert(v.WRITE, "expect write event")
assert(v.EXTEND, "expect extend event")
count = count + 1
end
assert_equal(count, 1)
assert(fd:close())
assert(kfd:close())
end,
test_kqueue_read = function()
local kfd = assert(S.kqueue())
local p1, p2 = assert(S.pipe())
local kevs = t.kevents{{fd = p1, filter = "read", flags = "add"}}
assert(kfd:kevent(kevs, nil))
local a, b, n = assert(kfd:kevent(nil, kevs, 0))
assert_equal(n, 0) -- no events yet
local str = "test"
p2:write(str)
local count = 0
for k, v in assert(kfd:kevent(nil, kevs, 0)) do
assert_equal(v.size, #str) -- size will be amount available to read
count = count + 1
end
assert_equal(count, 1) -- 1 event readable now
local r, err = p1:read()
local _, _, n = assert(kfd:kevent(nil, kevs, 0))
assert_equal(n, 0) -- no events any more
assert(p2:close())
local count = 0
for k, v in assert(kfd:kevent(nil, kevs, 0)) do
assert(v.EOF, "expect EOF event")
count = count + 1
end
assert_equal(count, 1)
assert(p1:close())
assert(kfd:close())
end,
test_kqueue_write = function()
local kfd = assert(S.kqueue())
local p1, p2 = assert(S.pipe())
local kevs = t.kevents{{fd = p2, filter = "write", flags = "add"}}
assert(kfd:kevent(kevs, nil))
local count = 0
for k, v in assert(kfd:kevent(nil, kevs, 0)) do
assert(v.size > 0) -- size will be amount free in buffer
count = count + 1
end
assert_equal(count, 1) -- one event
assert(p1:close()) -- close read end
count = 0
for k, v in assert(kfd:kevent(nil, kevs, 0)) do
assert(v.EOF, "expect EOF event")
count = count + 1
end
assert_equal(count, 1)
assert(p2:close())
assert(kfd:close())
end,
test_kqueue_timer = function()
local kfd = assert(S.kqueue())
local kevs = t.kevents{{ident = 0, filter = "timer", flags = "add, oneshot", data = 10}}
assert(kfd:kevent(kevs, nil))
local count = 0
for k, v in assert(kfd:kevent(nil, kevs)) do
assert_equal(v.size, 1) -- count of expiries is 1 as oneshot
count = count + 1
end
assert_equal(count, 1) -- will have expired by now
assert(kfd:close())
end,
}
test.bsd_extattr = {
teardown = clean,
test_extattr_empty_fd = function()
if not S.extattr_get_fd then error "skipped" end
local fd = assert(S.creat(tmpfile, "rwxu"))
assert(S.unlink(tmpfile))
local n, err = fd:extattr_get("user", "myattr", false) -- false does raw call with no buffer to return length
if not n and err.OPNOTSUPP then error "skipped" end -- fs does not support extattr
assert(not n and err.NOATTR)
assert(fd:close())
end,
test_extattr_getsetdel_fd = function()
if not S.extattr_get_fd then error "skipped" end
local fd = assert(S.creat(tmpfile, "rwxu"))
assert(S.unlink(tmpfile))
local n, err = fd:extattr_get("user", "myattr", false) -- false does raw call with no buffer to return length
if not n and err.OPNOTSUPP then error "skipped" end -- fs does not support extattr
assert(not n and err.NOATTR)
local n, err = fd:extattr_set("user", "myattr", "myvalue")
if not n and err.OPNOTSUPP then error "skipped" end -- fs does not support setting extattr
assert(n, err)
assert_equal(n, #"myvalue")
local str = assert(fd:extattr_get("user", "myattr"))
assert_equal(str, "myvalue")
local ok = assert(fd:extattr_delete("user", "myattr"))
local str, err = fd:extattr_get("user", "myattr")
assert(not str and err.NOATTR)
assert(fd:close())
end,
test_extattr_getsetdel_file = function()
if not S.extattr_get_fd then error "skipped" end
local fd = assert(S.creat(tmpfile, "rwxu"))
assert(fd:close())
local n, err = S.extattr_get_file(tmpfile, "user", "myattr", false) -- false does raw call with no buffer to return length
if not n and err.OPNOTSUPP then error "skipped" end -- fs does not support extattr
assert(not n and err.NOATTR)
local n, err = S.extattr_set_file(tmpfile, "user", "myattr", "myvalue")
if not n and err.OPNOTSUPP then error "skipped" end -- fs does not support setting extattr
assert(n, err)
assert_equal(n, #"myvalue")
local str = assert(S.extattr_get_file(tmpfile, "user", "myattr"))
assert_equal(str, "myvalue")
local ok = assert(S.extattr_delete_file(tmpfile, "user", "myattr"))
local str, err = S.extattr_get_file(tmpfile, "user", "myattr")
assert(not str and err.NOATTR)
assert(S.unlink(tmpfile))
end,
test_extattr_getsetdel_link = function()
if not S.extattr_get_fd then error "skipped" end
assert(S.symlink(tmpfile2, tmpfile))
local n, err = S.extattr_get_link(tmpfile, "user", "myattr", false) -- false does raw call with no buffer to return length
if not n and err.OPNOTSUPP then error "skipped" end -- fs does not support extattr
assert(not n and err.NOATTR)
local n, err = S.extattr_set_link(tmpfile, "user", "myattr", "myvalue")
if not n and err.OPNOTSUPP then error "skipped" end -- fs does not support setting extattr
assert(n, err)
assert_equal(n, #"myvalue")
local str = assert(S.extattr_get_link(tmpfile, "user", "myattr"))
assert_equal(str, "myvalue")
local ok = assert(S.extattr_delete_link(tmpfile, "user", "myattr"))
local str, err = S.extattr_get_link(tmpfile, "user", "myattr")
assert(not str and err.NOATTR)
assert(S.unlink(tmpfile))
end,
test_extattr_list_fd = function()
if not S.extattr_list_fd then error "skipped" end
local fd = assert(S.creat(tmpfile, "rwxu"))
assert(S.unlink(tmpfile))
local attrs, err = fd:extattr_list("user")
if not attrs and err.OPNOTSUPP then error "skipped" end -- fs does not support extattr
assert(attrs, err)
assert_equal(#attrs, 0)
assert(fd:extattr_set("user", "myattr", "myvalue"))
local attrs = assert(fd:extattr_list("user"))
assert_equal(#attrs, 1)
assert_equal(attrs[1], "myattr")
assert(fd:extattr_set("user", "newattr", "newvalue"))
local attrs = assert(fd:extattr_list("user"))
assert_equal(#attrs, 2)
assert((attrs[1] == "myattr" and attrs[2] == "newattr") or (attrs[2] == "myattr" and attrs[1] == "newattr"))
assert(fd:close())
end,
test_extattr_list_file = function()
if not S.extattr_list_file then error "skipped" end
local fd = assert(S.creat(tmpfile, "rwxu"))
local attrs, err = S.extattr_list_file(tmpfile, "user")
if not attrs and err.OPNOTSUPP then error "skipped" end -- fs does not support extattr
assert(attrs, err)
assert_equal(#attrs, 0)
assert(S.extattr_set_file(tmpfile, "user", "myattr", "myvalue"))
local attrs = assert(S.extattr_list_file(tmpfile, "user"))
assert_equal(#attrs, 1)
assert_equal(attrs[1], "myattr")
assert(S.extattr_set_file(tmpfile, "user", "newattr", "newvalue"))
local attrs = assert(S.extattr_list_file(tmpfile, "user"))
assert_equal(#attrs, 2)
assert((attrs[1] == "myattr" and attrs[2] == "newattr") or (attrs[2] == "myattr" and attrs[1] == "newattr"))
assert(S.unlink(tmpfile))
end,
test_extattr_list_link = function()
if not S.extattr_list_file then error "skipped" end
assert(S.symlink(tmpfile2, tmpfile))
local attrs, err = S.extattr_list_link(tmpfile, "user")
if not attrs and err.OPNOTSUPP then error "skipped" end -- fs does not support extattr
assert(attrs, err)
assert_equal(#attrs, 0)
assert(S.extattr_set_link(tmpfile, "user", "myattr", "myvalue"))
local attrs = assert(S.extattr_list_link(tmpfile, "user"))
assert_equal(#attrs, 1)
assert_equal(attrs[1], "myattr")
assert(S.extattr_set_link(tmpfile, "user", "newattr", "newvalue"))
local attrs = assert(S.extattr_list_link(tmpfile, "user"))
assert_equal(#attrs, 2)
assert((attrs[1] == "myattr" and attrs[2] == "newattr") or (attrs[2] == "myattr" and attrs[1] == "newattr"))
assert(S.unlink(tmpfile))
end,
test_extattr_list_long = function()
if not S.extattr_list_fd then error "skipped" end
local fd = assert(S.creat(tmpfile, "rwxu"))
assert(S.unlink(tmpfile))
local attrs, err = fd:extattr_list("user")
if not attrs and err.OPNOTSUPP then error "skipped" end -- fs does not support extattr
assert(attrs, err)
assert_equal(#attrs, 0)
local count = 100
for i = 1, count do
assert(fd:extattr_set("user", "myattr" .. i, "myvalue"))
end
local attrs = assert(fd:extattr_list("user"))
assert_equal(#attrs, count)
assert(fd:close())
end,
}
-- skip as no processes in rump
if not S.__rump then
test.kqueue.test_kqueue_proc = function()
local pid = assert(S.fork())
if pid == 0 then -- child
S.pause()
S.exit()
else -- parent
local kfd = assert(S.kqueue())
local kevs = t.kevents{{ident = pid, filter = "proc", flags = "add", fflags = "exit, fork, exec"}}
assert(kfd:kevent(kevs, nil))
assert(S.kill(pid, "term"))
local count = 0
for k, v in assert(kfd:kevent(nil, kevs, 1)) do
assert(v.EXIT)
count = count + 1
end
assert_equal(count, 1)
assert(kfd:close())
assert(S.waitpid(pid))
end
end
test.kqueue.test_kqueue_signal = function()
assert(S.signal("alrm", "ign"))
local kfd = assert(S.kqueue())
local kevs = t.kevents{{signal = "alrm", filter = "signal", flags = "add"}}
assert(kfd:kevent(kevs, nil))
assert(S.kill(0, "alrm"))
assert(S.kill(0, "alrm"))
local count = 0
for k, v in assert(kfd:kevent(nil, kevs, 1)) do
assert_equal(v.data, 2) -- event happened twice
count = count + 1
end
assert_equal(count, 1)
assert(S.signal("alrm", "dfl"))
end
end
return test
end
return {init = init}
| apache-2.0 |
samael65535/quick-ng | quick/framework/luaoc.lua | 20 | 2593 | --[[
Copyright (c) 2011-2014 chukong-inc.com
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.
]]
--------------------------------
-- @module luaoc
--[[--
Lua 与 Objective-C 的交互接口
]]
local luaoc = {}
local callStaticMethod = LuaObjcBridge.callStaticMethod
-- start --
--------------------------------
-- 调用Objective-C类的接口。
-- @function [parent=#luaoc] callStaticMethod
-- @param string className Objective-C类名
-- @param string methodName Objective-C类方法名
-- @param table args Objective-C类方法所需要的各种参数字典,key值为方法的参数名
-- @return boolean#boolean ret (return value: bool) ok, mixed ret ok为是否调用成功, ok为true时,ret为Objective-C方法的返回值,ok为false时,ret为出错原因
-- end --
function luaoc.callStaticMethod(className, methodName, args)
local ok, ret = callStaticMethod(className, methodName, args)
if not ok then
local msg = string.format("luaoc.callStaticMethod(\"%s\", \"%s\", \"%s\") - error: [%s] ",
className, methodName, tostring(args), tostring(ret))
if ret == -1 then
printError(msg .. "INVALID PARAMETERS")
elseif ret == -2 then
printError(msg .. "CLASS NOT FOUND")
elseif ret == -3 then
printError(msg .. "METHOD NOT FOUND")
elseif ret == -4 then
printError(msg .. "EXCEPTION OCCURRED")
elseif ret == -5 then
printError(msg .. "INVALID METHOD SIGNATURE")
else
printError(msg .. "UNKNOWN")
end
end
return ok, ret
end
return luaoc
| mit |
hsiaoyi/Melo | cocos2d/cocos/scripting/lua-bindings/auto/api/MenuItemFont.lua | 11 | 2660 |
--------------------------------
-- @module MenuItemFont
-- @extend MenuItemLabel
-- @parent_module cc
--------------------------------
-- Returns the name of the Font.<br>
-- js getFontNameObj<br>
-- js NA
-- @function [parent=#MenuItemFont] getFontNameObj
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- Set the font name .<br>
-- c++ can not overload static and non-static member functions with the same parameter types.<br>
-- so change the name to setFontNameObj.<br>
-- js setFontName<br>
-- js NA
-- @function [parent=#MenuItemFont] setFontNameObj
-- @param self
-- @param #string name
-- @return MenuItemFont#MenuItemFont self (return value: cc.MenuItemFont)
--------------------------------
-- Initializes a menu item from a string with a target/selector.
-- @function [parent=#MenuItemFont] initWithString
-- @param self
-- @param #string value
-- @param #function callback
-- @return bool#bool ret (return value: bool)
--------------------------------
-- get font size .<br>
-- js getFontSize<br>
-- js NA
-- @function [parent=#MenuItemFont] getFontSizeObj
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- Set font size.<br>
-- c++ can not overload static and non-static member functions with the same parameter types.<br>
-- so change the name to setFontSizeObj.<br>
-- js setFontSize<br>
-- js NA
-- @function [parent=#MenuItemFont] setFontSizeObj
-- @param self
-- @param #int size
-- @return MenuItemFont#MenuItemFont self (return value: cc.MenuItemFont)
--------------------------------
-- Set the default font name.
-- @function [parent=#MenuItemFont] setFontName
-- @param self
-- @param #string name
-- @return MenuItemFont#MenuItemFont self (return value: cc.MenuItemFont)
--------------------------------
-- Get default font size.
-- @function [parent=#MenuItemFont] getFontSize
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- Get the default font name.
-- @function [parent=#MenuItemFont] getFontName
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- Set default font size.
-- @function [parent=#MenuItemFont] setFontSize
-- @param self
-- @param #int size
-- @return MenuItemFont#MenuItemFont self (return value: cc.MenuItemFont)
--------------------------------
-- js ctor
-- @function [parent=#MenuItemFont] MenuItemFont
-- @param self
-- @return MenuItemFont#MenuItemFont self (return value: cc.MenuItemFont)
return nil
| apache-2.0 |
czfshine/UpAndAway | code/prefabs/cloud_fruit.lua | 2 | 3308 | BindGlobal()
local CFG = TheMod:GetConfig()
local assets =
{
Asset("ANIM", "anim/cloud_fruit.zip"),
Asset( "ATLAS", inventoryimage_atlas("cloud_fruit") ),
Asset( "IMAGE", inventoryimage_texture("cloud_fruit") ),
Asset( "ATLAS", inventoryimage_atlas("cloud_fruit_cooked") ),
Asset( "IMAGE", inventoryimage_texture("cloud_fruit_cooked") ),
}
local function fn(Sim)
local inst = CreateEntity()
inst.entity:AddTransform()
inst.entity:AddAnimState()
inst.entity:AddSoundEmitter()
MakeInventoryPhysics(inst)
inst.AnimState:SetBank("dragonfruit")
inst.AnimState:SetBuild("cloud_fruit")
inst.AnimState:PlayAnimation("idle")
------------------------------------------------------------------------
SetupNetwork(inst)
------------------------------------------------------------------------
inst:AddComponent("inspectable")
inst:AddComponent("inventoryitem")
inst.components.inventoryitem.atlasname = inventoryimage_atlas("cloud_fruit")
inst:AddComponent("stackable")
inst.components.stackable.maxsize = CFG.CLOUD_FRUIT.STACK_SIZE
inst:AddComponent("edible")
inst.components.edible.foodtype = CFG.CLOUD_FRUIT.FOODTYPE
inst.components.edible.healthvalue = CFG.CLOUD_FRUIT.UNCOOKED_HEALTH_VALUE
inst.components.edible.hungervalue = CFG.CLOUD_FRUIT.UNCOOKED_HUNGER_VALUE
inst.components.edible.sanityvalue = CFG.CLOUD_FRUIT.UNCOOKED_SANITY_VALUE
inst:AddComponent("cookable")
inst.components.cookable.product = CFG.CLOUD_FRUIT.COOKED_PRODUCT
inst:AddComponent("perishable")
inst.components.perishable:SetPerishTime(CFG.CLOUD_FRUIT.UNCOOKED_PERISH_TIME)
inst.components.perishable:StartPerishing()
inst.components.perishable.onperishreplacement = CFG.CLOUD_FRUIT.PERISH_ITEM
return inst
end
local function cookedfn(inst)
local inst = CreateEntity()
inst.entity:AddTransform()
inst.entity:AddAnimState()
inst.entity:AddSoundEmitter()
MakeInventoryPhysics(inst)
inst.AnimState:SetBank("dragonfruit")
inst.AnimState:SetBuild("cloud_fruit")
inst.AnimState:PlayAnimation("cooked")
------------------------------------------------------------------------
SetupNetwork(inst)
------------------------------------------------------------------------
inst:AddComponent("inspectable")
inst:AddComponent("inventoryitem")
inst.components.inventoryitem.atlasname = inventoryimage_atlas("cloud_fruit_cooked")
inst:AddComponent("stackable")
inst.components.stackable.maxsize = CFG.CLOUD_FRUIT.STACK_SIZE
inst:AddComponent("edible")
inst.components.edible.foodtype = CFG.CLOUD_FRUIT.FOODTYPE
inst.components.edible.healthvalue = CFG.CLOUD_FRUIT.COOKED_HEALTH_VALUE
inst.components.edible.hungervalue = CFG.CLOUD_FRUIT.COOKED_HUNGER_VALUE
inst.components.edible.sanityvalue = CFG.CLOUD_FRUIT.COOKED_SANITY_VALUE
inst:AddComponent("perishable")
inst.components.perishable:SetPerishTime(CFG.CLOUD_FRUIT.COOKED_PERISH_TIME)
inst.components.perishable:StartPerishing()
inst.components.perishable.onperishreplacement = CFG.CLOUD_FRUIT.PERISH_ITEM
return inst
end
return {
Prefab ("common/inventory/cloud_fruit", fn, assets, prefabs),
Prefab ("common/inventory/cloud_fruit_cooked", cookedfn, assets, prefabs)
}
| gpl-2.0 |
lukego/snabb | src/program/firehose/firehose.lua | 6 | 4726 | module(..., package.seeall)
local lib = require("core.lib")
local long_opts = {
help = "h",
example = "e",
["print-header"] = "H",
time = "t",
input = "i",
["ring-size"] = "r",
}
function fatal (reason)
print(reason)
os.exit(1)
end
function run (args)
local usage = require("program.firehose.README_inc")
local header = require("program.firehose.firehose_h_inc")
local example = require("program.firehose.example_inc")
local opt = {}
local time = nil
local pciaddresses = {}
local ring_size = 2048
function opt.h (arg) print(usage) main.exit(0) end
function opt.H (arg) print(header) main.exit(0) end
function opt.e (arg) print(example) main.exit(0) end
function opt.t (arg)
time = tonumber(arg)
if type(time) ~= 'number' then fatal("bad time value: " .. arg) end
end
function opt.i (arg)
table.insert(pciaddresses, arg)
end
function opt.r (arg)
ring_size = tonumber(arg)
if type(ring_size) ~= 'number' then fatal("bad ring size: " .. arg) end
if ring_size > 32*1024 then
fatal("ring size too large for hardware: " .. ring_size)
end
if math.log(ring_size)/math.log(2) % 1 ~= 0 then
fatal("ring size is not a power of two: " .. arg)
end
end
args = lib.dogetopt(args, opt, "hHet:i:r:", long_opts)
if #pciaddresses == 0 then
fatal("Usage error: no input sources given (-i). Use --help for usage.")
end
local sofile = args[1]
-- Load shared object
print("Loading shared object: "..sofile)
local ffi = require("ffi")
local C = ffi.C
local so = ffi.load(sofile)
ffi.cdef[[
void firehose_start();
void firehose_stop();
int firehose_callback_v1(const char *pciaddr, char **packets, void *rxring,
int ring_size, int index);
]]
-- Array where we store a function for each NIC that will process the traffic.
local run_functions = {}
for _,pciaddr in ipairs(pciaddresses) do
-- Initialize a device driver
print("Initializing NIC: "..pciaddr)
local pci = require("lib.hardware.pci")
pci.unbind_device_from_linux(pciaddr) -- make kernel/ixgbe release this device
local intel10g = require("apps.intel.intel10g")
-- Maximum buffers to avoid packet drops
intel10g.num_descriptors = ring_size
local nic = intel10g.new_sf({pciaddr=pciaddr})
nic:open()
-- Traffic processing
--
-- We are using a special-purpose receive method designed for fast
-- packet capture:
--
-- Statically allocate all packet buffers.
--
-- Statically initialize the hardware RX descriptor ring to point to
-- the preallocated packets.
--
-- Have the C callback loop directly over the RX ring to process the
-- packets that are ready.
--
-- This means that no work is done to allocate and free buffers or to
-- write new descriptors to the RX ring. This is expected to have
-- extremely low overhead to recieve each packet.
-- Set NIC to "legacy" descriptor format. In this mode the NIC "write
-- back" does not overwrite the address stored in the descriptor and
-- so this can be reused. See 82599 datasheet section 7.1.5.
nic.r.SRRCTL(10 + bit.lshift(1, 28))
-- Array of packet data buffers. This will be passed to C.
local packets = ffi.new("char*[?]", ring_size)
for i = 0, ring_size-1 do
-- Statically allocate a packet and put the address in the array
local p = packet.allocate()
packets[i] = p.data
-- Statically allocate the matching hardware receive descriptor
nic.rxdesc[i].data.address = memory.virtual_to_physical(p.data)
nic.rxdesc[i].data.dd = 0
end
nic.r.RDT(ring_size-1)
local index = 0 -- ring index of next packet
local rxring = nic.rxdesc
local run = function ()
index = so.firehose_callback_v1(pciaddr, packets, rxring, ring_size, index)
nic.r.RDT(index==0 and ring_size or index-1)
end
table.insert(run_functions, run)
end
print("Initializing callback library")
so.firehose_start()
-- Process traffic in infinite loop
print("Processing traffic...")
local deadline = time and (C.get_monotonic_time() + time)
while true do
for i = 1, 10000 do
for i = 1, #run_functions do
-- Run the traffic processing function for each NIC.
run_functions[i]()
end
end
if deadline and (C.get_monotonic_time() > deadline) then
so.firehose_stop()
break
end
end
end
| apache-2.0 |
xopxe/Toribio | tasks/bobot_server.lua | 1 | 4829 | local M = {}
local toribio = require 'toribio'
local devices = toribio.devices
local bobot = nil --require('comms/bobot').bobot
local log = require 'lumen.log'
table.pack=table.pack or function (...)
return {n=select('#',...),...}
end
local function split_words(s)
local words={}
for p in string.gmatch(s, "%S+") do
words[#words+1]=p
end
return words
end
local process = {}
process["INIT"] = function () --to check the new state of hardware on the fly
--server_init()
toribio.init(nil)
return 'ok'
end
process["REFRESH"] = function () --to check the new state of hardware on the fly
bobot.refresh()
return 'ok'
end
process["LIST"] = function ()
local ret,comma = "", ""
for name, _ in pairs(devices) do
ret = ret .. comma .. name
comma=","
end
return ret
end
--[[
process["LISTI"] = function ()
if baseboards then
for _, bb in ipairs(bobot.baseboards) do
local handler_size=bb:get_handler_size()
for i=1, handler_size do
t_handler = bb:get_handler_type(i)
end
end
end
end
--]]
process["OPEN"] = function (parameters)
local d = parameters[2]
local ep1= tonumber(parameters[3])
local ep2= tonumber(parameters[4])
if not d then
log('BOBOTSRV', 'ERROR', "ls:Missing 'device' parameter")
return
end
return "ok"
end
process["DESCRIBE"] = function (parameters)
local d = parameters[2]
local ep1= tonumber(parameters[3])
local ep2= tonumber(parameters[4])
if not d then
log ('BOBOTSRV', 'ERROR', "ls:Missing \"device\" parameter")
return
end
local device = devices[d]
--if not device.api then
-- return "missing driver"
--end
local skip_fields = {remove=true, name=true, register_callback=true, events=true,
task=true, filename=true, module=true, bobot_metadata=true}
local ret = "{"
for fname, fdef in pairs(device) do
if not skip_fields[fname] then
ret = ret .. fname .. "={"
ret = ret .. " parameters={"
local bobot_metadata = ((device.bobot_metadata or {})[fdef] or {
parameters={}, returns={}
})
local meta_parameters = bobot_metadata.parameters
for i,pars in ipairs(meta_parameters) do
ret = ret .. "[" ..i.."]={"
for k, v in pairs(pars) do
ret = ret .."['".. k .."']='"..tostring(v).."',"
end
ret = ret .. "},"
end
ret = ret .. "}, returns={"
local meta_returns = bobot_metadata.returns
for i,rets in ipairs(meta_returns) do
ret = ret .. "[" ..i.."]={"
for k, v in pairs(rets) do
ret = ret .."['".. k .."']='"..tostring(v).."',"
end
ret = ret .. "},"
end
ret = ret .. "}},"
end
end
ret=ret.."}"
return ret
end
process["CALL"] = function (parameters)
local d = parameters[2]
local call = parameters[3]
if not (d and call) then
log ('BOBOTSRV', 'ERROR', "ls:Missing parameters %s %s", d, call)
return
end
local device = devices[d]
local api_call=device[call];
if not api_call then return "missing call" end
local is_open = device.dev.handler or device.dev.name =='pnp'
if not is_open then
device.dev:open(1, 1)
end
--local tini=socket.gettime()
--local ok, ret = pcall (api_call.call, unpack(parameters,4))
--if not ok then print ("Error calling", ret) end
local ret = table.pack(pcall(device.dev.api[call].call, unpack(parameters,4)))
local ok = ret[1]
if ok then
return table.concat(ret, ',', 2)
else
print ("error calling", table.concat(ret, ',', 2))
end
end
process["CLOSEALL"] = function ()
if bobot and bobot.baseboards then
for _, bb in ipairs(bobot.baseboards) do
--this command closes all the open user modules
--it does not have sense with plug and play
bb:force_close_all() --modif andrew
end
end
return "ok"
end
process["BOOTLOADER"] = function ()
if bobot and bobot.baseboards then
for _, bb in ipairs(bobot.baseboards) do
bb:switch_to_bootloader()
end
end
return "ok"
end
process["QUIT"] = function ()
log ('BOBOTSRV', 'INFO', "Requested EXIT...")
os.exit()
return "ok"
end
M.init = function(conf)
local selector = require 'lumen.tasks.selector'
local ip = conf.ip or '127.0.0.1'
local port = conf.port or 2009
local tcprecv = selector.new_tcp_server(ip, port, 'line', function( inskt, line, err)
--print("bobot server:", inskt, line, err or '')
if not line then return end
local words=split_words(line)
local command=words[1]
if not command then
log ('BOBOTSRV', 'ERROR', "bs:Error parsing line %s", line)
else
if not process[command] then
log ('BOBOTSRV', 'ERROR', "bs:Command '%s' not supported:", command)
else
local ret = process[command](words) or ""
if ret then
inskt:send(ret.."\n")
else
log ('BOBOTSRV', 'ERROR', "Error calling '%s'", command)
inskt:send("\n")
end
end
end
return true
end)
end
return M
| mit |
mahdib9/ml | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_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*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
zeus-ff/adminbot | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_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*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
ln-zookeeper/wesnoth | data/ai/micro_ais/cas/ca_hang_out.lua | 2 | 5772 | local H = wesnoth.require "helper"
local AH = wesnoth.require "ai/lua/ai_helper.lua"
local LS = wesnoth.require "location_set"
local MAIUV = wesnoth.require "ai/micro_ais/micro_ai_unit_variables.lua"
local MAISD = wesnoth.require "ai/micro_ais/micro_ai_self_data.lua"
local M = wesnoth.map
local function get_hang_out_units(cfg)
local units = AH.get_units_with_moves {
side = wesnoth.current.side,
{ "and", H.get_child(cfg, "filter") }
}
return units
end
local ca_hang_out = {}
function ca_hang_out:evaluation(cfg, data)
-- Return 0 if the mobilize condition has previously been met
if MAISD.get_mai_self_data(data, cfg.ai_id, "mobilize_units") then
return 0
end
-- Otherwise check if any of the mobilize conditions are now met
local mobilize_condition = H.get_child(cfg, "mobilize_condition")
if (mobilize_condition and wesnoth.eval_conditional(mobilize_condition))
or (cfg.mobilize_on_gold_less_than and (wesnoth.sides[wesnoth.current.side].gold < cfg.mobilize_on_gold_less_than))
then
MAISD.insert_mai_self_data(data, cfg.ai_id, { mobilize_units = true })
-- Need to unmark all units also (all units, with and without moves)
local units = wesnoth.get_units { side = wesnoth.current.side, { "and", H.get_child(cfg, "filter") } }
for _,unit in ipairs(units) do
MAIUV.delete_mai_unit_variables(unit, cfg.ai_id)
end
return 0
end
if get_hang_out_units(cfg)[1] then return cfg.ca_score end
return 0
end
function ca_hang_out:execution(cfg)
local units = get_hang_out_units(cfg)
-- Get the locations close to which the units should hang out
-- cfg.filter_location defaults to the location of the side leader(s)
local filter_location = H.get_child(cfg, "filter_location") or {
{ "filter", { side = wesnoth.current.side, canrecruit = "yes" } }
}
local width, height = wesnoth.get_map_size()
local locs = wesnoth.get_locations {
x = '1-' .. width,
y = '1-' .. height,
{ "and", filter_location }
}
-- Get map of locations to be avoided.
-- Use [micro_ai][avoid] tag with priority over [ai][avoid].
-- If neither is given, default to all castle terrain.
local avoid_tag = H.get_child(cfg, "avoid")
local avoid_map
if avoid_tag then
avoid_map = LS.of_pairs(wesnoth.get_locations(avoid_tag))
else
local ai_tag = H.get_child(wesnoth.sides[wesnoth.current.side].__cfg, 'ai')
for aspect in H.child_range(ai_tag, 'aspect') do
if (aspect.id == 'avoid') then
local facet = H.get_child(aspect, 'facet')
if facet or aspect.name ~= "composite_aspect" then
-- If there's a [facet] child, it's set as a composite aspect,
-- with at least one facet.
-- But it might not be a composite aspect; it could be
-- a Lua aspect or a standard aspect.
avoid_map = LS.of_pairs(ai.aspects.avoid)
break
end
end
end
end
if avoid_map == nil then
avoid_map = LS.of_pairs(wesnoth.get_locations { terrain = 'C*,C*^*,*^C*' })
end
local max_rating, best_hex, best_unit = -9e99
for _,unit in ipairs(units) do
-- Only consider units that have not been marked yet
if (not MAIUV.get_mai_unit_variables(unit, cfg.ai_id, "moved")) then
local max_rating_unit, best_hex_unit = -9e99
-- Check out all unoccupied hexes the unit can reach
local reach_map = AH.get_reachable_unocc(unit)
reach_map:iter( function(x, y, v)
if (not avoid_map:get(x, y)) then
for _,loc in ipairs(locs) do
-- Main rating is the distance from any of the goal hexes
local rating = -M.distance_between(x, y, loc[1], loc[2])
-- Fastest unit moves first
rating = rating + unit.max_moves / 100.
-- Minor penalty for distance from current position of unit
-- so that there's not too much shuffling around
local rating = rating - M.distance_between(x, y, unit.x, unit.y) / 1000.
if (rating > max_rating_unit) then
max_rating_unit = rating
best_hex_unit = { x, y }
end
end
end
end)
-- Only consider a unit if the best hex found for it is not its current location
if best_hex_unit and ((best_hex_unit[1] ~= unit.x) or (best_hex_unit[2] ~= unit.y)) then
if (max_rating_unit > max_rating) then
max_rating = max_rating_unit
best_hex, best_unit = best_hex_unit, unit
end
end
end
end
-- If no valid locations/units were found or all units are in their
-- respective best locations already, we take moves away from all units
if (not best_unit) then
for _,unit in ipairs(units) do
AH.checked_stopunit_moves(ai, unit)
-- Also remove the markers
if unit and unit.valid then MAIUV.delete_mai_unit_variables(unit, cfg.ai_id) end
end
else
-- Otherwise move unit (partial move only) and mark as having been used
AH.checked_move(ai, best_unit, best_hex[1], best_hex[2])
if best_unit and best_unit.valid then
MAIUV.set_mai_unit_variables(best_unit, cfg.ai_id, { moved = true })
end
end
end
return ca_hang_out
| gpl-2.0 |
PlexChat/premake-core | src/_premake_main.lua | 5 | 7609 | --
-- _premake_main.lua
-- Script-side entry point for the main program logic.
-- Copyright (c) 2002-2015 Jason Perkins and the Premake project
--
local shorthelp = "Type 'premake5 --help' for help"
local versionhelp = "premake5 (Premake Build Script Generator) %s"
-- Load the collection of core scripts, required for everything else to work
local modules = dofile("_modules.lua")
local manifest = dofile("_manifest.lua")
for i = 1, #manifest do
dofile(manifest[i])
end
-- Create namespaces for myself
local p = premake
p.main = {}
local m = p.main
-- Keep a table of modules that have been preloaded, and their associated
-- "should load" test functions.
m._preloaded = {}
---
-- Add a new module loader that knows how to use the Premake paths like
-- PREMAKE_PATH and the --scripts option, and follows the module/module.lua
-- naming convention.
---
function m.installModuleLoader()
table.insert(package.loaders, 2, m.moduleLoader)
end
function m.moduleLoader(name)
local dir = path.getdirectory(name)
local base = path.getname(name)
if dir ~= "." then
dir = dir .. "/" .. base
else
dir = base
end
local full = dir .. "/" .. base .. ".lua"
-- list of paths where to look for the module
local paths = {
"modules/" .. full,
full,
name .. ".lua"
}
-- try to locate the module
for _, p in ipairs(paths) do
local file = os.locate(p)
if file then
local chunk, err = loadfile(file)
if chunk then
return chunk
end
if err then
return "\n\tload error " .. err
end
end
end
-- didn't find the module in supported paths, try the embedded scripts
for _, p in ipairs(paths) do
local chunk, err = loadfile("$/" .. p)
if chunk then
return chunk
end
end
end
---
-- Prepare the script environment; anything that should be done
-- before the system script gets a chance to run.
---
function m.prepareEnvironment()
math.randomseed(os.time())
_PREMAKE_DIR = path.getdirectory(_PREMAKE_COMMAND)
premake.path = premake.path .. ";" .. _PREMAKE_DIR .. ";" .. _MAIN_SCRIPT_DIR
end
---
-- Load the required core modules that are shipped as part of Premake and
-- expected to be present at startup. If a _preload.lua script is present,
-- that script is run and the return value (a "should load" test) is cached
-- to be called after baking is complete. Otherwise the module's main script
-- is run immediately.
---
function m.preloadModules()
for i = 1, #modules do
local name = modules[i]
local preloader = name .. "/_preload.lua"
preloader = os.locate("modules/" .. preloader) or os.locate(preloader)
if preloader then
m._preloaded[name] = include(preloader)
if not m._preloaded[name] then
p.warn("module '%s' should return function from _preload.lua", name)
end
else
require(name)
end
end
end
---
-- Look for and run the system-wide configuration script; make sure any
-- configuration scoping gets cleared before continuing.
---
function m.runSystemScript()
dofileopt(_OPTIONS["systemscript"] or { "premake5-system.lua", "premake-system.lua" })
filter {}
end
---
-- Look for a user project script, and set up the related global
-- variables if I can find one.
---
function m.locateUserScript()
local defaults = { "premake5.lua", "premake4.lua" }
for i = 1, #defaults do
if os.isfile(defaults[i]) then
_MAIN_SCRIPT = defaults[i]
break
end
end
if not _MAIN_SCRIPT then
_MAIN_SCRIPT = defaults[1]
end
if _OPTIONS.file then
_MAIN_SCRIPT = _OPTIONS.file
end
_MAIN_SCRIPT = path.getabsolute(_MAIN_SCRIPT)
_MAIN_SCRIPT_DIR = path.getdirectory(_MAIN_SCRIPT)
end
---
-- Set the action to be performed from the command line arguments.
---
function m.prepareAction()
-- The "next-gen" actions have now replaced their deprecated counterparts.
-- Provide a warning for a little while before I remove them entirely.
if _ACTION and _ACTION:endswith("ng") then
premake.warnOnce(_ACTION, "'%s' has been deprecated; use '%s' instead", _ACTION, _ACTION:sub(1, -3))
end
premake.action.set(_ACTION)
end
---
-- If there is a project script available, run it to get the
-- project information, available options and actions, etc.
---
function m.runUserScript()
if os.isfile(_MAIN_SCRIPT) then
dofile(_MAIN_SCRIPT)
end
end
---
-- Run the interactive prompt, if requested.
---
function m.checkInteractive()
if _OPTIONS.interactive then
debug.prompt()
end
end
---
-- Validate and process the command line options and arguments.
---
function m.processCommandLine()
-- Process special options
if (_OPTIONS["version"]) then
printf(versionhelp, _PREMAKE_VERSION)
os.exit(0)
end
if (_OPTIONS["help"]) then
premake.showhelp()
os.exit(1)
end
-- Validate the command-line arguments. This has to happen after the
-- script has run to allow for project-specific options
ok, err = premake.option.validate(_OPTIONS)
if not ok then
print("Error: " .. err)
os.exit(1)
end
-- If no further action is possible, show a short help message
if not _OPTIONS.interactive then
if not _ACTION then
print(shorthelp)
os.exit(1)
end
local action = premake.action.current()
if not action then
print("Error: no such action '" .. _ACTION .. "'")
os.exit(1)
end
if p.action.isConfigurable() and not os.isfile(_MAIN_SCRIPT) then
print(string.format("No Premake script (%s) found!", path.getname(_MAIN_SCRIPT)))
os.exit(1)
end
end
end
---
-- Override point, for logic that should run before baking.
---
function m.preBake()
if p.action.isConfigurable() then
print("Building configurations...")
end
end
---
-- "Bake" the project information, preparing it for use by the action.
---
function m.bake()
if p.action.isConfigurable() then
premake.oven.bake()
end
end
---
-- Override point, for logic that should run after baking but before
-- the configurations are validated.
---
function m.postBake()
local function shouldLoad(func)
for wks in p.global.eachWorkspace() do
for prj in p.workspace.eachproject(wks) do
for cfg in p.project.eachconfig(prj) do
if func(cfg) then
return true
end
end
end
end
end
-- any modules need to load to support this project?
for module, func in pairs(m._preloaded) do
if not package.loaded[module] and shouldLoad(func) then
require(module)
end
end
end
---
-- Sanity check the current project setup.
---
function m.validate()
if p.action.isConfigurable() then
p.container.validate(p.api.rootContainer())
end
end
---
-- Override point, for logic that should run after validation and
-- before the action takes control.
---
function m.preAction()
local action = premake.action.current()
printf("Running action '%s'...", action.trigger)
end
---
-- Hand over control to the action.
---
function m.callAction()
local action = premake.action.current()
premake.action.call(action.trigger)
end
---
-- Processing is complete.
---
function m.postAction()
if p.action.isConfigurable() then
print("Done.")
end
end
--
-- Script-side program entry point.
--
m.elements = {
m.installModuleLoader,
m.locateUserScript,
m.prepareEnvironment,
m.preloadModules,
m.runSystemScript,
m.prepareAction,
m.runUserScript,
m.checkInteractive,
m.processCommandLine,
m.preBake,
m.bake,
m.postBake,
m.validate,
m.preAction,
m.callAction,
m.postAction,
}
function _premake_main()
p.callArray(m.elements)
return 0
end
| bsd-3-clause |
chris5560/openwrt-luci | modules/luci-mod-admin-mini/luasrc/model/cbi/mini/luci.lua | 76 | 1122 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
require "luci.config"
local fs = require "nixio.fs"
m = Map("luci", translate("Web <abbr title=\"User Interface\">UI</abbr>"), translate("Here you can customize the settings and the functionality of <abbr title=\"Lua Configuration Interface\">LuCI</abbr>."))
-- force reload of global luci config namespace to reflect the changes
function m.commit_handler(self)
package.loaded["luci.config"] = nil
require "luci.config"
end
c = m:section(NamedSection, "main", "core", translate("General"))
l = c:option(ListValue, "lang", translate("Language"))
l:value("auto")
local i18ndir = luci.i18n.i18ndir .. "base."
for k, v in luci.util.kspairs(luci.config.languages) do
local file = i18ndir .. k:gsub("_", "-")
if k:sub(1, 1) ~= "." and fs.access(file .. ".lmo") then
l:value(k, v)
end
end
t = c:option(ListValue, "mediaurlbase", translate("Design"))
for k, v in pairs(luci.config.themes) do
if k:sub(1, 1) ~= "." then
t:value(v, k)
end
end
return m
| apache-2.0 |
xdemolish/darkstar | scripts/globals/items/plate_of_boiled_barnacles_+1.lua | 36 | 1282 | -----------------------------------------
-- ID: 5981
-- Item: Plate of Boiled Barnacles +1
-- Food Effect: 60 Mins, All Races
-----------------------------------------
-- Charisma -2
-- Defense % 26 Cap 135
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5981);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_CHR, -2);
target:addMod(MOD_FOOD_DEFP, 26);
target:addMod(MOD_FOOD_DEF_CAP, 135);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_CHR, -2);
target:delMod(MOD_FOOD_DEFP, 26);
target:delMod(MOD_FOOD_DEF_CAP, 135);
end;
| gpl-3.0 |
xdemolish/darkstar | scripts/zones/Valkurm_Dunes/npcs/Medicine_Axe.lua | 17 | 1864 | -----------------------------------
-- Area: Valkurm Dunes
-- NPC: Medicine Axe
-- Type: Outpost Vendor
-- @pos 144 -7 104 103
-----------------------------------
package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
require("scripts/zones/Valkurm_Dunes/TextIDs");
local region = ZULKHEIM;
local csid = 0x7ff4;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local owner = GetRegionOwner(region);
local arg1 = getArg1(owner,player);
if(owner == player:getNation()) then
nation = 1;
elseif(arg1 < 1792) then
nation = 2;
else
nation = 0;
end
player:startEvent(csid,nation,OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP(),0,0,0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("OPTION: %u",option);
player:updateEvent(player:getGil(),OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP());
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if(option == 1) then
ShowOPVendorShop(player);
elseif(option == 2) then
if (player:delGil(OP_TeleFee(player,region))) then
toHomeNation(player);
end
elseif(option == 6) then
player:delCP(OP_TeleFee(player,region));
toHomeNation(player);
end
end; | gpl-3.0 |
xdemolish/darkstar | scripts/zones/Lower_Jeuno/npcs/Chimh_Dlesbah.lua | 38 | 1042 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Chimh Dlesbah
-- Type: Event Scene Replayer
-- @zone: 245
-- @pos -71.995 -1 -115.882
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x2770);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
xdemolish/darkstar | scripts/zones/The_Celestial_Nexus/Zone.lua | 32 | 1663 | -----------------------------------
--
-- Zone: The_Celestial_Nexus (181)
--
-----------------------------------
package.loaded["scripts/zones/The_Celestial_Nexus/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/The_Celestial_Nexus/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-697.114,-6.656,-32.351,0);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
lukego/snabb | src/program/packetblaster/packetblaster.lua | 5 | 3467 | module(..., package.seeall)
local engine = require("core.app")
local config = require("core.config")
local timer = require("core.timer")
local pci = require("lib.hardware.pci")
local intel10g = require("apps.intel.intel10g")
local intel_app = require("apps.intel.intel_app")
local basic_apps = require("apps.basic.basic_apps")
local main = require("core.main")
local PcapReader= require("apps.pcap.pcap").PcapReader
local Synth = require("apps.test.synth").Synth
local LoadGen = require("apps.intel.loadgen").LoadGen
local lib = require("core.lib")
local ffi = require("ffi")
local C = ffi.C
local usage = require("program.packetblaster.README_inc")
local usage_replay = require("program.packetblaster.replay.README_inc")
local usage_synth = require("program.packetblaster.synth.README_inc")
local long_opts = {
duration = "D",
help = "h",
src = "s",
dst = "d",
sizes = "S"
}
function run (args)
local opt = {}
local mode = table.remove(args, 1)
local duration
local c = config.new()
function opt.D (arg)
duration = assert(tonumber(arg), "duration is not a number!")
end
function opt.h (arg)
if mode == 'replay' then print(usage_replay)
elseif mode == 'synth' then print(usage_synth)
else print(usage) end
main.exit(1)
end
if mode == 'replay' and #args > 1 then
args = lib.dogetopt(args, opt, "hD:", long_opts)
local filename = table.remove(args, 1)
config.app(c, "pcap", PcapReader, filename)
config.app(c, "loop", basic_apps.Repeater)
config.app(c, "source", basic_apps.Tee)
config.link(c, "pcap.output -> loop.input")
config.link(c, "loop.output -> source.input")
elseif mode == 'synth' and #args >= 1 then
local source
local destination
local sizes
function opt.s (arg) source = arg end
function opt.d (arg) destination = arg end
function opt.S (arg)
sizes = {}
for size in string.gmatch(arg, "%d+") do
sizes[#sizes+1] = tonumber(size)
end
end
args = lib.dogetopt(args, opt, "hD:s:d:S:", long_opts)
config.app(c, "source", Synth, { sizes = sizes,
src = source,
dst = destination })
else
opt.h()
end
local patterns = args
local nics = 0
pci.scan_devices()
for _,device in ipairs(pci.devices) do
if is_device_suitable(device, patterns) then
nics = nics + 1
local name = "nic"..nics
config.app(c, name, LoadGen, device.pciaddress)
config.link(c, "source."..tostring(nics).."->"..name..".input")
end
end
assert(nics > 0, "<PCI> matches no suitable devices.")
engine.busywait = true
intel10g.num_descriptors = 32*1024
engine.configure(c)
local fn = function ()
print("Transmissions (last 1 sec):")
engine.report_apps()
end
local t = timer.new("report", fn, 1e9, 'repeating')
timer.activate(t)
if duration then engine.main({duration=duration})
else engine.main() end
end
function is_device_suitable (pcidev, patterns)
if not pcidev.usable or pcidev.driver ~= 'apps.intel.intel_app' then
return false
end
if #patterns == 0 then
return true
end
for _, pattern in ipairs(patterns) do
if pci.qualified(pcidev.pciaddress):gmatch(pattern)() then
return true
end
end
end
| apache-2.0 |
xdemolish/darkstar | scripts/zones/Metalworks/npcs/Naji.lua | 17 | 4890 | -----------------------------------
-- Area: Metalworks
-- NPC: Naji
-- Involved in Quests: The doorman (finish), Riding on the Clouds
-- Involved in Mission: Bastok 6-2
-- @pos 64 -14 -4 237
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 6) then
if(trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_2",0);
player:tradeComplete();
player:addKeyItem(SMILING_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:hasKeyItem(YASINS_SWORD)) then -- The Doorman, WAR AF1
player:startEvent(0x02ee);
elseif(player:getCurrentMission(BASTOK) ~= 255) then
local currentMission = player:getCurrentMission(BASTOK);
if(currentMission == THE_ZERUHN_REPORT and player:hasKeyItem(ZERUHN_REPORT)) then
if(player:seenKeyItem(ZERUHN_REPORT)) then
player:startEvent(0x02C6,0);
else
player:startEvent(0x02C6,1);
end
elseif(currentMission == THE_CRYSTAL_LINE and player:hasKeyItem(C_L_REPORTS)) then
player:startEvent(0x02c7);
elseif(currentMission == THE_EMISSARY and player:hasKeyItem(KINDRED_REPORT)) then
player:startEvent(0x02ca);
elseif(currentMission == THE_EMISSARY) then
if(player:hasKeyItem(LETTER_TO_THE_CONSULS_BASTOK) == false and player:getVar("MissionStatus") == 0) then
player:startEvent(0x02c9);
else
player:showText(npc,GOOD_LUCK);
end
elseif(player:hasKeyItem(MESSAGE_TO_JEUNO_BASTOK) and player:getVar("MissionStatus") == 0) then
player:startEvent(0x02d0);
elseif(currentMission == DARKNESS_RISING and player:getVar("MissionStatus") == 1) then
player:startEvent(0x02d1);
elseif(player:hasKeyItem(BURNT_SEAL)) then
player:startEvent(0x02d2);
elseif(currentMission == THE_PIRATE_S_COVE and player:getVar("MissionStatus") == 0) then
player:startEvent(0x02f9);
elseif(currentMission == THE_PIRATE_S_COVE and player:getVar("MissionStatus") == 3) then
player:startEvent(0x02fa);
else
player:startEvent(0x02bc);
end
elseif(player:hasKeyItem(YASINS_SWORD)) then -- The Doorman
player:startEvent(0x02ee);
else
player:startEvent(0x02bc);
end
end;
-- 0x02c6 0x02c7 0x02bc 0x02c9 0x02ca 0x02cb 0x02cd 0x02d0 0x02d1 0x02ee 0x03f0 0x03f1 0x02f9
-- 0x02fa 0x030e 0x0325 0x034d 0x036d 0x03aa 0x03ab 0x03ac 0x03ad 0x03ae 0x03cb 0x03c9 0x03ca
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x02ee) then
if(player:getFreeSlotsCount(0) >= 1) then
player:addItem(16678);
player:messageSpecial(ITEM_OBTAINED, 16678); -- Razor Axe
player:delKeyItem(YASINS_SWORD);
player:setVar("theDoormanCS",0);
player:addFame(BASTOK,BAS_FAME*30);
player:completeQuest(BASTOK,THE_DOORMAN);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 16678); -- Razor Axe
end
elseif(csid == 0x02C6) then
player:delKeyItem(ZERUHN_REPORT);
player:completeMission(BASTOK,THE_ZERUHN_REPORT);
elseif(csid == 0x02c9) then
player:addKeyItem(LETTER_TO_THE_CONSULS_BASTOK);
player:messageSpecial(KEYITEM_OBTAINED,LETTER_TO_THE_CONSULS_BASTOK);
player:setVar("MissionStatus",1);
elseif(csid == 0x02d0 and option == 0 or csid == 0x02d1) then
player:delKeyItem(MESSAGE_TO_JEUNO_BASTOK);
player:addKeyItem(NEW_FEIYIN_SEAL);
player:messageSpecial(KEYITEM_OBTAINED,NEW_FEIYIN_SEAL);
player:setVar("MissionStatus",10);
elseif(csid == 0x02d0 and option == 1) then
player:delKeyItem(MESSAGE_TO_JEUNO_BASTOK);
player:setVar("MissionStatus",1);
elseif(csid == 0x02f9) then
player:setVar("MissionStatus",1);
elseif(csid == 0x02ca or csid == 0x02d2 or csid == 0x02fa) then
finishMissionTimeline(player,1,csid,option);
end
end; | gpl-3.0 |
kissthink/OpenRA | mods/ra/maps/soviet-04a/main.lua | 15 | 4321 |
RunInitialActivities = function()
Harvester.FindResources()
IdlingUnits()
Trigger.AfterDelay(10, function()
BringPatrol1()
BringPatrol2()
BuildBase()
end)
Utils.Do(Map.NamedActors, function(actor)
if actor.Owner == Greece and actor.HasProperty("StartBuildingRepairs") then
Trigger.OnDamaged(actor, function(building)
if building.Owner == Greece and building.Health < 3/4 * building.MaxHealth then
building.StartBuildingRepairs()
end
end)
end
end)
Reinforcements.Reinforce(player, SovietMCV, SovietStartToBasePath, 0, function(mcv)
mcv.Move(StartCamPoint.Location)
end)
Media.PlaySpeechNotification(player, "ReinforcementsArrived")
Trigger.OnKilled(Barr, function(building)
BaseBuildings[2][4] = false
end)
Trigger.OnKilled(Proc, function(building)
BaseBuildings[3][4] = false
end)
Trigger.OnKilled(Weap, function(building)
BaseBuildings[4][4] = false
end)
Trigger.OnEnteredFootprint(VillageCamArea, function(actor, id)
if actor.Owner == player then
local camera = Actor.Create("camera", true, { Owner = player, Location = VillagePoint.Location })
Trigger.RemoveFootprintTrigger(id)
Trigger.OnAllKilled(Village, function()
camera.Destroy()
end)
end
end)
Trigger.OnAnyKilled(Civs, function()
Trigger.ClearAll(civ1)
Trigger.ClearAll(civ2)
Trigger.ClearAll(civ3)
local units = Reinforcements.Reinforce(Greece, Avengers, { SWRoadPoint.Location }, 0)
Utils.Do(units, function(unit)
unit.Hunt()
end)
end)
Runner1.Move(CrossroadsEastPoint.Location)
Runner2.Move(InVillagePoint.Location)
Tank5.Move(V2MovePoint.Location)
Trigger.AfterDelay(DateTime.Seconds(2), function()
Tank1.Stop()
Tank2.Stop()
Tank3.Stop()
Tank4.Stop()
Tank5.Stop()
Trigger.AfterDelay(1, function()
Tank1.Move(SovietBaseEntryPointNE.Location)
Tank2.Move(SovietBaseEntryPointW.Location)
Tank3.Move(SovietBaseEntryPointNE.Location)
Tank4.Move(SovietBaseEntryPointW.Location)
Tank5.Move(V2MovePoint.Location)
end)
end)
Trigger.AfterDelay(DateTime.Minutes(1), ProduceInfantry)
Trigger.AfterDelay(DateTime.Minutes(2), ProduceArmor)
if Map.Difficulty == "Hard" or Map.Difficulty == "Medium" then
Trigger.AfterDelay(DateTime.Seconds(15), ReinfInf)
end
Trigger.AfterDelay(DateTime.Minutes(1), ReinfInf)
Trigger.AfterDelay(DateTime.Minutes(3), ReinfInf)
Trigger.AfterDelay(DateTime.Minutes(2), ReinfArmor)
end
Tick = function()
if Greece.HasNoRequiredUnits() then
player.MarkCompletedObjective(KillAll)
player.MarkCompletedObjective(KillRadar)
end
if player.HasNoRequiredUnits() then
Greece.MarkCompletedObjective(BeatUSSR)
end
if Greece.Resources >= Greece.ResourceCapacity * 0.75 then
Greece.Cash = Greece.Cash + Greece.Resources - Greece.ResourceCapacity * 0.25
Greece.Resources = Greece.ResourceCapacity * 0.25
end
if RCheck then
RCheck = false
if Map.Difficulty == "Hard" then
Trigger.AfterDelay(DateTime.Seconds(150), ReinfArmor)
elseif Map.Difficulty == "Medium" then
Trigger.AfterDelay(DateTime.Minutes(5), ReinfArmor)
else
Trigger.AfterDelay(DateTime.Minutes(8), ReinfArmor)
end
end
end
WorldLoaded = function()
player = Player.GetPlayer("USSR")
Greece = Player.GetPlayer("Greece")
RunInitialActivities()
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
KillAll = player.AddPrimaryObjective("Defeat the Allied forces.")
BeatUSSR = Greece.AddPrimaryObjective("Defeat the Soviet forces.")
KillRadar = player.AddSecondaryObjective("Destroy Allied Radar Dome to stop enemy\nreinforcements.")
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "Lose")
end)
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "Win")
end)
Trigger.OnKilled(Radar, function()
player.MarkCompletedObjective(KillRadar)
Media.PlaySpeechNotification(player, "ObjectiveMet")
end)
Camera.Position = StartCamPoint.CenterPosition
end
| gpl-3.0 |
blacknewn/bl | plugins/Rank.lua | 1 | 1173 | --Begin Rank.lua By @MahDiRoO
do
local function run(msg, matches)
if matches[1]=="مقام من" and is_sudo(msg) or matches[1]=="me" and is_sudo(msg) or matches[1]=="Me" and is_sudo(msg) then
return "❤️شما صاحب ربات و سودو میباشید❤️"
elseif matches[1]=="مقام من" and is_admin(msg) or matches[1]=="me" and is_admin(msg) or matches[1]=="Me" and is_admin(msg) then
return "😎شما ادمین ربات و یک مقام پایین تر ازسودو میباشید😎"
elseif matches[1]=="مقام من" and is_owner(msg) or matches[1]=="me" and is_owner(msg) or matches[1]=="Me" and is_owner(msg) then
return "😀شما سازنده و صاحب گروه میباشید😀"
elseif matches[1]=="مقام من" and is_mod(msg) or matches[1]=="me" and is_mod(msg) or matches[1]=="ME" and is_mod(msg) then
return "👌😐شما کمک مدیراین گروه میباشید👌😐"
else
return "😫شما هیچ مقامی در ربات ندارید😫"
end
end
return {
patterns = {
"^(مقام من)$",
"^[!/#]([Mm]e)$",
"^([Mm]e)$",
},
run = run
}
end
--End Rank.lua-- | gpl-3.0 |
yangchaogit/ABTestingGateway | lib/abtesting/adapter/runtime.lua | 22 | 3599 | ---
-- @classmod abtesting.adapter.runtime
-- @release 0.0.1
local modulename = "abtestingAdapterRuntime"
local _M = {}
local metatable = {__index = _M}
_M._VERSION = "0.0.1"
local ERRORINFO = require('abtesting.error.errcode').info
---
-- @field fields
-- @warning this is a conf, may other file later
local fields= {}
fields.divModulename = 'divModulename'
fields.divDataKey = 'divDataKey'
fields.userInfoModulename = 'userInfoModulename'
local separator = ':'
---
-- runtimeInfoIO new function
-- @param database opened redis
-- @param baseLibrary a library(prefix of redis key) of runtime info
-- @return runtimeInfoIO object
_M.new = function(self, database, baseLibrary)
if not database then
error{ERRORINFO.PARAMETER_NONE, 'need a object of redis'}
end if not baseLibrary then
error{ERRORINFO.PARAMETER_NONE, 'need a library of runtime info'}
end
self.database = database
self.baseLibrary = baseLibrary
return setmetatable(self, metatable)
end
---
-- set runtime info(diversion modulename and diversion metadata key)
-- @param domain is a domain name to search runtime info
-- @param ... now is diversion modulename and diversion data key
-- @return if returned, the return value always SUCCESS
_M.set = function(self, domain, ...)
local info = {...}
local divModulename = info[1]
local divDataKey = info[2]
local userInfoModulename = info[3]
local database = self.database
local divModulenamekey = table.concat({self.baseLibrary, domain, fields.divModulename}, separator)
local divDataKeyOfKey = table.concat({self.baseLibrary, domain, fields.divDataKey}, separator)
local userInfoModulenameKey = table.concat({self.baseLibrary, domain, fields.userInfoModulename}, separator)
local ok, err = database:mset(divModulenamekey, divModulename,
divDataKeyOfKey, divDataKey,
userInfoModulenameKey, userInfoModulename)
if not ok then error{ERRORINFO.REDIS_ERROR, err} end
return ERRORINFO.SUCCESS
end
---
-- delete runtime info(diversion modulename and diversion metadata key)
-- @param domain a domain of delete
-- @return if returned, the return value always SUCCESS
_M.del = function(self, domain)
local database = self.database
local divModulenamekey = table.concat({self.baseLibrary, domain, fields.divModulename}, separator)
local divDataKeyOfKey = table.concat({self.baseLibrary, domain, fields.divDataKey}, separator)
local userInfoModulenameKey = table.concat({self.baseLibrary, domain, fields.userInfoModulename}, separator)
local ok, err = database:del(divModulenamekey, divDataKeyOfKey, userInfoModulenameKey)
if not ok then error{ERRORINFO.REDIS_ERROR, err} end
return ERRORINFO.SUCCESS
end
---
-- get runtime info(diversion modulename and diversion metadata key)
-- @param domain is a domain name to search runtime info
-- @return a table of diversion modulename and diversion metadata key
_M.get = function(self, domain)
local database = self.database
local divModulenameKey = table.concat({self.baseLibrary, domain, fields.divModulename}, separator)
local divDataKeyOfKey = table.concat({self.baseLibrary, domain, fields.divDataKey}, separator)
local userInfoModulenameKey = table.concat({self.baseLibrary, domain, fields.userInfoModulename}, separator)
local response, err = database:mget(divModulenameKey, divDataKeyOfKey, userInfoModulenameKey)
if not response then
error{ERRORINFO.REDIS_ERROR, err}
end
return response
end
return _M
| mit |
lighter-cd/premake4-mobile | tests/base/test_api.lua | 54 | 11362 | --
-- tests/base/test_api.lua
-- Automated test suite for the project API support functions.
-- Copyright (c) 2008-2011 Jason Perkins and the Premake project
--
T.api = { }
local suite = T.api
local sln
function suite.setup()
sln = solution "MySolution"
end
--
-- premake.getobject() tests
--
function suite.getobject_RaisesError_OnNoContainer()
premake.CurrentContainer = nil
c, err = premake.getobject("container")
test.istrue(c == nil)
test.isequal("no active solution or project", err)
end
function suite.getobject_RaisesError_OnNoActiveSolution()
premake.CurrentContainer = { }
c, err = premake.getobject("solution")
test.istrue(c == nil)
test.isequal("no active solution", err)
end
function suite.getobject_RaisesError_OnNoActiveConfig()
premake.CurrentConfiguration = nil
c, err = premake.getobject("config")
test.istrue(c == nil)
test.isequal("no active solution, project, or configuration", err)
end
--
-- premake.setarray() tests
--
function suite.setarray_Inserts_OnStringValue()
premake.CurrentConfiguration = { }
premake.CurrentConfiguration.myfield = { }
premake.setarray("config", "myfield", "hello")
test.isequal("hello", premake.CurrentConfiguration.myfield[1])
end
function suite.setarray_Inserts_OnTableValue()
premake.CurrentConfiguration = { }
premake.CurrentConfiguration.myfield = { }
premake.setarray("config", "myfield", { "hello", "goodbye" })
test.isequal("hello", premake.CurrentConfiguration.myfield[1])
test.isequal("goodbye", premake.CurrentConfiguration.myfield[2])
end
function suite.setarray_Appends_OnNewValues()
premake.CurrentConfiguration = { }
premake.CurrentConfiguration.myfield = { "hello" }
premake.setarray("config", "myfield", "goodbye")
test.isequal("hello", premake.CurrentConfiguration.myfield[1])
test.isequal("goodbye", premake.CurrentConfiguration.myfield[2])
end
function suite.setarray_FlattensTables()
premake.CurrentConfiguration = { }
premake.CurrentConfiguration.myfield = { }
premake.setarray("config", "myfield", { {"hello"}, {"goodbye"} })
test.isequal("hello", premake.CurrentConfiguration.myfield[1])
test.isequal("goodbye", premake.CurrentConfiguration.myfield[2])
end
function suite.setarray_RaisesError_OnInvalidValue()
premake.CurrentConfiguration = { }
premake.CurrentConfiguration.myfield = { }
ok, err = pcall(function () premake.setarray("config", "myfield", "bad", { "Good", "Better", "Best" }) end)
test.isfalse(ok)
end
function suite.setarray_CorrectsCase_OnConstrainedValue()
premake.CurrentConfiguration = { }
premake.CurrentConfiguration.myfield = { }
premake.setarray("config", "myfield", "better", { "Good", "Better", "Best" })
test.isequal("Better", premake.CurrentConfiguration.myfield[1])
end
--
-- premake.setstring() tests
--
function suite.setstring_Sets_OnNewProperty()
premake.CurrentConfiguration = { }
premake.setstring("config", "myfield", "hello")
test.isequal("hello", premake.CurrentConfiguration.myfield)
end
function suite.setstring_Overwrites_OnExistingProperty()
premake.CurrentConfiguration = { }
premake.CurrentConfiguration.myfield = "hello"
premake.setstring("config", "myfield", "goodbye")
test.isequal("goodbye", premake.CurrentConfiguration.myfield)
end
function suite.setstring_RaisesError_OnInvalidValue()
premake.CurrentConfiguration = { }
ok, err = pcall(function () premake.setstring("config", "myfield", "bad", { "Good", "Better", "Best" }) end)
test.isfalse(ok)
end
function suite.setstring_CorrectsCase_OnConstrainedValue()
premake.CurrentConfiguration = { }
premake.setstring("config", "myfield", "better", { "Good", "Better", "Best" })
test.isequal("Better", premake.CurrentConfiguration.myfield)
end
--
-- premake.setkeyvalue() tests
--
function suite.setkeyvalue_Inserts_OnStringValue()
premake.CurrentConfiguration = { }
premake.setkeyvalue("config", "vpaths", { ["Headers"] = "*.h" })
test.isequal({"*.h"}, premake.CurrentConfiguration.vpaths["Headers"])
end
function suite.setkeyvalue_Inserts_OnTableValue()
premake.CurrentConfiguration = { }
premake.setkeyvalue("config", "vpaths", { ["Headers"] = {"*.h","*.hpp"} })
test.isequal({"*.h","*.hpp"}, premake.CurrentConfiguration.vpaths["Headers"])
end
function suite.setkeyvalue_Inserts_OnEmptyStringKey()
premake.CurrentConfiguration = { }
premake.setkeyvalue("config", "vpaths", { [""] = "src" })
test.isequal({"src"}, premake.CurrentConfiguration.vpaths[""])
end
function suite.setkeyvalue_RaisesError_OnString()
premake.CurrentConfiguration = { }
ok, err = pcall(function () premake.setkeyvalue("config", "vpaths", "Headers") end)
test.isfalse(ok)
end
function suite.setkeyvalue_InsertsString_IntoExistingKey()
premake.CurrentConfiguration = { }
premake.setkeyvalue("config", "vpaths", { ["Headers"] = "*.h" })
premake.setkeyvalue("config", "vpaths", { ["Headers"] = "*.hpp" })
test.isequal({"*.h","*.hpp"}, premake.CurrentConfiguration.vpaths["Headers"])
end
function suite.setkeyvalue_InsertsTable_IntoExistingKey()
premake.CurrentConfiguration = { }
premake.setkeyvalue("config", "vpaths", { ["Headers"] = {"*.h"} })
premake.setkeyvalue("config", "vpaths", { ["Headers"] = {"*.hpp"} })
test.isequal({"*.h","*.hpp"}, premake.CurrentConfiguration.vpaths["Headers"])
end
--
-- accessor tests
--
function suite.accessor_CanRetrieveString()
sln.blocks[1].kind = "ConsoleApp"
test.isequal("ConsoleApp", kind())
end
--
-- solution() tests
--
function suite.solution_SetsCurrentContainer_OnName()
test.istrue(sln == premake.CurrentContainer)
end
function suite.solution_CreatesNewObject_OnNewName()
solution "MySolution2"
test.isfalse(sln == premake.CurrentContainer)
end
function suite.solution_ReturnsPrevious_OnExistingName()
solution "MySolution2"
local sln2 = solution "MySolution"
test.istrue(sln == sln2)
end
function suite.solution_SetsCurrentContainer_OnExistingName()
solution "MySolution2"
solution "MySolution"
test.istrue(sln == premake.CurrentContainer)
end
function suite.solution_ReturnsNil_OnNoActiveSolutionAndNoName()
premake.CurrentContainer = nil
test.isnil(solution())
end
function suite.solution_ReturnsCurrentSolution_OnActiveSolutionAndNoName()
test.istrue(sln == solution())
end
function suite.solution_ReturnsCurrentSolution_OnActiveProjectAndNoName()
project "MyProject"
test.istrue(sln == solution())
end
function suite.solution_LeavesProjectActive_OnActiveProjectAndNoName()
local prj = project "MyProject"
solution()
test.istrue(prj == premake.CurrentContainer)
end
function suite.solution_LeavesConfigActive_OnActiveSolutionAndNoName()
local cfg = configuration "windows"
solution()
test.istrue(cfg == premake.CurrentConfiguration)
end
function suite.solution_LeavesConfigActive_OnActiveProjectAndNoName()
project "MyProject"
local cfg = configuration "windows"
solution()
test.istrue(cfg == premake.CurrentConfiguration)
end
function suite.solution_SetsName_OnNewName()
test.isequal("MySolution", sln.name)
end
function suite.solution_AddsNewConfig_OnNewName()
test.istrue(#sln.blocks == 1)
end
function suite.solution_AddsNewConfig_OnName()
local num = #sln.blocks
solution "MySolution"
test.istrue(#sln.blocks == num + 1)
end
--
-- configuration() tests
--
function suite.configuration_RaisesError_OnNoContainer()
premake.CurrentContainer = nil
local fn = function() configuration{"Debug"} end
ok, err = pcall(fn)
test.isfalse(ok)
end
function suite.configuration_SetsCurrentConfiguration_OnKeywords()
local cfg = configuration {"Debug"}
test.istrue(premake.CurrentConfiguration == cfg)
end
function suite.configuration_AddsToContainer_OnKeywords()
local cfg = configuration {"Debug"}
test.istrue(cfg == sln.blocks[#sln.blocks])
end
function suite.configuration_ReturnsCurrent_OnNoKeywords()
local cfg = configuration()
test.istrue(cfg == sln.blocks[1])
end
function suite.configuration_SetsTerms()
local cfg = configuration {"aa", "bb"}
test.isequal({"aa", "bb"}, cfg.terms)
end
function suite.configuration_SetsTermsWithNestedTables()
local cfg = configuration { {"aa", "bb"}, "cc" }
test.isequal({"aa", "bb", "cc"}, cfg.terms)
end
function suite.configuration_CanReuseTerms()
local cfg = configuration { "aa", "bb" }
local cfg2 = configuration { cfg.terms, "cc" }
test.isequal({"aa", "bb", "cc"}, cfg2.terms)
end
--
-- project() tests
--
function suite.project_RaisesError_OnNoSolution()
premake.CurrentContainer = nil
local fn = function() project("MyProject") end
ok, err = pcall(fn)
test.isfalse(ok)
end
function suite.project_SetsCurrentContainer_OnName()
local prj = project "MyProject"
test.istrue(prj == premake.CurrentContainer)
end
function suite.project_CreatesNewObject_OnNewName()
local prj = project "MyProject"
local pr2 = project "MyProject2"
test.isfalse(prj == premake.CurrentContainer)
end
function suite.project_AddsToSolution_OnNewName()
local prj = project "MyProject"
test.istrue(prj == sln.projects[1])
end
function suite.project_ReturnsPrevious_OnExistingName()
local prj = project "MyProject"
local pr2 = project "MyProject2"
local pr3 = project "MyProject"
test.istrue(prj == pr3)
end
function suite.project_SetsCurrentContainer_OnExistingName()
local prj = project "MyProject"
local pr2 = project "MyProject2"
local pr3 = project "MyProject"
test.istrue(prj == premake.CurrentContainer)
end
function suite.project_ReturnsNil_OnNoActiveProjectAndNoName()
test.isnil(project())
end
function suite.project_ReturnsCurrentProject_OnActiveProjectAndNoName()
local prj = project "MyProject"
test.istrue(prj == project())
end
function suite.project_LeavesProjectActive_OnActiveProjectAndNoName()
local prj = project "MyProject"
project()
test.istrue(prj == premake.CurrentContainer)
end
function suite.project_LeavesConfigActive_OnActiveProjectAndNoName()
local prj = project "MyProject"
local cfg = configuration "Windows"
project()
test.istrue(cfg == premake.CurrentConfiguration)
end
function suite.project_SetsName_OnNewName()
prj = project("MyProject")
test.isequal("MyProject", prj.name)
end
function suite.project_SetsSolution_OnNewName()
prj = project("MyProject")
test.istrue(sln == prj.solution)
end
function suite.project_SetsConfiguration()
prj = project("MyProject")
test.istrue(premake.CurrentConfiguration == prj.blocks[1])
end
function suite.project_SetsUUID()
local prj = project "MyProject"
test.istrue(prj.uuid)
end
--
-- uuid() tests
--
function suite.uuid_makes_uppercase()
premake.CurrentContainer = {}
uuid "7CBB5FC2-7449-497f-947F-129C5129B1FB"
test.isequal(premake.CurrentContainer.uuid, "7CBB5FC2-7449-497F-947F-129C5129B1FB")
end
--
-- Fields with allowed value lists should be case-insensitive.
--
function suite.flags_onCaseMismatch()
premake.CurrentConfiguration = {}
flags "symbols"
test.isequal(premake.CurrentConfiguration.flags[1], "Symbols")
end
function suite.flags_onCaseMismatchAndAlias()
premake.CurrentConfiguration = {}
flags "optimisespeed"
test.isequal(premake.CurrentConfiguration.flags[1], "OptimizeSpeed")
end
| mit |
hsiaoyi/Melo | cocos2d/cocos/scripting/lua-bindings/auto/api/Text.lua | 3 | 9617 |
--------------------------------
-- @module Text
-- @extend Widget
-- @parent_module ccui
--------------------------------
-- Enable shadow for the label.<br>
-- todo support blur for shadow effect<br>
-- param shadowColor The color of shadow effect.<br>
-- param offset The offset of shadow effect.<br>
-- param blurRadius The blur radius of shadow effect.
-- @function [parent=#Text] enableShadow
-- @param self
-- @return Text#Text self (return value: ccui.Text)
--------------------------------
-- Gets the font size of label.<br>
-- return The font size.
-- @function [parent=#Text] getFontSize
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
--
-- @function [parent=#Text] getString
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- @overload self, int
-- @overload self
-- @function [parent=#Text] disableEffect
-- @param self
-- @param #int effect
-- @return Text#Text self (return value: ccui.Text)
--------------------------------
-- Return current effect type.
-- @function [parent=#Text] getLabelEffectType
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- Gets text color.<br>
-- return Text color.
-- @function [parent=#Text] getTextColor
-- @param self
-- @return color4b_table#color4b_table ret (return value: color4b_table)
--------------------------------
-- Sets text vertical alignment.<br>
-- param alignment vertical text alignment type
-- @function [parent=#Text] setTextVerticalAlignment
-- @param self
-- @param #int alignment
-- @return Text#Text self (return value: ccui.Text)
--------------------------------
-- Sets the font name of label.<br>
-- If you are trying to use a system font, you could just pass a font name<br>
-- If you are trying to use a TTF, you should pass a file path to the TTF file<br>
-- Usage:<br>
-- code<br>
-- create a system font UIText<br>
-- Text *text = Text::create("Hello", "Arial", 20);<br>
-- it will change the font to system font no matter the previous font type is TTF or system font<br>
-- text->setFontName("Marfelt");<br>
-- it will change the font to TTF font no matter the previous font type is TTF or system font<br>
-- text->setFontName("xxxx/xxx.ttf");<br>
-- endcode<br>
-- param name Font name.
-- @function [parent=#Text] setFontName
-- @param self
-- @param #string name
-- @return Text#Text self (return value: ccui.Text)
--------------------------------
-- Sets the touch scale enabled of label.<br>
-- param enabled Touch scale enabled of label.
-- @function [parent=#Text] setTouchScaleChangeEnabled
-- @param self
-- @param #bool enabled
-- @return Text#Text self (return value: ccui.Text)
--------------------------------
-- Return shadow effect offset value.
-- @function [parent=#Text] getShadowOffset
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
--
-- @function [parent=#Text] setString
-- @param self
-- @param #string text
-- @return Text#Text self (return value: ccui.Text)
--------------------------------
-- Return the outline effect size value.
-- @function [parent=#Text] getOutlineSize
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
--
-- @function [parent=#Text] init
-- @param self
-- @param #string textContent
-- @param #string fontName
-- @param #float fontSize
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Return the shadow effect blur radius.
-- @function [parent=#Text] getShadowBlurRadius
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Gets the touch scale enabled of label.<br>
-- return Touch scale enabled of label.
-- @function [parent=#Text] isTouchScaleChangeEnabled
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Gets the font name.<br>
-- return Font name.
-- @function [parent=#Text] getFontName
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- Sets the rendering size of the text, you should call this method<br>
-- along with calling `ignoreContentAdaptWithSize(false)`, otherwise the text area<br>
-- size is calculated by the real size of the text content.<br>
-- param size The text rendering area size.
-- @function [parent=#Text] setTextAreaSize
-- @param self
-- @param #size_table size
-- @return Text#Text self (return value: ccui.Text)
--------------------------------
-- Gets the string length of the label.<br>
-- Note: This length will be larger than the raw string length,<br>
-- if you want to get the raw string length,<br>
-- you should call this->getString().size() instead.<br>
-- return String length.
-- @function [parent=#Text] getStringLength
-- @param self
-- @return long#long ret (return value: long)
--------------------------------
-- Gets the render size in auto mode.<br>
-- return The size of render size in auto mode.
-- @function [parent=#Text] getAutoRenderSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- Enable outline for the label.<br>
-- It only works on IOS and Android when you use System fonts.<br>
-- param outlineColor The color of outline.<br>
-- param outlineSize The size of outline.
-- @function [parent=#Text] enableOutline
-- @param self
-- @param #color4b_table outlineColor
-- @param #int outlineSize
-- @return Text#Text self (return value: ccui.Text)
--------------------------------
-- Return current effect color value.
-- @function [parent=#Text] getEffectColor
-- @param self
-- @return color4b_table#color4b_table ret (return value: color4b_table)
--------------------------------
-- Gets the font type.<br>
-- return The font type.
-- @function [parent=#Text] getType
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- Gets text horizontal alignment.<br>
-- return Horizontal text alignment type
-- @function [parent=#Text] getTextHorizontalAlignment
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- Return whether the shadow effect is enabled.
-- @function [parent=#Text] isShadowEnabled
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Sets the font size of label.<br>
-- param size The font size.
-- @function [parent=#Text] setFontSize
-- @param self
-- @param #float size
-- @return Text#Text self (return value: ccui.Text)
--------------------------------
-- Return the shadow effect color value.
-- @function [parent=#Text] getShadowColor
-- @param self
-- @return color4b_table#color4b_table ret (return value: color4b_table)
--------------------------------
-- Sets text color.<br>
-- param color Text color.
-- @function [parent=#Text] setTextColor
-- @param self
-- @param #color4b_table color
-- @return Text#Text self (return value: ccui.Text)
--------------------------------
-- Only support for TTF.<br>
-- param glowColor The color of glow.
-- @function [parent=#Text] enableGlow
-- @param self
-- @param #color4b_table glowColor
-- @return Text#Text self (return value: ccui.Text)
--------------------------------
-- Gets text vertical alignment.<br>
-- return Vertical text alignment type
-- @function [parent=#Text] getTextVerticalAlignment
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- Return the text rendering area size.<br>
-- return The text rendering area size.
-- @function [parent=#Text] getTextAreaSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- Sets text horizontal alignment.<br>
-- param alignment Horizontal text alignment type
-- @function [parent=#Text] setTextHorizontalAlignment
-- @param self
-- @param #int alignment
-- @return Text#Text self (return value: ccui.Text)
--------------------------------
-- @overload self, string, string, float
-- @overload self
-- @function [parent=#Text] create
-- @param self
-- @param #string textContent
-- @param #string fontName
-- @param #float fontSize
-- @return Text#Text ret (return value: ccui.Text)
--------------------------------
--
-- @function [parent=#Text] createInstance
-- @param self
-- @return Ref#Ref ret (return value: cc.Ref)
--------------------------------
--
-- @function [parent=#Text] getVirtualRenderer
-- @param self
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
--
-- @function [parent=#Text] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Returns the "class name" of widget.
-- @function [parent=#Text] getDescription
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
--
-- @function [parent=#Text] getVirtualRendererSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- Default constructor.<br>
-- js ctor<br>
-- lua new
-- @function [parent=#Text] Text
-- @param self
-- @return Text#Text self (return value: ccui.Text)
return nil
| apache-2.0 |
xdemolish/darkstar | scripts/globals/spells/bluemagic/triumphant_roar.lua | 3 | 1125 | -----------------------------------------
-- Spell: Triumphant Roar
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local power = 15
local duration = 90;
if(caster:hasStatusEffect(EFFECT_DIFFUSION)) then
local diffMerit = caster:getMerit(MERIT_DIFFUSION);
if(diffMerit > 0) then
duration = duration + (duration/100)* diffMerit;
end
caster:delStatusEffect(EFFECT_DIFFUSION);
end
if(caster:hasStatusEffect(EFFECT_ATTACK_BOOST) == true) then
local effect = caster:getStatusEffect(EFFECT_ATTACK_BOOST);
effect:setPower(effect:getPower() + power);
caster:addMod(MOD_ATTP,power);
else
caster:addStatusEffect(EFFECT_ATTACK_BOOST,power,1,duration);
end
return EFFECT_ATTACK_BOOST;
end; | gpl-3.0 |
xdemolish/darkstar | scripts/zones/Windurst_Waters/npcs/Lago-Charago.lua | 38 | 1427 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Lago-Charago
-- Type: Adventurer's Assistant
-- @pos -57.271 -11.75 92.503 238
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatWindurst = player:getVar("WildcatWindurst");
if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,11) == false) then
player:startEvent(0x03ac);
else
player:startEvent(0x012c);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x03ac) then
player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",11,true);
end
end;
| gpl-3.0 |
xopxe/Toribio | tasks/inotifier.lua | 1 | 2266 | local M = {}
local sched=require 'lumen.sched'
local selector = require "lumen.tasks.selector"
local nixio = require 'nixio'
--executes s on the console and returns the output
local run_shell = function (s)
local f = io.popen(s) -- runs command
local l = f:read("*a") -- read output of command
f:close()
return l
end
M.init = function(masks_to_watch)
M.events = {
file_add = {},
file_del = {},
}
M.task = sched.run(function()
require 'catalog'.get_catalog('tasks'):register(masks_to_watch, sched.running_task)
if #run_shell('which inotifywait')==0 then
error('inotifywait not available')
end
local paths_to_watch = {}
for _, mask in ipairs(masks_to_watch) do
--print('DDDDDDDDDDDDD+', mask)
--string.match(mask, '^(.*%/)[^%/]*$')
local dir = nixio.fs.dirname(mask)
paths_to_watch[dir..'/']=true
--print('DDDDDDDDDDDDD-', dir)
end
local command = 'inotifywait -q -c -m -e create,delete'
for path, _ in pairs(paths_to_watch) do
command = command..' '..path
end
--print('+++++++++INOTIFY:', command)
local watcherfd=selector.grab_stdout (command, 'line', nil)
local waitd_inotify={watcherfd.events.data}
--generate events for already existing files
for _, devmask in ipairs(masks_to_watch) do
for devfile in nixio.fs.glob(devmask) do
print('existing file', devfile)
sched.schedule_signal(M.events.file_add, devfile, devmask)
end
end
--monitor files
while true do
local _,line=sched.wait(waitd_inotify)
if line then
local path, action, file = string.match(line, '^([^,]+),(.+),([^,]+)$')
local fullpath=path..file
--print('INOTIFY', action, fullpath)
if action=='CREATE' then
for _, mask in ipairs(masks_to_watch) do
for devfile in nixio.fs.glob(mask) do
if devfile==fullpath then
print('FILE+', fullpath, mask)
sched.schedule_signal(M.events.file_add, fullpath, mask)
end
--print('confline starting', devfile, modulename)
--local devmodule = require ('../drivers/filedev/'..modulename)
--devmodule.init(devfile)
end
end
elseif action=='DELETE' then
print('FILE-', fullpath)
sched.schedule_signal(M.events.file_del, fullpath)
end
end
end
end)
end
return M | mit |
BlackMesaRP/NS-Black-Mesa | plugins/m9k/entities/weapons/m9k_l85/shared.lua | 2 | 3681 | -- Variables that are used on both client and server
SWEP.Gun = ("m9k_l85") -- must be the name of your swep but NO CAPITALS!
SWEP.Category = "M9K Assault Rifles"
SWEP.Author = ""
SWEP.Contact = ""
SWEP.Purpose = ""
SWEP.Instructions = ""
SWEP.MuzzleAttachment = "1" -- Should be "1" for CSS models or "muzzle" for hl2 models
SWEP.ShellEjectAttachment = "2" -- Should be "2" for CSS models or "1" for hl2 models
SWEP.PrintName = "L85" -- Weapon name (Shown on HUD)
SWEP.Slot = 2 -- Slot in the weapon selection menu
SWEP.SlotPos = 3 -- Position in the slot
SWEP.DrawAmmo = true -- Should draw the default HL2 ammo counter
SWEP.DrawWeaponInfoBox = false -- Should draw the weapon info box
SWEP.BounceWeaponIcon = false -- Should the weapon icon bounce?
SWEP.DrawCrosshair = true -- Set false if you want no crosshair from hip
SWEP.Weight = 50 -- Rank relative ot other weapons. bigger is better
SWEP.AutoSwitchTo = true -- Auto switch to if we pick it up
SWEP.AutoSwitchFrom = true -- Auto switch from if you pick up a better weapon
SWEP.XHair = true -- Used for returning crosshair after scope. Must be the same as DrawCrosshair
SWEP.BoltAction = false -- Is this a bolt action rifle?
SWEP.HoldType = "ar2" -- how others view you carrying the weapon
-- normal melee melee2 fist knife smg ar2 pistol rpg physgun grenade shotgun crossbow slam passive
-- you're mostly going to use ar2, smg, shotgun or pistol. rpg and crossbow make for good sniper rifles
SWEP.ViewModelFOV = 70
SWEP.ViewModelFlip = true
SWEP.ViewModel = "models/weapons/v_rif_l85.mdl" -- Weapon view model
SWEP.WorldModel = "models/weapons/w_l85a2.mdl" -- Weapon world model
SWEP.Base = "bobs_scoped_base"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.Primary.Sound = Sound("Weapon_l85.Single") -- script that calls the primary fire sound
SWEP.Primary.RPM = 675 -- This is in Rounds Per Minute
SWEP.Primary.ClipSize = 30 -- Size of a clip
SWEP.Primary.DefaultClip = 60 -- Bullets you start with
SWEP.Primary.KickUp = .4 -- Maximum up recoil (rise)
SWEP.Primary.KickDown = .4 -- Maximum down recoil (skeet)
SWEP.Primary.KickHorizontal = .5 -- Maximum up recoil (stock)
SWEP.Primary.Automatic = true -- Automatic/Semi Auto
SWEP.Primary.Ammo = "ar2" -- pistol, 357, smg1, ar2, buckshot, slam, SniperPenetratedRound, AirboatGun
-- Pistol, buckshot, and slam always ricochet. Use AirboatGun for a light metal peircing shotgun pellets
SWEP.Secondary.ScopeZoom = 4
SWEP.Secondary.UseACOG = true -- Choose one scope type
SWEP.Secondary.UseMilDot = false -- I mean it, only one
SWEP.Secondary.UseSVD = false -- If you choose more than one, your scope will not show up at all
SWEP.Secondary.UseParabolic = false
SWEP.Secondary.UseElcan = false
SWEP.Secondary.UseGreenDuplex = false
SWEP.Secondary.UseAimpoint = false
SWEP.Secondary.UseMatador = false
SWEP.data = {}
SWEP.data.ironsights = 1
SWEP.ScopeScale = 0.5
SWEP.ReticleScale = 0.6
SWEP.Primary.NumShots = 1 --how many bullets to shoot per trigger pull
SWEP.Primary.Damage = 29 --base damage per bullet
SWEP.Primary.Spread = .023 --define from-the-hip accuracy 1 is terrible, .0001 is exact)
SWEP.Primary.IronAccuracy = .015 -- ironsight accuracy, should be the same for shotguns
-- enter iron sight info and bone mod info below
SWEP.IronSightsPos = Vector (2.275, -2.9708, 0.5303)
SWEP.IronSightsAng = Vector (0, 0, 0)
SWEP.SightsPos = Vector (2.275, -2.9708, 0.5303)
SWEP.SightsAng = Vector (0, 0, 0)
SWEP.RunSightsPos = Vector (-3.0328, 0, 1.888)
SWEP.RunSightsAng = Vector (-24.2146, -36.522, 10) | gpl-3.0 |
blockplanet/blockplanet | builtin/game/mod_profiling.lua | 4 | 10780 | -- Minetest: builtin/game/mod_profiling.lua
local mod_statistics = {}
mod_statistics.step_total = 0
mod_statistics.data = {}
mod_statistics.stats = {}
mod_statistics.stats["total"] = {
min_us = math.huge,
max_us = 0,
avg_us = 0,
min_per = 100,
max_per = 100,
avg_per = 100
}
local replacement_table = {
"register_globalstep",
"register_on_placenode",
"register_on_dignode",
"register_on_punchnode",
"register_on_generated",
"register_on_newplayer",
"register_on_dieplayer",
"register_on_respawnplayer",
"register_on_prejoinplayer",
"register_on_joinplayer",
"register_on_leaveplayer",
"register_on_cheat",
"register_on_chat_message",
"register_on_player_receive_fields",
"register_on_mapgen_init",
"register_on_craft",
"register_craft_predict",
"register_on_item_eat"
}
--------------------------------------------------------------------------------
function mod_statistics.log_time(type, modname, time_in_us)
if modname == nil then
modname = "builtin"
end
if mod_statistics.data[modname] == nil then
mod_statistics.data[modname] = {}
end
if mod_statistics.data[modname][type] == nil then
mod_statistics.data[modname][type] = 0
end
mod_statistics.data[modname][type] =
mod_statistics.data[modname][type] + time_in_us
mod_statistics.step_total = mod_statistics.step_total + time_in_us
end
--------------------------------------------------------------------------------
function mod_statistics.update_statistics(dtime)
for modname,types in pairs(mod_statistics.data) do
if mod_statistics.stats[modname] == nil then
mod_statistics.stats[modname] = {
min_us = math.huge,
max_us = 0,
avg_us = 0,
min_per = 100,
max_per = 0,
avg_per = 0
}
end
local modtime = 0
for type,time in pairs(types) do
modtime = modtime + time
if mod_statistics.stats[modname].types == nil then
mod_statistics.stats[modname].types = {}
end
if mod_statistics.stats[modname].types[type] == nil then
mod_statistics.stats[modname].types[type] = {
min_us = math.huge,
max_us = 0,
avg_us = 0,
min_per = 100,
max_per = 0,
avg_per = 0
}
end
local toupdate = mod_statistics.stats[modname].types[type]
--update us values
toupdate.min_us = math.min(time, toupdate.min_us)
toupdate.max_us = math.max(time, toupdate.max_us)
--TODO find better algorithm
toupdate.avg_us = toupdate.avg_us * 0.99 + modtime * 0.01
--update percentage values
local cur_per = (time/mod_statistics.step_total) * 100
toupdate.min_per = math.min(toupdate.min_per, cur_per)
toupdate.max_per = math.max(toupdate.max_per, cur_per)
--TODO find better algorithm
toupdate.avg_per = toupdate.avg_per * 0.99 + cur_per * 0.01
mod_statistics.data[modname][type] = 0
end
--per mod statistics
--update us values
mod_statistics.stats[modname].min_us =
math.min(modtime, mod_statistics.stats[modname].min_us)
mod_statistics.stats[modname].max_us =
math.max(modtime, mod_statistics.stats[modname].max_us)
--TODO find better algorithm
mod_statistics.stats[modname].avg_us =
mod_statistics.stats[modname].avg_us * 0.99 + modtime * 0.01
--update percentage values
local cur_per = (modtime/mod_statistics.step_total) * 100
mod_statistics.stats[modname].min_per =
math.min(mod_statistics.stats[modname].min_per, cur_per)
mod_statistics.stats[modname].max_per =
math.max(mod_statistics.stats[modname].max_per, cur_per)
--TODO find better algorithm
mod_statistics.stats[modname].avg_per =
mod_statistics.stats[modname].avg_per * 0.99 + cur_per * 0.01
end
--update "total"
mod_statistics.stats["total"].min_us =
math.min(mod_statistics.step_total, mod_statistics.stats["total"].min_us)
mod_statistics.stats["total"].max_us =
math.max(mod_statistics.step_total, mod_statistics.stats["total"].max_us)
--TODO find better algorithm
mod_statistics.stats["total"].avg_us =
mod_statistics.stats["total"].avg_us * 0.99 +
mod_statistics.step_total * 0.01
mod_statistics.step_total = 0
end
--------------------------------------------------------------------------------
local function build_callback(log_id, fct)
return function( toregister )
local modname = core.get_current_modname()
fct(function(...)
local starttime = core.get_us_time()
-- note maximum 10 return values are supported unless someone finds
-- a way to store a variable lenght return value list
local r0, r1, r2, r3, r4, r5, r6, r7, r8, r9 = toregister(...)
local delta = core.get_us_time() - starttime
mod_statistics.log_time(log_id, modname, delta)
return r0, r1, r2, r3, r4, r5, r6, r7, r8, r9
end
)
end
end
--------------------------------------------------------------------------------
function profiling_print_log(cmd, filter)
print("Filter:" .. dump(filter))
core.log("action", "Values below show times/percentages per server step.")
core.log("action", "Following suffixes are used for entities:")
core.log("action", "\t#oa := on_activate, #os := on_step, #op := on_punch, #or := on_rightclick, #gs := get_staticdata")
core.log("action",
string.format("%16s | %25s | %10s | %10s | %10s | %9s | %9s | %9s",
"modname", "type" , "min µs", "max µs", "avg µs", "min %", "max %", "avg %")
)
core.log("action",
"-----------------+---------------------------+-----------+" ..
"-----------+-----------+-----------+-----------+-----------")
for modname,statistics in pairs(mod_statistics.stats) do
if modname ~= "total" then
if (filter == "") or (modname == filter) then
if modname:len() > 16 then
modname = "..." .. modname:sub(-13)
end
core.log("action",
string.format("%16s | %25s | %9d | %9d | %9d | %9d | %9d | %9d",
modname,
" ",
statistics.min_us,
statistics.max_us,
statistics.avg_us,
statistics.min_per,
statistics.max_per,
statistics.avg_per)
)
if core.setting_getbool("detailed_profiling") then
if statistics.types ~= nil then
for type,typestats in pairs(statistics.types) do
if type:len() > 25 then
type = "..." .. type:sub(-22)
end
core.log("action",
string.format(
"%16s | %25s | %9d | %9d | %9d | %9d | %9d | %9d",
" ",
type,
typestats.min_us,
typestats.max_us,
typestats.avg_us,
typestats.min_per,
typestats.max_per,
typestats.avg_per)
)
end
end
end
end
end
end
core.log("action",
"-----------------+---------------------------+-----------+" ..
"-----------+-----------+-----------+-----------+-----------")
if filter == "" then
core.log("action",
string.format("%16s | %25s | %9d | %9d | %9d | %9d | %9d | %9d",
"total",
" ",
mod_statistics.stats["total"].min_us,
mod_statistics.stats["total"].max_us,
mod_statistics.stats["total"].avg_us,
mod_statistics.stats["total"].min_per,
mod_statistics.stats["total"].max_per,
mod_statistics.stats["total"].avg_per)
)
end
core.log("action", " ")
return true
end
--------------------------------------------------------------------------------
local function initialize_profiling()
core.log("action", "Initialize tracing")
mod_statistics.entity_callbacks = {}
-- first register our own globalstep handler
core.register_globalstep(mod_statistics.update_statistics)
local rp_register_entity = core.register_entity
core.register_entity = function(name, prototype)
local modname = core.get_current_modname()
local new_on_activate = nil
local new_on_step = nil
local new_on_punch = nil
local new_rightclick = nil
local new_get_staticdata = nil
if prototype.on_activate ~= nil then
local cbid = name .. "#oa"
mod_statistics.entity_callbacks[cbid] = prototype.on_activate
new_on_activate = function(self, staticdata, dtime_s)
local starttime = core.get_us_time()
mod_statistics.entity_callbacks[cbid](self, staticdata, dtime_s)
local delta = core.get_us_time() -starttime
mod_statistics.log_time(cbid, modname, delta)
end
end
if prototype.on_step ~= nil then
local cbid = name .. "#os"
mod_statistics.entity_callbacks[cbid] = prototype.on_step
new_on_step = function(self, dtime)
local starttime = core.get_us_time()
mod_statistics.entity_callbacks[cbid](self, dtime)
local delta = core.get_us_time() -starttime
mod_statistics.log_time(cbid, modname, delta)
end
end
if prototype.on_punch ~= nil then
local cbid = name .. "#op"
mod_statistics.entity_callbacks[cbid] = prototype.on_punch
new_on_punch = function(self, hitter)
local starttime = core.get_us_time()
mod_statistics.entity_callbacks[cbid](self, hitter)
local delta = core.get_us_time() -starttime
mod_statistics.log_time(cbid, modname, delta)
end
end
if prototype.rightclick ~= nil then
local cbid = name .. "#rc"
mod_statistics.entity_callbacks[cbid] = prototype.rightclick
new_rightclick = function(self, clicker)
local starttime = core.get_us_time()
mod_statistics.entity_callbacks[cbid](self, clicker)
local delta = core.get_us_time() -starttime
mod_statistics.log_time(cbid, modname, delta)
end
end
if prototype.get_staticdata ~= nil then
local cbid = name .. "#gs"
mod_statistics.entity_callbacks[cbid] = prototype.get_staticdata
new_get_staticdata = function(self)
local starttime = core.get_us_time()
local retval = mod_statistics.entity_callbacks[cbid](self)
local delta = core.get_us_time() -starttime
mod_statistics.log_time(cbid, modname, delta)
return retval
end
end
prototype.on_activate = new_on_activate
prototype.on_step = new_on_step
prototype.on_punch = new_on_punch
prototype.rightclick = new_rightclick
prototype.get_staticdata = new_get_staticdata
rp_register_entity(name,prototype)
end
for i,v in ipairs(replacement_table) do
local to_replace = core[v]
core[v] = build_callback(v, to_replace)
end
local rp_register_abm = core.register_abm
core.register_abm = function(spec)
local modname = core.get_current_modname()
local replacement_spec = {
nodenames = spec.nodenames,
neighbors = spec.neighbors,
interval = spec.interval,
chance = spec.chance,
action = function(pos, node, active_object_count, active_object_count_wider)
local starttime = core.get_us_time()
spec.action(pos, node, active_object_count, active_object_count_wider)
local delta = core.get_us_time() - starttime
mod_statistics.log_time("abm", modname, delta)
end
}
rp_register_abm(replacement_spec)
end
core.log("action", "Mod profiling initialized")
end
initialize_profiling()
| gpl-3.0 |
xdemolish/darkstar | scripts/zones/Rabao/npcs/Shiny_Teeth.lua | 36 | 1675 | -----------------------------------
-- Area: Rabao
-- NPC: Shiny Teeth
-- Standard Merchant NPC
-- @pos -30 8 99 247
-----------------------------------
package.loaded["scripts/zones/Rabao/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/zones/Rabao/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,SHINY_TEETH_SHOP_DIALOG);
stock = {0x4042,1867, --Dagger 1867 - 2111
0x404C,11128, --Kris 11128 - 12096
0x4052,2231, --Knife 2231 - 2522
0x40A8,4163, --Scimitar 4163 - 4706
0x40A9,35308, --Tulwar 35308
0x40AE,62560, --Falchion 62560 - 70720
0x42A4,2439, --Rod 2439 - 4680
0x4011,103803, --Jamadhars 103803 - 104944
0x4303,23887, --Composite Bow 23887 - 24150
0x4392,294, --Tathlum 294 - 332
0x43A8,7, --Iron Arrow 7 - 10
0x43BC,92, --Bullet 92 - 174
0x43A3,5460, --Riot Grenade 5460 - 5520
0x4384,8996} --Chakram 8996 - 10995
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
xdemolish/darkstar | scripts/zones/Newton_Movalpolos/npcs/Furnace_Hatch.lua | 13 | 2789 | -----------------------------------
-- Area: Newton Movalpolos
-- NPC: Furnace_Hatch
-----------------------------------
package.loaded["scripts/zones/Newton_Movalpolos/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Newton_Movalpolos/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(trade:getItemCount() == 1 and trade:hasItemQty(947,1)) then
player:tradeComplete();
-- player:messageSpecial(???); -- Needs retail info
local npcid = npc:getID();
local Door_Offset = 16826582; -- _0c0 in NPC_List
if(npcid == Door_Offset+29 or npcid == Door_Offset+28 or npcid == Door_Offset+27)then
if(GetNPCByID(Door_Offset+10):getAnimation() == 8)then
GetNPCByID(Door_Offset+10):setAnimation(9);
GetNPCByID(Door_Offset+11):setAnimation(8);
GetNPCByID(Door_Offset+8):setAnimation(9);
GetNPCByID(Door_Offset+9):setAnimation(8);
else
GetNPCByID(Door_Offset+10):setAnimation(8);
GetNPCByID(Door_Offset+11):setAnimation(9);
GetNPCByID(Door_Offset+8):setAnimation(8);
GetNPCByID(Door_Offset+9):setAnimation(9);
end
elseif (npcid == Door_Offset+25)then
if(GetNPCByID(Door_Offset+3):getAnimation() == 8)then
GetNPCByID(Door_Offset+3):setAnimation(9);
GetNPCByID(Door_Offset+2):setAnimation(8);
GetNPCByID(Door_Offset+1):setAnimation(9);
GetNPCByID(Door_Offset):setAnimation(8);
else
GetNPCByID(Door_Offset+3):setAnimation(8);
GetNPCByID(Door_Offset+2):setAnimation(9);
GetNPCByID(Door_Offset+1):setAnimation(8);
GetNPCByID(Door_Offset):setAnimation(9);
end
elseif (npcid == Door_Offset+26)then
if(GetNPCByID(Door_Offset+4):getAnimation() == 8)then
GetNPCByID(Door_Offset+4):setAnimation(9);
GetNPCByID(Door_Offset+5):setAnimation(8);
GetNPCByID(Door_Offset+6):setAnimation(9);
GetNPCByID(Door_Offset+7):setAnimation(8);
else
GetNPCByID(Door_Offset+4):setAnimation(8);
GetNPCByID(Door_Offset+5):setAnimation(9);
GetNPCByID(Door_Offset+6):setAnimation(8);
GetNPCByID(Door_Offset+7):setAnimation(9);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
xdemolish/darkstar | scripts/globals/spells/invisible.lua | 22 | 1187 | -----------------------------------------
-- Spell: Invisible
-- Lessens chance of being detected by sight.
-- Duration is random number between 30 seconds and 5 minutes
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
if (target:hasStatusEffect(EFFECT_INVISIBLE) == false) then
local duration = math.random(30, 300);
if (caster:hasStatusEffect(EFFECT_COMPOSURE) == true and caster:getID() == target:getID()) then
duration = duration * 3;
end
if (target:getMainLvl() < 20) then
duration = duration * target:getMainLvl() / 20; -- level adjustment
end
if (target:getEquipID(15) == 13692) then -- skulker's cape
duration = duration * 1.5;
end
spell:setMsg(230);
target:addStatusEffect(EFFECT_INVISIBLE,0,10,(math.floor(duration) * SNEAK_INVIS_DURATION_MULTIPLIER));
else
spell:setMsg(75); -- no effect.
end
return EFFECT_INVISIBLE;
end; | gpl-3.0 |
sevenbot/sasa | plugins/moderation.lua | 29 | 12162 | do
local function check_member(extra, success, result)
local data = extra.data
for k,v in pairs(result.members) do
if v.id ~= our_id then
data[tostring(extra.msg.to.id)] = {
moderators = {[tostring(v.id)] = '@'..v.username},
settings = {
set_name = string.gsub(extra.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 send_large_msg(get_receiver(extra.msg), 'You have been promoted as moderator for this group.')
end
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been promoted as moderator for this group.')
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been demoted from moderator of this group.')
end
local function admin_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_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(extra, success, result)
for k,v in pairs(result.members) do
if v.username == extra.username then
if extra.mod_cmd == 'promote' then
return promote(extra.receiver, '@'..extra.username, v.id)
elseif extra.mod_cmd == 'demote' then
return demote(extra.receiver, '@'..extra.username, v.id)
elseif extra.mod_cmd == 'adminprom' then
return admin_promote(extra.receiver, '@'..extra.username, v.id)
elseif extra.mod_cmd == 'admindem' then
return admin_demote(extra.receiver, '@'..extra.username, v.id)
end
end
end
send_large_msg(extra.receiver, 'No user '..extra.username..' in this group.')
end
local function action_by_id(extra, success, result)
if success == 1 then
for k,v in pairs(result.members) do
if extra.matches[2] == tostring(v.id) then
if extra.matches[1] == 'promote' then
return promote('chat#id'..result.id, 'user#id'..extra.matches[2], tostring(v.id))
elseif extra.matches[1] == 'demote' then
return demote('chat#id'..result.id, 'user#id'..extra.matches[2], tostring(v.id))
elseif extra.matches[1] == 'adminprom' then
return admin_promote('chat#id'..result.id, 'user#id'..extra.matches[2], tostring(v.id))
elseif extra.matches[1] == 'admindem' then
return admin_demote('chat#id'..result.id, 'user#id'..extra.matches[2], tostring(v.id))
end
end
end
send_large_msg('chat#id'..result.id, 'No user user#id'..extra.matches[2]..' in this group.')
end
end
local function action_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' and not is_sudo(member_id) then
if extra.msg.text == '!promote' then
return promote(get_receiver(msg), member_username, member_id)
elseif extra.msg.text == '!demote' then
return demote(get_receiver(msg), member_username, member_id)
elseif extra.msg.text == '!adminprom' then
return admin_promote(get_receiver(msg), member_username, member_id)
elseif extra.msg.text == '!admindem' then
return admin_demote(get_receiver(msg), member_username, member_id)
end
else
return 'Use This in Your Groups.'
end
end
function run(msg, matches)
local receiver = get_receiver(msg)
if is_chat_msg(msg) then
if is_mod(msg.from.id, msg.to.id) then
if matches[1] == 'promote' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg})
end
if matches[2] then
if string.match(matches[2], '^%d+$') then
chat_info(receiver, action_by_id, {msg=msg, matches=matches})
elseif string.match(matches[2], '^@.+$') then
local username = string.gsub(matches[2], '@', '')
chat_info(receiver, username_id, {mod_cmd=matches[1], receiver=receiver, username=username})
end
end
elseif matches[1] == 'demote' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg})
end
if matches[2] then
if string.match(matches[2], '^%d+$') then
demote(receiver, 'user_'..matches[2], matches[2])
elseif string.match(matches[2], '^@.+$') then
local username = string.gsub(matches[2], '@', '')
if username == msg.from.username then
return 'You can\'t demote yourself.'
else
chat_info(receiver, username_id, {mod_cmd=matches[1], receiver=receiver, username=username})
end
end
end
elseif matches[1] == 'modlist' then
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = 'List of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message .. '- '..v..' [' ..k.. '] \n'
end
return message
end
end
if is_admin(msg.from.id, msg.to.id) then
if matches[1] == 'adminprom' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg})
end
if matches[2] then
if string.match(matches[2], '^%d+$') then
chat_info(receiver, action_by_id, {msg=msg, matches=matches})
elseif matches[2] and string.match(matches[2], '^@.+$') then
local username = string.gsub(matches[2], '@', '')
chat_info(receiver, username_id, {mod_cmd=matches[1], receiver=receiver, username=username})
end
end
elseif matches[1] == 'admindem' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg})
end
if matches[2] then
if string.match(matches[2], '^%d+$') then
admin_demote(receiver, 'user_'..matches[2], matches[2])
elseif string.match(matches[2], '^@.+$') then
local username = string.gsub(matches[2], '@', '')
chat_info(receiver, username_id, {mod_cmd=matches[1], receiver=receiver, username=username})
end
end
elseif matches[1] == 'adminlist' then
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if next(data['admins']) == nil then --fix way
return 'No admin available.'
end
for k,v in pairs(data['admins']) do
message = 'List for Bot admins:\n'..'- '..v..' ['..k..'] \n'
end
return message
end
end
else
return 'Only works on group'
end
if matches[1] == 'chat_created' and msg.from.id == 0 then
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
chat_info(get_receiver(msg), check_member,{data=data, msg=msg})
else
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
local username = msg.from.username or msg.from.print_name
-- create data array in moderation.json
data[tostring(msg.to.id)] = {
moderators ={[tostring(msg.from.id)] = '@'..username},
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, and @'..username..' has been promoted as moderator for this group.'
end
end
end
return {
description = 'Moderation plugin',
usage = {
moderator = {
'!promote : If typed when replying, promote replied user as moderator',
'!promote <user_id> : Promote user_id as moderator',
'!promote @<username> : Promote username as moderator',
'!demote : If typed when replying, demote replied user from moderator',
'!demote <user_id> : Demote user_id from moderator',
'!demote @<username> : Demote username from moderator',
'!modlist : List of moderators'
},
sudo = {
'!adminprom : If typed when replying, promote replied user as admin.',
'!adminprom <user_id> : Promote user_id as admin.',
'!adminprom @<username> : Promote username as admin.',
'!admindem : If typed when replying, demote replied user from admin.',
'!admindem <user_id> : Demote user_id from admin.',
'!admindem @<username> : Demote username from admin.'
},
},
patterns = {
'^!(admindem) (%d+)$',
'^!(admindem) (.*)$',
'^!(admindem)$',
'^!(adminlist)$',
'^!(adminprom) (%d+)$',
'^!(adminprom) (.*)$',
'^!(adminprom)$',
'^!(demote) (.*)$',
'^!(demote)$',
'^!(modlist)$',
'^!(promote) (.*)$',
'^!(promote)$',
'^!(promote) (%d+)$',
'^!!tgservice (chat_add_user)$',
'^!!tgservice (chat_created)$'
},
run = run
}
end
| gpl-2.0 |
blockplanet/blockplanet | games/blockplanet/mods/default/items/books.lua | 1 | 2321 | local function book_on_use(itemstack, user, pointed_thing)
local player_name = user:get_player_name()
local data = minetest.deserialize(itemstack:get_metadata())
local title, text, owner = "", "", player_name
if data then
title, text, owner = data.title, data.text, data.owner
end
local formspec
if owner == player_name then
formspec = "size[8,8]"..default.gui_bg..
"field[0.5,1;7.5,0;title;Title:;"..
minetest.formspec_escape(title).."]"..
"textarea[0.5,1.5;7.5,7;text;Contents:;"..
minetest.formspec_escape(text).."]"..
"button_exit[2.5,7.5;3,1;save;Save]"
else
formspec = "size[8,8]"..default.gui_bg..
"label[0.5,0.5;by "..owner.."]"..
"label[0.5,0;"..minetest.formspec_escape(title).."]"..
"textarea[0.5,1.5;7.5,7;;"..minetest.formspec_escape(text)..";]"
end
minetest.show_formspec(user:get_player_name(), "default:book", formspec)
end
minetest.register_on_player_receive_fields(function(player, form_name, fields)
if form_name ~= "default:book" or not fields.save or
fields.title == "" or fields.text == "" then
return
end
local inv = player:get_inventory()
local stack = player:get_wielded_item()
local new_stack, data
if stack:get_name() ~= "default:book_written" then
local count = stack:get_count()
if count == 1 then
stack:set_name("default:book_written")
else
stack:set_count(count - 1)
new_stack = ItemStack("default:book_written")
end
else
data = minetest.deserialize(stack:get_metadata())
end
if not data then data = {} end
data.title = fields.title
data.text = fields.text
data.owner = player:get_player_name()
local data_str = minetest.serialize(data)
if new_stack then
new_stack:set_metadata(data_str)
if inv:room_for_item("main", new_stack) then
inv:add_item("main", new_stack)
else
minetest.add_item(player:getpos(), new_stack)
end
else
stack:set_metadata(data_str)
end
player:set_wielded_item(stack)
end)
minetest.register_craftitem("default:book", {
description = "Book",
inventory_image = "default_book.png",
groups = {book=1,fuel=2},
on_use = book_on_use,
})
minetest.register_craftitem("default:book_written", {
description = "Book with Text",
inventory_image = "default_book_written.png",
groups = {book=1, not_in_creative_inventory=1, fuel=2},
stack_max = 1,
on_use = book_on_use,
})
| gpl-3.0 |
xdemolish/darkstar | scripts/globals/abilities/pets/tail_whip.lua | 6 | 1265 | ---------------------------------------------------
-- Tail Whip M=5
---------------------------------------------------
require("/scripts/globals/settings");
require("/scripts/globals/status");
require("/scripts/globals/monstertpmoves");
require("/scripts/globals/summon");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = 5;
local totaldamage = 0;
local damage = AvatarPhysicalMove(pet,target,skill,numhits,accmod,dmgmod,0,TP_NO_EFFECT,1,2,3);
totaldamage = AvatarFinalAdjustments(damage.dmg,pet,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_PIERCE,numhits);
local duration = 120;
local resm = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL, 5);
if resm < 0.25 then
resm = 0;
end
duration = duration * resm
if(duration > 0 and AvatarPhysicalHit(skill, totaldamage) and target:hasStatusEffect(EFFECT_WEIGHT) == false) then
target:addStatusEffect(EFFECT_WEIGHT, 50, 0, duration);
end
target:delHP(totaldamage);
target:updateEnmityFromDamage(pet,totaldamage);
return totaldamage;
end | gpl-3.0 |
chris5560/openwrt-luci | protocols/luci-proto-relay/luasrc/model/cbi/admin_network/proto_relay.lua | 70 | 1945 | -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
local ipaddr, network
local forward_bcast, forward_dhcp, gateway, expiry, retry, table
ipaddr = section:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Address to access local relay bridge"))
ipaddr.datatype = "ip4addr"
network = s:taboption("general", DynamicList, "network", translate("Relay between networks"))
network.widget = "checkbox"
network.exclude = arg[1]
network.template = "cbi/network_netlist"
network.nocreate = true
network.nobridges = true
network.novirtual = true
network:depends("proto", "relay")
forward_bcast = section:taboption("advanced", Flag, "forward_bcast",
translate("Forward broadcast traffic"))
forward_bcast.default = forward_bcast.enabled
forward_dhcp = section:taboption("advanced", Flag, "forward_dhcp",
translate("Forward DHCP traffic"))
forward_dhcp.default = forward_dhcp.enabled
gateway = section:taboption("advanced", Value, "gateway",
translate("Use DHCP gateway"),
translate("Override the gateway in DHCP responses"))
gateway.datatype = "ip4addr"
gateway:depends("forward_dhcp", forward_dhcp.enabled)
expiry = section:taboption("advanced", Value, "expiry",
translate("Host expiry timeout"),
translate("Specifies the maximum amount of seconds after which hosts are presumed to be dead"))
expiry.placeholder = "30"
expiry.datatype = "min(1)"
retry = section:taboption("advanced", Value, "retry",
translate("ARP retry threshold"),
translate("Specifies the maximum amount of failed ARP requests until hosts are presumed to be dead"))
retry.placeholder = "5"
retry.datatype = "min(1)"
table = section:taboption("advanced", Value, "table",
translate("Use routing table"),
translate("Override the table used for internal routes"))
table.placeholder = "16800"
table.datatype = "range(0,65535)"
| apache-2.0 |
PlexChat/premake-core | tests/oven/test_filtering.lua | 9 | 1712 | --
-- tests/oven/test_filtering.lua
-- Test the project object configuration accessor.
-- Copyright (c) 2011-2014 Jason Perkins and the Premake project
--
local suite = test.declare("oven_filtering")
--
-- Setup
--
local wks, prj
function suite.setup()
wks = test.createWorkspace()
end
local function prepare()
wks = test.getWorkspace(wks)
prj = test.getproject(wks, 1)
end
--
-- Test filtering by the selected action.
--
function suite.onAction()
_ACTION = "vs2012"
filter { "action:vs2012" }
defines { "USE_VS2012" }
prepare()
test.isequal({ "USE_VS2012" }, prj.defines)
end
function suite.onActionMismatch()
_ACTION = "vs2010"
filter { "action:vs2012" }
defines { "USE_VS2012" }
prepare()
test.isequal({}, prj.defines)
end
--
-- Test filtering on command line options.
--
function suite.onOptionNoValue()
_OPTIONS["release"] = ""
filter { "options:release" }
defines { "USE_RELEASE" }
prepare()
test.isequal({ "USE_RELEASE" }, prj.defines)
end
function suite.onOptionNoValueUnset()
filter { "options:release" }
defines { "USE_RELEASE" }
prepare()
test.isequal({ }, prj.defines)
end
function suite.onOptionWithValue()
_OPTIONS["renderer"] = "opengl"
filter { "options:renderer=opengl" }
defines { "USE_OPENGL" }
prepare()
test.isequal({ "USE_OPENGL" }, prj.defines)
end
function suite.onOptionWithValueMismatch()
_OPTIONS["renderer"] = "direct3d"
filter { "options:renderer=opengl" }
defines { "USE_OPENGL" }
prepare()
test.isequal({ }, prj.defines)
end
function suite.onOptionWithValueUnset()
filter { "options:renderer=opengl" }
defines { "USE_OPENGL" }
prepare()
test.isequal({ }, prj.defines)
end
| bsd-3-clause |
xdemolish/darkstar | scripts/globals/mobskills/Haymaker.lua | 6 | 1038 | ---------------------------------------------
-- Haymaker
--
-- Description: Punches the daylights out of all targets in front. Additional effect: Amnesia
-- Type: Physical
-- Utsusemi/Blink absorb: Unknown
-- Range: Front cone
-- Notes: Only used by Gurfurlur the Menacing.
---------------------------------------------
require("/scripts/globals/settings");
require("/scripts/globals/status");
require("/scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = 2;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_H2H,info.hitslanded);
local typeEffect = EFFECT_AMNESIA;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 60);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
xdemolish/darkstar | scripts/globals/items/dish_of_spaghetti_nero_di_seppia.lua | 35 | 1800 | -----------------------------------------
-- ID: 5193
-- Item: dish_of_spaghetti_nero_di_seppia
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP % 17 (cap 130)
-- Dexterity 3
-- Vitality 2
-- Agility -1
-- Mind -2
-- Charisma -1
-- Double Attack 1
-- Store TP 6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5193);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 17);
target:addMod(MOD_FOOD_HP_CAP, 130);
target:addMod(MOD_DEX, 3);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_AGI, -1);
target:addMod(MOD_MND, -2);
target:addMod(MOD_CHR, -1);
target:addMod(MOD_DOUBLE_ATTACK, 1);
target:addMod(MOD_STORETP, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 17);
target:delMod(MOD_FOOD_HP_CAP, 130);
target:delMod(MOD_DEX, 3);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_AGI, -1);
target:delMod(MOD_MND, -2);
target:delMod(MOD_CHR, -1);
target:delMod(MOD_DOUBLE_ATTACK, 1);
target:delMod(MOD_STORETP, 6);
end;
| gpl-3.0 |
xdemolish/darkstar | scripts/zones/RuLude_Gardens/npcs/relic.lua | 41 | 1848 | -----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: <this space intentionally left blank>
-- @pos 0 8 -40 243
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/RuLude_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece
if (player:getVar("RELIC_IN_PROGRESS") == 18293 and trade:getItemCount() == 4 and trade:hasItemQty(18293,1) and
trade:hasItemQty(1576,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1457,1)) then
player:startEvent(10035,18294);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 10035) then
if (player:getFreeSlotsCount() < 2) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18294);
player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1456);
else
player:tradeComplete();
player:addItem(18294);
player:addItem(1456,30);
player:messageSpecial(ITEM_OBTAINED,18294);
player:messageSpecial(ITEMS_OBTAINED,1456,30);
player:setVar("RELIC_IN_PROGRESS",0);
end
end
end; | gpl-3.0 |
hsiaoyi/Melo | cocos2d/plugin/samples/HelloPluginsLua/src/TestFBShareScene.lua | 6 | 13701 | local visibleSize = cc.Director:getInstance():getVisibleSize()
local origin = cc.Director:getInstance():getVisibleOrigin()
local posBR = cc.p(origin.x + visibleSize.width, origin.y)
local TestFBShareScene = class("TestFBShareScene",function()
return cc.Scene:create()
end)
function TestFBShareScene.create()
local scene = TestFBShareScene.new()
return scene
end
function TestFBShareScene:ctor()
local title = cc.Label:createWithSystemFont("Test Facebook share", "Arial", 32)
title:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - 50)
self:addChild(title)
local sdkVersion = "SDK Version is: " .. plugin.FacebookAgent:getInstance():getSDKVersion()
local subTitle = cc.Label:createWithSystemFont(sdkVersion, "Arial", 12)
subTitle:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - 74)
self:addChild(subTitle)
self:createLayerMenu()
end
function TestFBShareScene:sceenshot(filename)
local visibleSize = cc.Director:getInstance():getVisibleSize()
local origin = cc.Director:getInstance():getVisibleOrigin()
local tex = cc.RenderTexture:create(visibleSize.width, visibleSize.height, cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888)
tex:setPosition((origin.x + visibleSize.width) / 2, (origin.y + visibleSize.height) / 2)
tex:begin()
cc.Director:getInstance():getRunningScene():visit()
tex:endToLua()
local imgPath = cc.FileUtils:getInstance():getWritablePath()
if imgPath == "" then
return ""
end
local ret = tex:saveToFile(filename, cc.IMAGE_FORMAT_JPEG)
if ret then
imgPath = imgPath .. filename
print(string.format("save image to %s", imgPath))
return imgPath
end
return ""
end
local secondMenuItem_SL = {
{"share a simple link", function(tag, sender)
local params = {
dialog = "share_link",
link = "http://www.cocos2d-x.org",
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
else
params.dialog = "feed_dialog"
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
end
end},
{"share a Text link", function(tag, sender)
local params = {
dialog = "share_link",
name = "Cocos2dx-lua web site",
caption = "Cocos2dx-lua caption",
description = "Cocos2dx-lua description",
link = "http://www.cocos2d-x.org",
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
else
params.dialog = "feed_dialog"
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
end
end},
{"share a Picture link", function(tag, sender)
local params = {
dialog = "share_link",
name = "Cocos2dx-lua web site",
caption = "Cocos2dx-lua caption",
description = "Cocos2dx-lua description",
to = "100006738453912",--android only web view support
picture = "http://files.cocos2d-x.org/images/orgsite/logo.png",
link = "http://www.cocos2d-x.org",
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
else
params.dialog = "feed_dialog"
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
end
end},
{"share a media link", function(tag, sender)
local params = {
dialog = "share_link",
name = "Cocos2dx-lua web site",
caption = "Cocos2dx-lua caption",
description = "Cocos2dx-lua description",
media_source = "http://221.203.1.212/youku/6775B002C8F48839F6AFA63BDA/0300200100540438A173C515AA2BED245C4903-F675-B311-EF1A-4544B5C04370.mp4",
link = "http://www.cocos2d-x.org",
}
-- only support in web dialog
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
end},
}
local secondMenuItem_AR = {
{"Invites request", function(tag, sender)
local params = {
message = "Cocos2dx-lua is a great game engine",
title = "Cocos2dx-lua title",
}
plugin.FacebookAgent:getInstance():appRequest(params, function(ret, msg)
print(msg)
end)
end},
{"Target invite request", function(tag, sender)
local params = {
message = "Cocos2dx-lua is a great game engine",
title = "Cocos2dx-lua title",
to = "100006738453912, 10204182777160522",
}
--android only web view support to
plugin.FacebookAgent:getInstance():appRequest(params, function(ret, msg)
print(msg)
end)
end},
{"Specific lists of friends", function(tag, sender)
local params = {
message = "Cocos2dx-lua is a great game engine",
title = "Cocos2dx-lua title",
filters = "[{\"name\":\"company\", \"user_ids\":[\"100006738453912\",\"10204182777160522\"]}]",
}
-- android not support filters
plugin.FacebookAgent:getInstance():appRequest(params, function(ret, msg)
print(msg)
end)
end},
{"Sending requests explicitly", function(tag, sender)
local params = {
message = "Cocos2dx-lua is a great game engine",
to = "100006738453912",
action_type = "send",
object_id = "191181717736427",-- 191181717736427 1426774790893461
}
--android not support action_type
plugin.FacebookAgent:getInstance():appRequest(params, function(ret, msg)
print(msg)
end)
end},
{"Turn-based games", function(tag, sender)
local params = {
message = "Cocos2dx-lua is a great game engine",
title = "Cocos2dx-lua title",
to = "100006738453912",
action_type = "turn",
}
-- android not support action_type
plugin.FacebookAgent:getInstance():appRequest(params, function(ret, msg)
print(msg)
end)
end},
}
function TestFBShareScene:showSecondMenu(tag)
local secondMenu = self:getChildByTag(2)
if nil ~= secondMenu then
local visibleSize = cc.Director:getInstance():getVisibleSize()
local origin = cc.Director:getInstance():getVisibleOrigin()
local posBR = cc.p(origin.x + visibleSize.width, origin.y)
secondMenu:removeAllChildren()
local top = 90
if 0 == tag then
for i = 1, table.getn(secondMenuItem_SL) do
local label = cc.Label:createWithSystemFont(secondMenuItem_SL[i][1], "Arial", 18)
local menuItem = cc.MenuItemLabel:create(label)
menuItem:registerScriptTapHandler(secondMenuItem_SL[i][2])
menuItem:setPosition(cc.p(visibleSize.width / 9, visibleSize.height - top))
secondMenu:addChild(menuItem, 0, i - 1 )
top = top + 50
end
else
for i = 1, table.getn(secondMenuItem_AR) do
local label = cc.Label:createWithSystemFont(secondMenuItem_AR[i][1], "Arial", 18)
local menuItem = cc.MenuItemLabel:create(label)
menuItem:registerScriptTapHandler(secondMenuItem_AR[i][2])
menuItem:setPosition(cc.p(visibleSize.width / 9, visibleSize.height - top))
secondMenu:addChild(menuItem, 0, i - 1 )
top = top + 50
end
end
end
end
function TestFBShareScene:createLayerMenu()
local backItem = cc.MenuItemFont:create("Back")
backItem:registerScriptTapHandler(function()
cc.Director:getInstance():replaceScene(require("HelloWorldScene").create())
end)
local backSize = backItem:getContentSize()
backItem:setPosition(posBR.x - backSize.width / 2, posBR.y + backSize.height / 2)
local menu = cc.Menu:create(backItem)
menu:setPosition(cc.p(0,0))
self:addChild(menu, 0, 1)
local menuItemNames =
{
{"Share link", function(tag, sender)
self:showSecondMenu(0)
end},
{"Share open graph", function(tag, sender)
local params = {
dialog = "share_open_graph",
action_type = "cocostestmyfc:share",
preview_property_name = "cocos_document",
title = "Cocos2dx-lua Game Engine",
image = "http://files.cocos2d-x.org/images/orgsite/logo.png",
url = "http://cocos2d-x.org/docs/catalog/en",
description = "cocos document",
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
else
print("Can't open dialog for share_open_graph")
end
end},
{"Share photo", function(tag, sender)
local fileName = "facebookshare.jpg"
local imgPath = self:sceenshot(fileName)
local delay = cc.DelayTime:create(2.0)
local share = cc.CallFunc:create(function( ... )
local params = {
dialog = "share_photo",
photo = imgPath,
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
else
print("Can't open dialog for share_open_graph")
end
end)
local seq = cc.Sequence:create(delay, share)
self:runAction(seq)
end},
{"Link message", function(tag, sender)
local params = {
dialog = "message_link",
description = "Cocos2dx-lua is a great game engine",
title = "Cocos2dx-lua",
link = "http://www.cocos2d-x.org",
imageUrl = "http://files.cocos2d-x.org/images/orgsite/logo.png",
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg )
print(msg)
end)
else
print("Can't open dialog for message_link")
end
end},
{"Open graph message", function(tag, sender)
local params = {
dialog = "share_open_graph",
action_type = "cocostestmyfc:share",
preview_property_name = "cocos_document",
title = "Cocos2dx-lua Game Engine",
image = "http://files.cocos2d-x.org/images/orgsite/logo.png",
url = "http://cocos2d-x.org/docs/catalog/en",
description = "cocos document",
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg )
print(msg)
end)
else
print("Can't open dialog for message_open_graph")
end
end},
{"Photo message", function(tag, sender)
local fileName = "facebookmessage.jpg"
local imgPath = self:sceenshot(fileName)
local delay = cc.DelayTime:create(2.0)
local share = cc.CallFunc:create(function()
local params = {
dialog = "message_photo",
photo = imgPath,
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg )
print(msg)
end)
else
print("Can't open dialog for message_photo")
end
end)
local seq = cc.Sequence:create(delay, share)
self:runAction(seq)
end},
{"App request", function(tag, sender)
self:showSecondMenu(1)
end},
}
local y_pos = 0
for i = 1, table.getn(menuItemNames) do
local label = cc.Label:createWithSystemFont(menuItemNames[i][1], "Arial", 22)
local menuItem = cc.MenuItemLabel:create(label)
menuItem:registerScriptTapHandler(menuItemNames[i][2])
y_pos = visibleSize.height - 35 * (i - 1) - 100
menuItem:setPosition(origin.x + 100, y_pos)
menu:addChild(menuItem, 0, i -1 )
end
--create second menu
local secondMenu = cc.Menu:create()
secondMenu:setPosition(cc.p(340, 0))
self:addChild(secondMenu, 0, 2)
end
return TestFBShareScene
| apache-2.0 |
nichwall/cuberite | lib/tolua++/src/bin/lua/verbatim.lua | 44 | 1667 | -- tolua: verbatim class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id: verbatim.lua,v 1.3 2000/01/24 20:41:16 celes Exp $
-- 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.
-- Verbatim class
-- Represents a line translated directed to the binding file.
-- The following filds are stored:
-- line = line text
classVerbatim = {
line = '',
cond = nil, -- condition: where to generate the code (s=suport, r=register)
}
classVerbatim.__index = classVerbatim
setmetatable(classVerbatim,classFeature)
-- preamble verbatim
function classVerbatim:preamble ()
if self.cond == '' then
write(self.line)
end
end
-- support code
function classVerbatim:supcode ()
if strfind(self.cond,'s') then
write(self.line)
write('\n')
end
end
-- register code
function classVerbatim:register (pre)
if strfind(self.cond,'r') then
write(self.line)
end
end
-- Print method
function classVerbatim:print (ident,close)
print(ident.."Verbatim{")
print(ident.." line = '"..self.line.."',")
print(ident.."}"..close)
end
-- Internal constructor
function _Verbatim (t)
setmetatable(t,classVerbatim)
append(t)
return t
end
-- Constructor
-- Expects a string representing the text line
function Verbatim (l,cond)
if strsub(l,1,1) == "'" then
l = strsub(l,2)
elseif strsub(l,1,1) == '$' then
cond = 'sr' -- generates in both suport and register fragments
l = strsub(l,2)
end
return _Verbatim {
line = l,
cond = cond or '',
}
end
| apache-2.0 |
xdemolish/darkstar | scripts/zones/Den_of_Rancor/Zone.lua | 2 | 1798 | -----------------------------------
--
-- Zone: Den_of_Rancor (160)
--
-----------------------------------
package.loaded["scripts/zones/Den_of_Rancor/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/globals/zone");
require("scripts/zones/Den_of_Rancor/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local tomes = {17433087,17433088,17433089,17433090,17433091,17433092};
SetGroundsTome(tomes);
UpdateTreasureSpawnPoint(17433074);
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(196.421,34.595,-60.319,110);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
botfam/botfam | libs/fakeredis.lua | 650 | 40405 | local unpack = table.unpack or unpack
--- Bit operations
local ok,bit
if _VERSION == "Lua 5.3" then
bit = (load [[ return {
band = function(x, y) return x & y end,
bor = function(x, y) return x | y end,
bxor = function(x, y) return x ~ y end,
bnot = function(x) return ~x end,
rshift = function(x, n) return x >> n end,
lshift = function(x, n) return x << n end,
} ]])()
else
ok,bit = pcall(require,"bit")
if not ok then bit = bit32 end
end
assert(type(bit) == "table", "module for bitops not found")
--- default sleep
local default_sleep
do
local ok, mod = pcall(require, "socket")
if ok and type(mod) == "table" then
default_sleep = mod.sleep
else
default_sleep = function(n)
local t0 = os.clock()
while true do
local delta = os.clock() - t0
if (delta < 0) or (delta > n) then break end
end
end
end
end
--- Helpers
local xdefv = function(ktype)
if ktype == "list" then
return {head = 0, tail = 0}
elseif ktype == "zset" then
return {
list = {},
set = {},
}
else return {} end
end
local xgetr = function(self, k, ktype)
if self.data[k] then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
assert(self.data[k].value)
return self.data[k].value
else return xdefv(ktype) end
end
local xgetw = function(self, k, ktype)
if self.data[k] and self.data[k].value then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
else
self.data[k] = {ktype = ktype, value = xdefv(ktype)}
end
return self.data[k].value
end
local empty = function(self, k)
local v, t = self.data[k].value, self.data[k].ktype
if t == nil then
return true
elseif t == "string" then
return not v[1]
elseif (t == "hash") or (t == "set") then
for _,_ in pairs(v) do return false end
return true
elseif t == "list" then
return v.head == v.tail
elseif t == "zset" then
if #v.list == 0 then
for _,_ in pairs(v.set) do error("incoherent") end
return true
else
for _,_ in pairs(v.set) do return(false) end
error("incoherent")
end
else error("unsupported") end
end
local cleanup = function(self, k)
if empty(self, k) then self.data[k] = nil end
end
local is_integer = function(x)
return (type(x) == "number") and (math.floor(x) == x)
end
local overflows = function(n)
return (n > 2^53-1) or (n < -2^53+1)
end
local is_bounded_integer = function(x)
return (is_integer(x) and (not overflows(x)))
end
local is_finite_number = function(x)
return (type(x) == "number") and (x > -math.huge) and (x < math.huge)
end
local toint = function(x)
if type(x) == "string" then x = tonumber(x) end
return is_bounded_integer(x) and x or nil
end
local tofloat = function(x)
if type(x) == "number" then return x end
if type(x) ~= "string" then return nil end
local r = tonumber(x)
if r then return r end
if x == "inf" or x == "+inf" then
return math.huge
elseif x == "-inf" then
return -math.huge
else return nil end
end
local tostr = function(x)
if is_bounded_integer(x) then
return string.format("%d", x)
else return tostring(x) end
end
local char_bitcount = function(x)
assert(
(type(x) == "number") and
(math.floor(x) == x) and
(x >= 0) and (x < 256)
)
local n = 0
while x ~= 0 do
x = bit.band(x, x-1)
n = n+1
end
return n
end
local chkarg = function(x)
if type(x) == "number" then x = tostr(x) end
assert(type(x) == "string")
return x
end
local chkargs = function(n, ...)
local arg = {...}
assert(#arg == n)
for i=1,n do arg[i] = chkarg(arg[i]) end
return unpack(arg)
end
local getargs = function(...)
local arg = {...}
local n = #arg; assert(n > 0)
for i=1,n do arg[i] = chkarg(arg[i]) end
return arg
end
local getargs_as_map = function(...)
local arg, r = getargs(...), {}
assert(#arg%2 == 0)
for i=1,#arg,2 do r[arg[i]] = arg[i+1] end
return r
end
local chkargs_wrap = function(f, n)
assert( (type(f) == "function") and (type(n) == "number") )
return function(self, ...) return f(self, chkargs(n, ...)) end
end
local lset_to_list = function(s)
local r = {}
for v,_ in pairs(s) do r[#r+1] = v end
return r
end
local nkeys = function(x)
local r = 0
for _,_ in pairs(x) do r = r + 1 end
return r
end
--- Commands
-- keys
local del = function(self, ...)
local arg = getargs(...)
local r = 0
for i=1,#arg do
if self.data[arg[i]] then r = r + 1 end
self.data[arg[i]] = nil
end
return r
end
local exists = function(self, k)
return not not self.data[k]
end
local keys = function(self, pattern)
assert(type(pattern) == "string")
-- We want to convert the Redis pattern to a Lua pattern.
-- Start by escaping dashes *outside* character classes.
-- We also need to escape percents here.
local t, p, n = {}, 1, #pattern
local p1, p2
while true do
p1, p2 = pattern:find("%[.+%]", p)
if p1 then
if p1 > p then
t[#t+1] = {true, pattern:sub(p, p1-1)}
end
t[#t+1] = {false, pattern:sub(p1, p2)}
p = p2+1
if p > n then break end
else
t[#t+1] = {true, pattern:sub(p, n)}
break
end
end
for i=1,#t do
if t[i][1] then
t[i] = t[i][2]:gsub("[%%%-]", "%%%0")
else t[i] = t[i][2]:gsub("%%", "%%%%") end
end
-- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]'
-- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is.
-- Wrap in '^$' to enforce bounds.
local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0")
:gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$"
local r = {}
for k,_ in pairs(self.data) do
if k:match(lp) then r[#r+1] = k end
end
return r
end
local _type = function(self, k)
return self.data[k] and self.data[k].ktype or "none"
end
local randomkey = function(self)
local ks = lset_to_list(self.data)
local n = #ks
if n > 0 then
return ks[math.random(1, n)]
else return nil end
end
local rename = function(self, k, k2)
assert((k ~= k2) and self.data[k])
self.data[k2] = self.data[k]
self.data[k] = nil
return true
end
local renamenx = function(self, k, k2)
if self.data[k2] then
return false
else
return rename(self, k, k2)
end
end
-- strings
local getrange, incrby, set
local append = function(self, k, v)
local x = xgetw(self, k, "string")
x[1] = (x[1] or "") .. v
return #x[1]
end
local bitcount = function(self, k, i1, i2)
k = chkarg(k)
local s
if i1 or i2 then
assert(i1 and i2, "ERR syntax error")
s = getrange(self, k, i1, i2)
else
s = xgetr(self, k, "string")[1] or ""
end
local r, bytes = 0,{s:byte(1, -1)}
for i=1,#bytes do
r = r + char_bitcount(bytes[i])
end
return r
end
local bitop = function(self, op, k, ...)
assert(type(op) == "string")
op = op:lower()
assert(
(op == "and") or
(op == "or") or
(op == "xor") or
(op == "not"),
"ERR syntax error"
)
k = chkarg(k)
local arg = {...}
local good_arity = (op == "not") and (#arg == 1) or (#arg > 0)
assert(good_arity, "ERR wrong number of arguments for 'bitop' command")
local l, vals = 0, {}
local s
for i=1,#arg do
s = xgetr(self, arg[i], "string")[1] or ""
if #s > l then l = #s end
vals[i] = s
end
if l == 0 then
del(self, k)
return 0
end
local vector_mt = {__index=function() return 0 end}
for i=1,#vals do
vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt)
end
local r = {}
if op == "not" then
assert(#vals[1] == l)
for i=1,l do
r[i] = bit.band(bit.bnot(vals[1][i]), 0xff)
end
else
local _op = bit["b" .. op]
for i=1,l do
local t = {}
for j=1,#vals do t[j] = vals[j][i] end
r[i] = _op(unpack(t))
end
end
set(self, k, string.char(unpack(r)))
return l
end
local decr = function(self, k)
return incrby(self, k, -1)
end
local decrby = function(self, k, n)
n = toint(n)
assert(n, "ERR value is not an integer or out of range")
return incrby(self, k, -n)
end
local get = function(self, k)
local x = xgetr(self, k, "string")
return x[1]
end
local getbit = function(self, k, offset)
k = chkarg(k)
offset = toint(offset)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
if bytepos >= #s then return 0 end
local char = s:sub(bytepos+1, bytepos+1):byte()
return bit.band(bit.rshift(char, 7-bitpos), 1)
end
getrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetr(self, k, "string")
x = x[1] or ""
if i1 >= 0 then i1 = i1 + 1 end
if i2 >= 0 then i2 = i2 + 1 end
return x:sub(i1, i2)
end
local getset = function(self, k, v)
local r = get(self, k)
set(self, k, v)
return r
end
local incr = function(self, k)
return incrby(self, k, 1)
end
incrby = function(self, k, n)
k, n = chkarg(k), toint(n)
assert(n, "ERR value is not an integer or out of range")
local x = xgetw(self, k, "string")
local i = toint(x[1] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[1] = tostr(i)
return i
end
local incrbyfloat = function(self, k, n)
k, n = chkarg(k), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "string")
local i = tofloat(x[1] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[1] = tostr(i)
return i
end
local mget = function(self, ...)
local arg, r = getargs(...), {}
for i=1,#arg do r[i] = get(self, arg[i]) end
return r
end
local mset = function(self, ...)
local argmap = getargs_as_map(...)
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
local msetnx = function(self, ...)
local argmap = getargs_as_map(...)
for k,_ in pairs(argmap) do
if self.data[k] then return false end
end
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
set = function(self, k, v)
self.data[k] = {ktype = "string", value = {v}}
return true
end
local setbit = function(self, k, offset, b)
k = chkarg(k)
offset, b = toint(offset), toint(b)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
assert(
(b == 0) or (b == 1),
"ERR bit is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
local pad = {s}
for i=2,bytepos+2-#s do pad[i] = "\0" end
s = table.concat(pad)
assert(#s >= bytepos+1)
local before = s:sub(1, bytepos)
local char = s:sub(bytepos+1, bytepos+1):byte()
local after = s:sub(bytepos+2, -1)
local old = bit.band(bit.rshift(char, 7-bitpos), 1)
if b == 1 then
char = bit.bor(bit.lshift(1, 7-bitpos), char)
else
char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char)
end
local r = before .. string.char(char) .. after
set(self, k, r)
return old
end
local setnx = function(self, k, v)
if self.data[k] then
return false
else
return set(self, k, v)
end
end
local setrange = function(self, k, i, s)
local k, s = chkargs(2, k, s)
i = toint(i)
assert(i and (i >= 0))
local x = xgetw(self, k, "string")
local y = x[1] or ""
local ly, ls = #y, #s
if i > ly then -- zero padding
local t = {}
for i=1, i-ly do t[i] = "\0" end
y = y .. table.concat(t) .. s
else
y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly)
end
x[1] = y
return #y
end
local strlen = function(self, k)
local x = xgetr(self, k, "string")
return x[1] and #x[1] or 0
end
-- hashes
local hdel = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local r = 0
local x = xgetw(self, k, "hash")
for i=1,#arg do
if x[arg[i]] then r = r + 1 end
x[arg[i]] = nil
end
cleanup(self, k)
return r
end
local hget
local hexists = function(self, k, k2)
return not not hget(self, k, k2)
end
hget = function(self, k, k2)
local x = xgetr(self, k, "hash")
return x[k2]
end
local hgetall = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,v in pairs(x) do r[_k] = v end
return r
end
local hincrby = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), toint(n)
assert(n, "ERR value is not an integer or out of range")
assert(type(n) == "number")
local x = xgetw(self, k, "hash")
local i = toint(x[k2] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[k2] = tostr(i)
return i
end
local hincrbyfloat = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "hash")
local i = tofloat(x[k2] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[k2] = tostr(i)
return i
end
local hkeys = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,_ in pairs(x) do r[#r+1] = _k end
return r
end
local hlen = function(self, k)
local x = xgetr(self, k, "hash")
return nkeys(x)
end
local hmget = function(self, k, k2s)
k = chkarg(k)
assert((type(k2s) == "table"))
local r = {}
local x = xgetr(self, k, "hash")
for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end
return r
end
local hmset = function(self, k, ...)
k = chkarg(k)
local arg = {...}
if type(arg[1]) == "table" then
assert(#arg == 1)
local x = xgetw(self, k, "hash")
for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end
else
assert(#arg % 2 == 0)
local x = xgetw(self, k, "hash")
local t = getargs(...)
for i=1,#t,2 do x[t[i]] = t[i+1] end
end
return true
end
local hset = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
local r = not x[k2]
x[k2] = v
return r
end
local hsetnx = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
if x[k2] == nil then
x[k2] = v
return true
else
return false
end
end
local hvals = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _,v in pairs(x) do r[#r+1] = v end
return r
end
-- lists (head = left, tail = right)
local _l_real_i = function(x, i)
if i < 0 then
return x.tail+i+1
else
return x.head+i+1
end
end
local _l_len = function(x)
return x.tail - x.head
end
local _block_for = function(self, timeout)
if timeout > 0 then
local sleep = self.sleep or default_sleep
if type(sleep) == "function" then
sleep(timeout)
else
error("sleep function unavailable", 0)
end
else
error("operation would block", 0)
end
end
local rpoplpush
local blpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpoplpush = function(self, k1, k2, timeout)
k1, k2 = chkargs(2, k1, k2)
timeout = toint(timeout)
if not self.data[k1] then _block_for(self, timeout) end
return rpoplpush(self, k1, k2)
end
local lindex = function(self, k, i)
k = chkarg(k)
i = assert(toint(i))
local x = xgetr(self, k, "list")
return x[_l_real_i(x, i)]
end
local linsert = function(self, k, mode, pivot, v)
mode = mode:lower()
assert((mode == "before") or (mode == "after"))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local p = nil
for i=x.head+1, x.tail do
if x[i] == pivot then
p = i
break
end
end
if not p then return -1 end
if mode == "after" then
for i=x.head+1, p do x[i-1] = x[i] end
x.head = x.head - 1
else
for i=x.tail, p, -1 do x[i+1] = x[i] end
x.tail = x.tail + 1
end
x[p] = v
return _l_len(x)
end
local llen = function(self, k)
local x = xgetr(self, k, "list")
return _l_len(x)
end
local lpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return r
end
local lpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x[x.head] = vs[i]
x.head = x.head - 1
end
return _l_len(x)
end
local lpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x[x.head] = v
x.head = x.head - 1
return _l_len(x)
end
local lrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x, r = xgetr(self, k, "list"), {}
i1 = math.max(_l_real_i(x, i1), x.head+1)
i2 = math.min(_l_real_i(x, i2), x.tail)
for i=i1,i2 do r[#r+1] = x[i] end
return r
end
local _lrem_i = function(x, p)
for i=p,x.tail do
x[i] = x[i+1]
end
x.tail = x.tail - 1
end
local _lrem_l = function(x, v, s)
assert(v)
if not s then s = x.head+1 end
for i=s,x.tail do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local _lrem_r = function(x, v, s)
assert(v)
if not s then s = x.tail end
for i=s,x.head+1,-1 do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local lrem = function(self, k, count, v)
k, v = chkarg(k), chkarg(v)
count = assert(toint(count))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local n, last = 0, nil
local op = (count < 0) and _lrem_r or _lrem_l
local limited = (count ~= 0)
count = math.abs(count)
while true do
last = op(x, v, last)
if last then
n = n+1
if limited then
count = count - 1
if count == 0 then break end
end
else break end
end
return n
end
local lset = function(self, k, i, v)
k, v = chkarg(k), chkarg(v)
i = assert(toint(i))
if not self.data[k] then
error("ERR no such key")
end
local x = xgetw(self, k, "list")
local l = _l_len(x)
if i >= l or i < -l then
error("ERR index out of range")
end
x[_l_real_i(x, i)] = v
return true
end
local ltrim = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetw(self, k, "list")
i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2)
for i=x.head+1,i1-1 do x[i] = nil end
for i=i2+1,x.tail do x[i] = nil end
x.head = math.max(i1-1, x.head)
x.tail = math.min(i2, x.tail)
assert(
(x[x.head] == nil) and
(x[x.tail+1] == nil)
)
cleanup(self, k)
return true
end
local rpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return r
end
rpoplpush = function(self, k1, k2)
local v = rpop(self, k1)
if not v then return nil end
lpush(self, k2, v)
return v
end
local rpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x.tail = x.tail + 1
x[x.tail] = vs[i]
end
return _l_len(x)
end
local rpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x.tail = x.tail + 1
x[x.tail] = v
return _l_len(x)
end
-- sets
local sadd = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if not x[arg[i]] then
x[arg[i]] = true
r = r + 1
end
end
return r
end
local scard = function(self, k)
local x = xgetr(self, k, "set")
return nkeys(x)
end
local _sdiff = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
for v,_ in pairs(x) do r[v] = true end
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = nil end
end
return r
end
local sdiff = function(self, k, ...)
return lset_to_list(_sdiff(self, k, ...))
end
local sdiffstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sdiff(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local _sinter = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
local y
for v,_ in pairs(x) do
r[v] = true
for i=1,#arg do
y = xgetr(self, arg[i], "set")
if not y[v] then r[v] = nil; break end
end
end
return r
end
local sinter = function(self, k, ...)
return lset_to_list(_sinter(self, k, ...))
end
local sinterstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sinter(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local sismember = function(self, k, v)
local x = xgetr(self, k, "set")
return not not x[v]
end
local smembers = function(self, k)
local x = xgetr(self, k, "set")
return lset_to_list(x)
end
local smove = function(self, k, k2, v)
local x = xgetr(self, k, "set")
if x[v] then
local y = xgetw(self, k2, "set")
x[v] = nil
y[v] = true
return true
else return false end
end
local spop = function(self, k)
local x, r = xgetw(self, k, "set"), nil
local l = lset_to_list(x)
local n = #l
if n > 0 then
r = l[math.random(1, n)]
x[r] = nil
end
cleanup(self, k)
return r
end
local srandmember = function(self, k, count)
k = chkarg(k)
local x = xgetr(self, k, "set")
local l = lset_to_list(x)
local n = #l
if not count then
if n > 0 then
return l[math.random(1, n)]
else return nil end
end
count = toint(count)
if (count == 0) or (n == 0) then return {} end
if count >= n then return l end
local r = {}
if count > 0 then -- distinct elements
for i=0,count-1 do
r[#r+1] = table.remove(l, math.random(1, n-i))
end
else -- allow repetition
for i=1,-count do
r[#r+1] = l[math.random(1, n)]
end
end
return r
end
local srem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if x[arg[i]] then
x[arg[i]] = nil
r = r + 1
end
end
cleanup(self, k)
return r
end
local _sunion = function(self, ...)
local arg = getargs(...)
local r = {}
local x
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = true end
end
return r
end
local sunion = function(self, k, ...)
return lset_to_list(_sunion(self, k, ...))
end
local sunionstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sunion(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
-- zsets
local _z_p_mt = {
__eq = function(a, b)
if a.v == b.v then
assert(a.s == b.s)
return true
else return false end
end,
__lt = function(a, b)
if a.s == b.s then
return (a.v < b.v)
else
return (a.s < b.s)
end
end,
}
local _z_pair = function(s, v)
assert(
(type(s) == "number") and
(type(v) == "string")
)
local r = {s = s, v = v}
return setmetatable(r, _z_p_mt)
end
local _z_pairs = function(...)
local arg = {...}
assert((#arg > 0) and (#arg % 2 == 0))
local ps = {}
for i=1,#arg,2 do
ps[#ps+1] = _z_pair(
assert(tofloat(arg[i])),
chkarg(arg[i+1])
)
end
return ps
end
local _z_insert = function(x, ix, p)
assert(
(type(x) == "table") and
(type(ix) == "number") and
(type(p) == "table")
)
local l = x.list
table.insert(l, ix, p)
for i=ix+1,#l do
x.set[l[i].v] = x.set[l[i].v] + 1
end
x.set[p.v] = ix
end
local _z_remove = function(x, v)
if not x.set[v] then return false end
local l, ix = x.list, x.set[v]
assert(l[ix].v == v)
table.remove(l, ix)
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - 1
end
x.set[v] = nil
return true
end
local _z_remove_range = function(x, i1, i2)
local l = x.list
i2 = i2 or i1
assert(
(i1 > 0) and
(i2 >= i1) and
(i2 <= #l)
)
local ix, n = i1, i2-i1+1
for i=1,n do
x.set[l[ix].v] = nil
table.remove(l, ix)
end
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - n
end
return n
end
local _z_update = function(x, p)
local l = x.list
local found = _z_remove(x, p.v)
local ix = nil
for i=1,#l do
if l[i] > p then
ix = i; break
end
end
if not ix then ix = #l+1 end
_z_insert(x, ix, p)
return found
end
local _z_coherence = function(x)
local l, s = x.list, x.set
local found, n = {}, 0
for val,pos in pairs(s) do
if found[pos] then return false end
found[pos] = true
n = n + 1
if not (l[pos] and (l[pos].v == val)) then
return false
end
end
if #l ~= n then return false end
for i=1, n-1 do
if l[i].s > l[i+1].s then return false end
end
return true
end
local _z_normrange = function(l, i1, i2)
i1, i2 = assert(toint(i1)), assert(toint(i2))
if i1 < 0 then i1 = #l+i1 end
if i2 < 0 then i2 = #l+i2 end
i1, i2 = math.max(i1+1, 1), i2+1
if (i2 < i1) or (i1 > #l) then return nil end
i2 = math.min(i2, #l)
return i1, i2
end
local _zrbs_opts = function(...)
local arg = {...}
if #arg == 0 then return {} end
local ix, opts = 1, {}
while type(arg[ix]) == "string" do
if arg[ix] == "withscores" then
opts.withscores = true
ix = ix + 1
elseif arg[ix] == "limit" then
opts.limit = {
offset = assert(toint(arg[ix+1])),
count = assert(toint(arg[ix+2])),
}
ix = ix + 3
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.withscores = opts.withscores or _o.withscores
if _o.limit then
opts.limit = {
offset = assert(toint(_o.limit.offset or _o.limit[1])),
count = assert(toint(_o.limit.count or _o.limit[2])),
}
end
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.limit then
assert(
(opts.limit.count >= 0) and
(opts.limit.offset >= 0)
)
end
return opts
end
local _z_store_params = function(dest, numkeys, ...)
dest = chkarg(dest)
numkeys = assert(toint(numkeys))
assert(numkeys > 0)
local arg = {...}
assert(#arg >= numkeys)
local ks = {}
for i=1, numkeys do ks[i] = chkarg(arg[i]) end
local ix, opts = numkeys+1,{}
while type(arg[ix]) == "string" do
if arg[ix] == "weights" then
opts.weights = {}
ix = ix + 1
for i=1, numkeys do
opts.weights[i] = assert(toint(arg[ix]))
ix = ix + 1
end
elseif arg[ix] == "aggregate" then
opts.aggregate = assert(chkarg(arg[ix+1]))
ix = ix + 2
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.weights = opts.weights or _o.weights
opts.aggregate = opts.aggregate or _o.aggregate
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.aggregate then
assert(
(opts.aggregate == "sum") or
(opts.aggregate == "min") or
(opts.aggregate == "max")
)
else opts.aggregate = "sum" end
if opts.weights then
assert(#opts.weights == numkeys)
for i=1,#opts.weights do
assert(type(opts.weights[i]) == "number")
end
else
opts.weights = {}
for i=1, numkeys do opts.weights[i] = 1 end
end
opts.keys = ks
opts.dest = dest
return opts
end
local _zrbs_limits = function(x, s1, s2, descending)
local s1_incl, s2_incl = true, true
if s1:sub(1, 1) == "(" then
s1, s1_incl = s1:sub(2, -1), false
end
s1 = assert(tofloat(s1))
if s2:sub(1, 1) == "(" then
s2, s2_incl = s2:sub(2, -1), false
end
s2 = assert(tofloat(s2))
if descending then
s1, s2 = s2, s1
s1_incl, s2_incl = s2_incl, s1_incl
end
if s2 < s1 then return nil end
local l = x.list
local i1, i2
local fst, lst = l[1].s, l[#l].s
if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end
if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end
if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end
if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end
for i=1,#l do
if (i1 and i2) then break end
if (not i1) then
if l[i].s > s1 then i1 = i end
if s1_incl and l[i].s == s1 then i1 = i end
end
if (not i2) then
if l[i].s > s2 then i2 = i-1 end
if (not s2_incl) and l[i].s == s2 then i2 = i-1 end
end
end
assert(i1 and i2)
if descending then
return #l-i2, #l-i1
else
return i1-1, i2-1
end
end
local dbg_zcoherence = function(self, k)
local x = xgetr(self, k, "zset")
return _z_coherence(x)
end
local zadd = function(self, k, ...)
k = chkarg(k)
local ps = _z_pairs(...)
local x = xgetw(self, k, "zset")
local n = 0
for i=1,#ps do
if not _z_update(x, ps[i]) then n = n+1 end
end
return n
end
local zcard = function(self, k)
local x = xgetr(self, k, "zset")
return #x.list
end
local zcount = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return i2 - i1 + 1
end
local zincrby = function(self, k, n, v)
k,v = chkargs(2, k, v)
n = assert(tofloat(n))
local x = xgetw(self, k, "zset")
local p = x.list[x.set[v]]
local s = p and (p.s + n) or n
_z_update(x, _z_pair(s, v))
return s
end
local zinterstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local aggregate
if params.aggregate == "sum" then
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
aggregate = math.min
elseif params.aggregate == "max" then
aggregate = math.max
else error() end
local y = xgetr(self, params.keys[1], "zset")
local p1, p2
for j=1,#y.list do
p1 = _z_pair(y.list[j].s, y.list[j].v)
_z_update(x, p1)
end
for i=2,#params.keys do
y = xgetr(self, params.keys[i], "zset")
local to_remove, to_update = {}, {}
for j=1,#x.list do
p1 = x.list[j]
if y.set[p1.v] then
p2 = _z_pair(
aggregate(
p1.s,
params.weights[i] * y.list[y.set[p1.v]].s
),
p1.v
)
to_update[#to_update+1] = p2
else
to_remove[#to_remove+1] = p1.v
end
end
for j=1,#to_remove do _z_remove(x, to_remove[j]) end
for j=1,#to_update do _z_update(x, to_update[j]) end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
local _zranger = function(descending)
return function(self, k, i1, i2, opts)
k = chkarg(k)
local withscores = false
if type(opts) == "table" then
withscores = opts.withscores
elseif type(opts) == "string" then
assert(opts:lower() == "withscores")
withscores = true
else assert(opts == nil) end
local x = xgetr(self, k, "zset")
local l = x.list
i1, i2 = _z_normrange(l, i1, i2)
if not i1 then return {} end
local inc = 1
if descending then
i1 = #l - i1 + 1
i2 = #l - i2 + 1
inc = -1
end
local r = {}
if withscores then
for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end
else
for i=i1, i2, inc do r[#r+1] = l[i].v end
end
return r
end
end
local zrange = _zranger(false)
local zrevrange = _zranger(true)
local _zrangerbyscore = function(descending)
return function(self, k, s1, s2, ...)
k, s1, s2 = chkargs(3, k, s1, s2)
local opts = _zrbs_opts(...)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, descending)
if not (i1 and i2) then return {} end
if opts.limit then
if opts.limit.count == 0 then return {} end
i1 = i1 + opts.limit.offset
if i1 > i2 then return {} end
i2 = math.min(i2, i1+opts.limit.count-1)
end
if descending then
return zrevrange(self, k, i1, i2, opts)
else
return zrange(self, k, i1, i2, opts)
end
end
end
local zrangebyscore = _zrangerbyscore(false)
local zrevrangebyscore = _zrangerbyscore(true)
local zrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return r-1
else return nil end
end
local zrem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "zset"), 0
for i=1,#arg do
if _z_remove(x, arg[i]) then r = r + 1 end
end
cleanup(self, k)
return r
end
local zremrangebyrank = function(self, k, i1, i2)
k = chkarg(k)
local x = xgetw(self, k, "zset")
i1, i2 = _z_normrange(x.list, i1, i2)
if not i1 then
cleanup(self, k)
return 0
end
local n = _z_remove_range(x, i1, i2)
cleanup(self, k)
return n
end
local zremrangebyscore = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return zremrangebyrank(self, k, i1, i2)
end
local zrevrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return #x.list-r
else return nil end
end
local zscore = function(self, k, v)
local x = xgetr(self, k, "zset")
local p = x.list[x.set[v]]
if p then
return p.s
else return nil end
end
local zunionstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local default_score, aggregate
if params.aggregate == "sum" then
default_score = 0
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
default_score = math.huge
aggregate = math.min
elseif params.aggregate == "max" then
default_score = -math.huge
aggregate = math.max
else error() end
local y, p1, p2
for i=1,#params.keys do
y = xgetr(self, params.keys[i], "zset")
for j=1,#y.list do
p1 = y.list[j]
p2 = _z_pair(
aggregate(
params.weights[i] * p1.s,
x.set[p1.v] and x.list[x.set[p1.v]].s or default_score
),
p1.v
)
_z_update(x, p2)
end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
-- connection
local echo = function(self, v)
return v
end
local ping = function(self)
return true
end
-- server
local flushdb = function(self)
self.data = {}
return true
end
--- Class
local methods = {
-- keys
del = del, -- (...) -> #removed
exists = chkargs_wrap(exists, 1), -- (k) -> exists?
keys = keys, -- (pattern) -> list of keys
["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none]
randomkey = randomkey, -- () -> [k|nil]
rename = chkargs_wrap(rename, 2), -- (k,k2) -> true
renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2
-- strings
append = chkargs_wrap(append, 2), -- (k,v) -> #new
bitcount = bitcount, -- (k,[start,end]) -> n
bitop = bitop, -- ([and|or|xor|not],k,...)
decr = chkargs_wrap(decr, 1), -- (k) -> new
decrby = decrby, -- (k,n) -> new
get = chkargs_wrap(get, 1), -- (k) -> [v|nil]
getbit = getbit, -- (k,offset) -> b
getrange = getrange, -- (k,start,end) -> string
getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil]
incr = chkargs_wrap(incr, 1), -- (k) -> new
incrby = incrby, -- (k,n) -> new
incrbyfloat = incrbyfloat, -- (k,n) -> new
mget = mget, -- (k1,...) -> {v1,...}
mset = mset, -- (k1,v1,...) -> true
msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k)
set = chkargs_wrap(set, 2), -- (k,v) -> true
setbit = setbit, -- (k,offset,b) -> old
setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?)
setrange = setrange, -- (k,offset,val) -> #new
strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0]
-- hashes
hdel = hdel, -- (k,sk1,...) -> #removed
hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists?
hget = chkargs_wrap(hget,2), -- (k,sk) -> v
hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map
hincrby = hincrby, -- (k,sk,n) -> new
hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new
hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys
hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0]
hmget = hmget, -- (k,{sk1,...}) -> {v1,...}
hmset = hmset, -- (k,{sk1=v1,...}) -> true
hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed?
hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?)
hvals = chkargs_wrap(hvals, 1), -- (k) -> values
-- lists
blpop = blpop, -- (k1,...) -> k,v
brpop = brpop, -- (k1,...) -> k,v
brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v
lindex = lindex, -- (k,i) -> v
linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after)
llen = chkargs_wrap(llen, 1), -- (k) -> #list
lpop = chkargs_wrap(lpop, 1), -- (k) -> v
lpush = lpush, -- (k,v1,...) -> #list (after)
lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after)
lrange = lrange, -- (k,start,stop) -> list
lrem = lrem, -- (k,count,v) -> #removed
lset = lset, -- (k,i,v) -> true
ltrim = ltrim, -- (k,start,stop) -> true
rpop = chkargs_wrap(rpop, 1), -- (k) -> v
rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v
rpush = rpush, -- (k,v1,...) -> #list (after)
rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after)
-- sets
sadd = sadd, -- (k,v1,...) -> #added
scard = chkargs_wrap(scard, 1), -- (k) -> [n|0]
sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...)
sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0
sinter = sinter, -- (k1,...) -> set
sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0
sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member?
smembers = chkargs_wrap(smembers, 1), -- (k) -> set
smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1)
spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil]
srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...]
srem = srem, -- (k,v1,...) -> #removed
sunion = sunion, -- (k1,...) -> set
sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0
-- zsets
zadd = zadd, -- (k,score,member,[score,member,...])
zcard = chkargs_wrap(zcard, 1), -- (k) -> n
zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count
zincrby = zincrby, -- (k,score,v) -> score
zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card
zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts
zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank
zrem = zrem, -- (k,v1,...) -> #removed
zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed
zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed
zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts
zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank
zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score
zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card
-- connection
echo = chkargs_wrap(echo, 1), -- (v) -> v
ping = ping, -- () -> true
-- server
flushall = flushdb, -- () -> true
flushdb = flushdb, -- () -> true
-- debug
dbg_zcoherence = dbg_zcoherence,
}
local new = function()
local r = {data = {}}
return setmetatable(r,{__index = methods})
end
return {
new = new,
}
| gpl-2.0 |
Javaxio/BadRotations | Libs/LibRangeCheck-2.0/LibStub-1.0/tests/test.lua | 86 | 2013 | debugstack = debug.traceback
strmatch = string.match
loadfile("../LibStub.lua")()
local lib, oldMinor = LibStub:NewLibrary("Pants", 1) -- make a new thingy
assert(lib) -- should return the library table
assert(not oldMinor) -- should not return the old minor, since it didn't exist
-- the following is to create data and then be able to check if the same data exists after the fact
function lib:MyMethod()
end
local MyMethod = lib.MyMethod
lib.MyTable = {}
local MyTable = lib.MyTable
local newLib, newOldMinor = LibStub:NewLibrary("Pants", 1) -- try to register a library with the same version, should silently fail
assert(not newLib) -- should not return since out of date
local newLib, newOldMinor = LibStub:NewLibrary("Pants", 0) -- try to register a library with a previous, should silently fail
assert(not newLib) -- should not return since out of date
local newLib, newOldMinor = LibStub:NewLibrary("Pants", 2) -- register a new version
assert(newLib) -- library table
assert(rawequal(newLib, lib)) -- should be the same reference as the previous
assert(newOldMinor == 1) -- should return the minor version of the previous version
assert(rawequal(lib.MyMethod, MyMethod)) -- verify that values were saved
assert(rawequal(lib.MyTable, MyTable)) -- verify that values were saved
local newLib, newOldMinor = LibStub:NewLibrary("Pants", "Blah 3 Blah") -- register a new version with a string minor version (instead of a number)
assert(newLib) -- library table
assert(newOldMinor == 2) -- previous version was 2
local newLib, newOldMinor = LibStub:NewLibrary("Pants", "Blah 4 and please ignore 15 Blah") -- register a new version with a string minor version (instead of a number)
assert(newLib)
assert(newOldMinor == 3) -- previous version was 3 (even though it gave a string)
local newLib, newOldMinor = LibStub:NewLibrary("Pants", 5) -- register a new library, using a normal number instead of a string
assert(newLib)
assert(newOldMinor == 4) -- previous version was 4 (even though it gave a string) | gpl-3.0 |
kissthink/OpenRA | mods/cnc/maps/nod06a/nod06a.lua | 19 | 7647 | NodStartUnitsRight = { 'ltnk', 'bike', 'e1', 'e1', 'e3', 'e3' }
NodStartUnitsLeft = { 'ltnk', 'ltnk', 'bggy', 'e1', 'e1', 'e1', 'e1', 'e3', 'e3', 'e3', 'e3' }
Chn1Units = { 'e1', 'e1', 'e1', 'e1', 'e1' }
Chn2Units = { 'e2', 'e2', 'e2', 'e2', 'e2' }
Obj2Units = { 'ltnk', 'bike', 'e1', 'e1', 'e1' }
Chn3CellTriggerActivator = { CPos.New(49,58), CPos.New(48,58), CPos.New(49,57), CPos.New(48,57), CPos.New(49,56), CPos.New(48,56), CPos.New(49,55), CPos.New(48,55) }
DzneCellTriggerActivator = { CPos.New(61,45), CPos.New(60,45), CPos.New(59,45), CPos.New(58,45), CPos.New(57,45), CPos.New(61,44), CPos.New(60,44), CPos.New(59,44), CPos.New(58,44), CPos.New(57,44), CPos.New(61,43), CPos.New(60,43), CPos.New(58,43), CPos.New(57,43), CPos.New(61,42), CPos.New(60,42), CPos.New(59,42), CPos.New(58,42), CPos.New(57,42), CPos.New(61,41), CPos.New(60,41), CPos.New(59,41), CPos.New(58,41), CPos.New(57,41) }
Win1CellTriggerActivator = { CPos.New(59,43) }
Win2CellTriggerActivator = { CPos.New(54,58), CPos.New(53,58), CPos.New(52,58), CPos.New(54,57), CPos.New(53,57), CPos.New(52,57), CPos.New(54,56), CPos.New(53,56), CPos.New(52,56), CPos.New(54,55), CPos.New(53,55), CPos.New(52,55) }
Grd2ActorTriggerActivator = { Guard1, Guard2, Guard3 }
Atk1ActorTriggerActivator = { Atk1Activator1, Atk1Activator2 }
Atk2ActorTriggerActivator = { Atk2Activator1, Atk2Activator2 }
Chn1ActorTriggerActivator = { Chn1Activator1, Chn1Activator2, Chn1Activator3, Chn1Activator4, Chn1Activator5 }
Chn2ActorTriggerActivator = { Chn2Activator1, Chn2Activator2, Chn2Activator3 }
Obj2ActorTriggerActivator = { Chn1Activator1, Chn1Activator2, Chn1Activator3, Chn1Activator4, Chn1Activator5, Chn2Activator1, Chn2Activator2, Chn2Activator3, Atk3Activator }
Chn1Waypoints = { ChnEntry.Location, waypoint5.Location }
Chn2Waypoints = { ChnEntry.Location, waypoint6.Location }
Gdi3Waypoints = { waypoint1, waypoint3, waypoint7, waypoint8, waypoint9 }
Gdi4Waypoints = { waypoint4, waypoint10, waypoint9, waypoint11, waypoint9, waypoint10 }
Gdi5Waypoints = { waypoint1, waypoint4 }
Gdi6Waypoints = { waypoint2, waypoints3 }
Grd1TriggerFunctionTime = DateTime.Seconds(3)
Grd1TriggerFunction = function()
MyActors = Utils.Take(2, GDI.GetActorsByType('mtnk'))
Utils.Do(MyActors, function(actor)
MovementAndHunt(actor, Gdi3Waypoints)
end)
end
Grd2TriggerFunction = function()
if not Grd2Switch then
for type, count in pairs({ ['e1'] = 2, ['e2'] = 1, ['jeep'] = 1 }) do
MyActors = Utils.Take(count, GDI.GetActorsByType(type))
Utils.Do(MyActors, function(actor)
MovementAndHunt(actor, Gdi4Waypoints)
end)
end
Grd2Swicth = true
end
end
Atk1TriggerFunction = function()
if not Atk1Switch then
for type, count in pairs({ ['e1'] = 3, ['e2'] = 3, ['jeep'] = 1 }) do
MyActors = Utils.Take(count, GDI.GetActorsByType(type))
Utils.Do(MyActors, function(actor)
MovementAndHunt(actor, Gdi5Waypoints)
end)
end
Atk1Switch = true
end
end
Atk2TriggerFunction = function()
if not Atk2Switch then
for type, count in pairs({ ['mtnk'] = 1, ['jeep'] = 1 }) do
MyActors = Utils.Take(count, GDI.GetActorsByType(type))
Utils.Do(MyActors, function(actor)
MovementAndHunt(actor, Gdi6Waypoints)
end)
end
Atk2Switch = true
end
end
Atk3TriggerFunction = function()
if not Atk3Switch then
Atk3Switch = true
if not Radar.IsDead then
local targets = Nod.GetGroundAttackers()
local target = targets[DateTime.GameTime % #targets + 1].CenterPosition
if target then
Radar.SendAirstrike(target, false, Facing.NorthEast + 4)
end
end
end
end
Chn1TriggerFunction = function()
local cargo = Reinforcements.ReinforceWithTransport(GDI, 'tran', Chn1Units, Chn1Waypoints, { waypoint14.Location })[2]
Utils.Do(cargo, function(actor)
IdleHunt(actor)
end)
end
Chn2TriggerFunction = function()
local cargo = Reinforcements.ReinforceWithTransport(GDI, 'tran', Chn2Units, Chn2Waypoints, { waypoint14.Location })[2]
Utils.Do(cargo, function(actor)
IdleHunt(actor)
end)
end
Obj2TriggerFunction = function()
Nod.MarkCompletedObjective(NodObjective2)
Reinforcements.Reinforce(Nod, Obj2Units, { Obj2UnitsEntry.Location, waypoint13.Location }, 15)
end
MovementAndHunt = function(unit, waypoints)
if unit ~= nil then
Utils.Do(waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
IdleHunt(unit)
end
end
InsertNodUnits = function()
Camera.Position = UnitsRallyRight.CenterPosition
Media.PlaySpeechNotification(Nod, "Reinforce")
Reinforcements.Reinforce(Nod, NodStartUnitsLeft, { UnitsEntryLeft.Location, UnitsRallyLeft.Location }, 15)
Reinforcements.Reinforce(Nod, NodStartUnitsRight, { UnitsEntryRight.Location, UnitsRallyRight.Location }, 15)
end
WorldLoaded = function()
GDI = Player.GetPlayer("GDI")
Nod = Player.GetPlayer("Nod")
Trigger.OnObjectiveAdded(Nod, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(Nod, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(Nod, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerWon(Nod, function()
Media.PlaySpeechNotification(Nod, "Win")
end)
Trigger.OnPlayerLost(Nod, function()
Media.PlaySpeechNotification(Nod, "Lose")
end)
NodObjective1 = Nod.AddPrimaryObjective("Steal the GDI nuclear detonator.")
NodObjective2 = Nod.AddSecondaryObjective("Destroy the houses of the GDI supporters\nin the village.")
GDIObjective = GDI.AddPrimaryObjective("Stop the Nod taskforce from escaping with the detonator.")
InsertNodUnits()
Trigger.AfterDelay(Grd1TriggerFunctionTime, Grd1TriggerFunction)
Utils.Do(Grd2ActorTriggerActivator, function(actor)
Trigger.OnDiscovered(actor, Grd2TriggerFunction)
end)
OnAnyDamaged(Atk1ActorTriggerActivator, Atk1TriggerFunction)
OnAnyDamaged(Atk2ActorTriggerActivator, Atk2TriggerFunction)
Trigger.OnDamaged(Atk3Activator, Atk3TriggerFunction)
Trigger.OnAllKilled(Chn1ActorTriggerActivator, Chn1TriggerFunction)
Trigger.OnAllKilled(Chn2ActorTriggerActivator, Chn2TriggerFunction)
Trigger.OnEnteredFootprint(Chn3CellTriggerActivator, function(a, id)
if a.Owner == Nod then
Media.PlaySpeechNotification(Nod, "Reinforce")
Reinforcements.ReinforceWithTransport(Nod, 'tran', nil, { ChnEntry.Location, waypoint17.Location }, nil, nil, nil)
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnEnteredFootprint(DzneCellTriggerActivator, function(a, id)
if a.Owner == Nod then
Actor.Create('flare', true, { Owner = Nod, Location = waypoint17.Location })
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnAllRemovedFromWorld(Obj2ActorTriggerActivator, Obj2TriggerFunction)
Trigger.OnEnteredFootprint(Win1CellTriggerActivator, function(a, id)
if a.Owner == Nod then
NodObjective3 = Nod.AddPrimaryObjective("Move to the evacuation point.")
Nod.MarkCompletedObjective(NodObjective1)
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnEnteredFootprint(Win2CellTriggerActivator, function(a, id)
if a.Owner == Nod and NodObjective3 then
Nod.MarkCompletedObjective(NodObjective3)
Trigger.RemoveFootprintTrigger(id)
end
end)
end
Tick = function()
if DateTime.GameTime > 2 and Nod.HasNoRequiredUnits() then
GDI.MarkCompletedObjective(GDIObjective)
end
end
IdleHunt = function(unit)
if not unit.IsDead then
Trigger.OnIdle(unit, unit.Hunt)
end
end
OnAnyDamaged = function(actors, func)
Utils.Do(actors, function(actor)
Trigger.OnDamaged(actor, func)
end)
end
| gpl-3.0 |
simonswine/chdkptp | lua/ustime.lua | 1 | 2556 | --[[
Copyright (C) 2010-2011 <reyalp (at) gmail dot com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--]]
--[[
utilities for working with microsecond time provided by sys.gettimeofday
depends on chdkpt sys
in some windows variants, sys.gettimeofday will return much lower precision, ~15ms
]]
local proto={}
local mt={
__index=function(t,key)
return proto[key];
end,
-- TODO can add some more methods so regular operators work
}
local ustime={}
--[[
create a new ustime, defaulting to current time
]]
function ustime.new(sec,usec)
-- TODO user values are not normalized
local t={sec=sec,usec=usec}
setmetatable(t,mt)
if not sec then
t:get()
elseif not usec then
t.usec=0
end
return t;
end
--[[
return difference as number of microseconds
if only one time is given, subtract from current time
no provision is made for overflow
]]
function ustime.diff(t1,t0)
if not t0 then
t0 = t1
t1 = ustime.new()
end
return (t1.sec - t0.sec)*1000000 + t1.usec - t0.usec
end
--[[
difference in ms
]]
function ustime.diffms(t1,t0)
return ustime.diff(t1,t0)/1000
end
--[[
formate with os.date with additional formats
%_m = milliseconds part
%_u = microseconds part
]]
function ustime.format(t,fmt)
if fmt then
fmt = fmt:gsub('%%_([um])',function(c)
if c == 'u' then
return string.format('%06d',t.usec)
end
if c == 'm' then
return string.format('%03d',t.usec/1000)
end
end)
end
return os.date(fmt,t.sec)
end
function proto:get()
self.sec,self.usec = sys.gettimeofday()
end
-- assumes number is double
-- TODO why didn't I just do the whole thing in floating point ?
function proto:normalize()
local v = (self.sec + self.usec/1000000)
self.sec = math.floor(v)
self.usec = (v - self.sec)*1000000
end
function proto:addus(us)
self.usec = self.usec + us
self:normalize()
end
function proto:addms(ms)
self:addus(1000*ms)
end
proto.diff = ustime.diff
proto.diffms = ustime.diffms
proto.format = ustime.format
return ustime
| gpl-2.0 |
xdemolish/darkstar | scripts/zones/Nashmau/npcs/Fhe_Maksojha.lua | 19 | 2153 | -----------------------------------
-- Area: Nashmau
-- NPC: Fhe Maksojha
-- Type: Standard NPC
-- @pos 19.084 -7 71.287 53
-----------------------------------
package.loaded["scripts/zones/Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Nashmau/TextIDs");
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local notmeanttobe = player:getQuestStatus(AHT_URHGAN,NOT_MEANT_TO_BE);
local notMeantToBeProg = player:getVar("notmeanttobeCS");
if(notmeanttobe == QUEST_AVAILABLE) then
player:startEvent(0x0125);
elseif(notMeantToBeProg == 1) then
player:startEvent(0x0127);
elseif(notMeantToBeProg == 2) then
player:startEvent(0x0126);
elseif(notMeantToBeProg == 3) then
player:startEvent(0x0128);
elseif(notMeantToBeProg == 5) then
player:startEvent(0x0129);
elseif(notmeanttobe == QUEST_COMPLETED) then
player:startEvent(0x012a);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if(csid == 0x0125) then
player:setVar("notmeanttobeCS",1);
player:addQuest(AHT_URHGAN,NOT_MEANT_TO_BE);
elseif(csid == 0x0126) then
player:setVar("notmeanttobeCS",3);
elseif(csid == 0x0129) then
if(player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINEDX,2187,3);
else
player:setVar("notmeanttobeCS",0);
player:addItem(2187,3);
player:messageSpecial(ITEM_OBTAINEDX,2187,3);
player:completeQuest(AHT_URHGAN,NOT_MEANT_TO_BE);
end
end
end;
| gpl-3.0 |
samael65535/quick-ng | cocos/scripting/lua-bindings/auto/api/ComAudio.lua | 8 | 6116 |
--------------------------------
-- @module ComAudio
-- @extend Component
-- @parent_module ccs
--------------------------------
--
-- @function [parent=#ComAudio] stopAllEffects
-- @param self
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] getEffectsVolume
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
--
-- @function [parent=#ComAudio] stopEffect
-- @param self
-- @param #unsigned int nSoundId
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] getBackgroundMusicVolume
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
--
-- @function [parent=#ComAudio] willPlayBackgroundMusic
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#ComAudio] setBackgroundMusicVolume
-- @param self
-- @param #float volume
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] end
-- @param self
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
-- @overload self
-- @overload self, bool
-- @function [parent=#ComAudio] stopBackgroundMusic
-- @param self
-- @param #bool bReleaseData
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] pauseBackgroundMusic
-- @param self
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] isBackgroundMusicPlaying
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#ComAudio] isLoop
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#ComAudio] resumeAllEffects
-- @param self
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] pauseAllEffects
-- @param self
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] preloadBackgroundMusic
-- @param self
-- @param #char pszFilePath
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
-- @overload self, char
-- @overload self, char, bool
-- @overload self
-- @function [parent=#ComAudio] playBackgroundMusic
-- @param self
-- @param #char pszFilePath
-- @param #bool bLoop
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
-- @overload self, char
-- @overload self, char, bool
-- @overload self
-- @function [parent=#ComAudio] playEffect
-- @param self
-- @param #char pszFilePath
-- @param #bool bLoop
-- @return unsigned int#unsigned int ret (return value: unsigned int)
--------------------------------
--
-- @function [parent=#ComAudio] preloadEffect
-- @param self
-- @param #char pszFilePath
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] setLoop
-- @param self
-- @param #bool bLoop
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] unloadEffect
-- @param self
-- @param #char pszFilePath
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] rewindBackgroundMusic
-- @param self
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] pauseEffect
-- @param self
-- @param #unsigned int nSoundId
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] resumeBackgroundMusic
-- @param self
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] setFile
-- @param self
-- @param #char pszFilePath
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] setEffectsVolume
-- @param self
-- @param #float volume
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] getFile
-- @param self
-- @return char#char ret (return value: char)
--------------------------------
--
-- @function [parent=#ComAudio] resumeEffect
-- @param self
-- @param #unsigned int nSoundId
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] create
-- @param self
-- @return ComAudio#ComAudio ret (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] createInstance
-- @param self
-- @return Ref#Ref ret (return value: cc.Ref)
--------------------------------
--
-- @function [parent=#ComAudio] setEnabled
-- @param self
-- @param #bool b
-- @return ComAudio#ComAudio self (return value: ccs.ComAudio)
--------------------------------
--
-- @function [parent=#ComAudio] isEnabled
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#ComAudio] serialize
-- @param self
-- @param #void r
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#ComAudio] init
-- @param self
-- @return bool#bool ret (return value: bool)
return nil
| mit |
nazrhyn/epgp-tep | libs/AceAddon-3.0/AceAddon-3.0.lua | 66 | 25788 | --- **AceAddon-3.0** provides a template for creating addon objects.
-- It'll provide you with a set of callback functions that allow you to simplify the loading
-- process of your addon.\\
-- Callbacks provided are:\\
-- * **OnInitialize**, which is called directly after the addon is fully loaded.
-- * **OnEnable** which gets called during the PLAYER_LOGIN event, when most of the data provided by the game is already present.
-- * **OnDisable**, which is only called when your addon is manually being disabled.
-- @usage
-- -- A small (but complete) addon, that doesn't do anything,
-- -- but shows usage of the callbacks.
-- local MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")
--
-- function MyAddon:OnInitialize()
-- -- do init tasks here, like loading the Saved Variables,
-- -- or setting up slash commands.
-- end
--
-- function MyAddon:OnEnable()
-- -- Do more initialization here, that really enables the use of your addon.
-- -- Register Events, Hook functions, Create Frames, Get information from
-- -- the game that wasn't available in OnInitialize
-- end
--
-- function MyAddon:OnDisable()
-- -- Unhook, Unregister Events, Hide frames that you created.
-- -- You would probably only use an OnDisable if you want to
-- -- build a "standby" mode, or be able to toggle modules on/off.
-- end
-- @class file
-- @name AceAddon-3.0.lua
-- @release $Id: AceAddon-3.0.lua 1084 2013-04-27 20:14:11Z nevcairiel $
local MAJOR, MINOR = "AceAddon-3.0", 12
local AceAddon, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceAddon then return end -- No Upgrade needed.
AceAddon.frame = AceAddon.frame or CreateFrame("Frame", "AceAddon30Frame") -- Our very own frame
AceAddon.addons = AceAddon.addons or {} -- addons in general
AceAddon.statuses = AceAddon.statuses or {} -- statuses of addon.
AceAddon.initializequeue = AceAddon.initializequeue or {} -- addons that are new and not initialized
AceAddon.enablequeue = AceAddon.enablequeue or {} -- addons that are initialized and waiting to be enabled
AceAddon.embeds = AceAddon.embeds or setmetatable({}, {__index = function(tbl, key) tbl[key] = {} return tbl[key] end }) -- contains a list of libraries embedded in an addon
-- Lua APIs
local tinsert, tconcat, tremove = table.insert, table.concat, table.remove
local fmt, tostring = string.format, tostring
local select, pairs, next, type, unpack = select, pairs, next, type, unpack
local loadstring, assert, error = loadstring, assert, error
local setmetatable, getmetatable, rawset, rawget = setmetatable, getmetatable, rawset, rawget
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: LibStub, IsLoggedIn, geterrorhandler
--[[
xpcall safecall implementation
]]
local xpcall = xpcall
local function errorhandler(err)
return geterrorhandler()(err)
end
local function CreateDispatcher(argCount)
local code = [[
local xpcall, eh = ...
local method, ARGS
local function call() return method(ARGS) end
local function dispatch(func, ...)
method = func
if not method then return end
ARGS = ...
return xpcall(call, eh)
end
return dispatch
]]
local ARGS = {}
for i = 1, argCount do ARGS[i] = "arg"..i end
code = code:gsub("ARGS", tconcat(ARGS, ", "))
return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(xpcall, errorhandler)
end
local Dispatchers = setmetatable({}, {__index=function(self, argCount)
local dispatcher = CreateDispatcher(argCount)
rawset(self, argCount, dispatcher)
return dispatcher
end})
Dispatchers[0] = function(func)
return xpcall(func, errorhandler)
end
local function safecall(func, ...)
-- we check to see if the func is passed is actually a function here and don't error when it isn't
-- this safecall is used for optional functions like OnInitialize OnEnable etc. When they are not
-- present execution should continue without hinderance
if type(func) == "function" then
return Dispatchers[select('#', ...)](func, ...)
end
end
-- local functions that will be implemented further down
local Enable, Disable, EnableModule, DisableModule, Embed, NewModule, GetModule, GetName, SetDefaultModuleState, SetDefaultModuleLibraries, SetEnabledState, SetDefaultModulePrototype
-- used in the addon metatable
local function addontostring( self ) return self.name end
-- Check if the addon is queued for initialization
local function queuedForInitialization(addon)
for i = 1, #AceAddon.initializequeue do
if AceAddon.initializequeue[i] == addon then
return true
end
end
return false
end
--- Create a new AceAddon-3.0 addon.
-- Any libraries you specified will be embeded, and the addon will be scheduled for
-- its OnInitialize and OnEnable callbacks.
-- The final addon object, with all libraries embeded, will be returned.
-- @paramsig [object ,]name[, lib, ...]
-- @param object Table to use as a base for the addon (optional)
-- @param name Name of the addon object to create
-- @param lib List of libraries to embed into the addon
-- @usage
-- -- Create a simple addon object
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceEvent-3.0")
--
-- -- Create a Addon object based on the table of a frame
-- local MyFrame = CreateFrame("Frame")
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon(MyFrame, "MyAddon", "AceEvent-3.0")
function AceAddon:NewAddon(objectorname, ...)
local object,name
local i=1
if type(objectorname)=="table" then
object=objectorname
name=...
i=2
else
name=objectorname
end
if type(name)~="string" then
error(("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - string expected got '%s'."):format(type(name)), 2)
end
if self.addons[name] then
error(("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - Addon '%s' already exists."):format(name), 2)
end
object = object or {}
object.name = name
local addonmeta = {}
local oldmeta = getmetatable(object)
if oldmeta then
for k, v in pairs(oldmeta) do addonmeta[k] = v end
end
addonmeta.__tostring = addontostring
setmetatable( object, addonmeta )
self.addons[name] = object
object.modules = {}
object.orderedModules = {}
object.defaultModuleLibraries = {}
Embed( object ) -- embed NewModule, GetModule methods
self:EmbedLibraries(object, select(i,...))
-- add to queue of addons to be initialized upon ADDON_LOADED
tinsert(self.initializequeue, object)
return object
end
--- Get the addon object by its name from the internal AceAddon registry.
-- Throws an error if the addon object cannot be found (except if silent is set).
-- @param name unique name of the addon object
-- @param silent if true, the addon is optional, silently return nil if its not found
-- @usage
-- -- Get the Addon
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
function AceAddon:GetAddon(name, silent)
if not silent and not self.addons[name] then
error(("Usage: GetAddon(name): 'name' - Cannot find an AceAddon '%s'."):format(tostring(name)), 2)
end
return self.addons[name]
end
-- - Embed a list of libraries into the specified addon.
-- This function will try to embed all of the listed libraries into the addon
-- and error if a single one fails.
--
-- **Note:** This function is for internal use by :NewAddon/:NewModule
-- @paramsig addon, [lib, ...]
-- @param addon addon object to embed the libs in
-- @param lib List of libraries to embed into the addon
function AceAddon:EmbedLibraries(addon, ...)
for i=1,select("#", ... ) do
local libname = select(i, ...)
self:EmbedLibrary(addon, libname, false, 4)
end
end
-- - Embed a library into the addon object.
-- This function will check if the specified library is registered with LibStub
-- and if it has a :Embed function to call. It'll error if any of those conditions
-- fails.
--
-- **Note:** This function is for internal use by :EmbedLibraries
-- @paramsig addon, libname[, silent[, offset]]
-- @param addon addon object to embed the library in
-- @param libname name of the library to embed
-- @param silent marks an embed to fail silently if the library doesn't exist (optional)
-- @param offset will push the error messages back to said offset, defaults to 2 (optional)
function AceAddon:EmbedLibrary(addon, libname, silent, offset)
local lib = LibStub:GetLibrary(libname, true)
if not lib and not silent then
error(("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Cannot find a library instance of %q."):format(tostring(libname)), offset or 2)
elseif lib and type(lib.Embed) == "function" then
lib:Embed(addon)
tinsert(self.embeds[addon], libname)
return true
elseif lib then
error(("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Library '%s' is not Embed capable"):format(libname), offset or 2)
end
end
--- Return the specified module from an addon object.
-- Throws an error if the addon object cannot be found (except if silent is set)
-- @name //addon//:GetModule
-- @paramsig name[, silent]
-- @param name unique name of the module
-- @param silent if true, the module is optional, silently return nil if its not found (optional)
-- @usage
-- -- Get the Addon
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- -- Get the Module
-- MyModule = MyAddon:GetModule("MyModule")
function GetModule(self, name, silent)
if not self.modules[name] and not silent then
error(("Usage: GetModule(name, silent): 'name' - Cannot find module '%s'."):format(tostring(name)), 2)
end
return self.modules[name]
end
local function IsModuleTrue(self) return true end
--- Create a new module for the addon.
-- The new module can have its own embeded libraries and/or use a module prototype to be mixed into the module.\\
-- A module has the same functionality as a real addon, it can have modules of its own, and has the same API as
-- an addon object.
-- @name //addon//:NewModule
-- @paramsig name[, prototype|lib[, lib, ...]]
-- @param name unique name of the module
-- @param prototype object to derive this module from, methods and values from this table will be mixed into the module (optional)
-- @param lib List of libraries to embed into the addon
-- @usage
-- -- Create a module with some embeded libraries
-- MyModule = MyAddon:NewModule("MyModule", "AceEvent-3.0", "AceHook-3.0")
--
-- -- Create a module with a prototype
-- local prototype = { OnEnable = function(self) print("OnEnable called!") end }
-- MyModule = MyAddon:NewModule("MyModule", prototype, "AceEvent-3.0", "AceHook-3.0")
function NewModule(self, name, prototype, ...)
if type(name) ~= "string" then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - string expected got '%s'."):format(type(name)), 2) end
if type(prototype) ~= "string" and type(prototype) ~= "table" and type(prototype) ~= "nil" then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'prototype' - table (prototype), string (lib) or nil expected got '%s'."):format(type(prototype)), 2) end
if self.modules[name] then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - Module '%s' already exists."):format(name), 2) end
-- modules are basically addons. We treat them as such. They will be added to the initializequeue properly as well.
-- NewModule can only be called after the parent addon is present thus the modules will be initialized after their parent is.
local module = AceAddon:NewAddon(fmt("%s_%s", self.name or tostring(self), name))
module.IsModule = IsModuleTrue
module:SetEnabledState(self.defaultModuleState)
module.moduleName = name
if type(prototype) == "string" then
AceAddon:EmbedLibraries(module, prototype, ...)
else
AceAddon:EmbedLibraries(module, ...)
end
AceAddon:EmbedLibraries(module, unpack(self.defaultModuleLibraries))
if not prototype or type(prototype) == "string" then
prototype = self.defaultModulePrototype or nil
end
if type(prototype) == "table" then
local mt = getmetatable(module)
mt.__index = prototype
setmetatable(module, mt) -- More of a Base class type feel.
end
safecall(self.OnModuleCreated, self, module) -- Was in Ace2 and I think it could be a cool thing to have handy.
self.modules[name] = module
tinsert(self.orderedModules, module)
return module
end
--- Returns the real name of the addon or module, without any prefix.
-- @name //addon//:GetName
-- @paramsig
-- @usage
-- print(MyAddon:GetName())
-- -- prints "MyAddon"
function GetName(self)
return self.moduleName or self.name
end
--- Enables the Addon, if possible, return true or false depending on success.
-- This internally calls AceAddon:EnableAddon(), thus dispatching a OnEnable callback
-- and enabling all modules of the addon (unless explicitly disabled).\\
-- :Enable() also sets the internal `enableState` variable to true
-- @name //addon//:Enable
-- @paramsig
-- @usage
-- -- Enable MyModule
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Enable()
function Enable(self)
self:SetEnabledState(true)
-- nevcairiel 2013-04-27: don't enable an addon/module if its queued for init still
-- it'll be enabled after the init process
if not queuedForInitialization(self) then
return AceAddon:EnableAddon(self)
end
end
--- Disables the Addon, if possible, return true or false depending on success.
-- This internally calls AceAddon:DisableAddon(), thus dispatching a OnDisable callback
-- and disabling all modules of the addon.\\
-- :Disable() also sets the internal `enableState` variable to false
-- @name //addon//:Disable
-- @paramsig
-- @usage
-- -- Disable MyAddon
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyAddon:Disable()
function Disable(self)
self:SetEnabledState(false)
return AceAddon:DisableAddon(self)
end
--- Enables the Module, if possible, return true or false depending on success.
-- Short-hand function that retrieves the module via `:GetModule` and calls `:Enable` on the module object.
-- @name //addon//:EnableModule
-- @paramsig name
-- @usage
-- -- Enable MyModule using :GetModule
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Enable()
--
-- -- Enable MyModule using the short-hand
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyAddon:EnableModule("MyModule")
function EnableModule(self, name)
local module = self:GetModule( name )
return module:Enable()
end
--- Disables the Module, if possible, return true or false depending on success.
-- Short-hand function that retrieves the module via `:GetModule` and calls `:Disable` on the module object.
-- @name //addon//:DisableModule
-- @paramsig name
-- @usage
-- -- Disable MyModule using :GetModule
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Disable()
--
-- -- Disable MyModule using the short-hand
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyAddon:DisableModule("MyModule")
function DisableModule(self, name)
local module = self:GetModule( name )
return module:Disable()
end
--- Set the default libraries to be mixed into all modules created by this object.
-- Note that you can only change the default module libraries before any module is created.
-- @name //addon//:SetDefaultModuleLibraries
-- @paramsig lib[, lib, ...]
-- @param lib List of libraries to embed into the addon
-- @usage
-- -- Create the addon object
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")
-- -- Configure default libraries for modules (all modules need AceEvent-3.0)
-- MyAddon:SetDefaultModuleLibraries("AceEvent-3.0")
-- -- Create a module
-- MyModule = MyAddon:NewModule("MyModule")
function SetDefaultModuleLibraries(self, ...)
if next(self.modules) then
error("Usage: SetDefaultModuleLibraries(...): cannot change the module defaults after a module has been registered.", 2)
end
self.defaultModuleLibraries = {...}
end
--- Set the default state in which new modules are being created.
-- Note that you can only change the default state before any module is created.
-- @name //addon//:SetDefaultModuleState
-- @paramsig state
-- @param state Default state for new modules, true for enabled, false for disabled
-- @usage
-- -- Create the addon object
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")
-- -- Set the default state to "disabled"
-- MyAddon:SetDefaultModuleState(false)
-- -- Create a module and explicilty enable it
-- MyModule = MyAddon:NewModule("MyModule")
-- MyModule:Enable()
function SetDefaultModuleState(self, state)
if next(self.modules) then
error("Usage: SetDefaultModuleState(state): cannot change the module defaults after a module has been registered.", 2)
end
self.defaultModuleState = state
end
--- Set the default prototype to use for new modules on creation.
-- Note that you can only change the default prototype before any module is created.
-- @name //addon//:SetDefaultModulePrototype
-- @paramsig prototype
-- @param prototype Default prototype for the new modules (table)
-- @usage
-- -- Define a prototype
-- local prototype = { OnEnable = function(self) print("OnEnable called!") end }
-- -- Set the default prototype
-- MyAddon:SetDefaultModulePrototype(prototype)
-- -- Create a module and explicitly Enable it
-- MyModule = MyAddon:NewModule("MyModule")
-- MyModule:Enable()
-- -- should print "OnEnable called!" now
-- @see NewModule
function SetDefaultModulePrototype(self, prototype)
if next(self.modules) then
error("Usage: SetDefaultModulePrototype(prototype): cannot change the module defaults after a module has been registered.", 2)
end
if type(prototype) ~= "table" then
error(("Usage: SetDefaultModulePrototype(prototype): 'prototype' - table expected got '%s'."):format(type(prototype)), 2)
end
self.defaultModulePrototype = prototype
end
--- Set the state of an addon or module
-- This should only be called before any enabling actually happend, e.g. in/before OnInitialize.
-- @name //addon//:SetEnabledState
-- @paramsig state
-- @param state the state of an addon or module (enabled=true, disabled=false)
function SetEnabledState(self, state)
self.enabledState = state
end
--- Return an iterator of all modules associated to the addon.
-- @name //addon//:IterateModules
-- @paramsig
-- @usage
-- -- Enable all modules
-- for name, module in MyAddon:IterateModules() do
-- module:Enable()
-- end
local function IterateModules(self) return pairs(self.modules) end
-- Returns an iterator of all embeds in the addon
-- @name //addon//:IterateEmbeds
-- @paramsig
local function IterateEmbeds(self) return pairs(AceAddon.embeds[self]) end
--- Query the enabledState of an addon.
-- @name //addon//:IsEnabled
-- @paramsig
-- @usage
-- if MyAddon:IsEnabled() then
-- MyAddon:Disable()
-- end
local function IsEnabled(self) return self.enabledState end
local mixins = {
NewModule = NewModule,
GetModule = GetModule,
Enable = Enable,
Disable = Disable,
EnableModule = EnableModule,
DisableModule = DisableModule,
IsEnabled = IsEnabled,
SetDefaultModuleLibraries = SetDefaultModuleLibraries,
SetDefaultModuleState = SetDefaultModuleState,
SetDefaultModulePrototype = SetDefaultModulePrototype,
SetEnabledState = SetEnabledState,
IterateModules = IterateModules,
IterateEmbeds = IterateEmbeds,
GetName = GetName,
}
local function IsModule(self) return false end
local pmixins = {
defaultModuleState = true,
enabledState = true,
IsModule = IsModule,
}
-- Embed( target )
-- target (object) - target object to embed aceaddon in
--
-- this is a local function specifically since it's meant to be only called internally
function Embed(target, skipPMixins)
for k, v in pairs(mixins) do
target[k] = v
end
if not skipPMixins then
for k, v in pairs(pmixins) do
target[k] = target[k] or v
end
end
end
-- - Initialize the addon after creation.
-- This function is only used internally during the ADDON_LOADED event
-- It will call the **OnInitialize** function on the addon object (if present),
-- and the **OnEmbedInitialize** function on all embeded libraries.
--
-- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing.
-- @param addon addon object to intialize
function AceAddon:InitializeAddon(addon)
safecall(addon.OnInitialize, addon)
local embeds = self.embeds[addon]
for i = 1, #embeds do
local lib = LibStub:GetLibrary(embeds[i], true)
if lib then safecall(lib.OnEmbedInitialize, lib, addon) end
end
-- we don't call InitializeAddon on modules specifically, this is handled
-- from the event handler and only done _once_
end
-- - Enable the addon after creation.
-- Note: This function is only used internally during the PLAYER_LOGIN event, or during ADDON_LOADED,
-- if IsLoggedIn() already returns true at that point, e.g. for LoD Addons.
-- It will call the **OnEnable** function on the addon object (if present),
-- and the **OnEmbedEnable** function on all embeded libraries.\\
-- This function does not toggle the enable state of the addon itself, and will return early if the addon is disabled.
--
-- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing.
-- Use :Enable on the addon itself instead.
-- @param addon addon object to enable
function AceAddon:EnableAddon(addon)
if type(addon) == "string" then addon = AceAddon:GetAddon(addon) end
if self.statuses[addon.name] or not addon.enabledState then return false end
-- set the statuses first, before calling the OnEnable. this allows for Disabling of the addon in OnEnable.
self.statuses[addon.name] = true
safecall(addon.OnEnable, addon)
-- make sure we're still enabled before continueing
if self.statuses[addon.name] then
local embeds = self.embeds[addon]
for i = 1, #embeds do
local lib = LibStub:GetLibrary(embeds[i], true)
if lib then safecall(lib.OnEmbedEnable, lib, addon) end
end
-- enable possible modules.
local modules = addon.orderedModules
for i = 1, #modules do
self:EnableAddon(modules[i])
end
end
return self.statuses[addon.name] -- return true if we're disabled
end
-- - Disable the addon
-- Note: This function is only used internally.
-- It will call the **OnDisable** function on the addon object (if present),
-- and the **OnEmbedDisable** function on all embeded libraries.\\
-- This function does not toggle the enable state of the addon itself, and will return early if the addon is still enabled.
--
-- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing.
-- Use :Disable on the addon itself instead.
-- @param addon addon object to enable
function AceAddon:DisableAddon(addon)
if type(addon) == "string" then addon = AceAddon:GetAddon(addon) end
if not self.statuses[addon.name] then return false end
-- set statuses first before calling OnDisable, this allows for aborting the disable in OnDisable.
self.statuses[addon.name] = false
safecall( addon.OnDisable, addon )
-- make sure we're still disabling...
if not self.statuses[addon.name] then
local embeds = self.embeds[addon]
for i = 1, #embeds do
local lib = LibStub:GetLibrary(embeds[i], true)
if lib then safecall(lib.OnEmbedDisable, lib, addon) end
end
-- disable possible modules.
local modules = addon.orderedModules
for i = 1, #modules do
self:DisableAddon(modules[i])
end
end
return not self.statuses[addon.name] -- return true if we're disabled
end
--- Get an iterator over all registered addons.
-- @usage
-- -- Print a list of all installed AceAddon's
-- for name, addon in AceAddon:IterateAddons() do
-- print("Addon: " .. name)
-- end
function AceAddon:IterateAddons() return pairs(self.addons) end
--- Get an iterator over the internal status registry.
-- @usage
-- -- Print a list of all enabled addons
-- for name, status in AceAddon:IterateAddonStatus() do
-- if status then
-- print("EnabledAddon: " .. name)
-- end
-- end
function AceAddon:IterateAddonStatus() return pairs(self.statuses) end
-- Following Iterators are deprecated, and their addon specific versions should be used
-- e.g. addon:IterateEmbeds() instead of :IterateEmbedsOnAddon(addon)
function AceAddon:IterateEmbedsOnAddon(addon) return pairs(self.embeds[addon]) end
function AceAddon:IterateModulesOfAddon(addon) return pairs(addon.modules) end
-- Event Handling
local function onEvent(this, event, arg1)
-- 2011-08-17 nevcairiel - ignore the load event of Blizzard_DebugTools, so a potential startup error isn't swallowed up
if (event == "ADDON_LOADED" and arg1 ~= "Blizzard_DebugTools") or event == "PLAYER_LOGIN" then
-- if a addon loads another addon, recursion could happen here, so we need to validate the table on every iteration
while(#AceAddon.initializequeue > 0) do
local addon = tremove(AceAddon.initializequeue, 1)
-- this might be an issue with recursion - TODO: validate
if event == "ADDON_LOADED" then addon.baseName = arg1 end
AceAddon:InitializeAddon(addon)
tinsert(AceAddon.enablequeue, addon)
end
if IsLoggedIn() then
while(#AceAddon.enablequeue > 0) do
local addon = tremove(AceAddon.enablequeue, 1)
AceAddon:EnableAddon(addon)
end
end
end
end
AceAddon.frame:RegisterEvent("ADDON_LOADED")
AceAddon.frame:RegisterEvent("PLAYER_LOGIN")
AceAddon.frame:SetScript("OnEvent", onEvent)
-- upgrade embeded
for name, addon in pairs(AceAddon.addons) do
Embed(addon, true)
end
-- 2010-10-27 nevcairiel - add new "orderedModules" table
if oldminor and oldminor < 10 then
for name, addon in pairs(AceAddon.addons) do
addon.orderedModules = {}
for module_name, module in pairs(addon.modules) do
tinsert(addon.orderedModules, module)
end
end
end
| bsd-3-clause |
begeekmyfriend/smithsnmp | mibs/snmptrap.lua | 1 | 3330 | --
-- This file is part of SmithSNMP
-- Copyright (C) 2014, Credo Semiconductor Inc.
-- Copyright (C) 2015, Leo Ma <begeekmyfriend@gmail.com>
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FTrap A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License along
-- with this program; if not, write to the Free Software Foundation, Inc.,
-- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--
local mib = require "smithsnmp"
local trap = require "smithsnmp.trap"
-- scalar index
local snmpTrapOID = 1
local snmpTrapEnterprise = 3
local snmpTrapPollInterv = 42
-- Trap OID
local trap_generic_oid = {}
local trap_specific_oid = {}
-- Trap group
local trapGroup = {}
local trap_poll_interv = 0
local trap_poll_set = function(v)
assert(type(v) == 'number')
if v ~= 0 then
trap.disable()
trap_poll_interv = v
trap.enable(v)
else
trap.disable()
end
end
local trapGroup = {
[snmpTrapOID] = mib.ConstOid(function () return trap_generic_oid end),
[snmpTrapEnterprise] = mib.ConstOid(function () return trap_specific_oid end),
[snmpTrapPollInterv] = mib.Timeticks(function () return trap_poll_interv end,
function (v) trap_poll_set(v) return end),
}
-- register generic trap oid
local trap_generic_reg = function (oid)
assert(type(oid) == 'string')
trap_generic_oid = {}
for i in string.gmatch(oid, "%d+") do
table.insert(trap_generic_oid, tonumber(i))
end
-- Register snmpTrapOID as a default SNMP trap varbind.
trap.object_register(".1.3.6.1.6.3.1.1.4.1.0", trapGroup[snmpTrapOID], function() return true end)
end
-- unregister generic trap oid
local trap_generic_unreg = function (oid)
assert(type(oid) == 'string')
trap_generic_oid = {}
-- Unregister snmpTrapOID SNMP trap varbind.
trap.object_unregister(".1.3.6.1.6.3.1.1.4.1.0")
end
-- register specific trap oid
local trap_specific_reg = function (oid)
assert(type(oid) == 'string')
trap_specific_oid = {}
for i in string.gmatch(oid, "%d+") do
table.insert(trap_specific_oid, tonumber(i))
end
-- Register snmpTrapEnterprise as a default SNMP trap varbind.
trap.object_register(".1.3.6.1.6.3.1.1.4.3.0", trapGroup[snmpTrapEnterprise], function() return true end)
end
-- unregister specific trap oid
local trap_specific_unreg = function (oid)
assert(type(oid) == 'string')
trap_specific_oid = {}
-- Unregister snmpTrapEnterprise SNMP trap varbind.
trap.object_unregister(".1.3.6.1.6.3.1.1.4.3.0")
end
local snmpTrapMethods = {
["trap_generic_reg"] = trap_generic_reg,
["trap_generic_unreg"] = trap_generic_unreg,
["trap_specific_reg"] = trap_specific_reg,
["trap_specific_unreg"] = trap_specific_unreg,
}
mib.module_method_register(snmpTrapMethods)
return trapGroup
| gpl-2.0 |
gutenye/tagen.lua | lib/tagen/stringx.lua | 1 | 8430 | --- Ruby-style extended string library.
--
-- If you want to make these available as string methods, then say
-- `stringx.import()` to bring them into the standard `string` table.
--
-- See @{03-strings.md|the Guide}
--
-- Dependencies: `tagen.core`, `tagen.array`, `tagen.regexp`
-- @module tagen.stringx
local tagen = require("tagen.core")
local Array = require("tagen.array")
local Regexp = require("tagen.regexp")
local pd = tagen.pd
local assert_arg = tagen.assert_arg
local stringx = {}
function stringx.import()
tagen.import(stringx, string)
end
function stringx.dup(self)
return self..""
end
stringx.length = string.len
function stringx.is_empty(self)
assert_arg(1, self, "string")
return #self == 0
end
-- slice(index, count=1)
function stringx.slice(self, index, count)
count = count or 1
assert_arg(1, self, "string")
assert_arg(2, index, "number")
assert_arg(3, count, "number")
local j
if index > 0 then
j = index + count -1
else
j = index - count + 1
end
return string.sub(self, index, j)
end
local function _find_all(self, str, offset)
local plain
if tagen.kind_of(str, Regexp) then str = str.source; plain = false else plain = true end
if str == "" then return #self+1,#self end
local i1,i2 = string.find(self, str, offset, plain)
local res
local k = 0
while i1 do
res = i1
k = k + 1
i1,i2 = string.find(self, str, i2+1, plain)
end
return res,k
end
--- count all instances of substring in string.
-- count(string)
-- count(pattern)
function stringx.count(self, str)
assert_arg(1, self, "string")
assert_arg(2, str, {"string", Regexp})
local i, k = _find_all(self, str, 1)
return k
end
-- index(string, offset=1)
-- index(pattern, offset=1)
function stringx.index(self, str, offset)
offset = offset or 1
assert_arg(1, self, "string")
assert_arg(2, str, {"string", Regexp})
assert_arg(3, offset, "number")
if tagen.kind_of(str, Regexp) then
return string.find(self, str.source, offset)
else
return string.find(self, str, offset, true)
end
end
-- index(string, offset=1)
-- index(pattern, offset=1)
function stringx.rindex(self, str, offset)
offset = offset or 1
assert_arg(1, self, "string")
assert_arg(2, str, {"string", Regexp})
assert_arg(3, offset, "number")
self = string.sub(self, 1, -offset)
local idx = _find_all(self,str,1)
if idx then
return idx
else
return nil
end
end
-- include(str)
-- include(pat)
function stringx.include(self, str)
assert_arg(1, self, "string")
assert_arg(2, str, {"string", Regexp})
local ret
if tagen.kind_of(str, Regexp) then
ret = string.find(self, str.source)
else
ret = string.find(self, str, 1, true)
end
if ret then
return true
else
return false
end
end
stringx.contains = stringx.include
function stringx.start_with(self, ...)
assert_arg(1, self, "string")
local args = table.pack(...)
for i=1,args.n do
if string.find(self, args[i], 1, true) == 1 then
return true
end
end
return false
end
--- does string end with the given substring?.
-- @param s a string
-- @param send a substring or a table of suffixes
function stringx.end_with(self, ...)
assert_arg(1, self, "string")
local args = table.pack(...)
for i=1,args.n do
local arg = args[i]
if #self >= #arg and string.find(self, arg, #self-#arg+1, true) then
return true
end
end
return false
end
-- chars(func)
function stringx.chars(self, func)
assert_arg(1, self, "string")
assert_arg(2, func, "function")
for c in self:gmatch(".") do
func(c)
end
end
stringx.each_char = stringx.chars
function stringx.lines(self, func)
for line in self:gmatch("[^\n]*\n?") do
if line == "" then
break
end
func(line)
end
end
stringx.each_line = stringx.lines
-- delete(string) -> rest,deleted
-- delete(pattern) -> rest,deleted
-- NOT IN PLACE
function stringx.delete(self, str)
assert_arg(1, self, "string")
assert_arg(2, str, {"string", Regexp})
local plain, i, j
if tagen.kind_of(str, Regexp) then str = str.source; plain = false else plain = true end
i, j = string.find(self, str, 1, plain)
if i == nil then
return nil, nil
else
rest = string.sub(self, 1, i-1)..string.sub(self, j+1, -1)
deleted = string.sub(self, i, j)
return rest, deleted
end
end
function stringx.strip(self)
assert_arg(1, self, "string")
local ret = string.gsub(self, "^%s*", "")
ret = string.gsub(ret, "%s*$", "")
return ret
end
function stringx.lstrip(self)
assert_arg(1, self, "string")
return string.gsub(self, "^%s*", "")
end
function stringx.rstrip(self)
assert_arg(1, self, "string")
return string.gsub(self, "%s*$", "")
end
stringx.upcase = string.upper
stringx.downcase = string.lower
function stringx.swapcase(self)
assert_arg(1, self, "string")
return string.gsub(self, ".", function(c)
if string.match(c, "%u") then
return string.gsub(c, "%u", function(v) return string.lower(v) end)
else
return string.gsub(c, "%l", function(v) return string.upper(v) end)
end
end)
end
--- iniital word letters uppercase ('title case').
-- Here 'words' mean chunks of non-space characters.
-- @param self the string
-- @return a string with each word's first letter uppercase
function stringx.capitalize(self)
assert_arg(1, self, "string")
return string.gsub(self, '(%S)(%S*)',function(f,r)
return string.upper(f)..string.lower(r)
end)
end
-- (string, [limit])
-- (pattern, [limit])
function stringx.split(self, pat, limit)
assert_arg(1, self, "string")
assert_arg(2, pat, {"string", Regexp})
local plain
local idx, ary = 1, Array:new()
if tagen.instance_of(pat, Regexp) then pat = pat.source; plain = false else plain = true end
if pat == "" then return Array:new{self} end
while true do
local i, j = string.find(self, pat, idx, plain)
if i == nil then
ary:push(string.sub(self, idx))
local indexes = Array{}
ary = ary:reverse()
ary:each(function(v, i)
if v ~= "" then
return BREAK
end
indexes:push(i)
end)
indexes:each(function(i)
ary:delete_at(1)
end)
ary = ary:reverse()
return ary
end
ary:push(string.sub(self, idx, i-1))
if limit and ary:length() == limit then
ary[-1] = string.sub(self, idx)
return ary
end
idx = j + 1
end
end
--- partition the string using first occurance of a delimiter
function stringx.partition(self, sep)
assert_arg(1, self, "string")
assert_arg(2, sep, "string")
local i1,i2 = stringx.index(self, sep)
if not i1 or i1 == -1 then
return self,'',''
else
if not i2 then i2 = i1 end
return Array{string.sub(self,1,i1-1), string.sub(self,i1,i2), string.sub(self,i2+1)}
end
end
function stringx.insert(self, index, str)
assert_arg(1, self, "string")
assert_arg(2, index, "number")
assert_arg(3, str, {"string", "number"})
return string.sub(self, 1, index-1)..str..string.sub(self, index, -1)
end
local function _just(s,w,ch,left,right)
local n = #s
if w > n then
if not ch then ch = ' ' end
local f1,f2
if left and right then
local ln = math.ceil((w-n)/2)
local rn = w - n - ln
f1 = string.rep(ch,ln)
f2 = string.rep(ch,rn)
elseif right then
f1 = string.rep(ch,w-n)
f2 = ''
else
f2 = string.rep(ch,w-n)
f1 = ''
end
return f1..s..f2
else
return stringx.dup(s)
end
end
--- left-justify s with width w.
-- @param self the string
-- @param w width of justification
-- @param ch padding character, default ' '
function stringx.ljust(self, w, ch)
assert_arg(1, self, "string")
assert_arg(2, w, "number")
assert_arg(3, ch, "string")
return _just(self, w, ch, true, false)
end
--- right-justify s with width w.
-- @param s the string
-- @param w width of justification
-- @param ch padding character, default ' '
function stringx.rjust(self, w, ch)
assert_arg(1, self, "string")
assert_arg(2, w,'number')
return _just(self, w, ch, false, true)
end
--- center-justify s with width w.
-- @param s the string
-- @param w width of justification
-- @param ch padding character, default ' '
function stringx.center(self, w, ch)
assert_arg(1, self, "string")
assert_arg(2, w, "number")
assert_arg(3, ch, "string")
return _just(self, w, ch,true,true)
end
return stringx
| gpl-3.0 |
xdemolish/darkstar | scripts/globals/items/greedie.lua | 17 | 1316 | -----------------------------------------
-- ID: 4500
-- Item: greedie
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 1
-- Mind -3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if(target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4500);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 1);
target:addMod(MOD_MND, -3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 1);
target:delMod(MOD_MND, -3);
end;
| gpl-3.0 |
robotics-erlangen/autoref | autoref/gamecontroller.lua | 1 | 2089 | --[[***********************************************************************
* Copyright 2019 Andreas Wendler *
* Robotics Erlangen e.V. *
* http://www.robotics-erlangen.de/ *
* info@robotics-erlangen.de *
* *
* 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 of the License, or *
* 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 GameController = {}
local STATE_UNCONNECTED = 1
local STATE_CONNECTED = 2
local state = STATE_UNCONNECTED
function GameController.update()
if amun.connectGameController() then
if state == STATE_UNCONNECTED then
state = STATE_CONNECTED
amun.sendGameControllerMessage("AutoRefRegistration", {identifier="ER-Force"})
end
else
state = STATE_UNCONNECTED
end
end
function GameController.sendEvent(event)
event.origin = {"ER-Force"}
if state == STATE_CONNECTED then
amun.sendGameControllerMessage("AutoRefToController", {game_event=event})
else
log("Not connected to game controller!")
end
end
return GameController
| gpl-3.0 |
xdemolish/darkstar | scripts/globals/items/black_curry_bun_+1.lua | 35 | 1350 | -----------------------------------------
-- ID: 5764
-- Item: black_curry_bun+1
-- Food Effect: 60 minutes, All Races
-----------------------------------------
-- Intelligence +1
-- Vitality +4
-- Dexterity +2
-- Defense +~16%
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5764);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_INT, 1);
target:addMod(MOD_VIT, 4);
target:addMod(MOD_DEX, 2);
target:addMod(MOD_FOOD_DEFP, 16);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_INT, 1);
target:delMod(MOD_VIT, 4);
target:delMod(MOD_DEX, 2);
target:delMod(MOD_FOOD_DEFP, 16);
end; | gpl-3.0 |
mohammad24/unixx | plugins/media.lua | 297 | 1590 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
amheydari/cardpeek | dot_cardpeek_dir/scripts/calypso/c250n502.lua | 17 | 4335 | --
-- This file is part of Cardpeek, the smartcard reader utility.
--
-- Copyright 2009 by 'L1L1' and 2013-2014 by 'kalon33'
--
-- Cardpeek is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Cardpeek is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Cardpeek. If not, see <http://www.gnu.org/licenses/>.
--
---------------------------------------------------------------------
-- Most of the data and coding ideas in this file
-- was contributed by 'Pascal Terjan', based on location
-- data from 'Nicolas Derive'.
---------------------------------------------------------------------
require('lib.strict')
require('etc.grenoble-tag_stops')
require('etc.grenoble-tag_lines')
SERVICE_PROVIDERS = {
[3] = "TAG"
}
TRANSPORT_LIST = {
[1] = "Tram"
}
TRANSITION_LIST = {
[1] = "Entry",
[2] = "Exit",
[4] = "Inspection",
[6] = "Interchange (entry)",
[7] = "Interchange (exit)"
}
function navigo_process_events(ctx)
local EVENTS
local RECORD
local REF
local rec_index
local code_value
local code_transport
local code_transition
local code_transport_string
local code_transition_string
local code_string
local service_provider_value
local location_id_value
local route_number_value
local route_string
local sector_id
local station_id
local location_string
EVENTS = ui.tree_find_node(ctx,"Event logs, parsed");
if EVENTS==nil then
log.print(log.WARNING,"No event found in card")
return 0
end
for rec_index=1,16 do
RECORD = ui.tree_find_node(EVENTS,"record",rec_index)
if RECORD==nil then break end
REF = ui.tree_find_node(RECORD,"EventServiceProvider")
service_provider_value = bytes.tonumber(ui.tree_get_value(REF))
ui.tree_set_alt_value(REF,SERVICE_PROVIDERS[service_provider_value])
REF = ui.tree_find_node(RECORD,"EventCode")
code_value = bytes.tonumber(ui.tree_get_value(REF))
code_transport = bit.SHR(code_value,4)
code_transport_string = TRANSPORT_LIST[code_transport]
if code_transport_string==nil then code_transport_string = code_transport end
code_transition = bit.AND(code_value,0xF)
code_transition_string = TRANSITION_LIST[code_transition]
if (code_transition_string==nil) then code_transition_string = code_transition end
ui.tree_set_alt_value(REF,code_transport_string.." - "..code_transition_string)
if service_provider_value == 3 and code_transport <=1 then
REF = ui.tree_find_node(RECORD,"EventLocationId")
location_id_value = bytes.tonumber(ui.tree_get_value(REF))
-- sector_id = bit.SHR(location_id_value,9)
-- station_id = bit.AND(bit.SHR(location_id_value,4),0x1F)
-- if STOPS_LIST[sector_id]~=nil then
-- location_string = "secteur "..STOPS_LIST[sector_id]['name'].." - station "
-- if STOPS_LIST[sector_id][station_id]==nil then
-- location_string = location_string .. station_id
-- else
-- location_string = location_string .. STOPS_LIST[sector_id][station_id]
-- end
-- else
-- location_string = "secteur "..sector_id.." - station "..station_id
-- end
-- end
if STOPS_LIST[location_id_value]~=nil then
location_string = STOPS_LIST[location_id_value]
else
location_string = location_id_value
end
ui.tree_set_alt_value(REF,location_string)
REF = ui.tree_find_node(RECORD,"EventRouteNumber")
route_number_value = bytes.tonumber(ui.tree_get_value(REF))
if LINES_LIST[route_number_value]["name"] then
route_string = LINES_LIST[route_number_value]["name"]
else
-- route_string = route_number_value
route_string = LINES_LIST[route_number_value]["name"]
end
ui.tree_set_alt_value(REF,route_string)
end
end
end
navigo_process_events(CARD)
| gpl-3.0 |
xdemolish/darkstar | scripts/globals/items/serving_of_golden_royale.lua | 36 | 1429 | -----------------------------------------
-- ID: 5558
-- Item: Serving of Golden Royale
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP +10
-- MP +10
-- Intelligence +2
-- HP Recoverd while healing 2
-- MP Recovered while healing 2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5558);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 10);
target:addMod(MOD_MP, 10);
target:addMod(MOD_INT, 2);
target:addMod(MOD_HPHEAL, 2);
target:addMod(MOD_MPHEAL, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 10);
target:delMod(MOD_MP, 10);
target:delMod(MOD_INT, 2);
target:delMod(MOD_HPHEAL, 2);
target:delMod(MOD_MPHEAL, 2);
end;
| gpl-3.0 |
PlexChat/premake-core | src/actions/vstudio/vs2005_solution.lua | 2 | 7508 | --
-- vs2005_solution.lua
-- Generate a Visual Studio 2005-2012 solution.
-- Copyright (c) 2009-2015 Jason Perkins and the Premake project
--
premake.vstudio.sln2005 = {}
local p = premake
local vstudio = p.vstudio
local sln2005 = p.vstudio.sln2005
local project = p.project
local tree = p.tree
--
-- Return the list of sections contained in the solution.
--
function sln2005.solutionSections(wks)
return {
"ConfigurationPlatforms",
"SolutionProperties",
"NestedProjects",
}
end
--
-- Generate a Visual Studio 200x solution, with support for the new platforms API.
--
function sln2005.generate(wks)
-- Mark the file as Unicode
_p('\239\187\191')
sln2005.reorderProjects(wks)
sln2005.header()
sln2005.projects(wks)
p.push('Global')
sln2005.sections(wks)
p.pop('EndGlobal')
p.w()
end
--
-- Generate the solution header. Each Visual Studio action definition
-- should include its own version.
--
function sln2005.header()
local action = premake.action.current()
_p('Microsoft Visual Studio Solution File, Format Version %d.00', action.vstudio.solutionVersion)
_p('# Visual Studio %s', action.vstudio.versionName)
end
--
-- If a startup project is specified, move it (and any enclosing groups)
-- to the front of the project list. This will make Visual Studio treat
-- it like a startup project.
--
-- I force the new ordering into the tree so that it will get applied to
-- all sections of the solution; otherwise the first change to the solution
-- in the IDE will cause the orderings to get rewritten.
--
function sln2005.reorderProjects(wks)
if wks.startproject then
local np
local tr = p.workspace.grouptree(wks)
tree.traverse(tr, {
onleaf = function(n)
if n.project.name == wks.startproject then
np = n
end
end
})
while np and np.parent do
local p = np.parent
local i = table.indexof(p.children, np)
table.remove(p.children, i)
table.insert(p.children, 1, np)
np = p
end
end
end
--
-- Write out the list of projects and groups contained by the solution.
--
function sln2005.projects(wks)
local tr = p.workspace.grouptree(wks)
tree.traverse(tr, {
onleaf = function(n)
local prj = n.project
-- Build a relative path from the solution file to the project file
local prjpath = vstudio.projectfile(prj)
prjpath = vstudio.path(prj.workspace, prjpath)
-- Unlike projects, solutions must use old-school %...% DOS style
-- for environment variables.
prjpath = prjpath:gsub("$%((.-)%)", "%%%1%%")
_x('Project("{%s}") = "%s", "%s", "{%s}"', vstudio.tool(prj), prj.name, prjpath, prj.uuid)
sln2005.projectdependencies(prj)
_p('EndProject')
end,
onbranch = function(n)
_x('Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "%s", "%s", "{%s}"', n.name, n.name, n.uuid)
_p('EndProject')
end,
})
end
--
-- Write out the list of project dependencies for a particular project.
--
function sln2005.projectdependencies(prj)
local deps = project.getdependencies(prj)
if #deps > 0 then
_p(1,'ProjectSection(ProjectDependencies) = postProject')
for _, dep in ipairs(deps) do
_p(2,'{%s} = {%s}', dep.uuid, dep.uuid)
end
_p(1,'EndProjectSection')
end
end
--
-- Write out the tables that map solution configurations to project configurations.
--
function sln2005.configurationPlatforms(wks)
local descriptors = {}
local sorted = {}
for cfg in p.workspace.eachconfig(wks) do
-- Create a Visual Studio solution descriptor (i.e. Debug|Win32) for
-- this solution configuration. I need to use it in a few different places
-- below so it makes sense to precompute it up front.
local platform = vstudio.solutionPlatform(cfg)
descriptors[cfg] = string.format("%s|%s", cfg.buildcfg, platform)
-- Also add the configuration to an indexed table which I can sort below
table.insert(sorted, cfg)
end
-- Sort the solution configurations to match Visual Studio's preferred
-- order, which appears to be a simple alpha sort on the descriptors.
table.sort(sorted, function(cfg0, cfg1)
return descriptors[cfg0]:lower() < descriptors[cfg1]:lower()
end)
-- Now I can output the sorted list of solution configuration descriptors
-- Visual Studio assumes the first configurations as the defaults.
if wks.defaultplatform then
_p(1,'GlobalSection(SolutionConfigurationPlatforms) = preSolution')
table.foreachi(sorted, function (cfg)
if cfg.platform == wks.defaultplatform then
_p(2,'%s = %s', descriptors[cfg], descriptors[cfg])
end
end)
_p(1,"EndGlobalSection")
end
_p(1,'GlobalSection(SolutionConfigurationPlatforms) = preSolution')
table.foreachi(sorted, function (cfg)
if not wks.defaultplatform or cfg.platform ~= wks.defaultplatform then
_p(2,'%s = %s', descriptors[cfg], descriptors[cfg])
end
end)
_p(1,"EndGlobalSection")
-- For each project in the solution...
_p(1,"GlobalSection(ProjectConfigurationPlatforms) = postSolution")
local tr = p.workspace.grouptree(wks)
tree.traverse(tr, {
onleaf = function(n)
local prj = n.project
-- For each (sorted) configuration in the solution...
table.foreachi(sorted, function (cfg)
local platform, architecture
-- Look up the matching project configuration. If none exist, this
-- configuration has been excluded from the project, and should map
-- to closest available project configuration instead.
local prjCfg = project.getconfig(prj, cfg.buildcfg, cfg.platform)
local excluded = (prjCfg == nil or prjCfg.flags.ExcludeFromBuild)
if prjCfg == nil then
prjCfg = project.findClosestMatch(prj, cfg.buildcfg, cfg.platform)
end
local descriptor = descriptors[cfg]
local platform = vstudio.projectPlatform(prjCfg)
local architecture = vstudio.archFromConfig(prjCfg, true)
_p(2,'{%s}.%s.ActiveCfg = %s|%s', prj.uuid, descriptor, platform, architecture)
-- Only output Build.0 entries for buildable configurations
if not excluded and prjCfg.kind ~= premake.NONE then
_p(2,'{%s}.%s.Build.0 = %s|%s', prj.uuid, descriptor, platform, architecture)
end
end)
end
})
_p(1,"EndGlobalSection")
end
--
-- Write out contents of the SolutionProperties section; currently unused.
--
function sln2005.properties(wks)
_p('\tGlobalSection(SolutionProperties) = preSolution')
_p('\t\tHideSolutionNode = FALSE')
_p('\tEndGlobalSection')
end
--
-- Write out the NestedProjects block, which describes the structure of
-- any solution groups.
--
function sln2005.NestedProjects(wks)
local tr = p.workspace.grouptree(wks)
if tree.hasbranches(tr) then
_p(1,'GlobalSection(NestedProjects) = preSolution')
tree.traverse(tr, {
onnode = function(n)
if n.parent.uuid then
_p(2,'{%s} = {%s}', (n.project or n).uuid, n.parent.uuid)
end
end
})
_p(1,'EndGlobalSection')
end
end
--
-- Map solution sections to output functions. Tools that aren't listed will
-- be ignored.
--
sln2005.sectionmap = {
ConfigurationPlatforms = sln2005.configurationPlatforms,
SolutionProperties = sln2005.properties,
NestedProjects = sln2005.NestedProjects
}
--
-- Write out all of the workspace sections.
--
function sln2005.sections(wks)
for _, section in ipairs(sln2005.solutionSections(wks)) do
if sln2005.sectionmap[section] then
sln2005.sectionmap[section](wks)
end
end
end
| bsd-3-clause |
xdemolish/darkstar | scripts/zones/The_Shrouded_Maw/bcnms/waking_dreams.lua | 10 | 2480 | -----------------------------------
-- Area: The_Shrouded_Maw
-- Name: waking_dreams
-----------------------------------
package.loaded["scripts/zones/The_Shrouded_Maw/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/The_Shrouded_Maw/TextIDs");
require("scripts/globals/missions");
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
local inst = player:getBattlefieldID();
if(inst == 1)then
local TileOffset = 16818243;
for i = TileOffset, TileOffset+7 do
local TileOffsetA = GetNPCByID(i):getAnimation();
if (TileOffsetA == 8) then
GetNPCByID(i):setAnimation(9);
end
end
elseif(inst == 2)then
local TileOffset = 16818251;
for i = TileOffset, TileOffset+7 do
local TileOffsetA = GetNPCByID(i):getAnimation();
if (TileOffsetA == 8) then
GetNPCByID(i):setAnimation(9);
end
end
elseif(inst == 3)then
local TileOffset = 16818259;
for i = TileOffset, TileOffset+7 do
local TileOffsetA = GetNPCByID(i):getAnimation();
if (TileOffsetA == 8) then
GetNPCByID(i):setAnimation(9);
end
end
end
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if(player:hasKeyItem(VIAL_OF_DREAM_INCENSE)==true) then
player:addKeyItem(WHISPER_OF_DREAMS);
player:delKeyItem(VIAL_OF_DREAM_INCENSE);
player:messageSpecial(KEYITEM_OBTAINED,WHISPER_OF_DREAMS);
end
player:addTitle(HEIR_TO_THE_REALM_OF_DREAMS);
player:startEvent(0x7d02);
elseif(leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
end;
| gpl-3.0 |
sonicbikes/app-swamp | lib/std.lua | 1 | 2135 | -- Swamp Bike Opera embedded system for Kaffe Matthews
-- Copyright (C) 2012 Wolfgang Hauptfleisch, Dave Griffiths
--
-- 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 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
module("std", package.seeall)
---
-- @param command
function stdout(command)
local f = io.popen(command)
local l = f:read("*a")
f:close()
return l
end
---
--@param num
function round(num, idp)
local mult = 10^(idp or 0)
return math.floor(num * mult + 0.5) / mult
end
---
function trim(s)
if s then
s = string.gsub(s, "^%s*(.-)%s*$", "%1")
if string.len(s) > 0 then
return s
end
end
return false
end -- end trim
---
function split(str, pat)
local t = {}
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(t,cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t, cap)
end
return t
end
---
function dumptable(t, indent)
local indent=indent or ''
for key,value in pairs(t) do
io.write(indent,'[',tostring(key),']')
if type(value)=="table" then io.write(':\n') dumptable(value,indent..'\t')
else io.write(' = ',tostring(value),'\n') end
end
end -- end showtable
---
function normalize_string(s)
s = string.gsub(s, "%s%s", " ")
return s
end
---
function iterate_string(s)
local word_t
for word in string.gmatch(s, "(%w+)") do
table.insert(word_t, word)
end
return word_t
end
| gpl-2.0 |
grmss214/SHATELTEAM | plugins/google.lua | 336 | 1323 | do
local function googlethat(query)
local url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&safe=active&&rsz=5&'
local parameters = 'q='..(URL.escape(query) or '')
-- Do the request
local res, code = https.request(url..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=''
i = 0
for key,val in ipairs(results) do
i = i+1
stringresults=stringresults..i..'. '..val[1]..'\n'..val[2]..'\n'
end
return stringresults
end
local function run(msg, matches)
-- comment this line if you want this plugin works in private message.
if not is_chat_msg(msg) then return nil end
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = 'Returns five results from Google. Safe search is enabled by default.',
usage = ' !google [terms]: Searches Google and send results',
patterns = {
'^!google (.*)$',
'^%.[g|G]oogle (.*)$'
},
run = run
}
end
| gpl-2.0 |
xdemolish/darkstar | scripts/zones/Al_Zahbi/npcs/Bornahn.lua | 19 | 1146 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Bornahn
-- Guild Merchant NPC: Goldsmithing Guild
-- @pos 46.011 0.000 -42.713 48
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Al_Zahbi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:sendGuild(60429,8,23,4)) then
player:showText(npc,BORNAHN_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
xdemolish/darkstar | scripts/globals/items/tavnazian_goby.lua | 18 | 1263 | -----------------------------------------
-- ID: 5130
-- Item: Tavnazian Goby
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 4
-- Mind -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:getRace() ~= 7) then
result = 247;
end
if(target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5130);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 4);
target:addMod(MOD_MND, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 4);
target:delMod(MOD_MND, -4);
end;
| gpl-3.0 |
kaadmy/pixture | mods/player_skins/init.lua | 1 | 5015 | --
-- Player skins mod
-- By Kaadmy, for Pixture
--
player_skins = {}
-- Array of usable player skins
player_skins.skin_names = {"male", "female"}
if minetest.settings:get("player_skins_names") then
player_skins.skin_names = util.split(minetest.settings:get("player_skins_names"), ",")
end
player_skins.old_skins = {}
player_skins.skins = {}
local skins_file = minetest.get_worldpath() .. "/player_skins.dat"
local saving = false
local timer_interval = 1
local timer = 10
local function save_player_skins()
local f = io.open(skins_file, "w")
for name, tex in pairs(player_skins.skins) do
f:write(name .. " " .. tex .. "\n")
end
io.close(f)
end
local function delayed_save()
if not saving then
saving = true
minetest.after(40, save_player_skins)
end
end
local function load_player_skins()
local f = io.open(skins_file, "r")
if f then
repeat
local l = f:read("*l")
if l == nil then break end
for name, tex in string.gfind(l, "(.+) (.+)") do
player_skins.skins[name] = tex
end
until f:read(0) == nil
io.close(f)
else
save_player_skins()
end
end
local function is_valid_skin(tex)
for _, n in pairs(player_skins.skin_names) do
if n == tex then
return true
end
end
return false
end
function player_skins.get_skin(name)
return "player_skins_" .. player_skins.skins[name] .. ".png"
end
function player_skins.set_skin(name, tex)
if minetest.check_player_privs(name, {player_skin = true}) then
if is_valid_skin(tex) then
player_skins.skins[name] = tex
save_player_skins()
else
minetest.chat_send_player(name, "Invalid skin")
end
else
minetest.chat_send_player(
name,
"You do not have the privilege to change your skin."
)
end
end
local function on_load()
load_player_skins()
end
local function on_shutdown()
save_player_skins()
end
local function on_joinplayer(player)
local name = player:get_player_name()
if player_skins.skins[name] == nil then
player_skins.skins[name] = "male"
end
end
local function on_globalstep(dtime)
timer = timer + dtime
if timer < timer_interval then
return
end
timer = 0
for _, player in pairs(minetest.get_connected_players()) do
local name = player:get_player_name()
if player_skins.skins[name] ~= player_skins.old_skins[name] then
default.player_set_textures(
player, {
"player_skins_" .. player_skins.skins[name] .. ".png"
})
player_skins.old_skins[name] = player_skins.skins[name]
delayed_save()
end
end
end
minetest.after(0, on_load)
minetest.register_on_shutdown(on_shutdown)
minetest.register_on_joinplayer(on_joinplayer)
minetest.register_globalstep(on_globalstep)
local function get_chatparams()
local s = "["
for _, n in pairs(player_skins.skin_names) do
if s == "[" then
s = s .. n
else
s = s .. "|" .. n
end
end
return s .. "]"
end
function player_skins.get_formspec(playername)
local form = default.ui.get_page("default:default")
form = form .. "image[4,0;0.5,10.05;ui_vertical_divider.png]"
for i, name in ipairs(player_skins.skin_names) do
local x = 0.25
local y = i - 0.5
if i > 8 then
x = 4.5
y = y - 8
end
form = form .. default.ui.button(x, y, 2, 1, "skin_select_"
.. name, player_skins.skin_names[i])
form = form .. "image[" .. (x + 2.25) .. "," .. y.. ";1,1;player_skins_icon_"
.. name .. ".png]"
if player_skins.skins[playername] == name then
form = form .. "image[" .. (x + 3.25) .. "," .. (y + 0.25)
.. ";0.5,0.5;ui_checkmark.png]"
end
end
return form
end
minetest.register_on_player_receive_fields(
function(player, form_name, fields)
local name = player:get_player_name()
for fieldname, val in pairs(fields) do
local skinname = string.match(fieldname, "skin_select_(.*)")
if skinname ~= nil then
player_skins.set_skin(name, skinname)
minetest.show_formspec(name, "player_skins:player_skins",
player_skins.get_formspec(name))
end
end
end)
minetest.register_privilege("player_skin", "Can change player skin")
minetest.register_chatcommand(
"player_skin",
{
params = get_chatparams(),
description = "Set your player skin",
privs = {player_skin = true},
func = function(name, param)
if is_valid_skin(param) then
player_skins.set_skin(name, param)
elseif param == "" then
minetest.chat_send_player(
name,
"Current player skin: " .. player_skins.skins[name])
else
minetest.chat_send_player(
name,
"Bad param for /player_skin; type /help player_skin"
)
end
end
})
default.log("mod:player_skins", "loaded")
| lgpl-2.1 |
emmericp/libmoon | lua/packet.lua | 2 | 33219 | ---------------------------------
--- @file packet.lua
--- @brief Utility functions for packets (rte_mbuf).
--- Includes:
--- - General functions (timestamping, rate control, ...)
--- - Offloading
--- - Create packet types
---------------------------------
local ffi = require "ffi"
require "utils"
local dpdkc = require "dpdkc"
local dpdk = require "dpdk"
local log = require "log"
local colors = require "colors"
local bor, band, bnot, rshift, lshift= bit.bor, bit.band, bit.bnot, bit.rshift, bit.lshift
local istype = ffi.istype
local write = io.write
local strSplit = strSplit
--- Payload type, required by some protocols, defined before loading them
ffi.cdef[[
union payload_t {
uint8_t uint8[0];
uint16_t uint16[0];
uint32_t uint32[0];
uint64_t uint64[0];
};
]]
local proto = require "proto.proto"
-------------------------------------------------------------------------------------------
---- General functions
-------------------------------------------------------------------------------------------
--- Module for packets (rte_mbuf)
local pkt = {}
pkt.__index = pkt
--- Get a void* pointer to the packet data.
function pkt:getData()
return ffi.cast("void*", ffi.cast("uint8_t*", self.buf_addr) + self.data_off)
end
function pkt:getBytes()
return ffi.cast("uint8_t*", self.buf_addr) + self.data_off
end
function pkt:getTimesync()
return self.timesync
end
function pkt:dumpFlags()
log:debug(tostring(self.ol_flags) .. " " .. tostring(self.tx_offload))
end
--- Retrieve the time stamp information.
--- @return The timestamp or nil if the packet was not time stamped.
function pkt:getTimestamp(dev)
if bit.bor(self.ol_flags, dpdk.PKT_RX_IEEE1588_TMST) ~= 0 then
local data = ffi.cast("uint32_t* ", self:getData())
local low, high
if dev and dev.embeddedTimestampAtEndOfBuffer then
-- ixgbe-style nics that support this (i.e. x550)
local timestamp = ffi.cast("uint32_t*", ffi.cast("uint8_t*", self:getData()) + self:getSize() - 8)
low = timestamp[0]
high = timestamp[1]
return high * 10^9 + low
else
-- TODO: this is only tested with the Intel 82580 NIC at the moment
-- the datasheet claims that low and high are swapped, but this doesn't seem to be the case
-- TODO: check other NICs
low = data[2]
high = data[3]
return high * 2^32 + low
end
end
end
--- Check if the PKT_RX_IEEE1588_TMST flag is set.
--- Turns out that this flag is pretty pointless, it does not indicate
--- if the packet was actually timestamped, just that it came from a
--- queue/filter with timestamping enabled.
--- You probably want to use device:hasTimestamp() and check the sequence number.
function pkt:hasTimestamp()
return bit.bor(self.ol_flags, dpdk.PKT_RX_IEEE1588_TMST) ~= 0
end
function pkt:getSecFlags()
local secp = bit.rshift(bit.band(self.ol_flags, dpdk.PKT_RX_IPSEC_SECP), 11)
local secerr = bit.rshift(bit.band(self.ol_flags, bit.bor(dpdk.PKT_RX_SECERR_MSB, dpdk.PKT_RX_SECERR_LSB)), 12)
return secp, secerr
end
--- Offload VLAN tagging to the NIC for this packet.
function pkt:setVlan(vlan, pcp, cfi)
local tci = vlan + bit.lshift(pcp or 0, 13) + bit.lshift(cfi or 0, 12)
self.vlan_tci = tci
self.ol_flags = bit.bor(self.ol_flags, dpdk.PKT_TX_VLAN_PKT)
end
local VLAN_VALID_MASK = bit.bor(dpdk.PKT_RX_VLAN_PKT, dpdk.PKT_TX_VLAN_PKT)
--- Get the VLAN associated with a received packet.
function pkt:getVlan()
if bit.bor(self.ol_flags, VLAN_VALID_MASK) == 0 then
return nil
end
local tci = self.vlan_tci
return bit.band(tci, 0xFFF), bit.rshift(tci, 13), bit.band(bit.rshift(tci, 12), 1)
end
--- @todo TODO does
function pkt:setSize(size)
self.pkt_len = size
self.data_len = size
end
function pkt:getSize()
return self.pkt_len
end
--- Returns the packet data cast to the best fitting packet struct.
--- Starting with ethernet header.
--- @return packet data as cdata of best fitting packet
function pkt:get()
return self:getEthernetPacket():resolveLastHeader()
end
--- Dumps the packet data cast to the best fitting packet struct.
--- @param bytes number of bytes to dump, optional (default = packet size)
--- @param stream the stream to write to, optional (default = io.stdout)
--- @param colorized Print the dump with different colors for each protocol (default = true)
--- @param wireshark Dump in wireshark compatible format (Wireshark -> Import from Hex Dump)
function pkt:dump(bytes, stream, colorized, wireshark)
if type(bytes) == "userdata" then
stream = bytes
colorized = stream
bytes = nil
end
colorized = colorized == nil or colorized
self:get():dump(bytes or self.pkt_len, stream or io.stdout, colorized, wireshark)
end
function pkt:free()
dpdkc.rte_pktmbuf_free_export(self)
end
function pkt:removeFirst(bytes)
dpdkc.rte_pktmbuf_adj_export(self, bytes)
end
function pkt:removeLast(bytes)
dpdkc.rte_pktmbuf_trim_export(self, bytes)
end
-------------------------------------------------------------------------------------------------------
---- IPSec offloading
-------------------------------------------------------------------------------------------------------
--- Use IPsec offloading.
--- @param idx SA_IDX to use
--- @param sec_type IPSec type to use ("esp"/"ah")
--- @param esp_mode ESP mode to use encrypt(1) or authenticate(0)
function pkt:offloadIPSec(idx, sec_type, esp_mode)
local mode = esp_mode or 0
local t = nil
if sec_type == "esp" then
t = 1
elseif sec_type == "ah" then
t = 0
else
log:fatal("Wrong IPSec type (esp/ah)")
end
-- Set IPSec offload flag in advanced data transmit descriptor.
self.ol_flags = bit.bor(self.ol_flags, dpdk.PKT_TX_IPSEC)
-- Set 10 bit SA_IDX
--if idx < 0 or idx > 1023 then
-- error("SA_IDX has to be in range 0-2013")
--end
--self.ol_ipsec.sec.sa_idx = idx
self.ol_ipsec.data = bit.bor(self.ol_ipsec.data, bit.lshift(bit.band(idx, 0x3FF), 0))
-- Set ESP enc/auth mode
--if mode ~= 0 and mode ~= 1 then
-- error("Wrong IPSec mode")
--end
--self.ol_ipsec.sec.mode = mode
self.ol_ipsec.data = bit.bor(self.ol_ipsec.data, bit.lshift(bit.band(mode, 0x1), 20))
-- Set IPSec ESP/AH type
--if sec_type == "esp" then
-- self.ol_ipsec.sec.type = 1
--elseif sec_type == "ah" then
-- self.ol_ipsec.sec.type = 0
--else
-- error("Wrong IPSec type (esp/ah)")
--end
self.ol_ipsec.data = bit.bor(self.ol_ipsec.data, bit.lshift(bit.band(t, 0x1), 19))
end
--- Set the ESP trailer length
--- @param len ESP Trailer length in bytes
function pkt:setESPTrailerLength(len)
--Disable range check for performance reasons
--if len < 0 or len > 511 then
-- error("ESP trailer length has to be in range 0-511")
--end
--self.ol_ipsec.sec.esp_len = len -- dont use bitfields
self.ol_ipsec.data = bit.bor(self.ol_ipsec.data, bit.lshift(bit.band(len, 0x1FF), 10))
end
-------------------------------------------------------------------------------------------------------
---- Checksum offloading
-------------------------------------------------------------------------------------------------------
--- Instruct the NIC to calculate the IP checksum for this packet.
--- @param ipv4 Boolean to decide whether the packet uses IPv4 (set to nil/true) or IPv6 (set to anything else).
--- In case it is an IPv6 packet, do nothing (the header has no checksum).
--- @param l2Len Length of the layer 2 header in bytes (default 14 bytes for ethernet).
--- @param l3Len Length of the layer 3 header in bytes (default 20 bytes for IPv4).
function pkt:offloadIPChecksum(ipv4, l2Len, l3Len)
ipv4 = ipv4 == nil or ipv4
l2Len = l2Len or 14
if ipv4 then
l3Len = l3Len or 20
self.ol_flags = bit.bor(self.ol_flags, dpdk.PKT_TX_IPV4, dpdk.PKT_TX_IP_CKSUM)
else
l3Len = l3Len or 40
self.ol_flags = bit.bor(self.ol_flags, dpdk.PKT_TX_IPV4, dpdk.PKT_TX_IP_CKSUM)
end
self.tx_offload = l2Len + l3Len * 128
end
--- Instruct the NIC to calculate the IP and UDP checksum for this packet.
--- @param ipv4 Boolean to decide whether the packet uses IPv4 (set to nil/true) or IPv6 (set to anything else).
--- @param l2Len Length of the layer 2 header in bytes (default 14 bytes for ethernet).
--- @param l3Len Length of the layer 3 header in bytes (default 20 bytes for IPv4, 40 bytes for IPv6).
function pkt:offloadUdpChecksum(ipv4, l2Len, l3Len)
-- NOTE: this method cannot be moved to the udpPacket class because it doesn't (and can't) know the pktbuf it belongs to
ipv4 = ipv4 == nil or ipv4
l2Len = l2Len or 14
if ipv4 then
l3Len = l3Len or 20
self.ol_flags = bit.bor(self.ol_flags, dpdk.PKT_TX_IPV4, dpdk.PKT_TX_IP_CKSUM, dpdk.PKT_TX_UDP_CKSUM)
self.tx_offload = l2Len + l3Len * 128
-- calculate pseudo header checksum because the NIC doesn't do this...
dpdkc.calc_ipv4_pseudo_header_checksum(self:getData(), 20)
else
l3Len = l3Len or 40
self.ol_flags = bit.bor(self.ol_flags, dpdk.PKT_TX_IPV6, dpdk.PKT_TX_IP_CKSUM, dpdk.PKT_TX_UDP_CKSUM)
self.tx_offload = l2Len + l3Len * 128
-- calculate pseudo header checksum because the NIC doesn't do this...
dpdkc.calc_ipv6_pseudo_header_checksum(self:getData(), 30)
end
end
--- Instruct the NIC to calculate the IP and TCP checksum for this packet.
--- @param ipv4 Boolean to decide whether the packet uses IPv4 (set to nil/true) or IPv6 (set to anything else).
--- @param l2Len Length of the layer 2 header in bytes (default 14 bytes for ethernet).
--- @param l3Len Length of the layer 3 header in bytes (default 20 bytes for IPv4, 40 bytes for IPv6).
function pkt:offloadTcpChecksum(ipv4, l2Len, l3Len)
-- NOTE: this method cannot be moved to the udpPacket class because it doesn't (and can't) know the pktbuf it belongs to
ipv4 = ipv4 == nil or ipv4
l2Len = l2Len or 14
if ipv4 then
l3Len = l3Len or 20
self.ol_flags = bit.bor(self.ol_flags, dpdk.PKT_TX_IPV4, dpdk.PKT_TX_IP_CKSUM, dpdk.PKT_TX_TCP_CKSUM)
self.tx_offload = l2Len + l3Len * 128
-- calculate pseudo header checksum because the NIC doesn't do this...
dpdkc.calc_ipv4_pseudo_header_checksum(self:getData(), 25)
else
l3Len = l3Len or 40
self.ol_flags = bit.bor(self.ol_flags, dpdk.PKT_TX_IPV6, dpdk.PKT_TX_IP_CKSUM, dpdk.PKT_TX_TCP_CKSUM)
self.tx_offload = l2Len + l3Len * 128
-- calculate pseudo header checksum because the NIC doesn't do this...
dpdkc.calc_ipv6_pseudo_header_checksum(self:getData(), 35)
end
end
--- @todo TODO docu
function pkt:enableTimestamps()
self.ol_flags = bit.bor(self.ol_flags, dpdk.PKT_TX_IEEE1588_TMST)
end
----------------------------------------------------------------------------------
---- Create new packet type
----------------------------------------------------------------------------------
-- functions of the packet
local packetGetHeaders
local packetGetHeader
local packetDump
local packetFill
local packetGet
local packetResolveLastHeader
local packetCalculateChecksums
local packetMakeStruct
--- Create struct and functions for a new packet.
--- For implemented headers (see proto/) these packets are defined in the section 'Packet struct' of each protocol file
--- @param args list of keywords (see makeStruct)
--- @return returns the constructor/cast function for this packet
--- @see packetMakeStruct
function createStack(...)
local args = { ... }
local packet = {}
packet.__index = packet
local noPayload = args[#args] == "noPayload"
if noPayload then
args[#args] = nil
end
-- create struct
local packetName, ctype = packetMakeStruct(args, noPayload)
if not packetName then
log:warn("Failed to create new packet type.")
return
end
-- functions of the packet
packet.getArgs = function() return args end
packet.getName = function() return packetName end
packet.getHeaders = packetGetHeaders
packet.getHeader = packetGetHeader
packet.dump = packetDump
packet.fill = packetFill
packet.get = packetGet
packet.resolveLastHeader = packetResolveLastHeader
-- runtime critical function, load specific code during runtime
packet.setLength = packetSetLength(args)
-- functions for manual (not offloaded) checksum calculations
-- runtime critical function, load specific code during runtime
packet.calculateChecksums = packetCalculateChecksums(args)
for _, v in ipairs(args) do
local data = getHeaderData(v)
header = data['proto']
member = data['name']
-- if the header has a checksum, add a function to calculate it
if header == "ip4" or header == "icmp" then -- FIXME NYI or header == "udp" or header == "tcp" then
local key = 'calculate' .. member:gsub("^.", string.upper) .. 'Checksum'
packet[key] = function(self) self:getHeader(v):calculateChecksum() end
end
end
-- add functions to packet
ffi.metatype(packetName, packet)
-- return 'get'/'cast' for this kind of packet
return function(self) return ctype(self:getData()) end
end
function packetCreate(...)
log:warn('This function is deprecated and will be removed in the future.')
log:warn('Renamed to createStack(...)')
return createStack(...)
end
--- Get the name of the header, the name of the respective member and the length of the variable member
--- @param v Either the name of the header (then the member has the same name), or a table { header, name = member, length = length, subType = type }
--- @return Table with all data: { proto = header, name = member, length = length, subType = type }
function getHeaderData(v)
if not v then
return
elseif type(v) == "table" then
local header = v[1]
local member = v['name']
local subType
-- special alias for ethernet
if v[1] == "eth" or v[1] == "ethernet" then
header = "ethernet"
member = member or "eth"
end
member = member or header
if proto[header].defaultType then
subType = subType or proto[header].defaultType
end
return { proto = header, name = member, length = v['length'], subType = v['subType'] or subType }
else
-- only the header name is given -> member has same name, no variable length
-- special alias for ethernet
if v == "ethernet" or v == "eth" then
return { proto = "ethernet", name = "eth", length = nil, subType = "default" }
end
-- set default subtype if available
local subType
if proto[v].defaultType then
subType = subType or proto[v].defaultType
end
-- otherwise header name = member name
return { proto = v, name = v, length = nil, subType = subType }
end
end
--- Get all headers of a packet as list.
--- @param self The packet
--- @return Table of members of the packet
function packetGetHeaders(self)
local headers = {}
for i, v in ipairs(self:getArgs()) do
headers[i] = packetGetHeader(self, v)
end
return headers
end
--- Get the specified header of a packet (e.g. self.eth).
--- @param self the packet (cdata)
--- @param h header to be returned
--- @return The member of the packet
function packetGetHeader(self, h)
local member = getHeaderData(h)['name']
return self[member]
end
--- Print a hex dump of a packet.
--- @param self the packet
--- @param bytes Number of bytes to dump. If no size is specified the payload is truncated.
--- @param stream the IO stream to write to, optional (default = io.stdout)
--- @param colorized Dump the packet colorized, every protocol in a different color (default = true)
--- @param wireshark Dump in wireshark compatible format (Wireshark -> Import from Hex Dump)
function packetDump(self, bytes, stream, colorized, wireshark)
if type(bytes) == "userdata" then
-- if someone calls this directly on a packet
stream = bytes
bytes = nil
end
bytes = bytes or ffi.sizeof(self:getName())
stream = stream or io.stdout
colorized = colorized == nil or colorized
wireshark = wireshark or false
-- separators (protocol offsets) for colorized hex dump
local seps = { }
local colorCode = ''
if not wireshark then
-- print timestamp
stream:write(colorized and white(getTimeMicros()) or getTimeMicros())
-- headers in cleartext
for i, v in ipairs(self:getHeaders()) do
if colorized then
colorCode = getColorCode(i)
end
local str = v:getString()
if i == 1 then
stream:write(colorCode .. " " .. str .. "\n")
else
stream:write(colorCode .. str .. "\n")
end
seps[#seps + 1] = (seps[#seps] or 0 ) + ffi.sizeof(v)
end
end
-- hex dump
dumpHex(self, bytes, stream, colorized and seps or nil, wireshark)
end
--- Set all members of all headers.
--- Per default, all members are set to default values specified in the respective set function.
--- Optional named arguments can be used to set a member to a user-provided value.
--- The argument 'pktLength' can be used to automatically calculate and set the length member of headers (e.g. ip header).
--- @code
--- fill() --- only default values
--- fill{ ethSrc="12:23:34:45:56:67", ipTTL=100 } --- all members are set to default values with the exception of ethSrc and ipTTL
--- fill{ pktLength=64 } --- only default values, length members of the headers are adjusted
--- @endcode
--- @param self The packet
--- @param args Table of named arguments. For a list of available arguments see "See also"
--- @note This function is slow. If you want to modify members of a header during a time critical section of your script use the respective setters.
function packetFill(self, namedArgs)
namedArgs = namedArgs or {}
local headers = self:getHeaders()
local args = self:getArgs()
local accumulatedLength = 0
for i, v in ipairs(headers) do
local curMember = getHeaderData(args[i])['name']
local nextHeader = getHeaderData(args[i + 1])
nextHeader = nextHeader and nextHeader['proto']
namedArgs = v:setDefaultNamedArgs(curMember, namedArgs, nextHeader, accumulatedLength, ffi.sizeof(v))
v:fill(namedArgs, curMember)
accumulatedLength = accumulatedLength + ffi.sizeof(v)
end
end
--- Retrieve the values of all members as list of named arguments.
--- @param self The packet
--- @return Table of named arguments. For a list of arguments see "See also".
--- @see packetFill
function packetGet(self)
local namedArgs = {}
local args = self:getArgs()
for i, v in ipairs(self:getHeaders()) do
local member = getHeaderData(args[i])['name']
namedArgs = mergeTables(namedArgs, v:get(member))
end
return namedArgs
end
--- Try to find out what the next header in the payload of this packet is.
--- This function is only used for buf:get/buf:dump
--- @param self The packet
function packetResolveLastHeader(self)
local name = self:getName()
local headers = self:getHeaders()
-- do we have struct with correct sub-type?
local subType = headers[#headers]:getSubType()
if subType then
local sub = strSplit(name, "_")
if sub[#sub] ~= subType then
sub[#sub] = subType
local newName = table.concat(sub, "_")
return ffi.cast(newName .. "*", self):resolveLastHeader()
end
end
-- do we have struct with correct header length?
local len = headers[#headers]:getVariableLength()
if len and len > 0 then
local sub = strSplit(name, "_")
local l = sub[#sub - 1]
if len ~= l then
local newArgs = self:getArgs()
local last = newArgs[#newArgs]
if type(last) == "string" then
newArgs[#newArgs] = { last, last, length = len}
else
newArgs[#newArgs]["length"] = len
end
-- build name with len adjusted
sub[#sub - 1] = len
local newName = table.concat(sub, "_")
-- create stack if necessary
if not pkt.packetStructs[newName] then
pkt.TMP_PACKET = createStack(unpack(newArgs))
end
if name ~= newName then
return ffi.cast(newName .. "*", self):resolveLastHeader()
end
end
end
local nextHeader = headers[#headers]:resolveNextHeader()
-- unable to resolve: either there is no next header, or libmoon does not support it yet
-- either case, we stop and return current type of packet
if not nextHeader then
return self
else
local newName, nextMember
local next = getHeaderData(nextHeader)
nextHeader = next['proto']
nextMember = next['name']
nextSubType = next['subType']
nextLength = next['length']
-- we know the next header, append it
name = name .. "__" .. nextHeader
-- if simple struct (headername = membername) already exists we can directly cast
--nextMember = nextHeader
newName = name .. "_" .. nextMember .. "_x_" .. (nextSubType or "x")
if not pkt.packetStructs[newName] then
-- check if a similar struct with this header order exists
newName = name
local found = nil
for k, v in pairs(pkt.packetStructs) do
if string.find(k, newName) and not string.find(string.gsub(k, newName, ""), "__") then
-- the type matches and there are no further headers following (which would have been indicated by another "__")
found = k
break
end
end
if found then
newName = found
else
-- last resort: build new packet type. However, one has to consider that one header
-- might occur multiple times! In this case the member must get a new (unique!) name.
local args = self:getArgs()
local newArgs = {}
local counter = 1
local newMember = nextMember
-- build new args information and in the meantime check for duplicates
for i, v in ipairs(args) do
data = getHeaderData(v)
header = data['proto']
member = data['name']
if member == newMember then
-- found duplicate, increase counter for newMember and keep checking for this one now
counter = counter + 1
newMember = nextMember .. "" .. counter
end
newArgs[i] = v
end
-- add new header and member
newArgs[#newArgs + 1] = { nextHeader, name = newMember, subType = nextSubType, length = nextLength }
-- create new packet. It is unlikely that exactly this packet type with this made up naming scheme will be used
-- Therefore, we don't really want to "safe" the cast function
pkt.TMP_PACKET = createStack(unpack(newArgs))
-- name of the new packet type
newName = newName .. '_' .. newMember .. '_x_' .. (nextSubType or 'x')
end
end
-- finally, cast the packet to the next better fitting packet type and continue resolving
return ffi.cast(newName .. "*", self):resolveLastHeader()
end
end
--- Set length for all headers.
--- Necessary when sending variable sized packets.
--- @param self The packet
--- @param length Length of the packet. Value for respective length member of headers get calculated using this value.
function packetSetLength(args)
local str = ""
-- build the setLength functions for all the headers in this packet type
local accumulatedLength = 0
for _, v in ipairs(args) do
local data = getHeaderData(v)
header = data['proto']
member = data['name']
subType = data['subType']
header = subType and header .. "_" .. subType or header
if header == "ip4" or header == "udp" or header == "ptp" or header == "ipfix" then
str = str .. [[
self.]] .. member .. [[:setLength(length - ]] .. accumulatedLength .. [[)
]]
elseif header == "ip6" then
str = str .. [[
self.]] .. member .. [[:setLength(length - ]] .. accumulatedLength + 40 .. [[)
]]
end
accumulatedLength = accumulatedLength + ffi.sizeof("struct " .. header .. "_header")
end
-- build complete function
str = [[
return function(self, length)]]
.. str .. [[
end]]
-- load new function and return it
local func = assert(loadstring(str))()
return func
end
--- Calculate all checksums manually (not offloading them).
--- There also exist functions to calculate the checksum of only one header.
--- Naming convention: pkt:calculate<member>Checksum() (for all existing packets member = {Ip, Tcp, Udp, Icmp})
--- @note Calculating checksums manually is extremely slow compared to offloading this task to the NIC (~65% performance loss at the moment)
--- @todo Manual calculation of udp and tcp checksums NYI
function packetCalculateChecksums(args)
local str = ""
for _, v in ipairs(args) do
local data = getHeaderData(v)
header = data['proto']
member = data['name']
-- if the header has a checksum, call the function
if header == "ip4" or header == "icmp" then -- FIXME NYI or header == "udp"
str = str .. [[
self.]] .. member .. [[:calculateChecksum()
]]
elseif header == "tcp" then
str = str .. [[
self.]] .. member .. [[:calculateChecksum(data, len, ipv4)
]]
end
end
-- build complete function
str = [[
return function(self, data, len, ipv4)]]
.. str .. [[
end]]
-- load new function and return it
local func = assert(loadstring(str))()
return func
end
local createdHeaderStructs = {}
local headerStructTemplate = [[
struct __attribute__((__packed__)) NAME {
MEMBER};]]
local function defineHeaderStruct(p, subType, size)
local name = p .. (subType and "_" .. subType or "") .. "_header" .. (size and "_" .. size or "")
-- check whether it already ecists
if createdHeaderStructs[name] then
log:debug("Header struct " .. name .. " already exists, skipping.")
return name
end
-- build struct from template and proto header format
local str = headerStructTemplate
if proto[p].defaultType then
subType = subType or proto[p].defaultType
end
str = string.gsub(str, "MEMBER", (subType and proto[p][subType].headerFormat or proto[p].headerFormat))
-- set size of variable sized member
if proto[p].headerVariableMember then
local member = (subType and proto[p][subType].headerVariableMember or proto[p].headerVariableMember) .. "%["
str = string.gsub(str, member, member .. (size or 0))
end
-- build the name
str = string.gsub(str, "NAME", name)
-- define and add header related functions
ffi.cdef(str)
ffi.metatype("struct " .. name, (subType and proto[p][subType].metatype or proto[p].metatype))
log:debug("Created " .. name .. str)
-- add to list of already created header structs
createdHeaderStructs[name] = true
-- return name used to generate stack
return name
end
--- Table that contains the names and args of all created packet structs
pkt.packetStructs = {}
-- List all created packet structs enlisted in packetStructs
-- Debugging function
function listPacketStructs()
printf("All available packet structs:")
for k, v in pairs(pkt.packetStructs) do
printf(k)
end
end
--- Creates a packet struct (cdata) consisting of different headers.
--- Simply list the headers in the order you want them to be in a packet.
--- If you want the member to be named differently, use the following syntax:
--- normal: <header> ; different membername: { <header>, <member> }.
--- Supported keywords: eth, arp, ptp, ip, ip6, udp, tcp, icmp
--- @code
--- makeStruct('eth', { 'ip4', 'ip' }, 'udp') --- creates an UDP packet struct
--- --- the ip4 member of the packet is named 'ip'
--- @endcode
--- The name of the created (internal) struct looks as follows:
--- struct __HEADER1_MEMBER1__HEADER2_MEMBER2 ...
--- Only the "__" (double underscore) has the special meaning of "a new header starts with name
--- <everything until "_" (single underscore)>, followed by the member name <everything after "_"
--- until next header starts (indicated by next __)>"
--- @param args list of keywords/tables of keyword-member pairs
--- @param noPayload do not append payload VLA
--- @return name name of the struct
--- @return ctype ctype of the struct
function packetMakeStruct(args, noPayload)
local name = ""
local str = ""
local members = {}
-- add the specified headers and build the name
for _, v in ipairs(args) do
local data = getHeaderData(v)
header = data['proto']
member = data['name']
length = data['length']
subType = data['subType']
-- check for duplicate member names as ffi does not crash (it is mostly ignored)
if members[member] then
log:fatal("Member within this struct has same name: %s \n%s", member, str)
end
members[member] = true
local headerStruct = defineHeaderStruct(header, subType, length)
-- add header
str = str .. [[
struct ]] .. headerStruct .. ' ' .. member .. [[;
]]
-- build name
name = name .. "__" .. header .. "_" .. member .. "_" .. (length or "x") .. "_" .. (subType or "x")
end
-- handle raw packet
if name == "" then
name = "raw"
end
-- add rest of the struct
str = [[
struct __attribute__((__packed__)) ]]
.. name
.. [[ {
]]
.. str
.. (not noPayload and [[
union payload_t payload;
]] or "")
.. "};"
name = "struct " .. name
-- check uniqueness of packet type (name of struct)
if pkt.packetStructs[name] then
log:warn("Struct with name \"" .. name .. "\" already exists. Skipping.")
return
else
-- add to list of existing structs
pkt.packetStructs[name] = {args}
log:debug("Created struct %s", name)
log:debug("%s", str)
-- add struct definition
ffi.cdef(str)
-- return full name and typeof
return name, ffi.typeof(name .. "*")
end
end
--! Setter for raw packets
--! @param data: raw packet data
function pkt:setRawPacket(data)
self:setSize(#data)
ffi.copy(self:getData(), data)
end
---------------------------------------------------------------------------
---- Metatypes
---------------------------------------------------------------------------
ffi.metatype("struct rte_mbuf", pkt)
---------------------------------------------------------------------------
---- Protocol Stacks
---------------------------------------------------------------------------
pkt.getRawPacket = createStack()
pkt.getEthernetPacket = createStack("eth")
pkt.getEthPacket = pkt.getEthernetPacket
pkt.getEthernetVlanPacket = createStack({"eth", subType = "vlan"})
pkt.getEthVlanPacket = pkt.getEthernetVlanPacket
pkt.getEthernetQinQPacket = createStack({"eth", subType = "qinq"})
pkt.getEthQinQPacket = pkt.getEthernetQinQPacket
pkt.getIP4Packet = createStack("eth", "ip4")
pkt.getIP6Packet = createStack("eth", "ip6")
pkt.getIPPacket = function(self, ip4)
ip4 = ip4 == nil or ip4
if ip4 then
return pkt.getIP4Packet(self)
else
return pkt.getIP6Packet(self)
end
end
pkt.getArpPacket = createStack("eth", "arp")
pkt.getIcmp4Packet = createStack("eth", "ip4", "icmp")
pkt.getIcmp6Packet = createStack("eth", "ip6", "icmp")
pkt.getIcmpPacket = function(self, ip4)
ip4 = ip4 == nil or ip4
if ip4 then
return pkt.getIcmp4Packet(self)
else
return pkt.getIcmp6Packet(self)
end
end
pkt.getUdp4Packet = createStack("eth", "ip4", "udp")
pkt.getUdp6Packet = createStack("eth", "ip6", "udp")
pkt.getUdpPacket = function(self, ip4)
ip4 = ip4 == nil or ip4
if ip4 then
return pkt.getUdp4Packet(self)
else
return pkt.getUdp6Packet(self)
end
end
pkt.getTcp4Packet = createStack("eth", "ip4", "tcp")
pkt.getTcp6Packet = createStack("eth", "ip6", "tcp")
pkt.getTcpPacket = function(self, ip4)
ip4 = ip4 == nil or ip4
if ip4 then
return pkt.getTcp4Packet(self)
else
return pkt.getTcp6Packet(self)
end
end
pkt.getPtpPacket = createStack("eth", "ptp")
pkt.getUdpPtpPacket = createStack("eth", "ip4", "udp", "ptp")
pkt.getVxlanPacket = createStack("eth", "ip4", "udp", "vxlan")
pkt.getVxlanEthernetPacket = createStack("eth", "ip4", "udp", "vxlan", { "eth", name = "innerEth" })
pkt.getEsp4Packet = createStack("eth", "ip4", "esp")
pkt.getEsp6Packet = createStack("eth", "ip6", "esp")
pkt.getEspPacket = function(self, ip4)
ip4 = ip4 == nil or ip4
if ip4 then
return pkt.getEsp4Packet(self)
else
return pkt.getEsp6Packet(self)
end
end
pkt.getAH4Packet = createStack("eth", "ip4", "ah")
pkt.getAH6Packet = nil --createStack("eth", "ip6", "ah6") --TODO: AH6 needs to be implemented
pkt.getAHPacket = function(self, ip4)
ip4 = ip4 == nil or ip4
if ip4 then
return pkt.getAH4Packet(self)
else
return pkt.getAH6Packet(self)
end
end
pkt.getDns4Packet = createStack('eth', 'ip4', 'udp', 'dns')
pkt.getDns6Packet = createStack('eth', 'ip6', 'udp', 'dns')
pkt.getDnsPacket = function(self, ip4)
ip4 = ip4 == nil or ip4
if ip4 then
return pkt.getDns4Packet(self)
else
return pkt.getDns6Packet(self)
end
end
pkt.getSFlowPacket = createStack("eth", "ip4", "udp", {"sflow", subType = "ip4"}, "noPayload")
pkt.getIpfixPacket = createStack("eth", "ip4", "udp", "ipfix")
pkt.getLacpPacket = createStack('eth', 'lacp')
pkt.getGre4Packet = createStack("eth", "ip4", "gre")
pkt.getGre6Packet = createStack("eth", "ip6", "gre")
pkt.getGrePacket = function(self, ip4)
ip4 = ip4 == nil or ip4
if ip4 then
return pkt.getGre4Packet(self)
else
return pkt.getGre6Packet(self)
end
end
pkt.getGre4QinQPacket = createStack("eth", "ip4", "gre", {"eth", subType = "qinq", name = "etherQinQ"}, {"ip4", name = "nestedIp4"})
pkt.getGre6QinQPacket = createStack("eth", "ip6", "gre", {"eth", subType = "qinq", name = "etherQinQ"}, {"ip6", name = "nestedIp6"})
pkt.getGreQinQPacket = function(self, ip4)
ip4 = ip4 == nil or ip4
if ip4 then
return pkt.getGre4QinQPacket(self)
else
return pkt.getGre6QinQPacket(self)
end
end
pkt.getGreQinQArpPacket = createStack("eth", "ip4", "gre", {"eth", subType = "qinq", name = "etherQinQ"}, "arp")
pkt.getGre4QinQUdpPacket = createStack("eth", "ip4", "gre", {"eth", subType = "qinq", name = "etherQinQ"}, {"ip4", name = "nestedIp4"}, "udp")
pkt.getGre6QinQUdpPacket = createStack("eth", "ip6", "gre", {"eth", subType = "qinq", name = "etherQinQ"}, {"ip6", name = "nestedIp6"}, "udp")
pkt.getGreQinQUdpPacket = function(self, ip4)
ip4 = ip4 == nil or ip4
if ip4 then
return pkt.getGre4QinQUdpPacket(self)
else
return pkt.getGre6QinQUdpPacket(self)
end
end
return pkt
| mit |
chris5560/openwrt-luci | modules/luci-mod-freifunk/luasrc/controller/freifunk/freifunk.lua | 6 | 5893 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.freifunk.freifunk", package.seeall)
function index()
local uci = require "luci.model.uci".cursor()
local page
-- Frontend
page = node()
page.lock = true
page.target = alias("freifunk")
page.subindex = true
page.index = false
page = node("freifunk")
page.title = _("Freifunk")
page.target = alias("freifunk", "index")
page.order = 5
page.setuser = "nobody"
page.setgroup = "nogroup"
page.i18n = "freifunk"
page.index = true
page = node("freifunk", "index")
page.target = template("freifunk/index")
page.title = _("Overview")
page.order = 10
page.indexignore = true
page = node("freifunk", "contact")
page.target = template("freifunk/contact")
page.title = _("Contact")
page.order = 15
page = node("freifunk", "status")
page.target = template("freifunk/public_status")
page.title = _("Status")
page.order = 20
page.i18n = "base"
page.setuser = false
page.setgroup = false
entry({"freifunk", "status.json"}, call("jsonstatus"))
entry({"freifunk", "status", "zeroes"}, call("zeroes"), "Testdownload")
if nixio.fs.access("/usr/sbin/luci-splash") then
assign({"freifunk", "status", "splash"}, {"splash", "publicstatus"}, _("Splash"), 40)
end
page = assign({"freifunk", "olsr"}, {"admin", "status", "olsr"}, _("OLSR"), 30)
page.setuser = false
page.setgroup = false
if nixio.fs.access("/etc/config/luci_statistics") then
assign({"freifunk", "graph"}, {"admin", "statistics", "graph"}, _("Statistics"), 40)
end
-- backend
assign({"mini", "freifunk"}, {"admin", "freifunk"}, _("Freifunk"), 5)
entry({"admin", "freifunk"}, alias("admin", "freifunk", "index"), _("Freifunk"), 5)
page = node("admin", "freifunk")
page.target = template("freifunk/adminindex")
page.title = _("Freifunk")
page.order = 5
page = node("admin", "freifunk", "basics")
page.target = cbi("freifunk/basics")
page.title = _("Basic Settings")
page.order = 5
page = node("admin", "freifunk", "basics", "profile")
page.target = cbi("freifunk/profile")
page.title = _("Profile")
page.order = 10
page = node("admin", "freifunk", "basics", "profile_expert")
page.target = form("freifunk/profile_expert")
page.title = _("Profile (Expert)")
page.order = 20
page = node("admin", "freifunk", "Index-Page")
page.target = cbi("freifunk/user_index")
page.title = _("Index Page")
page.order = 50
page = node("admin", "freifunk", "contact")
page.target = cbi("freifunk/contact")
page.title = _("Contact")
page.order = 15
entry({"freifunk", "map"}, template("freifunk-map/frame"), _("Map"), 50)
entry({"freifunk", "map", "content"}, template("freifunk-map/map"), nil, 51)
entry({"admin", "freifunk", "profile_error"}, template("freifunk/profile_error"))
end
function zeroes()
local string = require "string"
local http = require "luci.http"
local zeroes = string.rep(string.char(0), 8192)
local cnt = 0
local lim = 1024 * 1024 * 1024
http.prepare_content("application/x-many-zeroes")
while cnt < lim do
http.write(zeroes)
cnt = cnt + #zeroes
end
end
function jsonstatus()
local root = {}
local sys = require "luci.sys"
local uci = require "luci.model.uci"
local util = require "luci.util"
local http = require "luci.http"
local json = require "luci.json"
local ltn12 = require "luci.ltn12"
local version = require "luci.version"
local webadmin = require "luci.tools.webadmin"
local cursor = uci.cursor_state()
local ffzone = webadmin.firewall_find_zone("freifunk")
local ffznet = ffzone and cursor:get("firewall", ffzone, "network")
local ffwifs = ffznet and util.split(ffznet, " ") or {}
local sysinfo = util.ubus("system", "info") or { }
local boardinfo = util.ubus("system", "board") or { }
local loads = sysinfo.load or { 0, 0, 0 }
local memory = sysinfo.memory or {
total = 0,
free = 0,
shared = 0,
buffered = 0
}
local swap = sysinfo.swap or {
total = 0,
free = 0
}
root.protocol = 1
root.system = {
uptime = { sysinfo.uptime or 0 },
loadavg = { loads[1] / 65535.0, loads[2] / 65535.0, loads[3] / 65535.0 },
sysinfo = {
boardinfo.system or "?",
boardinfo.model or "?",
memory.total,
0, -- former cached memory
memory.buffered,
memory.free,
0, -- former bogomips
swap.total,
0, -- former cached swap
swap.free
},
hostname = boardinfo.hostname
}
root.firmware = {
luciname=version.luciname,
luciversion=version.luciversion,
distname=version.distname,
distversion=version.distversion
}
root.freifunk = {}
cursor:foreach("freifunk", "public", function(s)
root.freifunk[s[".name"]] = s
end)
cursor:foreach("system", "system", function(s)
root.geo = {
latitude = s.latitude,
longitude = s.longitude
}
end)
root.network = {}
root.wireless = {devices = {}, interfaces = {}, status = {}}
local wifs = root.wireless.interfaces
for _, vif in ipairs(ffwifs) do
root.network[vif] = cursor:get_all("network", vif)
root.wireless.devices[vif] = cursor:get_all("wireless", vif)
cursor:foreach("wireless", "wifi-iface", function(s)
if s.device == vif and s.network == vif then
wifs[#wifs+1] = s
if s.ifname then
local iwinfo = luci.sys.wifi.getiwinfo(s.ifname)
if iwinfo then
root.wireless.status[s.ifname] = { }
local _, f
for _, f in ipairs({
"channel", "txpower", "bitrate", "signal", "noise",
"quality", "quality_max", "mode", "ssid", "bssid", "encryption", "ifname"
}) do
root.wireless.status[s.ifname][f] = iwinfo[f]
end
end
end
end
end)
end
http.prepare_content("application/json")
ltn12.pump.all(json.Encoder(root):source(), http.write)
end
| apache-2.0 |
xdemolish/darkstar | scripts/zones/Northern_San_dOria/npcs/Chaupire.lua | 17 | 1259 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Chaupire
-- Guild Merchant NPC: Woodworking Guild
-- @pos -174.476 3.999 281.854 231
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:sendGuild(5132,6,21,0)) then
player:showText(npc,CHAUPIRE_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
xdemolish/darkstar | scripts/globals/items/acorn_cookie.lua | 35 | 1338 | -----------------------------------------
-- ID: 4510
-- Item: Acorn Cookie
-- Food Effect: 3Min, All Races
-----------------------------------------
-- Magic Regen While Healing 3
-- Aquan Killer 5
-- Sleep Resist 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,180,4510);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MPHEAL, 3);
target:addMod(MOD_AQUAN_KILLER, 5);
target:addMod(MOD_SLEEPRES, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MPHEAL, 3);
target:delMod(MOD_AQUAN_KILLER, 5);
target:delMod(MOD_SLEEPRES, 5);
end;
| gpl-3.0 |
gutenye/tagen.lua | tests/test-set.lua | 10 | 3233 | class = require 'pl.class'
M = require 'pl.Map'
S = require 'pl.Set'
List = require 'pl.List'
asserteq = require 'pl.test' . asserteq
asserteq2 = require 'pl.test' . asserteq2
MultiMap = require 'pl.MultiMap'
OrderedMap = require 'pl.OrderedMap'
s1 = S{1,2}
s2 = S{1,2}
-- equality
asserteq(s1,s2)
-- union
asserteq(S{1,2} + S{2,3},S{1,2,3})
-- intersection
asserteq(S{1,2} * S{2,3}, S{2})
-- symmetric_difference
asserteq(S{1,2} ^ S{2,3}, S{1,3})
m = M{one=1,two=2}
asserteq(m,M{one=1,two=2})
m:update {three=3,four=4}
asserteq(m,M{one=1,two=2,three=3,four=4})
class.Animal()
function Animal:_init(name)
self.name = name
end
function Animal:__tostring()
return self.name..': '..self:speak()
end
class.Dog(Animal)
function Dog:speak()
return 'bark'
end
class.Cat(Animal)
function Cat:_init(name,breed)
self:super(name) -- must init base!
self.breed = breed
end
function Cat:speak()
return 'meow'
end
Lion = class(Cat)
function Lion:speak()
return 'roar'
end
fido = Dog('Fido')
felix = Cat('Felix','Tabby')
leo = Lion('Leo','African')
asserteq(tostring(fido),'Fido: bark')
asserteq(tostring(felix),'Felix: meow')
asserteq(tostring(leo),'Leo: roar')
assert(Dog:class_of(fido))
assert(fido:is_a(Dog))
assert(leo:is_a(Animal))
m = MultiMap()
m:set('john',1)
m:set('jane',3)
m:set('john',2)
ms = MultiMap{john={1,2},jane={3}}
asserteq(m,ms)
m = OrderedMap()
m:set('one',1)
m:set('two',2)
m:set('three',3)
asserteq(m:values(),List{1,2,3})
-- usually exercized like this:
--for k,v in m:iter() do print(k,v) end
fn = m:iter()
asserteq2 ('one',1,fn())
asserteq2 ('two',2,fn())
asserteq2 ('three',3,fn())
o1 = OrderedMap {{z=2},{beta=1},{name='fred'}}
asserteq(tostring(o1),'{z=2,beta=1,name="fred"}')
-- order of keys is not preserved here!
o2 = OrderedMap {z=4,beta=1.1,name='alice',extra='dolly'}
o1:update(o2)
asserteq(tostring(o1),'{z=4,beta=1.1,name="alice",extra="dolly"}')
o1:set('beta',nil)
asserteq(o1,OrderedMap{{z=4},{name='alice'},{extra='dolly'}})
o3 = OrderedMap()
o3:set('dog',10)
o3:set('cat',20)
o3:set('mouse',30)
asserteq(o3:keys(),{'dog','cat','mouse'})
o3:set('dog',nil)
asserteq(o3:keys(),{'cat','mouse'})
-- Vadim found a problem when clearing a key which did not exist already.
-- The keys list would then contain the key, although the map would not
o3:set('lizard',nil)
asserteq(o3:keys(),{'cat','mouse'})
asserteq(o3:values(), {20,30})
asserteq(tostring(o3),'{cat=20,mouse=30}')
-- copy constructor
o4 = OrderedMap(o3)
asserteq(o4,o3)
-- constructor throws an error if the argument is bad
-- (errors same as OrderedMap:update)
asserteq(false,pcall(function()
m = OrderedMap('string')
end))
---- changing order of key/value pairs ----
o3 = OrderedMap{{cat=20},{mouse=30}}
o3:insert(1,'bird',5) -- adds key/value before specified position
o3:insert(1,'mouse') -- moves key keeping old value
asserteq(o3:keys(),{'mouse','bird','cat'})
asserteq(tostring(o3),'{mouse=30,bird=5,cat=20}')
o3:insert(2,'cat',21) -- moves key and sets new value
asserteq(tostring(o3),'{mouse=30,cat=21,bird=5}')
-- if you don't specify a value for an unknown key, nothing happens to the map
o3:insert(3,'alligator')
asserteq(tostring(o3),'{mouse=30,cat=21,bird=5}')
| gpl-3.0 |
henrythasler/nodemcu | rc-car/src/webserver-websocket.lua | 1 | 4676 | local function encode(opcode, payload)
local len = #payload
local frame = {}
frame[#frame + 1] =
string.char(bit.bor(0x80, opcode), bit.bor((len < 126) and len or ((len < 0x10000) and 126 or 127)))
if len >= 0x10000 then
frame[#frame + 1] =
string.char(0, 0, 0, 0, -- 32 bit length is plenty, assume zero for rest
bit.band(bit.rshift(len, 24), 0xff),
bit.band(bit.rshift(len, 16), 0xff),
bit.band(bit.rshift(len, 8), 0xff),
bit.band(len, 0xff)
)
elseif len >= 126 then
frame[#frame + 1] = string.char(bit.band(bit.rshift(len, 8), 0xff), bit.band(len, 0xff))
end
frame[#frame + 1] = payload
return table.concat(frame)
end
return function(sck, request)
local opcodes = {[0] = "Continuation", [1] = "Text", [2] = "binary", [8] = "Close", [9] = "Ping", [10] = "Pong"}
local closingHandshake = false
local statusCode = nil
local txBufferContent = 0 -- keep track of transmit buffer content so we close the connection only AFTER everything was sent.
local function sendSensorData(local_conn)
if sensor:isPresent() then
local ax, ay, az, temperature, gx, gy, gz = sensor:readAll()
-- create json string
data =
string.format(
'{"ax":%f,"ay":%f,"az":%f,"gx":%f,"gy":%f,"gz":%f,"utc":%u,"temp":%f,"timestamp":%u}',
ax,
ay,
az,
gx,
gy,
gz,
rtctime.get(),
temperature,
tmr.now()
)
local_conn:send(encode(0x01, data)) -- send as "Text" (0x01)
txBufferContent = txBufferContent + 1
end
end
-- callback upon completion of current response
local function ws_sent(local_conn)
txBufferContent = (txBufferContent > 0) and (txBufferContent - 1) or 0
if closingHandshake then
if txBufferContent == 0 then
print("[ws] - closing")
local_conn:close()
maxThreads = maxThreads + 1
gpio.write(0, 0) -- turn LED on
end
elseif txBufferContent == 0 then
sendSensorData(local_conn)
end
end
local function ws_receive(local_conn, data)
local temp = {}
local payload = nil
for i = 1, #data do
temp[#temp + 1] = string.format("%X ", string.byte(data, i))
end
print("[ws] - received: " .. table.concat(temp))
local opcode = bit.band(string.byte(data, 1), 0x0f)
print("[ws] - Opcode: " .. opcodes[opcode])
local payloadLen = bit.band(string.byte(data, 2), 0x0f)
if payloadLen == 126 then
payloadLen = string.byte(data, 3) * 256 + string.byte(data, 4)
elseif payloadLen == 127 then
payloadLen = 0x10000 -- FIXME: needs implementation
end
print("[ws] - payloadLen=", payloadLen)
-- connection is about to be closed (either client or server initiated)
if opcode == 0x08 then
if closingHandshake then
print("[ws] - closingHandshake done - close")
local_conn:close()
else
closingHandshake = true
print("[ws] - closingHandshake return")
--statusCode = 1001
local_conn:send(
encode(0x08, "")
--string.char(bit.band(bit.rshift(statusCode, 8), 0xff), bit.band(statusCode, 0xff)))
)
txBufferContent = txBufferContent + 1
end
end
end
-- client closed the connection
local function ws_disconnect(local_conn)
print("[ws] - closed")
maxThreads = maxThreads + 1
gpio.write(0, 0) -- turn LED on
end
-- (un)register websocket callbacks
sck:on("sent", ws_sent)
sck:on("disconnection", ws_disconnect)
sck:on("receive", ws_receive)
-- compute response challenge as per rfc6455#section-1.3
local key = request:match("Sec%-WebSocket%-Key: ([A-Za-z0-9+/=]+)")
local accept = crypto.toBase64(crypto.hash("sha1", key .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))
-- delete unused webserver callback functions
on_sent = nil
on_receive = nil
dofile("webserver-header.lc")(
sck,
101,
nil,
false,
{"Sec-WebSocket-Accept: " .. accept, "Upgrade: websocket", "Connection: Upgrade"},
false
)
print("[ws] - open")
txBufferContent = txBufferContent + 1
return true
end
| mit |
czfshine/UpAndAway | code/prefabs/bee_marshmallow.lua | 2 | 7514 | BindGlobal()
local CFG = TheMod:GetConfig()
local beecommon = require "brains/beecommon"
local workersounds =
{
takeoff = "dontstarve/bee/bee_takeoff",
attack = "dontstarve/bee/bee_attack",
buzz = "dontstarve/bee/bee_fly_LP",
hit = "dontstarve/bee/bee_hurt",
death = "dontstarve/bee/bee_death",
}
local killersounds =
{
takeoff = "dontstarve/bee/killerbee_takeoff",
attack = "dontstarve/bee/killerbee_attack",
buzz = "dontstarve/bee/killerbee_fly_LP",
hit = "dontstarve/bee/killerbee_hurt",
death = "dontstarve/bee/killerbee_death",
}
local assets=
{
Asset("ANIM", "anim/bee_marshmallow.zip"),
Asset("ANIM", "anim/bee_angry_build.zip"),
Asset("ANIM", "anim/bee_build.zip"),
Asset("ANIM", "anim/bee.zip"),
Asset("SOUND", "sound/bee.fsb"),
Asset( "ATLAS", inventoryimage_atlas("bee_marshmallow") ),
Asset( "IMAGE", inventoryimage_texture("bee_marshmallow") ),
}
local prefabs = CFG.BEE_MARSHMALLOW.PREFABS
SetSharedLootTable( "bee_marshmallow", CFG.BEE_MARSHMALLOW.LOOT)
local workerbrain = require("brains/beebrain")
local killerbrain = require("brains/killerbeebrain")
local function KillerRetarget(inst)
return FindEntity(inst, 8, function(guy)
return (guy:HasTag("character") or guy:HasTag("animal") or guy:HasTag("monster") )
and not guy:HasTag("insect")
and inst.components.combat:CanTarget(guy)
end)
end
local function onunchargefn(inst)
inst.AnimState:SetBank("bee")
inst.AnimState:SetBuild("bee_marshmallow")
inst.AnimState:PlayAnimation("idle")
inst.Transform:SetScale(CFG.BEE_MARSHMALLOW.UNCHARGED_SCALE, CFG.BEE_MARSHMALLOW.UNCHARGED_SCALE, CFG.BEE_MARSHMALLOW.UNCHARGED_SCALE)
inst:RemoveTag("scarytoprey")
inst.components.health:SetMaxHealth(CFG.BEE_MARSHMALLOW.UNCHARGED_HEALTH)
inst.components.combat:SetDefaultDamage(CFG.BEE_MARSHMALLOW.UNCHARGED_DAMAGE)
inst.components.combat:SetAttackPeriod(CFG.BEE_MARSHMALLOW.UNCHARGED_ATTACK_PERIOD)
if not inst.components.pollinator then
inst:AddComponent("pollinator")
end
inst:SetBrain(workerbrain)
inst.sounds = workersounds
return inst
end
local function onchargefn(inst)
inst:AddTag("scarytoprey")
inst.AnimState:SetBank("bee")
inst.AnimState:SetBuild("bee_marshmallow")
inst.AnimState:PlayAnimation("idle")
inst.Transform:SetScale(CFG.BEE_MARSHMALLOW.CHARGED_SCALE, CFG.BEE_MARSHMALLOW.CHARGED_SCALE, CFG.BEE_MARSHMALLOW.CHARGED_SCALE)
inst.components.health:SetMaxHealth(CFG.BEE_MARSHMALLOW.CHARGED_HEALTH)
inst.components.combat:SetDefaultDamage(CFG.BEE_MARSHMALLOW.CHARGED_DAMAGE)
inst.components.combat:SetAttackPeriod(CFG.BEE_MARSHMALLOW.CHARGED_ATTACK_PERIOD)
inst.components.combat:SetRetargetFunction(2, KillerRetarget)
if inst.components.pollinator then
inst:RemoveComponent("pollinator")
end
inst:SetBrain(killerbrain)
inst.sounds = killersounds
return inst
end
local function OnAttacked(inst)
--
end
local function OnWorked(inst, worker)
local owner = inst.components.homeseeker and inst.components.homeseeker.home
if owner and owner.components.childspawner then
owner.components.childspawner:OnChildKilled(inst)
end
if worker.components.inventory then
FightStat_Caught(inst)
worker.components.inventory:GiveItem(inst, nil, Vector3(TheSim:GetScreenPos(inst.Transform:GetWorldPosition())))
end
end
local function OnDropped(inst)
inst.sg:GoToState("catchbreath")
if inst.components.workable then
inst.components.workable:SetWorkLeft(1)
end
if inst.brain then
inst.brain:Start()
end
if inst.sg then
inst.sg:Start()
end
if inst.components.stackable then
while inst.components.stackable:StackSize() > 1 do
local item = inst.components.stackable:Get()
if item then
if item.components.inventoryitem then
item.components.inventoryitem:OnDropped()
end
item.Physics:Teleport(inst.Transform:GetWorldPosition() )
end
end
end
end
local function OnPickedUp(inst)
inst.sg:GoToState("idle")
end
local function commonfn()
local inst = CreateEntity()
inst.entity:AddTransform()
inst.entity:AddAnimState()
inst.entity:AddSoundEmitter()
inst.entity:AddLightWatcher()
inst.entity:AddDynamicShadow()
inst.DynamicShadow:SetSize( .8, .5 )
inst.Transform:SetFourFaced()
inst.AnimState:SetBank("bee")
inst.AnimState:SetBuild("bee_marshmallow")
inst.AnimState:PlayAnimation("idle")
inst.AnimState:SetRayTestOnBB(true);
----------
inst:AddTag("bee")
inst:AddTag("insect")
inst:AddTag("hit_panic")
inst:AddTag("smallcreature")
MakeCharacterPhysics(inst, 1, .5)
inst.Physics:SetCollisionGroup(COLLISION.FLYERS)
inst.Physics:ClearCollisionMask()
inst.Physics:CollidesWith(COLLISION.WORLD)
inst.Physics:CollidesWith(COLLISION.FLYERS)
------------------------------------------------------------------------
SetupNetwork(inst)
------------------------------------------------------------------------
inst:AddComponent("locomotor") -- locomotor must be constructed before the stategraph
inst.components.locomotor:EnableGroundSpeedMultiplier(false)
inst.components.locomotor:SetTriggersCreep(false)
inst:SetStateGraph("SGbee")
inst:AddComponent("inventoryitem")
inst.components.inventoryitem.atlasname = inventoryimage_atlas("bee_marshmallow")
inst:AddComponent("stackable")
inst.components.inventoryitem.nobounce = true
inst.components.inventoryitem:SetOnDroppedFn(OnDropped)
inst.components.inventoryitem:SetOnPutInInventoryFn(OnPickedUp)
inst.components.inventoryitem.canbepickedup = false
---------------------
inst:AddComponent("lootdropper")
inst.components.lootdropper:SetChanceLootTable("bee_marshmallow")
inst.components.lootdropper.numrandomloot = CFG.BEE_MARSHMALLOW.NUMRANDOMLOOT
------------------
inst:AddComponent("workable")
inst.components.workable:SetWorkAction(ACTIONS.NET)
inst.components.workable:SetWorkLeft(1)
inst.components.workable:SetOnFinishCallback(OnWorked)
MakeSmallBurnableCharacter(inst, "body", Vector3(0, -1, 0))
MakeTinyFreezableCharacter(inst, "body", Vector3(0, -1, 0))
------------------
inst:AddComponent("health")
------------------
inst:AddComponent("combat")
inst.components.combat.hiteffectsymbol = "body"
------------------
inst:AddComponent("sleeper")
------------------
inst:AddComponent("knownlocations")
inst:AddComponent("edible")
inst.components.edible.foodtype = CFG.BEE_MARSHMALLOW.FOODTYPE
inst.components.edible.healthvalue = CFG.BEE_MARSHMALLOW.HEALTHVALUE
inst.components.edible.hungervalue = CFG.BEE_MARSHMALLOW.HUNGERVALUE
inst.components.edible.sanityvalue = CFG.BEE_MARSHMALLOW.SANITYVALUE
inst:AddComponent("inspectable")
inst:ListenForEvent("attacked", OnAttacked)
inst:AddComponent("staticchargeable")
inst.components.staticchargeable:SetOnChargeFn(onchargefn)
inst.components.staticchargeable:SetOnUnchargeFn(onunchargefn)
onunchargefn(inst)
return inst
end
return Prefab( "forest/monsters/bee_marshmallow", commonfn, assets, prefabs)
| gpl-2.0 |
grmss214/SHATELTEAM | plugins/Map.lua | 2 | 1495 | -- Implement a command !loc [area] which uses
-- the static map API to get a location image
-- Not sure if this is the proper way
-- Intent: get_latlong is in time.lua, we need it here
-- loadfile "time.lua"
-- Globals
-- If you have a google api key for the geocoding/timezone api
do
local api_key = nil
local base_api = "https://maps.googleapis.com/maps/api"
function get_staticmap(area)
local api = base_api .. "/staticmap?"
-- Get a sense of scale
local lat,lng,acc,types = get_latlong(area)
local scale = types[1]
if scale=="locality" then zoom=8
elseif scale=="country" then zoom=4
else zoom = 13 end
local parameters =
"size=600x300" ..
"&zoom=" .. zoom ..
"¢er=" .. URL.escape(area) ..
"&markers=color:red"..URL.escape("|"..area)
if api_key ~=nil and api_key ~= "" then
parameters = parameters .. "&key="..api_key
end
return lat, lng, api..parameters
end
function run(msg, matches)
local receiver = get_receiver(msg)
local lat,lng,url = get_staticmap(matches[1])
-- Send the actual location, is a google maps link
send_location(receiver, lat, lng, ok_cb, false)
-- Send a picture of the map, which takes scale into account
send_photo_from_url(receiver, url)
-- Return a link to the google maps stuff is now not needed anymore
return nil
end
return {
description = "Get Man Location by Name",
usage = "/map (name) : get map and location",
patterns = {"^map (.*)$"},
run = run
}
end
| gpl-2.0 |
jy723/ardupilot | Tools/CHDK-Scripts/kap_uav.lua | 183 | 28512 | --[[
KAP UAV Exposure Control Script v3.1
-- Released under GPL by waterwingz and wayback/peabody
http://chdk.wikia.com/wiki/KAP_%26_UAV_Exposure_Control_Script
@title KAP UAV 3.1
@param i Shot Interval (sec)
@default i 15
@range i 2 120
@param s Total Shots (0=infinite)
@default s 0
@range s 0 10000
@param j Power off when done?
@default j 0
@range j 0 1
@param e Exposure Comp (stops)
@default e 6
@values e -2.0 -1.66 -1.33 -1.0 -0.66 -0.33 0.0 0.33 0.66 1.00 1.33 1.66 2.00
@param d Start Delay Time (sec)
@default d 0
@range d 0 10000
@param y Tv Min (sec)
@default y 0
@values y None 1/60 1/100 1/200 1/400 1/640
@param t Target Tv (sec)
@default t 5
@values t 1/100 1/200 1/400 1/640 1/800 1/1000 1/1250 1/1600 1/2000
@param x Tv Max (sec)
@default x 3
@values x 1/1000 1/1250 1/1600 1/2000 1/5000 1/10000
@param f Av Low(f-stop)
@default f 4
@values f 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0
@param a Av Target (f-stop)
@default a 7
@values a 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0
@param m Av Max (f-stop)
@default m 13
@values m 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0
@param p ISO Min
@default p 1
@values p 80 100 200 400 800 1250 1600
@param q ISO Max1
@default q 2
@values q 100 200 400 800 1250 1600
@param r ISO Max2
@default r 3
@values r 100 200 400 800 1250 1600
@param n Allow use of ND filter?
@default n 1
@values n No Yes
@param z Zoom position
@default z 0
@values z Off 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100%
@param c Focus @ Infinity Mode
@default c 0
@values c None @Shot AFL MF
@param v Video Interleave (shots)
@default v 0
@values v Off 1 5 10 25 50 100
@param w Video Duration (sec)
@default w 10
@range w 5 300
@param u USB Shot Control?
@default u 0
@values u None On/Off OneShot PWM
@param b Backlight Off?
@default b 0
@range b 0 1
@param l Logging
@default l 3
@values l Off Screen SDCard Both
--]]
props=require("propcase")
capmode=require("capmode")
-- convert user parameter to usable variable names and values
tv_table = { -320, 576, 640, 736, 832, 896, 928, 960, 992, 1024, 1056, 1180, 1276}
tv96target = tv_table[t+3]
tv96max = tv_table[x+8]
tv96min = tv_table[y+1]
sv_table = { 381, 411, 507, 603, 699, 761, 795 }
sv96min = sv_table[p+1]
sv96max1 = sv_table[q+2]
sv96max2 = sv_table[r+2]
av_table = { 171, 192, 218, 265, 285, 322, 347, 384, 417, 446, 477, 510, 543, 576 }
av96target = av_table[a+1]
av96minimum = av_table[f+1]
av96max = av_table[m+1]
ec96adjust = (e - 6)*32
video_table = { 0, 1, 5, 10, 25, 50, 100 }
video_mode = video_table[v+1]
video_duration = w
interval = i*1000
max_shots = s
poff_if_done = j
start_delay = d
backlight = b
log_mode= l
focus_mode = c
usb_mode = u
if ( z==0 ) then zoom_setpoint = nil else zoom_setpoint = (z-1)*10 end
-- initial configuration values
nd96offset=3*96 -- ND filter's number of equivalent f-stops (f * 96)
infx = 50000 -- focus lock distance in mm (approximately 55 yards)
shot_count = 0 -- shot counter
blite_timer = 300 -- backlight off delay in 100mSec increments
old_console_timeout = get_config_value( 297 )
shot_request = false -- pwm mode flag to request a shot be taken
-- check camera Av configuration ( variable aperture and/or ND filter )
if n==0 then -- use of nd filter allowed?
if get_nd_present()==1 then -- check for ND filter only
Av_mode = 0 -- 0 = ND disabled and no iris available
else
Av_mode = 1 -- 1 = ND disabled and iris available
end
else
Av_mode = get_nd_present()+1 -- 1 = iris only , 2=ND filter only, 3= both ND & iris
end
function printf(...)
if ( log_mode == 0) then return end
local str=string.format(...)
if (( log_mode == 1) or (log_mode == 3)) then print(str) end
if ( log_mode > 1 ) then
local logname="A/KAP.log"
log=io.open(logname,"a")
log:write(os.date("%Y%b%d %X ")..string.format(...),"\n")
log:close()
end
end
tv_ref = { -- note : tv_ref values set 1/2 way between shutter speed values
-608, -560, -528, -496, -464, -432, -400, -368, -336, -304,
-272, -240, -208, -176, -144, -112, -80, -48, -16, 16,
48, 80, 112, 144, 176, 208, 240, 272, 304, 336,
368, 400, 432, 464, 496, 528, 560, 592, 624, 656,
688, 720, 752, 784, 816, 848, 880, 912, 944, 976,
1008, 1040, 1072, 1096, 1129, 1169, 1192, 1225, 1265, 1376 }
tv_str = {
">64",
"64", "50", "40", "32", "25", "20", "16", "12", "10", "8.0",
"6.0", "5.0", "4.0", "3.2", "2.5", "2.0", "1.6", "1.3", "1.0", "0.8",
"0.6", "0.5", "0.4", "0.3", "1/4", "1/5", "1/6", "1/8", "1/10", "1/13",
"1/15", "1/20", "1/25", "1/30", "1/40", "1/50", "1/60", "1/80", "1/100", "1/125",
"1/160", "1/200", "1/250", "1/320", "1/400", "1/500", "1/640", "1/800", "1/1000","1/1250",
"1/1600","1/2000","1/2500","1/3200","1/4000","1/5000","1/6400","1/8000","1/10000","hi" }
function print_tv(val)
if ( val == nil ) then return("-") end
local i = 1
while (i <= #tv_ref) and (val > tv_ref[i]) do i=i+1 end
return tv_str[i]
end
av_ref = { 160, 176, 208, 243, 275, 304, 336, 368, 400, 432, 464, 480, 496, 512, 544, 592, 624, 656, 688, 720, 752, 784 }
av_str = {"n/a","1.8", "2.0","2.2","2.6","2.8","3.2","3.5","4.0","4.5","5.0","5.6","5.9","6.3","7.1","8.0","9.0","10.0","11.0","13.0","14.0","16.0","hi"}
function print_av(val)
if ( val == nil ) then return("-") end
local i = 1
while (i <= #av_ref) and (val > av_ref[i]) do i=i+1 end
return av_str[i]
end
sv_ref = { 370, 397, 424, 456, 492, 523, 555, 588, 619, 651, 684, 731, 779, 843, 907 }
sv_str = {"n/a","80","100","120","160","200","250","320","400","500","640","800","1250","1600","3200","hi"}
function print_sv(val)
if ( val == nil ) then return("-") end
local i = 1
while (i <= #sv_ref) and (val > sv_ref[i]) do i=i+1 end
return sv_str[i]
end
function pline(message, line) -- print line function
fg = 258 bg=259
end
-- switch between shooting and playback modes
function switch_mode( m )
if ( m == 1 ) then
if ( get_mode() == false ) then
set_record(1) -- switch to shooting mode
while ( get_mode() == false ) do
sleep(100)
end
sleep(1000)
end
else
if ( get_mode() == true ) then
set_record(0) -- switch to playback mode
while ( get_mode() == true ) do
sleep(100)
end
sleep(1000)
end
end
end
-- focus lock and unlock
function lock_focus()
if (focus_mode > 1) then -- focus mode requested ?
if ( focus_mode == 2 ) then -- method 1 : set_aflock() command enables MF
if (chdk_version==120) then
set_aflock(1)
set_prop(props.AF_LOCK,1)
else
set_aflock(1)
end
if (get_prop(props.AF_LOCK) == 1) then printf(" AFL enabled") else printf(" AFL failed ***") end
else -- mf mode requested
if (chdk_version==120) then -- CHDK 1.2.0 : call event proc or levents to try and enable MF mode
if call_event_proc("SS.Create") ~= -1 then
if call_event_proc("SS.MFOn") == -1 then
call_event_proc("PT_MFOn")
end
elseif call_event_proc("RegisterShootSeqEvent") ~= -1 then
if call_event_proc("PT_MFOn") == -1 then
call_event_proc("MFOn")
end
end
if (get_prop(props.FOCUS_MODE) == 0 ) then -- MF not set - try levent PressSw1AndMF
post_levent_for_npt("PressSw1AndMF")
sleep(500)
end
elseif (chdk_version >= 130) then -- CHDK 1.3.0 : set_mf()
if ( set_mf(1) == 0 ) then set_aflock(1) end -- as a fall back, try setting AFL is set_mf fails
end
if (get_prop(props.FOCUS_MODE) == 1) then printf(" MF enabled") else printf(" MF enable failed ***") end
end
sleep(1000)
set_focus(infx)
sleep(1000)
end
end
function unlock_focus()
if (focus_mode > 1) then -- focus mode requested ?
if (focus_mode == 2 ) then -- method 1 : AFL
if (chdk_version==120) then
set_aflock(0)
set_prop(props.AF_LOCK,0)
else
set_aflock(0)
end
if (get_prop(props.AF_LOCK) == 0) then printf(" AFL unlocked") else printf(" AFL unlock failed") end
else -- mf mode requested
if (chdk_version==120) then -- CHDK 1.2.0 : call event proc or levents to try and enable MF mode
if call_event_proc("SS.Create") ~= -1 then
if call_event_proc("SS.MFOff") == -1 then
call_event_proc("PT_MFOff")
end
elseif call_event_proc("RegisterShootSeqEvent") ~= -1 then
if call_event_proc("PT_MFOff") == -1 then
call_event_proc("MFOff")
end
end
if (get_prop(props.FOCUS_MODE) == 1 ) then -- MF not reset - try levent PressSw1AndMF
post_levent_for_npt("PressSw1AndMF")
sleep(500)
end
elseif (chdk_version >= 130) then -- CHDK 1.3.0 : set_mf()
if ( set_mf(0) == 0 ) then set_aflock(0) end -- fall back so reset AFL is set_mf fails
end
if (get_prop(props.FOCUS_MODE) == 0) then printf(" MF disabled") else printf(" MF disable failed") end
end
sleep(100)
end
end
-- zoom position
function update_zoom(zpos)
local count = 0
if(zpos ~= nil) then
zstep=((get_zoom_steps()-1)*zpos)/100
printf("setting zoom to "..zpos.." percent step="..zstep)
sleep(200)
set_zoom(zstep)
sleep(2000)
press("shoot_half")
repeat
sleep(100)
count = count + 1
until (get_shooting() == true ) or (count > 40 )
release("shoot_half")
end
end
-- restore camera settings on shutdown
function restore()
set_config_value(121,0) -- USB remote disable
set_config_value(297,old_console_timeout) -- restore console timeout value
if (backlight==1) then set_lcd_display(1) end -- display on
unlock_focus()
if( zoom_setpoint ~= nil ) then update_zoom(0) end
if( shot_count >= max_shots) and ( max_shots > 1) then
if ( poff_if_done == 1 ) then -- did script ending because # of shots done ?
printf("power off - shot count at limit") -- complete power down
sleep(2000)
post_levent_to_ui('PressPowerButton')
else
set_record(0) end -- just retract lens
end
end
-- Video mode
function check_video(shot)
local capture_mode
if ((video_mode>0) and(shot>0) and (shot%video_mode == 0)) then
unlock_focus()
printf("Video mode started. Button:"..tostring(video_button))
if( video_button ) then
click "video"
else
capture_mode=capmode.get()
capmode.set('VIDEO_STD')
press("shoot_full")
sleep(300)
release("shoot_full")
end
local end_second = get_day_seconds() + video_duration
repeat
wait_click(500)
until (is_key("menu")) or (get_day_seconds() > end_second)
if( video_button ) then
click "video"
else
press("shoot_full")
sleep(300)
release("shoot_full")
capmode.set(capture_mode)
end
printf("Video mode finished.")
sleep(1000)
lock_focus()
return(true)
else
return(false)
end
end
-- PWM USB pulse functions
function ch1up()
printf(" * usb pulse = ch1up")
shot_request = true
end
function ch1mid()
printf(" * usb pulse = ch1mid")
if ( get_mode() == false ) then
switch_mode(1)
lock_focus()
end
end
function ch1down()
printf(" * usb pulse = ch1down")
switch_mode(0)
end
function ch2up()
printf(" * usb pulse = ch2up")
update_zoom(100)
end
function ch2mid()
printf(" * usb pulse = ch2mid")
if ( zoom_setpoint ~= nil ) then update_zoom(zoom_setpoint) else update_zoom(50) end
end
function ch2down()
printf(" * usb pulse = ch2down")
update_zoom(0)
end
function pwm_mode(pulse_width)
if pulse_width > 0 then
if pulse_width < 5 then ch1up()
elseif pulse_width < 8 then ch1mid()
elseif pulse_width < 11 then ch1down()
elseif pulse_width < 14 then ch2up()
elseif pulse_width < 17 then ch2mid()
elseif pulse_width < 20 then ch2down()
else printf(" * usb pulse width error") end
end
end
-- Basic exposure calculation using shutter speed and ISO only
-- called for Tv-only and ND-only cameras (cameras without an iris)
function basic_tv_calc()
tv96setpoint = tv96target
av96setpoint = nil
local min_av = get_prop(props.MIN_AV)
-- calculate required ISO setting
sv96setpoint = tv96setpoint + min_av - bv96meter
-- low ambient light ?
if (sv96setpoint > sv96max2 ) then -- check if required ISO setting is too high
sv96setpoint = sv96max2 -- clamp at max2 ISO if so
tv96setpoint = math.max(bv96meter+sv96setpoint-min_av,tv96min) -- recalculate required shutter speed down to Tv min
-- high ambient light ?
elseif (sv96setpoint < sv96min ) then -- check if required ISO setting is too low
sv96setpoint = sv96min -- clamp at minimum ISO setting if so
tv96setpoint = bv96meter + sv96setpoint - min_av -- recalculate required shutter speed and hope for the best
end
end
-- Basic exposure calculation using shutter speed, iris and ISO
-- called for iris-only and "both" cameras (cameras with an iris & ND filter)
function basic_iris_calc()
tv96setpoint = tv96target
av96setpoint = av96target
-- calculate required ISO setting
sv96setpoint = tv96setpoint + av96setpoint - bv96meter
-- low ambient light ?
if (sv96setpoint > sv96max1 ) then -- check if required ISO setting is too high
sv96setpoint = sv96max1 -- clamp at first ISO limit
av96setpoint = bv96meter + sv96setpoint - tv96setpoint -- calculate new aperture setting
if ( av96setpoint < av96min ) then -- check if new setting is goes below lowest f-stop
av96setpoint = av96min -- clamp at lowest f-stop
sv96setpoint = tv96setpoint + av96setpoint - bv96meter -- recalculate ISO setting
if (sv96setpoint > sv96max2 ) then -- check if the result is above max2 ISO
sv96setpoint = sv96max2 -- clamp at highest ISO setting if so
tv96setpoint = math.max(bv96meter+sv96setpoint-av96setpoint,tv96min) -- recalculate required shutter speed down to tv minimum
end
end
-- high ambient light ?
elseif (sv96setpoint < sv96min ) then -- check if required ISO setting is too low
sv96setpoint = sv96min -- clamp at minimum ISO setting if so
tv96setpoint = bv96meter + sv96setpoint - av96setpoint -- recalculate required shutter speed
if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast
tv96setpoint = tv96max -- clamp at maximum shutter speed if so
av96setpoint = bv96meter + sv96setpoint - tv96setpoint -- calculate new aperture setting
if ( av96setpoint > av96max ) then -- check if new setting is goes above highest f-stop
av96setpoint = av96max -- clamp at highest f-stop
tv96setpoint = bv96meter + sv96setpoint - av96setpoint -- recalculate shutter speed needed and hope for the best
end
end
end
end
-- calculate exposure for cams without adjustable iris or ND filter
function exposure_Tv_only()
insert_ND_filter = nil
basic_tv_calc()
end
-- calculate exposure for cams with ND filter only
function exposure_NDfilter()
insert_ND_filter = false
basic_tv_calc()
if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast
insert_ND_filter = true -- flag the ND filter to be inserted
bv96meter = bv96meter - nd96offset -- adjust meter for ND offset
basic_tv_calc() -- start over, but with new meter value
bv96meter = bv96meter + nd96offset -- restore meter for later logging
end
end
-- calculate exposure for cams with adjustable iris only
function exposure_iris()
insert_ND_filter = nil
basic_iris_calc()
end
-- calculate exposure for cams with both adjustable iris and ND filter
function exposure_both()
insert_ND_filter = false -- NOTE : assume ND filter never used automatically by Canon firmware
basic_iris_calc()
if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast
insert_ND_filter = true -- flag the ND filter to be inserted
bv96meter = bv96meter - nd96offset -- adjust meter for ND offset
basic_iris_calc() -- start over, but with new meter value
bv96meter = bv96meter + nd96offset -- restore meter for later logging
end
end
-- ========================== Main Program =================================
set_console_layout(1 ,1, 45, 14 )
printf("KAP 3.1 started - press MENU to exit")
bi=get_buildinfo()
printf("%s %s-%s %s %s %s", bi.version, bi.build_number, bi.build_revision, bi.platform, bi.platsub, bi.build_date)
chdk_version= tonumber(string.sub(bi.build_number,1,1))*100 + tonumber(string.sub(bi.build_number,3,3))*10 + tonumber(string.sub(bi.build_number,5,5))
if ( tonumber(bi.build_revision) > 0 ) then
build = tonumber(bi.build_revision)
else
build = tonumber(string.match(bi.build_number,'-(%d+)$'))
end
if ((chdk_version<120) or ((chdk_version==120)and(build<3276)) or ((chdk_version==130)and(build<3383))) then
printf("CHDK 1.2.0 build 3276 or higher required")
else
if( props.CONTINUOUS_AF == nil ) then caf=-999 else caf = get_prop(props.CONTINUOUS_AF) end
if( props.SERVO_AF == nil ) then saf=-999 else saf = get_prop(props.SERVO_AF) end
cmode = capmode.get_name()
printf("Mode:%s,Continuous_AF:%d,Servo_AF:%d", cmode,caf,saf)
printf(" Tv:"..print_tv(tv96target).." max:"..print_tv(tv96max).." min:"..print_tv(tv96min).." ecomp:"..(ec96adjust/96).."."..(math.abs(ec96adjust*10/96)%10) )
printf(" Av:"..print_av(av96target).." minAv:"..print_av(av96minimum).." maxAv:"..print_av(av96max) )
printf(" ISOmin:"..print_sv(sv96min).." ISO1:"..print_sv(sv96max1).." ISO2:"..print_sv(sv96max2) )
printf(" MF mode:"..focus_mode.." Video:"..video_mode.." USB:"..usb_mode)
printf(" AvM:"..Av_mode.." int:"..(interval/1000).." Shts:"..max_shots.." Dly:"..start_delay.." B/L:"..backlight)
sleep(500)
if (start_delay > 0 ) then
printf("entering start delay of ".. start_delay.." seconds")
sleep( start_delay*1000 )
end
-- enable USB remote in USB remote moded
if (usb_mode > 0 ) then
set_config_value(121,1) -- make sure USB remote is enabled
if (get_usb_power(1) == 0) then -- can we start ?
printf("waiting on USB signal")
repeat wait_click(20) until ((get_usb_power(1) == 1) or ( is_key("menu")))
else sleep(1000) end
printf("USB signal received")
end
-- switch to shooting mode
switch_mode(1)
-- set zoom position
update_zoom(zoom_setpoint)
-- lock focus at infinity
lock_focus()
-- disable flash and AF assist lamp
set_prop(props.FLASH_MODE, 2) -- flash off
set_prop(props.AF_ASSIST_BEAM,0) -- AF assist off if supported for this camera
set_config_value( 297, 60) -- set console timeout to 60 seconds
if (usb_mode > 2 ) then repeat until (get_usb_power(2) == 0 ) end -- flush pulse buffer
next_shot_time = get_tick_count()
script_exit = false
if( get_video_button() == 1) then video_button = true else video_button = false end
set_console_layout(2 ,0, 45, 4 )
repeat
if( ( (usb_mode < 2 ) and ( next_shot_time <= get_tick_count() ) )
or ( (usb_mode == 2 ) and (get_usb_power(2) > 0 ) )
or ( (usb_mode == 3 ) and (shot_request == true ) ) ) then
-- time to insert a video sequence ?
if( check_video(shot_count) == true) then next_shot_time = get_tick_count() end
-- intervalometer timing
next_shot_time = next_shot_time + interval
-- set focus at infinity ? (maybe redundant for AFL & MF mode but makes sure its set right)
if (focus_mode > 0) then
set_focus(infx)
sleep(100)
end
-- check exposure
local count = 0
local timeout = false
press("shoot_half")
repeat
sleep(50)
count = count + 1
if (count > 40 ) then timeout = true end
until (get_shooting() == true ) or (timeout == true)
-- shoot in auto mode if meter reading invalid, else calculate new desired exposure
if ( timeout == true ) then
release("shoot_half")
repeat sleep(50) until get_shooting() == false
shoot() -- shoot in Canon auto mode if we don't have a valid meter reading
shot_count = shot_count + 1
printf(string.format('IMG_%04d.JPG',get_exp_count()).." : shot in auto mode, meter reading invalid")
else
-- get meter reading values (and add in exposure compensation)
bv96raw=get_bv96()
bv96meter=bv96raw-ec96adjust
tv96meter=get_tv96()
av96meter=get_av96()
sv96meter=get_sv96()
-- set minimum Av to larger of user input or current min for zoom setting
av96min= math.max(av96minimum,get_prop(props.MIN_AV))
if (av96target < av96min) then av96target = av96min end
-- calculate required setting for current ambient light conditions
if (Av_mode == 1) then exposure_iris()
elseif (Av_mode == 2) then exposure_NDfilter()
elseif (Av_mode == 3) then exposure_both()
else exposure_Tv_only()
end
-- set up all exposure overrides
set_tv96_direct(tv96setpoint)
set_sv96(sv96setpoint)
if( av96setpoint ~= nil) then set_av96_direct(av96setpoint) end
if(Av_mode > 1) and (insert_ND_filter == true) then -- ND filter available and needed?
set_nd_filter(1) -- activate the ND filter
nd_string="NDin"
else
set_nd_filter(2) -- make sure the ND filter does not activate
nd_string="NDout"
end
-- and finally shoot the image
press("shoot_full_only")
sleep(100)
release("shoot_full")
repeat sleep(50) until get_shooting() == false
shot_count = shot_count + 1
-- update shooting statistic and log as required
shot_focus=get_focus()
if(shot_focus ~= -1) and (shot_focus < 20000) then
focus_string=" foc:"..(shot_focus/1000).."."..(((shot_focus%1000)+50)/100).."m"
if(focus_mode>0) then
error_string=" **WARNING : focus not at infinity**"
end
else
focus_string=" foc:infinity"
error_string=nil
end
printf(string.format('%d) IMG_%04d.JPG',shot_count,get_exp_count()))
printf(" meter : Tv:".. print_tv(tv96meter) .." Av:".. print_av(av96meter) .." Sv:"..print_sv(sv96meter).." "..bv96raw ..":"..bv96meter)
printf(" actual: Tv:".. print_tv(tv96setpoint).." Av:".. print_av(av96setpoint).." Sv:"..print_sv(sv96setpoint))
printf(" AvMin:".. print_av(av96min).." NDF:"..nd_string..focus_string )
if ((max_shots>0) and (shot_count >= max_shots)) then script_exit = true end
shot_request = false -- reset shot request flag
end
collectgarbage()
end
-- check if USB remote enabled in intervalometer mode and USB power is off -> pause if so
if ((usb_mode == 1 ) and (get_usb_power(1) == 0)) then
printf("waiting on USB signal")
unlock_focus()
switch_mode(0)
repeat wait_click(20) until ((get_usb_power(1) == 1) or ( is_key("menu")))
switch_mode(1)
lock_focus()
if ( is_key("menu")) then script_exit = true end
printf("USB wait finished")
sleep(100)
end
if (usb_mode == 3 ) then pwm_mode(get_usb_power(2)) end
if (blite_timer > 0) then
blite_timer = blite_timer-1
if ((blite_timer==0) and (backlight==1)) then set_lcd_display(0) end
end
if( error_string ~= nil) then
draw_string( 16, 144, string.sub(error_string.." ",0,42), 258, 259)
end
wait_click(100)
if( not( is_key("no_key"))) then
if ((blite_timer==0) and (backlight==1)) then set_lcd_display(1) end
blite_timer=300
if ( is_key("menu") ) then script_exit = true end
end
until (script_exit==true)
printf("script halt requested")
restore()
end
--[[ end of file ]]--
| gpl-3.0 |
hfjgjfg/mohammad | bot/utils.lua | 356 | 14963 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has superuser privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- user has admins privileges
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- user has moderator privileges
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
-- Berfungsi utk mengecek user jika plugin moderated = true
if plugin.moderated and not is_momod(msg) then --Cek apakah user adalah momod
if plugin.moderated and not is_admin(msg) then -- Cek apakah user adalah admin
if plugin.moderated and not is_sudo(msg) then -- Cek apakah user adalah sudoers
return false
end
end
end
-- Berfungsi mengecek user jika plugin privileged = true
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end | gpl-2.0 |
Andreas-Kreuz/ak-lua-skripte-fuer-eep | lua/LUA/ak/template/crossing-simple.lua | 1 | 4273 | -----------------------------------------------------------------------------------------------------------------------
-- Diese Skript ist eine kleine Vorlage für das Verwenden von Kreuzungen, WENN DU NOCH KEIN LUA IN DER ANLAGE BENUTZT
-- 1) Kopiere dieses Skript in das LUA-Verzeichnis von EEP
-- 2) Benenne die Kopie um, z.B. "anlage1.lua"
-- 3) Verwende die folgende Zeile im Lua-Editor von EEP, um Deine Kopie in EEP mit der Anlage zu laden
-- require("anlage1")
-----------------------------------------------------------------------------------------------------------------------
-- Diese Zeile lädt die Modulverwaltung der Lua-Bibliothek
local ModuleRegistry = require("ak.core.ModuleRegistry")
-- Diese Zeilen aktivieren die folgenden Module in der Modulverwaltung
-- * Core (immer benötigt)
-- * Data (Export der Daten für EEP)
-- * Crossing (für die Ampelsteuerung notwendig)
ModuleRegistry.registerModules(require("ak.core.CoreLuaModule"), require("ak.data.DataLuaModule"),
require("ak.road.CrossingLuaModul"))
-- Die EEPMain Methode wird von EEP genutzt. Sie muss immer 1 zurückgeben.
function EEPMain()
-- Die Modulverwaltung startet die Aufgaben in allen Modulen bei jedem fünften EEPMain-Aufruf
ModuleRegistry.runTasks(5)
return 1
end
-- Hier kommt eine Kreuzung mit 4 Fahrspuren
-- | N | | |
-- | lane 1 | | |
-- | | | |
-- |STRAIGHT| | |
-- S1 | +RIGHT | | |
-- K1 |========|========|========| K2
-- | | | |
-- K3 | | | |
-- ------------------------------+ + | |
-- | | |
-- | | |
-- | | |
-- ---------------------- ------+ |
-- | | |
-- W lane 2 LEFT+RIGHT |K5| |
-- | | |
-- ------------------------------+ + | |
-- K6, | | | |
-- K7 | | | | S2
-- In lane 2 all cars K8=|========|========|========|-K9
-- allowed to turn | | LEFT |STRAIGHT|
-- right when lane 3 | | | |
-- is turning left | | lane 3 | lane 4 |
-- (Route: RIGHT_TURN_ROUTE) | | S | S |
--
local Lane = require("ak.road.Lane")
local Crossing = require("ak.road.Crossing")
-- local CrossingSequence = require("ak.road.CrossingSequence")
-- local LaneSettings = require("ak.road.LaneSettings")
local TrafficLight = require("ak.road.TrafficLight")
local TrafficLightModel = require("ak.road.TrafficLightModel")
-- Ampeln für den Kraftfahrverkehr (K) und Strassenbahnen (S)
local K1, K2
-- 3 Schaltungen
local sequenceA, sequenceB
-- die Kreuzung
local crossing
-- Nutze einen Speicherslot in EEP um die Einstellungen für Kreuzungen zu laden und zu speichern
Crossing.loadSettingsFromSlot(10)
-- Erzeuge immer erst Deine Ampeln
K1 = TrafficLight:new("K1", 23, TrafficLightModel.JS2_3er_mit_FG) -- NORTH STRAIGHT 1 (right)
K2 = TrafficLight:new("K2", 24, TrafficLightModel.JS2_3er_mit_FG) -- NORTH STRAIGHT 2 (left)
-- Erzeuge Kreuzung und Fahrspuren
crossing = Crossing:new("Dein Kreuzungsname")
lane1 = Lane:new("Lane 1 N", 1, K1, {Lane.Directions.STRAIGHT, Lane.Directions.RIGHT})
lane2 = Lane:new("Lane 2 S", 2, K2, {Lane.Directions.STRAIGHT, Lane.Directions.RIGHT})
-- Lege die Schaltungen an und füge Ampeln für Fahrzeuge, Tram und Fußgänger hinzu
sequenceA = crossing:newSequence("Schaltung Fahrzeuge")
sequenceA:addCarLights(K1)
sequenceA:addPedestrianLights(K2)
sequenceB = crossing:newSequence("Schaltung Fussgaenger")
sequenceB:addCarLights(K2)
sequenceB:addPedestrianLights(K1)
| mit |
Javaxio/BadRotations | Rotations/Paladin/Protection/protectionPrettyBoy.lua | 1 | 39498 | local rotationName = "PrettyBoy"
---------------
--- Toggles ---
---------------
local function createToggles()
-- Rotation Button
RotationModes = {
[1] = { mode = "Auto", value = 1 , overlay = "Automatic Rotation", tip = "Swaps between Single and Multiple based on number of targets in range.", highlight = 1, icon = br.player.spell.eyeOfTyr },
[2] = { mode = "Mult", value = 2 , overlay = "Multiple Target Rotation", tip = "Multiple target rotation used.", highlight = 0, icon = br.player.spell.avengersShield },
[3] = { mode = "Sing", value = 3 , overlay = "Single Target Rotation", tip = "Single target rotation used.", highlight = 0, icon = br.player.spell.judgment },
[4] = { mode = "Off", value = 4 , overlay = "DPS Rotation Disabled", tip = "Disable DPS Rotation", highlight = 0, icon = br.player.spell.flashOfLight }
}
CreateButton("Rotation",1,0)
-- Cooldown Button
CooldownModes = {
[1] = { mode = "Auto", value = 1 , overlay = "Cooldowns Automated", tip = "Automatic Cooldowns - Boss Detection.", highlight = 1, icon = br.player.spell.avengingWrath },
[2] = { mode = "On", value = 1 , overlay = "Cooldowns Enabled", tip = "Cooldowns used regardless of target.", highlight = 0, icon = br.player.spell.avengingWrath },
[3] = { mode = "Off", value = 3 , overlay = "Cooldowns Disabled", tip = "No Cooldowns will be used.", highlight = 0, icon = br.player.spell.avengingWrath }
};
CreateButton("Cooldown",2,0)
-- Defensive Button
DefensiveModes = {
[1] = { mode = "On", value = 1 , overlay = "Defensive Enabled", tip = "Includes Defensive Cooldowns.", highlight = 1, icon = br.player.spell.guardianOfAncientKings },
[2] = { mode = "Off", value = 2 , overlay = "Defensive Disabled", tip = "No Defensives will be used.", highlight = 0, icon = br.player.spell.guardianOfAncientKings }
};
CreateButton("Defensive",3,0)
-- Interrupt Button
InterruptModes = {
[1] = { mode = "On", value = 1 , overlay = "Interrupts Enabled", tip = "Includes Basic Interrupts.", highlight = 1, icon = br.player.spell.hammerOfJustice },
[2] = { mode = "Off", value = 2 , overlay = "Interrupts Disabled", tip = "No Interrupts will be used.", highlight = 0, icon = br.player.spell.hammerOfJustice }
};
CreateButton("Interrupt",4,0)
-- Boss Encounter Case
BossCaseModes = {
[1] = { mode = "On", value = 1 , overlay = "BossCase Enabled", tip = "Boss Encounter Case Enabled.", highlight = 1, icon = br.player.spell.shieldOfTheRighteous },
[2] = { mode = "Off", value = 2 , overlay = "BossCase Disabled", tip = "Boss Encounter Case Disabled.", highlight = 0, icon = br.player.spell.shieldOfTheRighteous }
};
CreateButton("BossCase",5,0)
end
---------------
--- OPTIONS ---
---------------
local function createOptions()
local optionTable
local function rotationOptions()
-----------------------
--- GENERAL OPTIONS ---
-----------------------
section = br.ui:createSection(br.ui.window.profile, "General")
-- Blessing of Freedom
br.ui:createCheckbox(section, "Blessing of Freedom")
-- Taunt
br.ui:createCheckbox(section,"Taunt","|cffFFFFFFAuto Taunt usage.")
br.ui:checkSectionState(section)
------------------------
--- COOLDOWN OPTIONS ---
------------------------
section = br.ui:createSection(br.ui.window.profile, "Cooldowns")
-- Racial
br.ui:createCheckbox(section,"Racial")
-- Trinkets
br.ui:createSpinner(section, "Trinkets HP", 70, 0, 100, 5, "Health Percentage to use at")
br.ui:createDropdownWithout(section, "Trinkets", {"|cff00FF001st Only","|cff00FF002nd Only","|cffFFFF00Both","|cffFF0000None"}, 1, "|cffFFFFFFSelect Trinket Usage.")
-- Seraphim
br.ui:createSpinner(section, "Seraphim", 0, 0, 20, 2, "|cffFFFFFFEnemy TTD")
-- Avenging Wrath
br.ui:createSpinner(section, "Avenging Wrath", 30, 0, 200, 5, "|cffFFFFFFEnemy TTD")
-- Bastion of Light
br.ui:createCheckbox(section,"Bastion of Light")
br.ui:checkSectionState(section)
-------------------------
--- DEFENSIVE OPTIONS ---
-------------------------
section = br.ui:createSection(br.ui.window.profile, "Defensive")
-- Healthstone
br.ui:createSpinner(section, "Pot/Stoned", 30, 0, 100, 5, "|cffFFFFFFHealth Percentage to use at")
-- Gift of The Naaru
if br.player.race == "Draenei" then
br.ui:createSpinner(section, "Gift of the Naaru", 50, 0, 100, 5, "|cffFFFFFFHealth Percentage to use at")
end
-- Ardent Defender
br.ui:createSpinner(section, "Ardent Defender", 60, 0, 100, 5, "|cffFFBB00Health Percentage to use at")
-- Engineering: Gunpowder Charge
br.ui:createSpinner(section, "Gunpowder Charge", 30, 0, 200, 5, "|cffFFFFFFEnemy TTD")
-- Blinding Light
br.ui:createSpinner(section, "Blinding Light - HP", 50, 0, 100, 5, "|cffFFFFFFHealth Percentage to use at")
br.ui:createSpinner(section, "Blinding Light - AoE", 3, 0, 10, 1, "|cffFFFFFFNumber of Units in 5 Yards to Cast At")
-- Cleanse Toxin
br.ui:createDropdown(section, "Clease Toxin", {"|cff00FF00Player Only","|cffFFFF00Selected Target","|cffFF0000Mouseover Target"}, 1, "|ccfFFFFFFTarget to Cast On")
-- Divine Shield
br.ui:createSpinner(section, "Divine Shield", 5, 0, 100, 5, "|cffFFBB00Health Percentage to use at")
-- Eye of Tyr
br.ui:createSpinner(section, "Eye of Tyr - HP", 60, 0, 100, 5, "|cffFFFFFFHealth Percentage to use at")
br.ui:createSpinner(section, "Eye of Tyr - AoE", 4, 0, 10, 1, "|cffFFFFFFNumber of Units in 10 Yards to Cast At")
-- Flash of Light
br.ui:createSpinner(section, "Flash of Light", 50, 0, 100, 5, "|cffFFBB00Health Percentage to use at")
-- Guardian of Ancient Kings
br.ui:createSpinner(section, "Guardian of Ancient Kings", 30, 0, 100, 5, "|cffFFBB00Health Percentage to use at")
-- Hammer of Justice
br.ui:createSpinner(section, "Hammer of Justice - HP", 60, 0, 100, 5, "|cffFFBB00Health Percentage to use at")
br.ui:createCheckbox(section, "Hammer of Justice - Legendary")
-- Light of the Protector
br.ui:createSpinner(section, "Light of the Protector", 70, 0, 100, 5, "|cffFFBB00Health Percentage to use at.")
-- Hand of the Protector - on others
br.ui:createSpinner(section, "Hand of the Protector - Party", 40, 0, 100, 5, "|cffFFBB00队友Health Percentage to use at.")
-- Lay On Hands
br.ui:createSpinner(section, "Lay On Hands", 20, 0, 100, 5, "","Health Percentage to use at")
br.ui:createDropdownWithout(section, "Lay on Hands Target", {"|cffFFFFFFPlayer","|cffFFFFFFTarget", "|cffFFFFFFMouseover", "|cffFFFFFFTank", "|cffFFFFFFHealer", "|cffFFFFFFHealer/Tank", "|cffFFFFFFHealer/Damage", "|cffFFFFFFAny"}, 8, "|cffFFFFFFTarget for Lay On Hands")
-- Blessing of Protection
br.ui:createSpinner(section, "Blessing of Protection", 30, 0, 100, 5, "","Health Percentage to use at")
br.ui:createDropdownWithout(section, "Blessing of Protection Target", {"|cffFFFFFFPlayer","|cffFFFFFFTarget", "|cffFFFFFFMouseover", "|cffFFFFFFTank", "|cffFFFFFFHealer", "|cffFFFFFFHealer/Tank", "|cffFFFFFFHealer/Damage", "|cffFFFFFFAny"}, 7, "|cffFFFFFFTarget for Blessing of Protection")
-- Blessing Of Sacrifice
br.ui:createSpinner(section, "Blessing Of Sacrifice", 40, 0, 100, 5, "","Health Percentage to use at")
br.ui:createDropdownWithout(section, "Blessing Of Sacrifice Target", {"|cffFFFFFFTarget", "|cffFFFFFFMouseover", "|cffFFFFFFTank", "|cffFFFFFFHealer", "|cffFFFFFFHealer/Tank", "|cffFFFFFFHealer/Damage", "|cffFFFFFFAny"}, 6, "|cffFFFFFFTarget for Blessing Of Sacrifice")
-- Shield of the Righteous
br.ui:createSpinner(section, "Shield of the Righteous - HP", 60, 0 , 100, 5, "|cffFFBB00Health Percentage to use at")
-- Redemption
br.ui:createDropdown(section, "Redemption", {"|cffFFFF00Selected Target","|cffFF0000Mouseover Target"}, 1, "|ccfFFFFFFTarget to Cast On")
br.ui:checkSectionState(section)
-------------------------
--- INTERRUPT OPTIONS ---
-------------------------
section = br.ui:createSection(br.ui.window.profile, "Interrupts")
-- Blinding Light
br.ui:createCheckbox(section, "Blinding Light - INT")
-- Hammer of Justice
br.ui:createCheckbox(section, "Hammer of Justice - INT")
-- Rebuke
br.ui:createCheckbox(section, "Rebuke - INT")
-- Avenger's Shield
br.ui:createCheckbox(section, "Avenger's Shield - INT")
-- Interrupt Percentage
br.ui:createSpinner(section, "Interrupt At", 35, 0, 95, 5, "|cffFFBB00Cast Percentage to use at.")
br.ui:checkSectionState(section)
------------------------
--- ROTATION OPTIONS ---
------------------------
section = br.ui:createSection(br.ui.window.profile, "Rotation Options")
-- Avenger's Shield
br.ui:createCheckbox(section,"Avenger's Shield")
-- Consecration
br.ui:createCheckbox(section,"Consecration")
-- Blessed Hammer
br.ui:createCheckbox(section,"Blessed Hammer")
-- Hammer of the Righteous
br.ui:createCheckbox(section,"Hammer of the Righteous")
-- Judgment
br.ui:createCheckbox(section,"Judgment")
-- Shield of the Righteous
br.ui:createCheckbox(section,"Shield of the Righteous")
br.ui:checkSectionState(section)
----------------------
--- TOGGLE OPTIONS ---
----------------------
section = br.ui:createSection(br.ui.window.profile, "Toggle Keys")
-- Single/Multi Toggle
br.ui:createDropdown(section, "Rotation Mode", br.dropOptions.Toggle, 4)
--Cooldown Key Toggle
br.ui:createDropdown(section, "Cooldown Mode", br.dropOptions.Toggle, 3)
--Defensive Key Toggle
br.ui:createDropdown(section, "Defensive Mode", br.dropOptions.Toggle, 6)
-- Interrupts Key Toggle
br.ui:createDropdown(section, "Interrupt Mode", br.dropOptions.Toggle, 6)
-- Pause Toggle
br.ui:createDropdown(section, "Pause Mode", br.dropOptions.Toggle, 6)
br.ui:checkSectionState(section)
end
optionTable = {{
[1] = "Rotation Options",
[2] = rotationOptions,
}}
return optionTable
end
----------------
--- ROTATION ---
----------------
local function runRotation()
if br.timer:useTimer("debugProtection", math.random(0.15,0.3)) then
--Print("Running: "..rotationName)
---------------
--- Toggles ---
---------------
UpdateToggle("Rotation",0.25)
UpdateToggle("Cooldown",0.25)
UpdateToggle("Defensive",0.25)
UpdateToggle("Interrupt",0.25)
UpdateToggle("BossCase",0.25)
br.player.mode.BossCase = br.data.settings[br.selectedSpec].toggles["BossCase"]
--- FELL FREE TO EDIT ANYTHING BELOW THIS AREA THIS IS JUST HOW I LIKE TO SETUP MY ROTATIONS ---
--------------
--- Locals ---
--------------
local artifact = br.player.artifact
local buff = br.player.buff
local cast = br.player.cast
local cd = br.player.cd
local charges = br.player.charges
local combatTime = getCombatTime()
local debuff = br.player.debuff
local enemies = enemies or {}
local gcd = br.player.gcd
local hastar = GetObjectExists("target")
local healPot = getHealthPot()
local inCombat = br.player.inCombat
local level = br.player.level
local inInstance = br.player.instance=="party"
local inRaid = br.player.instance=="raid"
local lowest = br.friend[1]
local mode = br.player.mode
local php = br.player.health
local race = br.player.race
local racial = br.player.getRacial()
local resable = UnitIsPlayer("target") and UnitIsDeadOrGhost("target") and UnitIsFriend("target","player")
local solo = GetNumGroupMembers() == 0
local spell = br.player.spell
local talent = br.player.talent
local ttd = getTTD(br.player.units(5))
local units = units or {}
units.dyn5 = br.player.units(5)
units.dyn10 = br.player.units(10)
units.dyn30 = br.player.units(30)
enemies.yards5 = br.player.enemies(5)
enemies.yards10 = br.player.enemies(10)
enemies.yards30 = br.player.enemies(30)
if profileStop == nil then profileStop = false end
judgmentExists = debuff.judgment.exists(units.dyn5)
judgmentRemain = debuff.judgment.remain(units.dyn5)
if debuff.judgment.exists(units.dyn5) or level < 42 or (cd.judgment.remain() > 2 and not debuff.judgment.exists(units.dyn5)) then
judgmentVar = true
else
judgmentVar = false
end
local greaterBuff
greaterBuff = 0
local lowestUnit
lowestUnit = "player"
for i = 1, #br.friend do
local thisUnit = br.friend[i].unit
local thisHP = getHP(thisUnit)
local lowestHP = getHP(lowestUnit)
if thisHP < lowestHP then
lowestUnit = thisUnit
end
end
--------------------
--- Action Lists ---
--------------------
-- Action List - Extras
local function actionList_Extras()
-- Blessing of Freedom
if isChecked("Blessing of Freedom") and hasNoControl() then
if cast.blessingOfFreedom() then return end
end
-- Taunt
if isChecked("Taunt") and inInstance then
for i = 1, #enemies.yards30 do
local thisUnit = enemies.yards30[i]
if UnitThreatSituation("player", thisUnit) ~= nil and UnitThreatSituation("player", thisUnit) <= 2 and UnitAffectingCombat(thisUnit) then
if cast.handOfReckoning(thisUnit) then return end
end
end
end
end -- End Action List - Extras
local function BossEncounterCase()
-- Contemplation
if getDebuffRemain("player",200904) > 1 then
if cast.contemplation() then return end
end
-- Blessing of Freedom
for i = 1, #br.friend do
if getDebuffRemain(br.friend[i].unit,202615) > 1 or getDebuffRemain(br.friend[i].unit,211543) > 1 then
if cast.blessingOfFreedom(br.friend[i].unit) then return end
end
end
-- Blessing of Protection
for i = 1, #br.friend do
if getDebuffRemain(br.friend[i].unit,237726) > 1 or getDebuffRemain(br.friend[i].unit,196838) > 1 then
if cast.blessingOfProtection(br.friend[i].unit) then return end
end
end
for i = 1, #br.friend do
if getDebuffRemain(br.friend[i].unit,200238) > 1 and talent.blessingOfSpellwarding and not UnitIsUnit(br.friend[i].unit,"player") then
if cast.blessingOfSpellwarding(br.friend[i].unit) then return end
end
end
if GetObjectID("target") == 98965 then
if getHP("target") < 20 then
if cast.blessingOfProtection() then return end
end
end
-- Shield of the Righteous
if getDebuffRemain("player",204611) > 1 and not buff.shieldOfTheRighteous.exists() then
if cast.shieldOfTheRighteous() then return end
end
if getDebuffRemain("player",200238) > 1 and not buff.shieldOfTheRighteous.exists() then
if cast.shieldOfTheRighteous() then return end
end
if UnitCastingInfo("target") == GetSpellInfo(202019) and getBuffRemain("player",199368) < 1 and not buff.shieldOfTheRighteous.exists() then
if cast.shieldOfTheRighteous() then return end
end
if GetObjectID("target") == 99192 then
if getHP("target") < 50 and getHP("target") > 30 and not buff.shieldOfTheRighteous.exists() then
if cast.shieldOfTheRighteous() then return end
end
end
-- Shield of the Righteous
local Casting={
--spell_id , spell_name
{197418 , 'Vengeful Shear'}, --Black Rook Hold
{198245 , 'Brutal Haymaker'}, --Black Rook Hold
{198379 , 'Primal Rampage'}, --Darkheart Thicket
{204667 , 'Nightmare Breath'}, --Darkheart Thicket
{193092 , 'Bloodletting Sweep'}, --Halls of Valor
{192018 , 'Shield of Light'}, --Halls of Valor
{193668 , 'Savage Blade'}, --Halls of Valor
{198496 , 'Sunder'}, --Neltharion's Lair
{200732 , 'Molten Crash'}, --Neltharion's Lair
{193211 , 'Dark Slash'}, --Maw of Souls
{204151 , 'Darkstrikes'}, --Vault of the Wardens
{227493 , 'Mortal Strike'}, --Karazhan
{227832 , 'Coat Check'}, --Karazhan
{227628 , 'Piercing Missiles'}, --Karazhan
{235751 , 'Timber Smash'}, --Cathedral of Eternal Night
{233155 , 'Carrion Swarm'}, --Cathedral of Eternal Night
}
for i=1 , #Casting do
local spell_id = Casting[i][1]
local spell_name = Casting[i][2]
if UnitCastingInfo("target") == GetSpellInfo(spell_id) and not buff.shieldOfTheRighteous.exists() then
if cast.shieldOfTheRighteous() then Print("damage reduction in advance..."..spell_name) return end
end
end
end
-- Action List - Defensives
local function actionList_Defensive()
if useDefensive() then
-- Pot/Stoned
if isChecked("Pot/Stoned") and php <= getOptionValue("Pot/Stoned")
and inCombat and (hasHealthPot() or hasItem(5512))
then
if canUse(5512) then
useItem(5512)
elseif canUse(healPot) then
useItem(healPot)
end
end
-- Divine Shield
if isChecked("Divine Shield") then
if php <= getOptionValue("Divine Shield") and inCombat then
if cast.divineShield() then return end
end
end
-- Gift of the Naaru
if isChecked("Gift of the Naaru") and php <= getOptionValue("Gift of the Naaru") and php > 0 and race == "Draenei" then
if castSpell("player",racial,false,false,false) then return end
end
-- Light of the Protector
if isChecked("Light of the Protector") and php <= getOptionValue("Light of the Protector") and (not hasEquiped(144275) or (hasEquiped(144275) and (not lotpTime or GetTime() - lotpTime > 1 ))) then
if cast.lightOfTheProtector("player") then return end
if cast.handOfTheProtector("player") then return end
lotpTime = GetTime()
end
-- Hand of the Protector - Others
if isChecked("Hand of the Protector - Party") and talent.handOfTheProtector and (not hasEquiped(144275) or (hasEquiped(144275) and (not hotpTime or GetTime() - hotpTime > 1 ))) then
if lowest.hp < getOptionValue("Hand of the Protector - Party") then
if cast.handOfTheProtector(lowest.unit) then return end
hotpTime = GetTime()
end
end
-- Lay On Hands
if isChecked("Lay On Hands") and inCombat then
-- Player
if getOptionValue("Lay on Hands Target") == 1 then
if php <= getValue("Lay On Hands") then
if cast.layOnHands("player") then return true end
end
-- Target
elseif getOptionValue("Lay on Hands Target") == 2 then
if getHP("target") <= getValue("Lay On Hands") then
if cast.layOnHands("target") then return true end
end
-- Mouseover
elseif getOptionValue("Lay on Hands Target") == 3 then
if getHP("mouseover") <= getValue("Lay On Hands") then
if cast.layOnHands("mouseover") then return true end
end
elseif getHP(lowestUnit) <= getValue("Lay On Hands") then
-- Tank
if getOptionValue("Lay on Hands Target") == 4 then
if UnitGroupRolesAssigned(lowestUnit) == "TANK" then
if cast.layOnHands(lowestUnit) then return true end
end
-- Healer
elseif getOptionValue("Lay on Hands Target") == 5 then
if UnitGroupRolesAssigned(lowestUnit) == "HEALER" then
if cast.layOnHands(lowestUnit) then return true end
end
-- Healer/Tank
elseif getOptionValue("Lay on Hands Target") == 6 then
if UnitGroupRolesAssigned(lowestUnit) == "HEALER" or UnitGroupRolesAssigned(lowestUnit) == "TANK" then
if cast.layOnHands(lowestUnit) then return true end
end
-- Healer/Damager
elseif getOptionValue("Lay on Hands Target") == 7 then
if UnitGroupRolesAssigned(lowestUnit) == "HEALER" or UnitGroupRolesAssigned(lowestUnit) == "DAMAGER" then
if cast.layOnHands(lowestUnit) then return true end
end
-- Any
elseif getOptionValue("Lay on Hands Target") == 8 then
if cast.layOnHands(lowestUnit) then return true end
end
end
end
-- Blessing of Protection
if isChecked("Blessing of Protection") and inCombat then
-- Player
if getOptionValue("Blessing of Protection Target") == 1 then
if php <= getValue("Blessing of Protection") then
if cast.blessingOfProtection("player") then return true end
end
-- Target
elseif getOptionValue("Blessing of Protection Target") == 2 then
if getHP("target") <= getValue("Blessing of Protection") then
if cast.blessingOfProtection("target") then return true end
end
-- Mouseover
elseif getOptionValue("Blessing of Protection Target") == 3 then
if getHP("mouseover") <= getValue("Blessing of Protection") then
if cast.blessingOfProtection("mouseover") then return true end
end
elseif getHP(lowestUnit) <= getValue("Blessing of Protection") then
-- Tank
if getOptionValue("Blessing of Protection Target") == 4 then
if UnitGroupRolesAssigned(lowestUnit) == "TANK" then
if cast.blessingOfProtection(lowestUnit) then return true end
end
-- Healer
elseif getOptionValue("Blessing of Protection Target") == 5 then
if UnitGroupRolesAssigned(lowestUnit) == "HEALER" then
if cast.blessingOfProtection(lowestUnit) then return true end
end
-- Healer/Tank
elseif getOptionValue("Blessing of Protection Target") == 6 then
if UnitGroupRolesAssigned(lowestUnit) == "HEALER" or UnitGroupRolesAssigned(lowestUnit) == "TANK" then
if cast.blessingOfProtection(lowestUnit) then return true end
end
-- Healer/Damager
elseif getOptionValue("Blessing of Protection Target") == 7 then
if UnitGroupRolesAssigned(lowestUnit) == "HEALER" or UnitGroupRolesAssigned(lowestUnit) == "DAMAGER" then
if cast.blessingOfProtection(lowestUnit) then return true end
end
-- Any
elseif getOptionValue("Blessing of Protection Target") == 8 then
if cast.blessingOfProtection(lowestUnit) then return true end
end
end
end
-- Engineering: Gunpowder Charge
if isChecked("Gunpowder Charge") and (getOptionValue("Gunpowder Charge") <= ttd ) and inCombat and canUse(132510) then
useItem(132510)
end
-- Blessing Of Sacrifice
if isChecked("Blessing Of Sacrifice") and php >= 50 and not UnitIsUnit(lowestUnit,"player") and inCombat then
-- Target
if getOptionValue("Blessing Of Sacrifice Target") == 1 then
if getHP("target") <= getValue("Blessing Of Sacrifice") then
if cast.blessingOfSacrifice("target") then return true end
end
-- Mouseover
elseif getOptionValue("Blessing Of Sacrifice Target") == 2 then
if getHP("mouseover") <= getValue("Blessing Of Sacrifice") then
if cast.blessingOfSacrifice("mouseover") then return true end
end
elseif getHP(lowestUnit) <= getValue("Blessing Of Sacrifice") then
-- Tank
if getOptionValue("Blessing Of Sacrifice Target") == 3 then
if UnitGroupRolesAssigned(lowestUnit) == "TANK" then
if cast.blessingOfSacrifice(lowestUnit) then return true end
end
-- Healer
elseif getOptionValue("Blessing Of Sacrifice Target") == 4 then
if UnitGroupRolesAssigned(lowestUnit) == "HEALER" then
if cast.blessingOfSacrifice(lowestUnit) then return true end
end
-- Healer/Tank
elseif getOptionValue("Blessing Of Sacrifice Target") == 5 then
if UnitGroupRolesAssigned(lowestUnit) == "HEALER" or UnitGroupRolesAssigned(lowestUnit) == "TANK" then
if cast.blessingOfSacrifice(lowestUnit) then return true end
end
-- Healer/Damager
elseif getOptionValue("Blessing Of Sacrifice Target") == 6 then
if UnitGroupRolesAssigned(lowestUnit) == "HEALER" or UnitGroupRolesAssigned(lowestUnit) == "DAMAGER" then
if cast.blessingOfSacrifice(lowestUnit) then return true end
end
-- Any
elseif getOptionValue("Blessing Of Sacrifice Target") == 7 then
if cast.blessingOfSacrifice(lowestUnit) then return true end
end
end
end
-- Cleanse Toxins
if isChecked("Clease Toxin") then
if getOptionValue("Clease Toxin")==1 and canDispel("player",spell.cleanseToxins) then
if cast.cleanseToxins("player") then return end
end
if getOptionValue("Clease Toxin")==2 and canDispel("target",spell.cleanseToxins) then
if cast.cleanseToxins("target") then return end
end
if getOptionValue("Clease Toxin")==3 and canDispel("mouseover",spell.cleanseToxins) then
if cast.cleanseToxins("mouseover") then return end
end
end
-- Eye of Tyr
if isChecked("Eye of Tyr - HP") and php <= getOptionValue("Eye of Tyr - HP") and inCombat and #enemies.yards10 > 0 then
if cast.eyeOfTyr() then return end
end
if isChecked("Eye of Tyr - AoE") and #enemies.yards10 >= getOptionValue("Eye of Tyr - AoE") and inCombat then
if cast.eyeOfTyr() then return end
end
-- Blinding Light
if isChecked("Blinding Light - HP") and php <= getOptionValue("Blinding Light - HP") and inCombat and #enemies.yards10 > 0 then
if cast.blindingLight() then return end
end
if isChecked("Blinding Light - AoE") and #enemies.yards5 >= getOptionValue("Blinding Light - AoE") and inCombat then
if cast.blindingLight() then return end
end
-- Shield of the Righteous
if isChecked("Shield of the Righteous - HP") then
if php <= getOptionValue("Shield of the Righteous - HP") and inCombat and not buff.shieldOfTheRighteous.exists() then
if cast.shieldOfTheRighteous() then return end
end
end
-- Guardian of Ancient Kings
if isChecked("Guardian of Ancient Kings") then
if php <= getOptionValue("Guardian of Ancient Kings") and inCombat and not buff.ardentDefender.exists() then
if cast.guardianOfAncientKings() then return end
end
end
-- Ardent Defender
if isChecked("Ardent Defender") then
if php <= getOptionValue("Ardent Defender") and inCombat and not buff.guardianOfAncientKings.exists() then
if cast.ardentDefender() then return end
end
end
-- Gift of the Naaru
if isChecked("Gift of the Naaru") and php <= getOptionValue("Gift of the Naaru") and php > 0 and race == "Draenei" then
if castSpell("player",racial,false,false,false) then return end
end
-- Hammer of Justice
if isChecked("Hammer of Justice - HP") and php <= getOptionValue("Hammer of Justice - HP") and inCombat then
if cast.hammerOfJustice(units.dyn10) then return end
end
if isChecked("Hammer of Justice - Legendary") and getHP("target") >= 75 and inCombat then
if cast.hammerOfJustice() then return end
end
-- Flash of Light
if isChecked("Flash of Light") then
if (forceHeal or (inCombat and php <= getOptionValue("Flash of Light") / 2) or (not inCombat and php <= getOptionValue("Flash of Light"))) and not isMoving("player") then
if cast.flashOfLight() then return end
end
end
-- Redemption
if isChecked("Redemption") then
if getOptionValue("Redemption")==1 and not isMoving("player") and resable then
if cast.redemption("target","dead") then return end
end
if getOptionValue("Redemption")==2 and not isMoving("player") and resable then
if cast.redemption("mouseover","dead") then return end
end
end
end
end -- End Action List - Defensive
-- Action List - Cooldowns
local function actionList_Cooldowns()
if useCDs() or burst then
-- Trinkets
if isChecked("Trinkets HP") and php <= getOptionValue("Trinkets HP") then
if (getOptionValue("Trinkets") == 1 or getOptionValue("Trinkets") == 3) and canUse(13) then
useItem(13)
end
if (getOptionValue("Trinkets") == 2 or getOptionValue("Trinkets") == 3) and canUse(14) then
seItem(14)
end
end
end -- End Cooldown Usage Check
end -- End Action List - Cooldowns
-- Action List - Interrupts
local function actionList_Interrupts()
if useInterrupts() then
if isChecked("Avenger's Shield - INT") then
for i = 1, #enemies.yards30 do
local thisUnit = enemies.yards30[i]
local distance = getDistance(thisUnit)
if canInterrupt(thisUnit, 100) then
if distance < 30 then
if cast.avengersShield() then return end
end
end
end
end
for i = 1, #enemies.yards10 do
local thisUnit = enemies.yards10[i]
local distance = getDistance(thisUnit)
if canInterrupt(thisUnit,getOptionValue("Interrupt At")) then
-- Hammer of Justice
if isChecked("Hammer of Justice - INT") and distance < 10 then
if cast.hammerOfJustice(thisUnit) then return end
end
-- Rebuke
if isChecked("Rebuke - INT") and distance < 5 then
if cast.rebuke(thisUnit) then return end
end
-- Blinding Light
if isChecked("Blinding Light - INT") and distance < 10 then
if cast.blindingLight() then return end
end
end
end
end
end -- End Action List - Interrupts
-- Action List - PreCombat
local function actionList_PreCombat()
-- PreCombat abilities listed here
end -- End Action List - PreCombat
-- Action List - Opener
local function actionList_Opener()
if isValidUnit("target") then
-- Judgment
if cast.judgment("target") then return end
-- Start Attack
if getDistance("target") < 5 and isValidUnit("target") then
StartAttack(units.dyn5)
end
end
end -- End Action List - Opener
---------------------
--- Begin Profile ---
---------------------
--Profile Stop | Pause
if not inCombat and not hastar and profileStop == true then
profileStop = false
elseif (inCombat and profileStop == true) or IsFlying() or pause() or mode.rotation == 4 then
return true
else
-----------------------
--- Extras Rotation ---
-----------------------
if actionList_Extras() then return end
---------------------------
--- Boss Encounter Case ---
---------------------------
if br.player.mode.BossCase == 1 then
if BossEncounterCase() then return end
end
--------------------------
--- Defensive Rotation ---
--------------------------
if actionList_Defensive() then return end
------------------------------
--- Out of Combat Rotation ---
------------------------------
if actionList_PreCombat() then return end
----------------------------
--- Out of Combat Opener ---
----------------------------
if actionList_Opener() then return end
--------------------------
--- In Combat Rotation ---
--------------------------
if inCombat and profileStop==false then
------------------------------
--- In Combat - Interrupts ---
------------------------------
if actionList_Interrupts() then return end
-----------------------------
--- In Combat - Cooldowns ---
-----------------------------
if actionList_Cooldowns() then return end
----------------------------------
--- In Combat - Begin Rotation ---
----------------------------------
--------------------------------
--- In Combat - SimCraft APL ---
--------------------------------
if not IsMounted() or buff.divineSteed.exists() then
-- Racials
-- berserking
if isChecked("Racial") and useCDs() then
if race == "Orc" or race == "Troll" and getSpellCD(racial) == 0 then
if castSpell("player",racial,false,false,false) then return end
end
end
if useCDs() and getDistance(units.dyn5) < 5 then
-- Seraphim
if isChecked("Seraphim") and charges.shieldOfTheRighteous.frac() >= 1.99 and (getOptionValue("Seraphim") <= ttd ) then
if cast.seraphim() then return end
end
-- Avenging Wrath
if isChecked("Avenging Wrath") and (not talent.seraphim or buff.seraphim.remain() > 15) and (getOptionValue("Avenging Wrath") <= ttd ) then
if cast.avengingWrath() then return end
end
-- Bastion of Light
if isChecked("Bastion of Light") and (charges.shieldOfTheRighteous.frac() < 0.2) and (not talent.seraphim or buff.seraphim.exists()) then
if cast.bastionOfLight() then return end
end
end
if not UnitIsFriend("target", "player") then
-- Shield of the Righteous
if isChecked("Shield of the Righteous") and (charges.shieldOfTheRighteous.frac() > 2.5) then
if cast.shieldOfTheRighteous(units.dyn5) then return end
end
-- Avenger's Shield
if isChecked("Avenger's Shield") then
if cast.avengersShield(units.dyn30) then return end
end
-- Consecration
if isChecked("Consecration") and not isMoving("player") and #enemies.yards10 >= 1 and getDistance(units.dyn5) < 5 and not UnitIsDeadOrGhost("target") then
if cast.consecration() then return end
end
-- Judgment
if isChecked("Judgment") then
if cast.judgment(units.dyn30) then return end
end
-- Blessed Hammer
if isChecked("Blessed Hammer") and talent.blessedHammer and #enemies.yards10 >= 1 then
if cast.blessedHammer() then return end
end
-- Hammer of the Righteous
if isChecked("Hammer of the Righteous") and not talent.blessedHammer then
if cast.hammerOfTheRighteous(units.dyn5) then return end
end
end
end
end -- End In Combat
end -- End Profile
end -- Timer
end -- runRotation
local id = 66
if br.rotations[id] == nil then br.rotations[id] = {} end
tinsert(br.rotations[id],{
name = rotationName,
toggles = createToggles,
options = createOptions,
run = runRotation,
})
| gpl-3.0 |
yylangchen/Sample_Lua | frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/CSLoader.lua | 5 | 3599 |
--------------------------------
-- @module CSLoader
-- @parent_module cc
--------------------------------
--
-- @function [parent=#CSLoader] createNodeFromJson
-- @param self
-- @param #string filename
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
--
-- @function [parent=#CSLoader] createNodeFromProtocolBuffers
-- @param self
-- @param #string filename
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
--
-- @function [parent=#CSLoader] init
-- @param self
--------------------------------
--
-- @function [parent=#CSLoader] setRecordXMLPath
-- @param self
-- @param #bool record
--------------------------------
--
-- @function [parent=#CSLoader] setJsonPath
-- @param self
-- @param #string jsonPath
--------------------------------
--
-- @function [parent=#CSLoader] loadNodeWithFile
-- @param self
-- @param #string fileName
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
--
-- @function [parent=#CSLoader] loadNodeWithContent
-- @param self
-- @param #string content
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
--
-- @function [parent=#CSLoader] isRecordProtocolBuffersPath
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#CSLoader] isRecordXMLPath
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#CSLoader] getProtocolBuffersPath
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
--
-- @function [parent=#CSLoader] getXMLPath
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
--
-- @function [parent=#CSLoader] createNodeFromXML
-- @param self
-- @param #string filename
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
--
-- @function [parent=#CSLoader] isRecordJsonPath
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#CSLoader] setRecordProtocolBuffersPath
-- @param self
-- @param #bool record
--------------------------------
--
-- @function [parent=#CSLoader] getJsonPath
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
--
-- @function [parent=#CSLoader] setRecordJsonPath
-- @param self
-- @param #bool record
--------------------------------
--
-- @function [parent=#CSLoader] setProtocolBuffersPath
-- @param self
-- @param #string protocolBuffersPath
--------------------------------
--
-- @function [parent=#CSLoader] purge
-- @param self
--------------------------------
--
-- @function [parent=#CSLoader] setXMLPath
-- @param self
-- @param #string xmlPath
--------------------------------
--
-- @function [parent=#CSLoader] destroyInstance
-- @param self
--------------------------------
--
-- @function [parent=#CSLoader] createNode
-- @param self
-- @param #string filename
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
--
-- @function [parent=#CSLoader] getInstance
-- @param self
-- @return CSLoader#CSLoader ret (return value: cc.CSLoader)
--------------------------------
--
-- @function [parent=#CSLoader] CSLoader
-- @param self
return nil
| mit |
omidtarh/o_m_i_dbot | plugins/vote.lua | 615 | 2128 | do
local _file_votes = './data/votes.lua'
function read_file_votes ()
local f = io.open(_file_votes, "r+")
if f == nil then
print ('Created voting file '.._file_votes)
serialize_to_file({}, _file_votes)
else
print ('Values loaded: '.._file_votes)
f:close()
end
return loadfile (_file_votes)()
end
function clear_votes (chat)
local _votes = read_file_votes ()
_votes [chat] = {}
serialize_to_file(_votes, _file_votes)
end
function votes_result (chat)
local _votes = read_file_votes ()
local results = {}
local result_string = ""
if _votes [chat] == nil then
_votes[chat] = {}
end
for user,vote in pairs (_votes[chat]) do
if (results [vote] == nil) then
results [vote] = user
else
results [vote] = results [vote] .. ", " .. user
end
end
for vote,users in pairs (results) do
result_string = result_string .. vote .. " : " .. users .. "\n"
end
return result_string
end
function save_vote(chat, user, vote)
local _votes = read_file_votes ()
if _votes[chat] == nil then
_votes[chat] = {}
end
_votes[chat][user] = vote
serialize_to_file(_votes, _file_votes)
end
function run(msg, matches)
if (matches[1] == "ing") then
if (matches [2] == "reset") then
clear_votes (tostring(msg.to.id))
return "Voting statistics reset.."
elseif (matches [2] == "stats") then
local votes_result = votes_result (tostring(msg.to.id))
if (votes_result == "") then
votes_result = "[No votes registered]\n"
end
return "Voting statistics :\n" .. votes_result
end
else
save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2])))
return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2]))
end
end
return {
description = "Plugin for voting in groups.",
usage = {
"!voting reset: Reset all the votes.",
"!vote [number]: Cast the vote.",
"!voting stats: Shows the statistics of voting."
},
patterns = {
"^!vot(ing) (reset)",
"^!vot(ing) (stats)",
"^!vot(e) ([0-9]+)$"
},
run = run
}
end | gpl-2.0 |
xdemolish/darkstar | scripts/globals/items/love_chocolate.lua | 35 | 1149 | -----------------------------------------
-- ID: 5230
-- Item: love_chocolate
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Magic Regen While Healing 4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5230);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MPHEAL, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MPHEAL, 4);
end;
| gpl-3.0 |
PlexChat/premake-core | tests/base/test_versions.lua | 12 | 3921 | --
-- tests/base/test_versions.lua
-- Verify the version comparisons.
-- Copyright (c) 2015 Jason Perkins and the Premake project
--
local suite = test.declare("premake_versions")
local p = premake
--
-- If only major version is specified, anything after should pass.
--
function suite.pass_majorOnly_sameMajor()
test.istrue(p.checkVersion("1.0.0", "1"))
end
function suite.pass_majorOnly_laterMajor()
test.istrue(p.checkVersion("2.0.0", "1"))
end
function suite.pass_majorOnly_laterMinor()
test.istrue(p.checkVersion("1.1.0", "1"))
end
function suite.pass_majorOnly_laterPatch()
test.istrue(p.checkVersion("1.0.1", "1"))
end
function suite.pass_majorOnly_alpha()
test.istrue(p.checkVersion("1.0.0.alpha1", "1"))
end
function suite.pass_majorOnly_dev()
test.istrue(p.checkVersion("1.0.0.dev", "1"))
end
function suite.fail_earlierMajor()
test.isfalse(p.checkVersion("0.9.0", "1"))
end
--
-- If major and minor are specified, anything after should pass
--
function suite.pass_majorMinor_sameMajorMinor()
test.istrue(p.checkVersion("1.1.0", "1.1"))
end
function suite.pass_majorMinor_sameMajorLaterMinor()
test.istrue(p.checkVersion("1.2.0", "1.1"))
end
function suite.pass_majorMinor_sameMajorLaterPath()
test.istrue(p.checkVersion("1.1.1", "1.1"))
end
function suite.pass_majorMinor_laterMajorSameMinor()
test.istrue(p.checkVersion("2.0.0", "1.1"))
end
function suite.pass_majorMinor_laterMajorEarlierMinor()
test.istrue(p.checkVersion("2.0.0", "1.1"))
end
function suite.pass_majorMinor_laterMajorLaterMinor()
test.istrue(p.checkVersion("2.2.0", "1.1"))
end
function suite.fail_majorMinor_sameMajorEarlierMinor()
test.isfalse(p.checkVersion("1.0.0", "1.1"))
end
function suite.fail_majorMinor_earlierMajor()
test.isfalse(p.checkVersion("0.9.0", "1.1"))
end
--
-- Alpha comes before beta comes before dev
--
function suite.pass_alphaBeforeBeta()
test.istrue(p.checkVersion("1.0.0.beta1", "1.0.0.alpha1"))
end
function suite.fail_alphaBeforeBeta()
test.isfalse(p.checkVersion("1.0.0.alpha1", "1.0.0.beta1"))
end
function suite.pass_betaBeforeDev()
test.istrue(p.checkVersion("1.0.0.dev", "1.0.0.beta1"))
end
function suite.fail_betaBeforeDev()
test.isfalse(p.checkVersion("1.0.0.beta1", "1.0.0.dev"))
end
--
-- Check ">=" operator
--
function suite.pass_ge_sameMajorMinorPatch()
test.istrue(p.checkVersion("1.1.0", ">=1.1"))
end
function suite.pass_ge_sameMajorMinorLaterPatch()
test.istrue(p.checkVersion("1.1.1", ">=1.1"))
end
function suite.pass_ge_laterMajorEarlierMinor()
test.istrue(p.checkVersion("2.0.1", ">=1.1"))
end
function suite.pass_ge_sameMajorLaterMinor()
test.istrue(p.checkVersion("1.2.1", ">=1.1"))
end
function suite.fail_ge_earlierMajor()
test.isfalse(p.checkVersion("0.1.1", ">=1.1"))
end
function suite.fail_ge_earlierMinor()
test.isfalse(p.checkVersion("1.0.1", ">=1.1"))
end
--
-- Check ">" operator
--
function suite.pass_gt_sameMajorMinorLaterPatch()
test.istrue(p.checkVersion("1.1.1", ">1.1"))
end
function suite.pass_gt_laterMajor()
test.istrue(p.checkVersion("2.0.1", ">1.1"))
end
function suite.pass_gt_laterMinor()
test.istrue(p.checkVersion("1.2.1", ">1.1"))
end
function suite.fail_gt_sameMajorMinorPatch()
test.isfalse(p.checkVersion("1.1.0", ">1.1"))
end
function suite.fail_gt_earlierMajor()
test.isfalse(p.checkVersion("0.1.1", ">1.1"))
end
function suite.fail_gt_earlierMinor()
test.isfalse(p.checkVersion("1.0.1", ">1.1"))
end
--
-- Check multiple conditions
--
function suite.pass_onMultipleConditions()
test.istrue(p.checkVersion("1.2.0.0", ">=1.0 <2.0"))
end
function suite.fail_onMultipleConditions()
test.isfalse(p.checkVersion("2.2.0.0", ">=1.0 <2.0"))
end
--
-- If there is no version information, fails.
--
function suite.fail_onNoVersion()
test.isfalse(p.checkVersion(nil, "1.0"))
end
| bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.