repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278 values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15 values |
|---|---|---|---|---|---|
jshackley/darkstar | scripts/globals/mobskills/Lethe_Arrows.lua | 25 | 1095 | ---------------------------------------------
-- Lethe Arrows
--
-- Description: Deals a ranged attack to target. Additional effect: Knockback, Bind, and Amnesia
-- Type: Ranged
-- Utsusemi/Blink absorb: Ignores Utsusemi
-- Range: Unknown
-- Notes:
---------------------------------------------
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 typeEffect = EFFECT_BIND;
MobStatusEffectMove(mob, target, typeEffect, 1, 0, 120);
typeEffect = EFFECT_AMNESIA;
MobStatusEffectMove(mob, target, typeEffect, 1, 0, 120);
local numhits = 1;
local accmod = 3;
local dmgmod = 4;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,2,3);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_RANGED,MOBPARAM_PIERCE,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Lufaise_Meadows/npcs/Jersey.lua | 19 | 1808 | -----------------------------------
-- Area: Lufaise Meadows
-- NPC: Jersey
-- Type: Outpost Vendor
-- @pos -548.706 -7.197 -53.897 24
-----------------------------------
package.loaded["scripts/zones/Lufaise_Meadows/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
require("scripts/zones/Lufaise_Meadows/TextIDs");
local region = TAVNAZIANARCH;
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 |
jshackley/darkstar | scripts/zones/Upper_Jeuno/npcs/Chocobo.lua | 2 | 5041 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Chocobo
-- Finishes Quest: Chocobo's Wounds
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Upper_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
ChocobosWounds = player:getQuestStatus(JEUNO,CHOCOBO_S_WOUNDS);
if (ChocobosWounds == 0) then
player:startEvent(0x003e);
elseif (ChocobosWounds == 1) then
count = trade:getItemCount();
gil = trade:getGil();
if (trade:hasItemQty(4545,1)) then
player:startEvent(0x004c);
elseif (trade:hasItemQty(534,1) and gil == 0 and count == 1) then
--Check feeding status.
feed = player:getVar("ChocobosWounds_Event");
feedMin = player:getVar("ChocobosWounds_Min");
feedReady = (feedMin <= os.time())
if (feed == 1) then
player:startEvent(0x0039);
elseif (feedReady == true) then
if (feed == 2) then
player:startEvent(0x003a);
elseif (feed == 3) then
player:startEvent(0x003b);
elseif (feed == 4) then
player:startEvent(0x003c);
elseif (feed == 5) then
player:startEvent(0x003f);
elseif (feed == 6) then
player:startEvent(0x0040);
end
else
if (feed > 2) then
player:startEvent(0x0049);
end
end
end
else
if (trade:hasItemQty(4545,1)) then
player:startEvent(0x0026);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
ChocobosWounds = player:getQuestStatus(JEUNO,CHOCOBO_S_WOUNDS);
if (ChocobosWounds == QUEST_COMPLETED and player:hasKeyItem(CHOCOBO_LICENSE) == false) then
-- this is a quick hack to let people get their license if it was lost
player:addKeyItem(CHOCOBO_LICENSE);
player:messageSpecial(KEYITEM_OBTAINED, CHOCOBO_LICENSE);
elseif (ChocobosWounds == QUEST_AVAILABLE) then
player:startEvent(0x003e);
elseif (ChocobosWounds == QUEST_ACCEPTED) then
feed = player:getVar("ChocobosWounds_Event");
if (feed == 1) then
player:startEvent(0x0067);
elseif (feed == 2) then
player:startEvent(0x0033);
elseif (feed == 3) then
player:startEvent(0x0034);
elseif (feed == 4) then
player:startEvent(0x003d);
elseif (feed == 5) then
player:startEvent(0x002e);
elseif (feed == 6) then
player:startEvent(0x0037);
end
elseif (ChocobosWounds == 2) then
player:startEvent(0x0037);
else
player:startEvent(0x0036);
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 == 0x0039) then
player:setVar("ChocobosWounds_Event", 2);
player:setVar("ChocobosWounds_Min",os.time() + 60);
elseif (csid == 0x003a) then
player:setVar("ChocobosWounds_Event", 3);
player:setVar("ChocobosWounds_Min",os.time() + 60);
elseif (csid == 0x003b) then
player:setVar("ChocobosWounds_Event", 4);
player:setVar("ChocobosWounds_Min",os.time() + 60);
player:tradeComplete();
player:startEvent(0x0063);
elseif (csid == 0x003c) then
player:setVar("ChocobosWounds_Event", 5);
player:setVar("ChocobosWounds_Min",os.time() + 60);
player:tradeComplete();
elseif (csid == 0x003f) then
player:setVar("ChocobosWounds_Event", 6);
player:setVar("ChocobosWounds_Min",os.time() + 60);
player:tradeComplete();
elseif (csid == 0x0040) then
player:addKeyItem(CHOCOBO_LICENSE);
player:messageSpecial(KEYITEM_OBTAINED, CHOCOBO_LICENSE);
player:addTitle(CHOCOBO_TRAINER);
player:setVar("ChocobosWounds_Event", 0);
player:setVar("ChocobosWounds_Min", 0);
player:addFame(JEUNO,30);
player:tradeComplete();
player:completeQuest(JEUNO,CHOCOBO_S_WOUNDS);
end
end;
| gpl-3.0 |
Mizugola/MeltingSaga | engine/Lib/Toolkit/Functions/version.lua | 5 | 2675 | local Color = require("Lib/StdLib/ConsoleColor");
local Route = require("Lib/Toolkit/Route");
local Style = require("Lib/Toolkit/Stylesheet");
return {
Functions = {
version = function()
Color.print({
{ text = "ÖbEngine is in version ", color = Style.Default},
{ text = obe.version, color = Style.Workspace},
}, 1);
end,
major = function()
local major_version = string.split(string.sub(obe.version, 2),".")[1];
Color.print({
{ text = "ÖbEngine's major version is ", color = Style.Default},
{ text = major_version, color = Style.Workspace},
}, 1);
end,
minor = function()
local minor_version = string.split(string.sub(obe.version, 2),".")[2];
Color.print({
{ text = "ÖbEngine's minor version is ", color = Style.Default},
{ text = minor_version, color = Style.Workspace},
}, 1);
end,
patch = function()
local patch_version = string.split(string.sub(obe.version, 2),".")[3];
Color.print({
{ text = "ÖbEngine's patch version is ", color = Style.Default},
{ text = patch_version, color = Style.Workspace},
}, 1);
end,
commit = function()
local commit_version = obe.commit;
Color.print({
{ text = "ÖbEngine's commit version is ", color = Style.Default},
{ text = commit_version, color = Style.Workspace},
}, 1);
end,
branch = function()
local branch_version = obe.branch;
Color.print({
{ text = "ÖbEngine's branch version is ", color = Style.Default},
{ text = branch_version, color = Style.Workspace},
}, 1);
end
},
Routes = {
Route.Help("Get ÖbEngine's version");
Route.Call("version");
major = Route.Node {
Route.Help("Get ÖbEngine's major version");
Route.Call("major");
},
minor = Route.Node {
Route.Help("Get ÖbEngine's minor version");
Route.Call("minor");
},
patch = Route.Node {
Route.Help("Get ÖbEngine's patch version");
Route.Call("patch");
},
commit = Route.Node {
Route.Help("Get ÖbEngine's commit version");
Route.Call("commit");
},
branch = Route.Node {
Route.Help("Get ÖbEngine's branch version");
Route.Call("branch");
}
}
}; | mit |
iofun/treehouse | luerl/e102182e51f9f096e5d523bc3b4bd3d7.lua | 1 | 2139 | -- The Science Facility is built by Terran following construction of the Starport.
-- Our unit function table
local this_unit = {}
-- Where we are and fast we move
local x, y, dx, dy
-- Our name
local name = "Terran_Science_Facility"
-- Our color
local color = "blue"
-- Our BWAPI unit type
local type = 116
-- Size of a clock tick msec
local tick
-- It's me, the unit structure
local me = unit.self()
-- The standard local variables
local label = "large_structure"
local armor = 1
local hitpoints,shield = 850,0
local ground_damage,air_damage = 0,0
local ground_cooldown,air_cooldown = 0,0
local ground_range,air_range = 0,0
local sight = 8
local supply = 0
local cooldown = 60
local mineral = 100
local gas = 150
local holdkey = "i"
-- The size of the region
local xsize,ysize = region.size()
-- The unit interface.
function this_unit.start() end
function this_unit.get_position() return x,y end
function this_unit.set_position(a1, a2) x,y = a1,a2 end
function this_unit.get_speed() return dx,dy end
function this_unit.set_speed(a1, a2) dx,dy = a1,a2 end
function this_unit.set_tick(a1) tick = a1 end
local function move_xy_bounce(x, y, dx, dy, valid_x, valid_y)
local nx = x + dx
local ny = y + dy
-- Bounce off the edge
if (not valid_x(nx)) then
nx = x - dx
dx = -dx
end
-- Bounce off the edge
if (not valid_y(ny)) then
ny = y - dy
dy = -dy
end
return nx, ny, dx, dy
end
local function move(x, y, dx, dy)
local nx,ny,ndx,ndy = move_xy_bounce(x, y, dx, dy,
region.valid_x, region.valid_y)
-- Where we were and where we are now.
local osx,osy = region.sector(x, y)
local nsx,nsy = region.sector(nx, ny)
if (osx ~= nsx or osy ~= nsy) then
-- In new sector, move us to the right sector
region.rem_sector(x, y)
region.add_sector(nx, ny)
end
return nx,ny,ndx,ndy
end
function this_unit.tick()
x,y,dx,dy = move(x, y, dx, dy)
end
function this_unit.attack()
-- The unit has been zapped and will die
region.rem_sector(x, y)
end
-- Return the unit table
return this_unit
| agpl-3.0 |
luastoned/turbo | examples/githubfeed.lua | 12 | 1795 | --- Turbo.lua Github Feed
--
-- Copyright 2013 John Abrahamsen
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-- This implementation uses the Github REST API to pull current amount of
-- watchers for the Turbo.lua repository.
TURBO_SSL = true -- Enable SSL as Github API requires HTTPS.
local turbo = require "turbo"
local yield = coroutine.yield
local GithubFeed = class("GithubFeed", turbo.web.RequestHandler)
function GithubFeed:get(search)
local res = yield(
turbo.async.HTTPClient():fetch("https://api.github.com/repos/kernelsauce/turbo"))
if res.error or res.headers:get_status_code() ~= 200 then
-- Check for errors.
-- If data could not be fetched a 500 error is sent as response.
error(turbo.web.HTTPError:new(500, res.error.message))
end
local json = turbo.escape.json_decode(res.body)
-- Ugly inlining of HTML code. You get the point!
self:write([[<html><head></head><body>]])
self:write(string.format(
[[
<h1>Turbo.lua Github feed<h1>
<p>Current watchers %d</p>
]],
json.watchers_count
))
self:write([[</body></html>]])
end
local application = turbo.web.Application:new({
{"^/$", GithubFeed}
})
application:listen(8888)
turbo.ioloop.instance():start()
| apache-2.0 |
jshackley/darkstar | scripts/zones/Pashhow_Marshlands/npcs/Stone_Monument.lua | 32 | 1300 | -----------------------------------
-- Area: Pashhow Marshlands
-- NPC: Stone Monument
-- Involved in quest "An Explorer's Footsteps"
-- @pos -300.672 21.620 304.179 109
-----------------------------------
package.loaded["scripts/zones/Pashhow_Marshlands/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Pashhow_Marshlands/TextIDs");
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0384);
end;
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then
player:tradeComplete();
player:addItem(570);
player:messageSpecial(ITEM_OBTAINED,570);
player:setVar("anExplorer-CurrentTablet",0x00100);
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 |
josetaas/YokiRaidCursor | Libs/MiddleClass/MiddleClass.lua | 1 | 4438 | local middleclass = LibStub:NewLibrary("MiddleClass", 1)
local function _createIndexWrapper(aClass, f)
if f == nil then
return aClass.__instanceDict
else
return function(self, name)
local value = aClass.__instanceDict[name]
if value ~= nil then
return value
elseif type(f) == "function" then
return (f(self, name))
else
return f[name]
end
end
end
end
local function _propagateInstanceMethod(aClass, name, f)
f = name == "__index" and _createIndexWrapper(aClass, f) or f
aClass.__instanceDict[name] = f
for subclass in pairs(aClass.subclasses) do
if rawget(subclass.__declaredMethods, name) == nil then
_propagateInstanceMethod(subclass, name, f)
end
end
end
local function _declareInstanceMethod(aClass, name, f)
aClass.__declaredMethods[name] = f
if f == nil and aClass.super then
f = aClass.super.__instanceDict[name]
end
_propagateInstanceMethod(aClass, name, f)
end
local function _tostring(self) return "class " .. self.name end
local function _call(self, ...) return self:new(...) end
local function _createClass(name, super)
local dict = {}
dict.__index = dict
local aClass = { name = name, super = super, static = {},
__instanceDict = dict, __declaredMethods = {},
subclasses = setmetatable({}, {__mode='k'}) }
if super then
setmetatable(aClass.static, { __index = function(_,k) return rawget(dict,k) or super.static[k] end })
else
setmetatable(aClass.static, { __index = function(_,k) return rawget(dict,k) end })
end
setmetatable(aClass, { __index = aClass.static, __tostring = _tostring,
__call = _call, __newindex = _declareInstanceMethod })
return aClass
end
local function _includeMixin(aClass, mixin)
assert(type(mixin) == 'table', "mixin must be a table")
for name,method in pairs(mixin) do
if name ~= "included" and name ~= "static" then aClass[name] = method end
end
for name,method in pairs(mixin.static or {}) do
aClass.static[name] = method
end
if type(mixin.included)=="function" then mixin:included(aClass) end
return aClass
end
local DefaultMixin = {
__tostring = function(self) return "instance of " .. tostring(self.class) end,
Initialize = function(self, ...) end,
IsInstanceOf = function(self, aClass)
return type(aClass) == 'table' and (aClass == self.class or self.class:isSubclassOf(aClass))
end,
static = {
allocate = function(self)
assert(type(self) == 'table', "Make sure that you are using 'Class:allocate' instead of 'Class.allocate'")
return setmetatable({ class = self }, self.__instanceDict)
end,
new = function(self, ...)
assert(type(self) == 'table', "Make sure that you are using 'Class:new' instead of 'Class.new'")
local instance = self:allocate()
instance:Initialize(...)
return instance
end,
subclass = function(self, name)
assert(type(self) == 'table', "Make sure that you are using 'Class:subclass' instead of 'Class.subclass'")
assert(type(name) == "string", "You must provide a name(string) for your class")
local subclass = _createClass(name, self)
for methodName, f in pairs(self.__instanceDict) do
_propagateInstanceMethod(subclass, methodName, f)
end
subclass.Initialize = function(instance, ...) return self.Initialize(instance, ...) end
self.subclasses[subclass] = true
self:subclassed(subclass)
return subclass
end,
subclassed = function(self, other) end,
isSubclassOf = function(self, other)
return type(other) == 'table' and
type(self.super) == 'table' and
( self.super == other or self.super:isSubclassOf(other) )
end,
include = function(self, ...)
assert(type(self) == 'table', "Make sure you that you are using 'Class:include' instead of 'Class.include'")
for _,mixin in ipairs({...}) do _includeMixin(self, mixin) end
return self
end
}
}
function middleclass.class(name, super)
assert(type(name) == 'string', "A name (string) is needed for the new class")
return super and super:subclass(name) or _includeMixin(_createClass(name), DefaultMixin)
end
setmetatable(middleclass, { __call = function(_, ...) return middleclass.class(...) end })
function middleclass:GetClassObject()
return middleclass
end
| mit |
nestharus/JASS | lua/wc3 project/utils/web/web.lua | 1 | 5305 | local socket = require("socket")
local http = require("socket.http")
local ftp = require("socket.ftp")
local url = require("socket.url")
local ltn12 = require("ltn12")
local lfs = require("lfs")
-- formats a number of seconds into human readable form
function nicetime(s)
local l = "s"
if s > 60 then
s = s / 60
l = "m"
if s > 60 then
s = s / 60
l = "h"
if s > 24 then
s = s / 24
l = "d" -- hmmm
end
end
end
if l == "s" then return string.format("%5.0f%s", s, l)
else return string.format("%5.2f%s", s, l) end
end
-- formats a number of bytes into human readable form
function nicesize(b)
local l = "B"
if b > 1024 then
b = b / 1024
l = "KB"
if b > 1024 then
b = b / 1024
l = "MB"
if b > 1024 then
b = b / 1024
l = "GB" -- hmmm
end
end
end
return string.format("%7.2f%2s", b, l)
end
-- returns a string with the current state of the download
local remaining_s = "%s received, %s/s throughput, %2.0f%% done, %s remaining"
local elapsed_s = "%s received, %s/s throughput, %s elapsed "
function gauge(got, delta, size)
local rate = got / delta
if size and size >= 1 then
return string.format(remaining_s, nicesize(got), nicesize(rate),
100*got/size, nicetime((size-got)/rate))
else
return string.format(elapsed_s, nicesize(got),
nicesize(rate), nicetime(delta))
end
end
-- creates a new instance of a receive_cb that saves to disk
-- kind of copied from luasocket's manual callback examples
function stats(size)
local start = socket.gettime()
local last = start
local got = 0
return function(chunk)
-- elapsed time since start
local current = socket.gettime()
if chunk then
-- total bytes received
got = got + string.len(chunk)
-- not enough time for estimate
if current - last > 1 then
io.stderr:write("\r", gauge(got, current - start, size))
io.stderr:flush()
last = current
end
else
-- close up
io.stderr:write("\r", gauge(got, current - start), "\n")
end
return chunk
end
end
-- determines the size of a http file
function gethttpsize(u)
local r, c, h = http.request {method = "HEAD", url = u}
if c == 200 then
return tonumber(h["content-length"])
end
end
-- downloads a file using the http protocol
function getbyhttp(u, file, sz)
local save = ltn12.sink.file(file or io.stdout)
local size2get = gethttpsize(u)
if not size2get then
io.stderr:write("Error contacting remote host.")
--if not sz then do_something() end
os.exit(0)
end
if size2get == sz then
print("File already completed.")
os.exit(0)
end
-- only print feedback if output is not stdout
if file then save = ltn12.sink.chain(stats(size2get), save) end
local hdrs
if sz then
-- resume header
hdrs = { ["Range"] = "bytes=" .. sz .."-" }
end
local r, c, h, s = http.request {url = u, sink = save, headers = hdrs }
-- todo: check for 206; fallback?
if c ~= 200 then io.stderr:write(s or c, "\n") end
end
-- downloads a file using the ftp protocol
function getbyftp(u, file, sz)
local save = ltn12.sink.file(file or io.stdout)
-- only print feedback if output is not stdout
-- and we don't know how big the file is
-- todo: can use SIZE file to get file size, but is not RFC
-- would probably be easier to do 2 ftp sessions
if file then save = ltn12.sink.chain(stats(), save) end
local gett = url.parse(u)
gett.sink = save
gett.type = "i"
if sz then
-- try to resume; fallback?
-- filler command (see below) + restart offset + retrieve file
-- bug? having REST first will return 350, ftp.get returns early
gett.command = 'SYST' .. '\n' .. 'REST ' .. sz .. '\nRETR'
end
local ret, err = ftp.get(gett)
if err then print(err) end
end
-- determines the scheme
function getscheme(u)
-- this is an heuristic to solve a common invalid url poblem
if not string.find(u, "//") then u = "//" .. u end
local parsed = url.parse(u, {scheme = "http"})
return parsed.scheme
end
-- gets a file either by http or ftp, saving as <name>
-- todo: check filesize etc before opening file
function get(u, name)
if not name then
-- use the basename from the url, assuming no spaces
-- better to exec `basename` instead?
name = string.gsub(u, '.*/', "")
-- todo: change this
if not name then
name = os.tmpname()
print ("Using " .. name .. " to store data")
end
end
local sz = lfs.attributes(name, "size")
local mode
if sz then
print ("File " .. name .. " found with a size of " .. sz)
print ("Trying to resume ...")
mode = "a+b"
else
mode = "wb"
end
local fout = name and io.open(name, mode)
local scheme = getscheme(u)
if scheme == "ftp" then getbyftp(u, fout, sz)
elseif scheme == "http" then getbyhttp(u, fout, sz)
else print("unknown scheme" .. scheme) end
end
| mit |
jshackley/darkstar | scripts/globals/items/piece_of_raisin_bread.lua | 35 | 1280 | -----------------------------------------
-- ID: 4546
-- Item: piece_of_raisin_bread
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Health 20
-- Dexterity -1
-- Vitality 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,1800,4546);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 20);
target:addMod(MOD_DEX, -1);
target:addMod(MOD_VIT, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 20);
target:delMod(MOD_DEX, -1);
target:delMod(MOD_VIT, 4);
end;
| gpl-3.0 |
DipColor/mehrabon3 | plugins/tweet.lua | 634 | 7120 | local OAuth = require "OAuth"
local consumer_key = ""
local consumer_secret = ""
local access_token = ""
local access_token_secret = ""
local twitter_url = "https://api.twitter.com/1.1/statuses/user_timeline.json"
local client = OAuth.new(consumer_key,
consumer_secret,
{ RequestToken = "https://api.twitter.com/oauth/request_token",
AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"},
AccessToken = "https://api.twitter.com/oauth/access_token"},
{ OAuthToken = access_token,
OAuthTokenSecret = access_token_secret})
local function send_generics_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
local f = cb_extra.func
-- 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,
func = f
}
-- Send first and postpone the others as callback
f(receiver, file_path, send_generics_from_url_callback, cb_extra)
end
local function send_generics_from_url(f, receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil,
func = f
}
send_generics_from_url_callback(cb_extra)
end
local function send_gifs_from_url(receiver, urls)
send_generics_from_url(send_document, receiver, urls)
end
local function send_videos_from_url(receiver, urls)
send_generics_from_url(send_video, receiver, urls)
end
local function send_all_files(receiver, urls)
local data = {
images = {
func = send_photos_from_url,
urls = {}
},
gifs = {
func = send_gifs_from_url,
urls = {}
},
videos = {
func = send_videos_from_url,
urls = {}
}
}
local table_to_insert = nil
for i,url in pairs(urls) do
local _, _, extension = string.match(url, "(https?)://([^\\]-([^\\%.]+))$")
local mime_type = mimetype.get_content_type_no_sub(extension)
if extension == 'gif' then
table_to_insert = data.gifs.urls
elseif mime_type == 'image' then
table_to_insert = data.images.urls
elseif mime_type == 'video' then
table_to_insert = data.videos.urls
else
table_to_insert = nil
end
if table_to_insert then
table.insert(table_to_insert, url)
end
end
for k, v in pairs(data) do
if #v.urls > 0 then
end
v.func(receiver, v.urls)
end
end
local function check_keys()
if consumer_key:isempty() then
return "Twitter Consumer Key is empty, write it in plugins/tweet.lua"
end
if consumer_secret:isempty() then
return "Twitter Consumer Secret is empty, write it in plugins/tweet.lua"
end
if access_token:isempty() then
return "Twitter Access Token is empty, write it in plugins/tweet.lua"
end
if access_token_secret:isempty() then
return "Twitter Access Token Secret is empty, write it in plugins/tweet.lua"
end
return ""
end
local function analyze_tweet(tweet)
local header = "Tweet from " .. tweet.user.name .. " (@" .. tweet.user.screen_name .. ")\n" -- "Link: https://twitter.com/statuses/" .. tweet.id_str
local text = tweet.text
-- replace short URLs
if tweet.entities.url then
for k, v in pairs(tweet.entities.urls) do
local short = v.url
local long = v.expanded_url
text = text:gsub(short, long)
end
end
-- remove urls
local urls = {}
if tweet.extended_entities and tweet.extended_entities.media then
for k, v in pairs(tweet.extended_entities.media) do
if v.video_info and v.video_info.variants then -- If it's a video!
table.insert(urls, v.video_info.variants[1].url)
else -- If not, is an image
table.insert(urls, v.media_url)
end
text = text:gsub(v.url, "") -- Replace the URL in text
end
end
return header, text, urls
end
local function sendTweet(receiver, tweet)
local header, text, urls = analyze_tweet(tweet)
-- send the parts
send_msg(receiver, header .. "\n" .. text, ok_cb, false)
send_all_files(receiver, urls)
return nil
end
local function getTweet(msg, base, all)
local receiver = get_receiver(msg)
local response_code, response_headers, response_status_line, response_body = client:PerformRequest("GET", twitter_url, base)
if response_code ~= 200 then
return "Can't connect, maybe the user doesn't exist."
end
local response = json:decode(response_body)
if #response == 0 then
return "Can't retrieve any tweets, sorry"
end
if all then
for i,tweet in pairs(response) do
sendTweet(receiver, tweet)
end
else
local i = math.random(#response)
local tweet = response[i]
sendTweet(receiver, tweet)
end
return nil
end
function isint(n)
return n==math.floor(n)
end
local function run(msg, matches)
local checked = check_keys()
if not checked:isempty() then
return checked
end
local base = {include_rts = 1}
if matches[1] == 'id' then
local userid = tonumber(matches[2])
if userid == nil or not isint(userid) then
return "The id of a user is a number, check this web: http://gettwitterid.com/"
end
base.user_id = userid
elseif matches[1] == 'name' then
base.screen_name = matches[2]
else
return ""
end
local count = 200
local all = false
if #matches > 2 and matches[3] == 'last' then
count = 1
if #matches == 4 then
local n = tonumber(matches[4])
if n > 10 then
return "You only can ask for 10 tweets at most"
end
count = matches[4]
all = true
end
end
base.count = count
return getTweet(msg, base, all)
end
return {
description = "Random tweet from user",
usage = {
"!tweet id [id]: Get a random tweet from the user with that ID",
"!tweet id [id] last: Get a random tweet from the user with that ID",
"!tweet name [name]: Get a random tweet from the user with that name",
"!tweet name [name] last: Get a random tweet from the user with that name"
},
patterns = {
"^!tweet (id) ([%w_%.%-]+)$",
"^!tweet (id) ([%w_%.%-]+) (last)$",
"^!tweet (id) ([%w_%.%-]+) (last) ([%d]+)$",
"^!tweet (name) ([%w_%.%-]+)$",
"^!tweet (name) ([%w_%.%-]+) (last)$",
"^!tweet (name) ([%w_%.%-]+) (last) ([%d]+)$"
},
run = run
}
| gpl-2.0 |
josetaas/YokiRaidCursor | Libs/Ace3/AceConfig-3.0/AceConfigRegistry-3.0/AceConfigRegistry-3.0.lua | 3 | 12528 | --- AceConfigRegistry-3.0 handles central registration of options tables in use by addons and modules.\\
-- Options tables can be registered as raw tables, OR as function refs that return a table.\\
-- Such functions receive three arguments: "uiType", "uiName", "appName". \\
-- * Valid **uiTypes**: "cmd", "dropdown", "dialog". This is verified by the library at call time. \\
-- * The **uiName** field is expected to contain the full name of the calling addon, including version, e.g. "FooBar-1.0". This is verified by the library at call time.\\
-- * The **appName** field is the options table name as given at registration time \\
--
-- :IterateOptionsTables() (and :GetOptionsTable() if only given one argument) return a function reference that the requesting config handling addon must call with valid "uiType", "uiName".
-- @class file
-- @name AceConfigRegistry-3.0
-- @release $Id: AceConfigRegistry-3.0.lua 1139 2016-07-03 07:43:51Z nevcairiel $
local MAJOR, MINOR = "AceConfigRegistry-3.0", 16
local AceConfigRegistry = LibStub:NewLibrary(MAJOR, MINOR)
if not AceConfigRegistry then return end
AceConfigRegistry.tables = AceConfigRegistry.tables or {}
local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0")
if not AceConfigRegistry.callbacks then
AceConfigRegistry.callbacks = CallbackHandler:New(AceConfigRegistry)
end
-- Lua APIs
local tinsert, tconcat = table.insert, table.concat
local strfind, strmatch = string.find, string.match
local type, tostring, select, pairs = type, tostring, select, pairs
local error, assert = error, assert
-----------------------------------------------------------------------
-- Validating options table consistency:
AceConfigRegistry.validated = {
-- list of options table names ran through :ValidateOptionsTable automatically.
-- CLEARED ON PURPOSE, since newer versions may have newer validators
cmd = {},
dropdown = {},
dialog = {},
}
local function err(msg, errlvl, ...)
local t = {}
for i=select("#",...),1,-1 do
tinsert(t, (select(i, ...)))
end
error(MAJOR..":ValidateOptionsTable(): "..tconcat(t,".")..msg, errlvl+2)
end
local isstring={["string"]=true, _="string"}
local isstringfunc={["string"]=true,["function"]=true, _="string or funcref"}
local istable={["table"]=true, _="table"}
local ismethodtable={["table"]=true,["string"]=true,["function"]=true, _="methodname, funcref or table"}
local optstring={["nil"]=true,["string"]=true, _="string"}
local optstringfunc={["nil"]=true,["string"]=true,["function"]=true, _="string or funcref"}
local optstringnumberfunc={["nil"]=true,["string"]=true,["number"]=true,["function"]=true, _="string, number or funcref"}
local optnumber={["nil"]=true,["number"]=true, _="number"}
local optmethod={["nil"]=true,["string"]=true,["function"]=true, _="methodname or funcref"}
local optmethodfalse={["nil"]=true,["string"]=true,["function"]=true,["boolean"]={[false]=true}, _="methodname, funcref or false"}
local optmethodnumber={["nil"]=true,["string"]=true,["function"]=true,["number"]=true, _="methodname, funcref or number"}
local optmethodtable={["nil"]=true,["string"]=true,["function"]=true,["table"]=true, _="methodname, funcref or table"}
local optmethodbool={["nil"]=true,["string"]=true,["function"]=true,["boolean"]=true, _="methodname, funcref or boolean"}
local opttable={["nil"]=true,["table"]=true, _="table"}
local optbool={["nil"]=true,["boolean"]=true, _="boolean"}
local optboolnumber={["nil"]=true,["boolean"]=true,["number"]=true, _="boolean or number"}
local basekeys={
type=isstring,
name=isstringfunc,
desc=optstringfunc,
descStyle=optstring,
order=optmethodnumber,
validate=optmethodfalse,
confirm=optmethodbool,
confirmText=optstring,
disabled=optmethodbool,
hidden=optmethodbool,
guiHidden=optmethodbool,
dialogHidden=optmethodbool,
dropdownHidden=optmethodbool,
cmdHidden=optmethodbool,
icon=optstringnumberfunc,
iconCoords=optmethodtable,
handler=opttable,
get=optmethodfalse,
set=optmethodfalse,
func=optmethodfalse,
arg={["*"]=true},
width=optstring,
}
local typedkeys={
header={},
description={
image=optstringnumberfunc,
imageCoords=optmethodtable,
imageHeight=optnumber,
imageWidth=optnumber,
fontSize=optstringfunc,
},
group={
args=istable,
plugins=opttable,
inline=optbool,
cmdInline=optbool,
guiInline=optbool,
dropdownInline=optbool,
dialogInline=optbool,
childGroups=optstring,
},
execute={
image=optstringnumberfunc,
imageCoords=optmethodtable,
imageHeight=optnumber,
imageWidth=optnumber,
},
input={
pattern=optstring,
usage=optstring,
control=optstring,
dialogControl=optstring,
dropdownControl=optstring,
multiline=optboolnumber,
},
toggle={
tristate=optbool,
image=optstringnumberfunc,
imageCoords=optmethodtable,
},
tristate={
},
range={
min=optnumber,
softMin=optnumber,
max=optnumber,
softMax=optnumber,
step=optnumber,
bigStep=optnumber,
isPercent=optbool,
},
select={
values=ismethodtable,
style={
["nil"]=true,
["string"]={dropdown=true,radio=true},
_="string: 'dropdown' or 'radio'"
},
control=optstring,
dialogControl=optstring,
dropdownControl=optstring,
itemControl=optstring,
},
multiselect={
values=ismethodtable,
style=optstring,
tristate=optbool,
control=optstring,
dialogControl=optstring,
dropdownControl=optstring,
},
color={
hasAlpha=optmethodbool,
},
keybinding={
-- TODO
},
}
local function validateKey(k,errlvl,...)
errlvl=(errlvl or 0)+1
if type(k)~="string" then
err("["..tostring(k).."] - key is not a string", errlvl,...)
end
if strfind(k, "[%c\127]") then
err("["..tostring(k).."] - key name contained control characters", errlvl,...)
end
end
local function validateVal(v, oktypes, errlvl,...)
errlvl=(errlvl or 0)+1
local isok=oktypes[type(v)] or oktypes["*"]
if not isok then
err(": expected a "..oktypes._..", got '"..tostring(v).."'", errlvl,...)
end
if type(isok)=="table" then -- isok was a table containing specific values to be tested for!
if not isok[v] then
err(": did not expect "..type(v).." value '"..tostring(v).."'", errlvl,...)
end
end
end
local function validate(options,errlvl,...)
errlvl=(errlvl or 0)+1
-- basic consistency
if type(options)~="table" then
err(": expected a table, got a "..type(options), errlvl,...)
end
if type(options.type)~="string" then
err(".type: expected a string, got a "..type(options.type), errlvl,...)
end
-- get type and 'typedkeys' member
local tk = typedkeys[options.type]
if not tk then
err(".type: unknown type '"..options.type.."'", errlvl,...)
end
-- make sure that all options[] are known parameters
for k,v in pairs(options) do
if not (tk[k] or basekeys[k]) then
err(": unknown parameter", errlvl,tostring(k),...)
end
end
-- verify that required params are there, and that everything is the right type
for k,oktypes in pairs(basekeys) do
validateVal(options[k], oktypes, errlvl,k,...)
end
for k,oktypes in pairs(tk) do
validateVal(options[k], oktypes, errlvl,k,...)
end
-- extra logic for groups
if options.type=="group" then
for k,v in pairs(options.args) do
validateKey(k,errlvl,"args",...)
validate(v, errlvl,k,"args",...)
end
if options.plugins then
for plugname,plugin in pairs(options.plugins) do
if type(plugin)~="table" then
err(": expected a table, got '"..tostring(plugin).."'", errlvl,tostring(plugname),"plugins",...)
end
for k,v in pairs(plugin) do
validateKey(k,errlvl,tostring(plugname),"plugins",...)
validate(v, errlvl,k,tostring(plugname),"plugins",...)
end
end
end
end
end
--- Validates basic structure and integrity of an options table \\
-- Does NOT verify that get/set etc actually exist, since they can be defined at any depth
-- @param options The table to be validated
-- @param name The name of the table to be validated (shown in any error message)
-- @param errlvl (optional number) error level offset, default 0 (=errors point to the function calling :ValidateOptionsTable)
function AceConfigRegistry:ValidateOptionsTable(options,name,errlvl)
errlvl=(errlvl or 0)+1
name = name or "Optionstable"
if not options.name then
options.name=name -- bit of a hack, the root level doesn't really need a .name :-/
end
validate(options,errlvl,name)
end
--- Fires a "ConfigTableChange" callback for those listening in on it, allowing config GUIs to refresh.
-- You should call this function if your options table changed from any outside event, like a game event
-- or a timer.
-- @param appName The application name as given to `:RegisterOptionsTable()`
function AceConfigRegistry:NotifyChange(appName)
if not AceConfigRegistry.tables[appName] then return end
AceConfigRegistry.callbacks:Fire("ConfigTableChange", appName)
end
-- -------------------------------------------------------------------
-- Registering and retreiving options tables:
-- validateGetterArgs: helper function for :GetOptionsTable (or, rather, the getter functions returned by it)
local function validateGetterArgs(uiType, uiName, errlvl)
errlvl=(errlvl or 0)+2
if uiType~="cmd" and uiType~="dropdown" and uiType~="dialog" then
error(MAJOR..": Requesting options table: 'uiType' - invalid configuration UI type, expected 'cmd', 'dropdown' or 'dialog'", errlvl)
end
if not strmatch(uiName, "[A-Za-z]%-[0-9]") then -- Expecting e.g. "MyLib-1.2"
error(MAJOR..": Requesting options table: 'uiName' - badly formatted or missing version number. Expected e.g. 'MyLib-1.2'", errlvl)
end
end
--- Register an options table with the config registry.
-- @param appName The application name as given to `:RegisterOptionsTable()`
-- @param options The options table, OR a function reference that generates it on demand. \\
-- See the top of the page for info on arguments passed to such functions.
-- @param skipValidation Skip options table validation (primarily useful for extremely huge options, with a noticeable slowdown)
function AceConfigRegistry:RegisterOptionsTable(appName, options, skipValidation)
if type(options)=="table" then
if options.type~="group" then -- quick sanity checker
error(MAJOR..": RegisterOptionsTable(appName, options): 'options' - missing type='group' member in root group", 2)
end
AceConfigRegistry.tables[appName] = function(uiType, uiName, errlvl)
errlvl=(errlvl or 0)+1
validateGetterArgs(uiType, uiName, errlvl)
if not AceConfigRegistry.validated[uiType][appName] and not skipValidation then
AceConfigRegistry:ValidateOptionsTable(options, appName, errlvl) -- upgradable
AceConfigRegistry.validated[uiType][appName] = true
end
return options
end
elseif type(options)=="function" then
AceConfigRegistry.tables[appName] = function(uiType, uiName, errlvl)
errlvl=(errlvl or 0)+1
validateGetterArgs(uiType, uiName, errlvl)
local tab = assert(options(uiType, uiName, appName))
if not AceConfigRegistry.validated[uiType][appName] and not skipValidation then
AceConfigRegistry:ValidateOptionsTable(tab, appName, errlvl) -- upgradable
AceConfigRegistry.validated[uiType][appName] = true
end
return tab
end
else
error(MAJOR..": RegisterOptionsTable(appName, options): 'options' - expected table or function reference", 2)
end
end
--- Returns an iterator of ["appName"]=funcref pairs
function AceConfigRegistry:IterateOptionsTables()
return pairs(AceConfigRegistry.tables)
end
--- Query the registry for a specific options table.
-- If only appName is given, a function is returned which you
-- can call with (uiType,uiName) to get the table.\\
-- If uiType&uiName are given, the table is returned.
-- @param appName The application name as given to `:RegisterOptionsTable()`
-- @param uiType The type of UI to get the table for, one of "cmd", "dropdown", "dialog"
-- @param uiName The name of the library/addon querying for the table, e.g. "MyLib-1.0"
function AceConfigRegistry:GetOptionsTable(appName, uiType, uiName)
local f = AceConfigRegistry.tables[appName]
if not f then
return nil
end
if uiType then
return f(uiType,uiName,1) -- get the table for us
else
return f -- return the function
end
end
| mit |
elbamos/nn | MultiLabelSoftMarginCriterion.lua | 14 | 1375 | --[[
-- A MultiLabel multiclass criterion based on sigmoid:
--
-- the loss is:
-- l(x,y) = - sum_i y[i] * log(p[i]) + (1 - y[i]) * log (1 - p[i])
-- where p[i] = exp(x[i]) / (1 + exp(x[i]))
--
-- and with weights:
-- l(x,y) = - sum_i weights[i] (y[i] * log(p[i]) + (1 - y[i]) * log (1 - p[i]))
--
--
--]]
local MultiLabelSoftMarginCriterion, parent =
torch.class('nn.MultiLabelSoftMarginCriterion', 'nn.Criterion')
function MultiLabelSoftMarginCriterion:__init(weights)
parent.__init(self)
self.lsm = nn.Sigmoid()
self.nll = nn.BCECriterion(weights)
end
function MultiLabelSoftMarginCriterion:updateOutput(input, target)
input = input:nElement() == 1 and input or input:squeeze()
target = target:nElement() == 1 and target or target:squeeze()
self.lsm:updateOutput(input)
self.nll:updateOutput(self.lsm.output, target)
self.output = self.nll.output
return self.output
end
function MultiLabelSoftMarginCriterion:updateGradInput(input, target)
local size = input:size()
input = input:nElement() ==1 and input or input:squeeze()
target = target:nElement() == 1 and target or target:squeeze()
self.nll:updateGradInput(self.lsm.output, target)
self.lsm:updateGradInput(input, self.nll.gradInput)
self.gradInput:view(self.lsm.gradInput, size)
return self.gradInput
end
return nn.MultiLabelSoftMarginCriterion
| bsd-3-clause |
Victek/wrt1900ac-aa | veriksystems/luci-0.11/libs/nixio/docsrc/nixio.fs.lua | 156 | 7907 | --- Low-level and high-level filesystem manipulation library.
module "nixio.fs"
--- Check user's permission on a file.
-- @class function
-- @name nixio.fs.access
-- @param path Path
-- @param mode1 First Mode to check ["f", "r", "w", "x"]
-- @param ... More Modes to check [-"-]
-- @return true
--- Strip the directory part from a path.
-- @class function
-- @name nixio.fs.basename
-- @usage This function cannot fail and will never return nil.
-- @param path Path
-- @return basename
--- Strip the base from a path.
-- @class function
-- @name nixio.fs.dirname
-- @usage This function cannot fail and will never return nil.
-- @param path Path
-- @return dirname
--- Return the cannonicalized absolute pathname.
-- @class function
-- @name nixio.fs.realpath
-- @param path Path
-- @return absolute path
--- Remove a file or directory.
-- @class function
-- @name nixio.fs.remove
-- @param path Path
-- @return true
--- Delete a name and - if no links are left - the associated file.
-- @class function
-- @name nixio.fs.unlink
-- @param path Path
-- @return true
--- Renames a file or directory.
-- @class function
-- @name nixio.fs.rename
-- @param src Source path
-- @param dest Destination path
-- @usage It is normally not possible to rename files accross fileystems.
-- @return true
--- Remove an empty directory.
-- @class function
-- @name nixio.fs.rmdir
-- @param path Path
-- @return true
--- Create a new directory.
-- @class function
-- @name nixio.fs.mkdir
-- @param path Path
-- @param mode File mode (optional, see chmod and umask)
-- @see nixio.fs.chmod
-- @see nixio.umask
-- @return true
--- Change the file mode.
-- @class function
-- @name nixio.fs.chmod
-- @usage Windows only supports setting the write-protection through the
-- "Writable to others" bit.
-- @usage <strong>Notice:</strong> The mode-flag for the functions
-- open, mkdir, mkfifo are affected by the umask.
-- @param path Path
-- @param mode File mode
-- [decimal mode number, "[-r][-w][-xsS][-r][-w][-xsS][-r][-w][-xtT]"]
-- @see nixio.umask
-- @return true
--- Iterate over the entries of a directory.
-- @class function
-- @name nixio.fs.dir
-- @usage The special entries "." and ".." are omitted.
-- @param path Path
-- @return directory iterator returning one entry per call
--- Create a hard link.
-- @class function
-- @name nixio.fs.link
-- @usage This function calls link() on POSIX and CreateHardLink() on Windows.
-- @param oldpath Path
-- @param newpath Path
-- @return true
--- Change file last access and last modification time.
-- @class function
-- @name nixio.fs.utimes
-- @param path Path
-- @param actime Last access timestamp (optional, default: current time)
-- @param mtime Last modification timestamp (optional, default: actime)
-- @return true
--- Get file status and attributes.
-- @class function
-- @name nixio.fs.stat
-- @param path Path
-- @param field Only return a specific field, not the whole table (optional)
-- @return Table containing: <ul>
-- <li>atime = Last access timestamp</li>
-- <li>blksize = Blocksize (POSIX only)</li>
-- <li>blocks = Blocks used (POSIX only)</li>
-- <li>ctime = Creation timestamp</li>
-- <li>dev = Device ID</li>
-- <li>gid = Group ID</li>
-- <li>ino = Inode</li>
-- <li>modedec = Mode converted into a decimal number</li>
-- <li>modestr = Mode as string as returned by `ls -l`</li>
-- <li>mtime = Last modification timestamp</li>
-- <li>nlink = Number of links</li>
-- <li>rdev = Device ID (if special file)</li>
-- <li>size = Size in bytes</li>
-- <li>type = ["reg", "dir", "chr", "blk", "fifo", "lnk", "sock"]</li>
-- <li>uid = User ID</li>
-- </ul>
--- Get file status and attributes and do not resolve if target is a symlink.
-- @class function
-- @name nixio.fs.lstat
-- @param path Path
-- @param field Only return a specific field, not the whole table (optional)
-- @see nixio.fs.stat
-- @return Table containing attributes (see stat for a detailed description)
--- (POSIX) Change owner and group of a file.
-- @class function
-- @name nixio.fs.chown
-- @param path Path
-- @param user User ID or Username (optional)
-- @param group Group ID or Groupname (optional)
-- @return true
--- (POSIX) Change owner and group of a file and do not resolve
-- if target is a symlink.
-- @class function
-- @name nixio.fs.lchown
-- @param path Path
-- @param user User ID or Username (optional)
-- @param group Group ID or Groupname (optional)
-- @return true
--- (POSIX) Create a FIFO (named pipe).
-- @class function
-- @name nixio.fs.mkfifo
-- @param path Path
-- @param mode File mode (optional, see chmod and umask)
-- @see nixio.fs.chmod
-- @see nixio.umask
-- @return true
--- (POSIX) Create a symbolic link.
-- @class function
-- @name nixio.fs.symlink
-- @param oldpath Path
-- @param newpath Path
-- @return true
--- (POSIX) Read the target of a symbolic link.
-- @class function
-- @name nixio.fs.readlink
-- @param path Path
-- @return target path
--- (POSIX) Find pathnames matching a pattern.
-- @class function
-- @name nixio.fs.glob
-- @param pattern Pattern
-- @return path iterator
-- @return number of matches
--- (POSIX) Get filesystem statistics.
-- @class function
-- @name nixio.fs.statvfs
-- @param path Path to any file within the filesystem.
-- @return Table containing: <ul>
-- <li>bavail = available blocks</li>
-- <li>bfree = free blocks</li>
-- <li>blocks = number of fragments</li>
-- <li>frsize = fragment size</li>
-- <li>favail = available inodes</li>
-- <li>ffree = free inodes</li>
-- <li>files = inodes</li>
-- <li>flag = flags</li>
-- <li>fsid = filesystem ID</li>
-- <li>namemax = maximum filename length</li>
-- </ul>
--- Read the contents of a file into a buffer.
-- @class function
-- @name nixio.fs.readfile
-- @param path Path
-- @param limit Maximum bytes to read (optional)
-- @return file contents
--- Write a buffer into a file truncating the file first.
-- @class function
-- @name nixio.fs.writefile
-- @param path Path
-- @param data Data to write
-- @return true
--- Copy data between files.
-- @class function
-- @name nixio.fs.datacopy
-- @param src Source file path
-- @param dest Destination file path
-- @param limit Maximum bytes to copy (optional)
-- @return true
--- Copy a file, directory or symlink non-recursively preserving file mode,
-- timestamps, owner and group.
-- @class function
-- @name nixio.fs.copy
-- @usage The destination must always be a full destination path e.g. do not
-- omit the basename even if source and destination basename are equal.
-- @param src Source path
-- @param dest Destination path
-- @return true
--- Rename a file, directory or symlink non-recursively across filesystems.
-- @class function
-- @name nixio.fs.move
-- @usage The destination must always be a full destination path e.g. do not
-- omit the basename even if source and destination basename are equal.
-- @param src Source path
-- @param dest Destination path
-- @return true
--- Create a directory and all needed parent directories recursively.
-- @class function
-- @name nixio.fs.mkdirr
-- @param dest Destination path
-- @param mode File mode (optional, see chmod and umask)
-- @see nixio.fs.chmod
-- @see nixio.umask
-- @return true
--- Rename a file, directory or symlink recursively across filesystems.
-- @class function
-- @name nixio.fs.mover
-- @usage The destination must always be a full destination path e.g. do not
-- omit the basename even if source and destination basename are equal.
-- @param src Source path
-- @param dest Destination path
-- @return true
--- Copy a file, directory or symlink recursively preserving file mode,
-- timestamps, owner and group.
-- @class function
-- @name nixio.fs.copyr
-- @usage The destination must always be a full destination path e.g. do not
-- omit the basename even if source and destination basename are equal.
-- @param src Source path
-- @param dest Destination path
-- @return true | gpl-2.0 |
coderczp/luajava | test/awtTest.lua | 8 | 1561 |
frame = luajava.newInstance("java.awt.Frame", "Lua Java Console")
console = luajava.newInstance("java.awt.TextArea")
buttons_pn = luajava.newInstance("java.awt.Panel")
execute_bt = luajava.newInstance("java.awt.Button", "Execute")
clear_bt = luajava.newInstance("java.awt.Button", "Clear")
exit_bt = luajava.newInstance("java.awt.Button", "Exit")
frame:setSize(600,300)
buttons_pn:add(execute_bt)
buttons_pn:add(clear_bt)
buttons_pn:add(exit_bt)
BorderLayout = luajava.bindClass("java.awt.BorderLayout")
frame:add(BorderLayout.NORTH, console)
frame:add(BorderLayout.SOUTH, buttons_pn)
frame:pack()
frame:show()
--
-- Listeners
--
execute_cb = {
actionPerformed = function(ev)
print("execute")
pcall(loadstring(console:getText()))
end
}
jproxy = luajava.createProxy("java.awt.event.ActionListener",execute_cb)
execute_bt:addActionListener(jproxy)
clear_cb = {actionPerformed= function (ev)
print("clear");
console:setText("");
end
}
jproxy = luajava.createProxy("java.awt.event.ActionListener" ,clear_cb)
clear_bt:addActionListener(jproxy)
exit_cb = { actionPerformed=function (ev)
print("exit")
frame:setVisible(false)
frame:dispose()
end
}
jproxyb = luajava.createProxy("java.awt.event.ActionListener" ,exit_cb)
exit_bt:addActionListener(jproxyb)
close_cb = { }
function close_cb.windowClosing(ev)
print("close")
frame:setVisible(false)
frame:dispose()
end
function close_cb.windowActivated(ev)
print("act")
end
jproxy = luajava.createProxy("java.awt.event.WindowListener", close_cb)
frame:addWindowListener(jproxy)
| mit |
opentibia/server | data/scripts/otstd/actions/mailbox.lua | 3 | 1101 |
otstd.mailbox = {}
otstd.mailboxes = {
[2593] = {},
[3981] = {}
}
function otstd.mailbox.handler(event)
local mail = event.item
local label = nil
if mail:getItemID() == 2595 then
label = filter((function(i) return i:getItemID() == 2599 end), mail:getItems())
if #label == 0 then
return
end
label = label[1]
end
if mail:getItemID() == 2597 then
label = mail
end
if not label then
-- Not a mail item
return
end
local text = label:getText()
local lines = text:explode()
if #lines < 2 then
for k, v in pairs(lines) do
s = s .. k .. '=' .. v .. ' '
end
event.creature:sendNote(s)
return
end
local name = lines[1]:strip_whitespace()
local town = map:getTown(lines[2]:strip_whitespace())
if not town then
return
end
sendMail(mail, name, town)
end
function otstd.mailbox.registerHandlers()
for id, data in pairs(otstd.mailboxes) do
if data.listener ~= nil then
stopListener(data.listener)
end
data.listener =
registerOnMoveItemToItem("after", "itemid", id, otstd.mailbox.handler)
end
end
otstd.mailbox.registerHandlers() | gpl-2.0 |
jshackley/darkstar | scripts/zones/Windurst_Waters/npcs/Angelica.lua | 36 | 5295 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Angelica
-- Starts and Finished Quest: A Pose By Any Other Name
-- Working 100%
-- @zone = 238
-- @pos = -70 -10 -6
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
posestatus = player:getQuestStatus(WINDURST,A_POSE_BY_ANY_OTHER_NAME);
if (posestatus == QUEST_AVAILABLE and player:getVar("QuestAPoseByOtherName_prog") == 0 and player:needToZone() == false) then
player:startEvent(0x0057); -- A POSE BY ANY OTHER NAME: Before Quest
player:setVar("QuestAPoseByOtherName_prog",1);
elseif (posestatus == QUEST_AVAILABLE and player:getVar("QuestAPoseByOtherName_prog") == 1) then
player:setVar("QuestAPoseByOtherName_prog",2);
mjob = player:getMainJob();
if (mjob == JOB_WAR or mjob == JOB_PLD or mjob == JOB_DRK or mjob == JOB_DRG or mjob == JOB_COR) then -- Quest Start: Bronze Harness (War/Pld/Drk/Drg/Crs)
player:startEvent(0x005c,0,0,0,12576);
player:setVar("QuestAPoseByOtherName_equip",12576);
elseif (mjob == JOB_MNK or mjob == JOB_BRD or mjob == JOB_BLU) then -- Quest Start: Robe (Mnk/Brd/Blu)
player:startEvent(0x005c,0,0,0,12600);
player:setVar("QuestAPoseByOtherName_equip",12600);
elseif (mjob == JOB_THF or mjob == JOB_BST or mjob == JOB_RNG or mjob == JOB_DNC) then -- Quest Start: Leather Vest (Thf/Bst/Rng/Dnc)
player:startEvent(0x005c,0,0,0,12568);
player:setVar("QuestAPoseByOtherName_equip",12568);
elseif (mjob == JOB_WHM or mjob == JOB_BLM or mjob == JOB_SMN or mjob == JOB_PUP or mjob == JOB_SCH) then -- Quest Start: Tunic (Whm/Blm/Rdm/Smn/Pup/Sch)
player:startEvent(0x005c,0,0,0,12608);
player:setVar("QuestAPoseByOtherName_equip",12608);
elseif (mjob == JOB_SAM or mjob == JOB_NIN) then -- Quest Start: Kenpogi(Sam/Nin)
player:startEvent(0x005c,0,0,0,12584);
player:setVar("QuestAPoseByOtherName_equip",12584);
end
elseif (posestatus == QUEST_ACCEPTED) then
starttime = player:getVar("QuestAPoseByOtherName_time");
if ((starttime + 600) >= os.time()) then
if (player:getEquipID(SLOT_BODY) == player:getVar("QuestAPoseByOtherName_equip")) then
player:startEvent(0x0060); ------------------------------------------ QUEST FINISH
else
player:startEvent(0x005d,0,0,0,player:getVar("QuestAPoseByOtherName_equip"));-- QUEST REMINDER
end
else
player:startEvent(0x0066); ------------------------------------------ QUEST FAILURE
end
elseif (posestatus == QUEST_COMPLETED and player:needToZone()) then
player:startEvent(0x0065); ----------------------------------------------- AFTER QUEST
else
rand = math.random(1,3);
if (rand == 1) then
player:startEvent(0x0056); -------------------------------------------- Standard Conversation 1
elseif (rand == 2) then
player:startEvent(0x0058); -------------------------------------------- Standard Conversation 2
else
player:startEvent(0x0059); -------------------------------------------- Standard Conversation 3
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x005c) then -------------------------- QUEST START
player:addQuest(WINDURST,A_POSE_BY_ANY_OTHER_NAME);
player:setVar("QuestAPoseByOtherName_time",os.time());
elseif (csid == 0x0060) then --------------------- QUEST FINFISH
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,206);
else
player:completeQuest(WINDURST,A_POSE_BY_ANY_OTHER_NAME)
player:addTitle(SUPER_MODEL);
player:addItem(206);
player:messageSpecial(ITEM_OBTAINED,206);
player:addKeyItem(ANGELICAS_AUTOGRAPH);
player:messageSpecial(KEYITEM_OBTAINED,ANGELICAS_AUTOGRAPH);
player:addFame(WINDURST,WIN_FAME*75);
player:setVar("QuestAPoseByOtherName_time",0);
player:setVar("QuestAPoseByOtherName_equip",0);
player:setVar("QuestAPoseByOtherName_prog",0);
player:needToZone(true);
end
elseif (csid == 0x0066) then ---------------------- QUEST FAILURE
player:delQuest(WINDURST,A_POSE_BY_ANY_OTHER_NAME);
player:addTitle(LOWER_THAN_THE_LOWEST_TUNNEL_WORM);
player:setVar("QuestAPoseByOtherName_time",0);
player:setVar("QuestAPoseByOtherName_equip",0);
player:setVar("QuestAPoseByOtherName_prog",0);
player:needToZone(true);
end
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Quicksand_Caves/mobs/Princeps_IV-XLV.lua | 1 | 1341 | -----------------------------------
-- Area: Quicksand Caves
-- MOB: Princeps IV-XLV
-- Pops in Bastok mission 8-1 "The Chains that Bind Us"
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobDisengage Action
-----------------------------------
function onMobDisengage(mob)
local self = mob:getID();
DespawnMob(self, 120);
end;
-----------------------------------
-- onMobDeath Action
-----------------------------------
function onMobDeath(mob,killer,ally)
if (ally:getCurrentMission(BASTOK) == THE_CHAINS_THAT_BIND_US and ally:getVar("MissionStatus") == 1) then
SetServerVariable("Bastok8-1LastClear", os.time());
end
end;
-----------------------------------
-- onMobDespawn Action
-----------------------------------
function onMobDespawn(mob)
local mobsup = GetServerVariable("BastokFight8_1");
SetServerVariable("BastokFight8_1",mobsup - 1);
if (GetServerVariable("BastokFight8_1") == 0) then
local npc = GetNPCByID(17629734); -- qm6
npc:setStatus(0); -- Reappear
end
end; | gpl-3.0 |
10sa/Advanced-Nutscript | nutscript/gamemode/libs/sh_logging.lua | 1 | 2680 | -- since it's really sensitive. localized.
local timeColor = Color(0, 255, 0)
local textColor = Color(255, 255, 255)
if SERVER then
local serverLog = {}
local autosavePerLines = 1000
-- for later filter use.
LOG_FILTER_DEVELOPER = 0
LOG_FILTER_CRITICAL = 1
LOG_FILTER_MAJOR = 2
LOG_FILTER_ITEM = 3
LOG_FILTER_CHAT = 4
LOG_FILTER_NOSAVE = 5
LOG_FILTER_CONCOMMAND = 6
--[[
Purpose: Add a line to the log.
--]]
function nut.util.AddLog(string, filter, consoleprint)
if (consoleprint != false) then
MsgC(timeColor, "[" .. os.date() .. "] ")
MsgC(textColor, string .. "\n")
for k, client in pairs(player.GetAll()) do
if (client:IsAdmin() and client:GetInfoNum("nut_showlogs", 1) > 0) then
netstream.Start(client, "nut_SendLogLine", string)
end
end
end
if (filter != LOG_FILTER_NOSAVE) then
table.insert(serverLog, "[" .. os.date() .. "] " .. string)
end
if (#serverLog >= autosavePerLines) then
nut.util.SaveLog()
end
end
--[[
Purpose: Get the current log
--]]
function nut.util.GetLog()
return serverLog
end
--[[
Purpose: Get a log.
--]]
function nut.util.SendLog(client)
-- body
end
--[[
Purpose: Save the log to the server.
--]]
function nut.util.SaveLog(autosave)
/*
-- for later use.
local filename = string.Replace(os.date(),":","_")
filename = string.Replace(filename,"/","_")
file.CreateDir("nutscript/"..SCHEMA.uniqueID.."/logs")
nut.util.WriteTable("logs/"..filename, serverLog, true)
*/
local string = ""
for k, v in pairs(serverLog) do
string = string .. v .. "\n"
end
local filename = string.Replace(os.date(),":","_")
filename = string.Replace(filename,"/","_")
filename = filename .. "_readable"
file.CreateDir("nutscript/"..SCHEMA.uniqueID.."/logs")
file.Write("nutscript/"..SCHEMA.uniqueID.."/logs/".. filename ..".txt", string)
serverLog = {}
end
/*
--[[
Purpose: Load the log and send to the admin.
Reserved for next feature.
--]]
function nut.util.LoadLog()
-- body
end
*/
AdvNut.hook.Add("PlayerSay", "nut_ChatLogging", function(player, text)
if nut.config.savechat then
nut.util.AddLog(Format("%s: %s", player:Name(), text), LOG_FILTER_CHAT, false)
else
nut.util.AddLog(Format("%s: %s", player:Name(), text), LOG_FILTER_NOSAVE, false)
end
end)
AdvNut.hook.Add("ShutDown", "nut_SaveLog", function(player, text)
nut.util.SaveLog()
end)
else
NUT_CVAR_SHOWLOGS = CreateClientConVar("nut_showlogs", "1", true, true)
netstream.Hook("nut_SendLogLine", function(string)
if (LocalPlayer():IsAdmin()) then
MsgC(timeColor, "[" .. os.date() .. "] ")
MsgC(textColor, string .. "\n")
end
end)
end | mit |
jshackley/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Animated_Tachi.lua | 1 | 1480 | -----------------------------------
-- Area: Dynamis Xarcabard
-- MOB: Animated Tachi
-----------------------------------
require("scripts/globals/status");
require("scripts/zones/Dynamis-Xarcabard/TextIDs");
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if (mob:AnimationSub() == 3) then
SetDropRate(117,1580,1000);
else
SetDropRate(117,1580,0);
end
target:showText(mob,ANIMATED_TACHI_DIALOG);
SpawnMob(17330445,120):updateEnmity(target);
SpawnMob(17330446,120):updateEnmity(target);
SpawnMob(17330447,120):updateEnmity(target);
SpawnMob(17330457,120):updateEnmity(target);
SpawnMob(17330458,120):updateEnmity(target);
SpawnMob(17330459,120):updateEnmity(target);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
-- TODO: add battle dialog
end;
-----------------------------------
-- onMobDisengage
-----------------------------------
function onMobDisengage(mob)
mob:showText(mob,ANIMATED_TACHI_DIALOG+2);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
ally:showText(mob,ANIMATED_TACHI_DIALOG+1);
DespawnMob(17330445);
DespawnMob(17330446);
DespawnMob(17330447);
DespawnMob(17330457);
DespawnMob(17330458);
DespawnMob(17330459);
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/weaponskills/slug_shot.lua | 30 | 1533 | -----------------------------------
-- Slug Shot
-- Marksmanship weapon skill
-- Skill Level: 175
-- Delivers an inparams.accurate attack that deals quintuple damage. params.accuracy varies with TP.
-- Despite the lack of a STR weaponskill mod, STR is still the most potent stat for increasing this weaponskill's damage to the point at which fSTR2 is capped.
-- Aligned with the Aqua Gorget, Light Gorget & Breeze Gorget.
-- Aligned with the Aqua Belt, Light Belt & Breeze Belt.
-- Element: None
-- Modifiers: AGI:70%
-- 100%TP 200%TP 300%TP
-- 5.00 5.00 5.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 5; params.ftp200 = 5; params.ftp300 = 5;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.8; params.acc200= 0.9; params.acc300= 1;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.agi_wsc = 0.7;
end
local damage, tpHits, extraHits = doRangedWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Garlaige_Citadel/npcs/qm12.lua | 34 | 1386 | -----------------------------------
-- Area: Garlaige Citadel
-- NPC: qm12 (???)
-- Involved in Quest: Hitting the Marquisate (THF AF3)
-- @pos -245.603 -5.500 139.855 200
-----------------------------------
package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Garlaige_Citadel/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hittingTheMarquisateHagainCS = player:getVar("hittingTheMarquisateHagainCS");
if (hittingTheMarquisateHagainCS == 4) then
player:messageSpecial(PRESENCE_FROM_CEILING);
player:setVar("hittingTheMarquisateHagainCS",5);
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);
end;
| gpl-3.0 |
VincentGong/chess | cocos2d-x/cocos/scripting/lua-bindings/auto/api/AtlasNode.lua | 3 | 2256 |
--------------------------------
-- @module AtlasNode
-- @extend Node,TextureProtocol
--------------------------------
-- @function [parent=#AtlasNode] updateAtlasValues
-- @param self
--------------------------------
-- @function [parent=#AtlasNode] getTexture
-- @param self
-- @return Texture2D#Texture2D ret (return value: cc.Texture2D)
--------------------------------
-- @function [parent=#AtlasNode] setTextureAtlas
-- @param self
-- @param #cc.TextureAtlas textureatlas
--------------------------------
-- @function [parent=#AtlasNode] getTextureAtlas
-- @param self
-- @return TextureAtlas#TextureAtlas ret (return value: cc.TextureAtlas)
--------------------------------
-- @function [parent=#AtlasNode] getQuadsToDraw
-- @param self
-- @return long#long ret (return value: long)
--------------------------------
-- @function [parent=#AtlasNode] setTexture
-- @param self
-- @param #cc.Texture2D texture2d
--------------------------------
-- @function [parent=#AtlasNode] setQuadsToDraw
-- @param self
-- @param #long long
--------------------------------
-- @function [parent=#AtlasNode] create
-- @param self
-- @param #string str
-- @param #int int
-- @param #int int
-- @param #int int
-- @return AtlasNode#AtlasNode ret (return value: cc.AtlasNode)
--------------------------------
-- @function [parent=#AtlasNode] draw
-- @param self
-- @param #cc.Renderer renderer
-- @param #cc.Mat4 mat4
-- @param #bool bool
--------------------------------
-- @function [parent=#AtlasNode] isOpacityModifyRGB
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#AtlasNode] setColor
-- @param self
-- @param #color3b_table color3b
--------------------------------
-- @function [parent=#AtlasNode] getColor
-- @param self
-- @return color3b_table#color3b_table ret (return value: color3b_table)
--------------------------------
-- @function [parent=#AtlasNode] setOpacityModifyRGB
-- @param self
-- @param #bool bool
--------------------------------
-- @function [parent=#AtlasNode] setOpacity
-- @param self
-- @param #unsigned char char
return nil
| mit |
jshackley/darkstar | scripts/zones/Maquette_Abdhaljs-Legion/Zone.lua | 32 | 1184 | -----------------------------------
--
-- Zone: Maquette Abdhaljs-Legion
--
-----------------------------------
package.loaded["scripts/zones/Maquette_Abdhaljs-Legion/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Maquette_Abdhaljs-Legion/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
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 |
jshackley/darkstar | scripts/zones/Beaucedine_Glacier/npcs/Chopapa_WW.lua | 30 | 3071 | -----------------------------------
-- Area: Beaucedine Glacier
-- NPC: Chopapa, W.W.
-- Type: Border Conquest Guards
-- @pos -227.956 -81.475 260.442 111
-----------------------------------
package.loaded["scripts/zones/Beaucedine_Glacier/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Beaucedine_Glacier/TextIDs");
local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = FAUREGANDI;
local csid = 0x7ff6;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
10sa/Advanced-Nutscript | nutscript/entities/entities/nut_money.lua | 1 | 1558 | AddCSLuaFile()
ENT.Type = "anim"
ENT.PrintName = "Money"
ENT.Author = "Chessnut"
ENT.Category = "Nutscript"
ENT.PersistentSave = false;
if (SERVER) then
function ENT:Initialize()
self:SetModel(nut.config.moneyModel)
self:PhysicsInit(SOLID_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetUseType(SIMPLE_USE)
self:SetNetVar("amount", 0)
local physObj = self:GetPhysicsObject()
if (IsValid(physObj)) then
physObj:Wake()
end
AdvNut.hook.Run("MoneyEntityCreated", self)
end
function ENT:SetMoney(amount)
if (amount <= 0) then
self:Remove()
end
self:SetNetVar("amount", amount)
end
function ENT:Use(activator)
local amount = self:GetNetVar("amount", 0)
if (amount > 0 and IsValid(activator) and activator.character and AdvNut.hook.Run("PlayerCanPickupMoney", activator, self) != false) then
if (self.owner == activator and self.charindex != activator.character.index) then
nut.util.Notify("You can't pick up your other character's money.", activator)
return
end
activator:GiveMoney(amount)
nut.util.Notify("You have picked up "..nut.currency.GetName(amount)..".", activator)
self:Remove()
end
end
function ENT:StartTouch(entity)
if (entity:GetClass() == "nut_money") then
self:SetMoney(self:GetNetVar("amount", 0) + entity:GetNetVar("amount", 0))
entity:Remove()
end
end
else
function ENT:DrawTargetID(x, y, alpha)
nut.util.DrawText(x, y, nut.currency.GetName(self:GetNetVar("amount", 0), true), Color(255, 255, 255, alpha))
end
end | mit |
wilhantian/catui | catui/Control/UIScrollBar.lua | 2 | 7683 | --[[
The MIT License (MIT)
Copyright (c) 2016 WilhanTian 田伟汉
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.
]]--
-------------------------------------
-- UIScrollBar
-- @usage
-- local bar = UIScrollBar:new()
-- bar:setSize(100, 20)
-- bar:setDir("vertical")
-------------------------------------
local UIScrollBar = UIControl:extend("UIScrollBar", {
upColor = nil,
downColor = nil,
hoverColor = nil,
backgroundColor = nil,
dir = "vertical", --horizontal
ratio = 3, --bar占多少比例
bar = nil,
barDown = false,
barPosRatio = 0,
})
-------------------------------------
-- construct
-------------------------------------
function UIScrollBar:init()
UIControl.init(self)
self.bar = UIButton:new()
self.bar.events:on(UI_MOUSE_DOWN, self.onBarDown, self)
self.bar.events:on(UI_MOUSE_MOVE, self.onBarMove, self)
self.bar.events:on(UI_MOUSE_UP, self.onBarUp, self)
self:addChild(self.bar)
self:initTheme()
self:setEnabled(true)
self.events:on(UI_DRAW, self.onDraw, self)
self.events:on(UI_MOUSE_DOWN, self.onBgDown, self)
end
-------------------------------------
-- (callback)
-- draw self
-------------------------------------
function UIScrollBar:onDraw()
local box = self:getBoundingBox()
local x, y = box.left, box.top
local w, h = box:getWidth(), box:getHeight()
local r, g, b, a = love.graphics.getColor()
local color = self.backgroundColor
love.graphics.setColor(color[1], color[2], color[3], color[4])
love.graphics.rectangle("fill", x, y, w, h)
love.graphics.setColor(r, g, b, a)
end
-------------------------------------
-- init Theme Style
-- @tab _theme
-------------------------------------
function UIScrollBar:initTheme(_theme)
local theme = theme or _theme
self.upColor = theme.scrollBar.upColor
self.downColor = theme.scrollBar.downColor
self.hoverColor = theme.scrollBar.hoverColor
self.backgroundColor = theme.scrollBar.backgroundColor
self.bar:setStroke(0)
self.bar:setUpColor(self.upColor)
self.bar:setDownColor(self.downColor)
self.bar:setHoverColor(self.hoverColor)
end
-------------------------------------
-- set bar scroll direction
-- @string dir "vertical" or "horizontal", default is vertical
-------------------------------------
function UIScrollBar:setDir(dir)
self.dir = dir
self:reset()
end
-------------------------------------
-- get bar scroll direction
-- @treturn string direction
-------------------------------------
function UIScrollBar:getDir()
return self.dir
end
-------------------------------------
-- (callback)
-- on bar down
-------------------------------------
function UIScrollBar:onBarDown(x, y)
self.barDown = true
end
-------------------------------------
-- (callback)
-- on bar move
-------------------------------------
function UIScrollBar:onBarMove(x, y, dx, dy)
if not self.barDown then return end
local bar = self.bar
if self.dir == "vertical" then
local after = bar:getY() + dy
if after < 0 then
after = 0
elseif after + bar:getHeight() > self:getHeight() then
after = self:getHeight() - bar:getHeight()
end
self.barPosRatio = after / (self:getHeight() - bar:getHeight())
else
local after = bar:getX() + dx
if after < 0 then
after = 0
elseif after + bar:getWidth() > self:getWidth() then
after = self:getWidth() - bar:getWidth()
end
self.barPosRatio = after / (self:getWidth() - bar:getWidth())
end
self:setBarPos(self.barPosRatio)
end
-------------------------------------
-- (callback)
-- on bar up
-------------------------------------
function UIScrollBar:onBarUp(x, y)
self.barDown = false
end
-------------------------------------
-- (callback)
-- on bar down
-------------------------------------
function UIScrollBar:onBgDown(x, y)
x, y = self:globalToLocal(x, y)
if self.dir == "vertical" then
self:setBarPos(y / self:getHeight())
else
self:setBarPos(x / self:getWidth())
end
end
-------------------------------------
-- (override)
-------------------------------------
function UIScrollBar:setSize(width, height)
UIControl.setSize(self, width, height)
self:reset()
end
-------------------------------------
-- (override)
-------------------------------------
function UIScrollBar:setWidth(width)
UIControl.setWidth(self, width)
self:reset()
end
-------------------------------------
-- (override)
-------------------------------------
function UIScrollBar:setHeight(height)
UIControl.setHeight(self, height)
self:reset()
end
-------------------------------------
-- set bar up color
-- @tab color
-------------------------------------
function UIScrollBar:setUpColor(color)
self.upColor = color
end
-------------------------------------
-- set bar down color
-- @tab color
-------------------------------------
function UIScrollBar:setDownColor(color)
self.downColor = color
end
-------------------------------------
-- set bar hover color
-- @tab color
-------------------------------------
function UIScrollBar:setHoverColor(color)
self.hoverColor = color
end
-------------------------------------
-- set bar position with ratio
-- @number ratio value: 0-1
-------------------------------------
function UIScrollBar:setRatio(ratio)
self.ratio = ratio < 1 and 1 or ratio
self:reset()
end
-------------------------------------
-- reset contorl
-------------------------------------
function UIScrollBar:reset()
local ratio = self.ratio
if self.dir == "vertical" then
self.bar:setWidth(self:getWidth())
self.bar:setHeight(self:getHeight() / ratio)
else
self.bar:setWidth(self:getWidth() / ratio)
self.bar:setHeight(self:getHeight())
end
self:setBarPos(self.barPosRatio)
end
-------------------------------------
-- set bar position with ratio
-- @number ratio
-------------------------------------
function UIScrollBar:setBarPos(ratio)
if ratio < 0 then ratio = 0 end
if ratio > 1 then ratio = 1 end
self.barPosRatio = ratio
if self.dir == "vertical" then
self.bar:setX(0)
self.bar:setY((self:getHeight() - self.bar:getHeight()) * ratio)
else
self.bar:setX((self:getWidth() - self.bar:getWidth()) * ratio)
self.bar:setY(0)
end
self.events:dispatch(UI_ON_SCROLL, ratio)
end
-------------------------------------
-- get bar position with ratio
-- @treturn number ratio
-------------------------------------
function UIScrollBar:getBarPos()
return self.barPosRatio
end
return UIScrollBar
| mit |
jshackley/darkstar | scripts/zones/Beaucedine_Glacier/mobs/Tundra_Tiger.lua | 2 | 1363 | -----------------------------------
-- Area: Beaucedine Glacier
-- MOB: Tundra Tiger
-- Note: PH for Nue, Kirata
-----------------------------------
require("scripts/globals/fieldsofvalor");
require("scripts/zones/Beaucedine_Glacier/MobIDs");
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
checkRegime(ally,mob,46,1);
checkRegime(ally,mob,47,1);
-- Kirata
mob = mob:getID();
if (Kirata_PH[mob] ~= nil) then
ToD = GetServerVariable("[POP]Kirata");
if (ToD <= os.time(t) and GetMobAction(Kirata) == 0) then
if (math.random((1),(15)) == 5) then
UpdateNMSpawnPoint(Kirata);
GetMobByID(Kirata):setRespawnTime(GetMobRespawnTime(mob));
SetServerVariable("[PH]Kirata", mob);
DeterMob(mob, true);
end
end
end
-- Nue
if (Nue_PH[mob] ~= nil) then
ToD = GetServerVariable("[POP]Nue");
if (ToD <= os.time(t) and GetMobAction(Nue) == 0) then
if (math.random((1),(15)) == 5) then
UpdateNMSpawnPoint(Nue);
GetMobByID(Nue):setRespawnTime(GetMobRespawnTime(mob));
SetServerVariable("[PH]Nue", mob);
DeterMob(mob, true);
end
end
end
end;
| gpl-3.0 |
jshackley/darkstar | scripts/globals/weaponskills/detonator.lua | 30 | 1630 | -----------------------------------
-- Detonator
-- Marksmanship weapon skill
-- Skill Level: 250
-- Delivers a single-hit attack. Damage varies with TP.
-- In order to obtain Detonator, the quest Shoot First, Ask Questions Later must be completed.
-- Despite the lack of a STR weaponskill mod, STR is still the most potent stat for increasing this weaponskill's damage to the point at which fSTR2 is capped.
-- Aligned with the Flame Gorget & Light Gorget.
-- Aligned with the Flame Belt & Light Belt.
-- Element: None
-- Modifiers: AGI:30%
-- 100%TP 200%TP 300%TP
-- 1.50 2.00 2.50
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1.5; params.ftp200 = 2; params.ftp300 = 2.5;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1.5; params.ftp200 = 2.5; params.ftp300 = 5.0;
params.agi_wsc = 0.7;
end
local damage, tpHits, extraHits = doRangedWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
rigeirani/arbc | plugins/add_rem.lua | 4 | 9472 | do
local function check_member(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
local username = v.username
data[tostring(msg.to.id)] = {
moderators = {[tostring(member_id)] = username},
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'no',
lock_photo = 'no',
lock_member = 'no'
}
}
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'انت الادمن هنا لان')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg})
else
if data[tostring(msg.to.id)] then
return 'المجموعة مظافة بلفعل'
end
if msg.from.username then
username = msg.from.username
else
username = msg.from.print_name
end
-- 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_name = 'no',
lock_photo = 'no',
lock_member = 'no'
}
}
save_data(_config.moderation.data, data)
return 'Group has been added, and @'..username..' has been addd as moderator for this group.'
end
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "للمطورين فقط"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
return 'المجموعة مظافة بلفعل'
end
-- create data array in moderation.json
data[tostring(msg.to.id)] = {
moderators ={},
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'no',
lock_photo = 'no',
lock_member = 'no'
}
}
save_data(_config.moderation.data, data)
return 'تمت اظافة المجموعة'
end
local function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if not data[tostring(msg.to.id)] then
return 'المجموعة غير مظافة'
end
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return 'تمت ازالة المجموعة'
end
local function add(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, '')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' انه مدير بلفعل')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' تم اظافة المدير')
end
local function rem(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..' لم يتم تعيينه مدير سابقا')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' تمت ازالة المدير')
end
local function admin_add(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..' تمت اظافته للقائمة السوداء')
end
local function admin_rem(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, 'المطور '..member_username..' تمت ازالته من القائمة السوداء')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'لا يوجد @'..member..' في هذه المجموعة.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'add' then
return add(receiver, member_username, member_id)
elseif mod_cmd == 'rem' then
return rem(receiver, member_username, member_id)
elseif mod_cmd == 'prom' then
return admin_add(receiver, member_username, member_id)
elseif mod_cmd == 'dem' then
return admin_rem(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function admin(msg)
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 'لا يوجد مدراء في المجموعة'
end
local message = 'قائمة المدراء ' .. 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
local function admin_list(msg)
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 'لا يوجد مطورين بعد.'
end
local message = 'القائمة السوداء:\n'
for k,v in pairs(data['admins']) do
message = message .. '- ' .. v ..' ['..k..'] \n'
end
return message
end
function run(msg, matches)
if matches[1] == 'debug' then
return debugs(msg)
end
if not is_chat_msg(msg) then
return "حصريا هذا الامر داخل المجموعة"
end
local mod_cmd = matches[1]
local receiver = get_receiver(msg)
if matches[1] == 'modadd' then
return modadd(msg)
end
if matches[1] == 'modrem' then
return modrem(msg)
end
if matches[1] == 'add' and matches[2] then
if not is_momod(msg) then
return "المدير يقوم بترقية المنصب فقط"
end
local member = string.gsub(matches[2], "@", "")
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'rem' and matches[2] then
if not is_momod(msg) then
return "المدير يقوم بازالة المنصب فقط"
end
if string.gsub(matches[2], "@", "") == msg.from.username then
return "لا يمكن ازالة نفسك"
end
local member = string.gsub(matches[2], "@", "")
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'admin' then
return admin(msg)
end
if matches[1] == 'prom' then
if not is_admin(msg) then
return "حصريا للمطورين فقط"
end
local member = string.gsub(matches[2], "@", "")
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'dem' then
if not is_admin(msg) then
return "حصريا للمطورين فقط"
end
local member = string.gsub(matches[2], "@", "")
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'black' then
if not is_admin(msg) then
return 'للمطورين فقط'
end
return admin_list(msg)
end
if matches[1] == 'chat_add_user' and msg.action.user.id == our_id then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 then
return automodadd(msg)
end
end
return {
patterns = {
"^[!/](modadd)$",
"^[!/](modrem)$",
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_created)$",
},
run = run,
}
end
| gpl-2.0 |
jshackley/darkstar | scripts/zones/RuAun_Gardens/npcs/_3m0.lua | 34 | 1118 | -----------------------------------
-- Area: Ru'Avitau Gate
-- NPC: _3m0
-- @pos 0.1 -45 -113 130
-----------------------------------
package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/RuAun_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local DoorID = npc:getID();
GetNPCByID(DoorID):openDoor(7);
GetNPCByID(DoorID+1):openDoor(7);
GetNPCByID(DoorID+2):openDoor(7);
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 |
LuaDist/lua-uri | uri/urn.lua | 2 | 3916 | local M = { _NAME = "uri.urn" }
local Util = require "uri._util"
local URI = require "uri"
Util.subclass_of(M, URI)
-- This implements RFC 2141, and attempts to change the class of the URI object
-- to one of its subclasses for further validation and normalization of the
-- namespace-specific string.
-- Check NID syntax matches RFC 2141 section 2.1.
local function _valid_nid (nid)
if nid == "" then return nil, "missing completely" end
if nid:len() > 32 then return nil, "too long" end
if not nid:find("^[A-Za-z0-9][-A-Za-z0-9]*$") then
return nil, "contains illegal character"
end
if nid:lower() == "urn" then return nil, "'urn' is reserved" end
return true
end
-- Check NSS syntax matches RFC 2141 section 2.2.
local function _valid_nss (nss)
if nss == "" then return nil, "can't be empty" end
if nss:find("[^A-Za-z0-9()+,%-.:=@;$_!*'/%%]") then
return nil, "contains illegal character"
end
return true
end
local function _validate_and_normalize_path (path)
local _, _, nid, nss = path:find("^([^:]+):(.*)$")
if not nid then return nil, "illegal path syntax for URN" end
local ok, msg = _valid_nid(nid)
if not ok then
return nil, "invalid namespace identifier (" .. msg .. ")"
end
ok, msg = _valid_nss(nss)
if not ok then
return nil, "invalid namespace specific string (" .. msg .. ")"
end
return nid:lower() .. ":" .. nss
end
-- TODO - this should check that percent-encoded bytes are valid UTF-8
function M.init (self)
if M._SUPER.query(self) then
return nil, "URNs may not have query parts"
end
if M._SUPER.host(self) then
return nil, "URNs may not have authority parts"
end
local path, msg = _validate_and_normalize_path(self:path())
if not path then return nil, msg end
M._SUPER.path(self, path)
local nid_class
= Util.attempt_require("uri.urn." .. self:nid():gsub("%-", "_"))
if nid_class then
setmetatable(self, nid_class)
if self.init ~= M.init then return self:init() end
end
return self
end
function M.nid (self, new)
local _, _, old = self:path():find("^([^:]+)")
if new then
new = new:lower()
if new ~= old then
local ok, msg = _valid_nid(new)
if not ok then
error("invalid namespace identifier (" .. msg .. ")")
end
end
Util.do_class_changing_change(self, M, "NID", new, function (uri, new)
M._SUPER.path(uri, new .. ":" .. uri:nss())
end)
end
return old
end
function M.nss (self, new)
local _, _, old = self:path():find(":(.*)")
if new and new ~= old then
local ok, msg = _valid_nss(new)
if not ok then
error("invalid namespace specific string (" .. msg .. ")")
end
M._SUPER.path(self, self:nid() .. ":" .. new)
end
return old
end
function M.path (self, new)
local old = M._SUPER.path(self)
if new and new ~= old then
local path, msg = _validate_and_normalize_path(new)
if not path then
error("invalid path for URN '" .. new .. "' (" ..msg .. ")")
end
local _, _, newnid, newnss = path:find("^([^:]+):(.*)")
if not newnid then error("bad path for URN, no NID part found") end
local ok, msg = _valid_nid(newnid)
if not ok then error("invalid namespace identifier (" .. msg .. ")") end
if newnid:lower() == self:nid() then
self:nss(newnss)
else
Util.do_class_changing_change(self, M, "path", path,
function (uri, new) M._SUPER.path(uri, new) end)
end
end
return old
end
Util.uri_part_not_allowed(M, "userinfo")
Util.uri_part_not_allowed(M, "host")
Util.uri_part_not_allowed(M, "port")
Util.uri_part_not_allowed(M, "query")
return M
-- vi:ts=4 sw=4 expandtab
| mit |
men232/greencode-framework | lua/greencode/plugins/tophud/cl_auto.lua | 1 | 3696 | --[[
© 2013 GmodLive private project do not share
without permission of its author (Andrew Mensky vk.com/men232).
--]]
local greenCode = greenCode;
local Material = Material;
local surface = surface;
local draw = draw;
local util = util;
local PLUGIN = PLUGIN or greenCode.plugin:Loader();
PLUGIN.stored = {};
PLUGIN.buffer = {};
PLUGIN.alpha = 0;
TOPHUD_ALPHA = 255;
--[[ Define the territory class metatable. --]]
TOPHUD_CLASS = TOPHUD_CLASS or {__index = TOPHUD_CLASS};
function TOPHUD_CLASS:__call( parameter, failSafe )
return self:Query( parameter, failSafe );
end;
function TOPHUD_CLASS:__tostring()
return "TOPHUD ["..self("name").."]";
end;
function TOPHUD_CLASS:IsValid()
return self.data != nil;
end;
function TOPHUD_CLASS:Query( key, failSafe )
if ( self.data and self.data[key] != nil ) then
return self.data[key];
else
return failSafe;
end;
end;
function TOPHUD_CLASS:New( tMergeTable )
local object = {
data = {
name = "Unknown",
priority = 1,
text = "",
icon = Material("icon16/user.png"),
uid = util.CRC( os.time() .. CurTime() .. SysTime().."_tophud" )
}
};
if ( tMergeTable ) then
table.Merge( object.data, tMergeTable );
end;
setmetatable( object, self );
self.__index = self;
return object;
end;
function TOPHUD_CLASS:SetData( key, value )
if ( self:IsValid() and self.data[key] != nil ) then
self.data[key] = value;
return true;
end;
end;
function TOPHUD_CLASS:Think() return; end;
function TOPHUD_CLASS:GetPriority() return self("priority", 1); end;
function TOPHUD_CLASS:GetName() return self("name", "Unknown"); end;
function TOPHUD_CLASS:GetText() return self("text", ""); end;
function TOPHUD_CLASS:GetIcon() return self("icon", Material("icon16/user.png")); end;
function TOPHUD_CLASS:UniqueID() return self("uid", -1); end;
function TOPHUD_CLASS:Register() return PLUGIN:RegisterHUD(self); end;
function PLUGIN:RegisterHUD( TOPHUD )
if ( TOPHUD and TOPHUD:IsValid() ) then
if ( !table.HasValue( self.stored, TOPHUD ) ) then
table.insert( self.stored, TOPHUD );
self.buffer = {};
local TOPHUD_COUNT = #self.stored;
for i=1, TOPHUD_COUNT do
local TOPHUD = self.stored[i];
if ( TOPHUD and TOPHUD:IsValid() ) then
local priority = TOPHUD:GetPriority();
if ( !self.buffer[priority] ) then
self.buffer[priority] = {};
end;
table.insert( self.buffer[priority], TOPHUD );
end;
end;
end;
end;
end;
function PLUGIN:Think()
if ( IsValid(greenCode.Client) ) then
local TOPHUD_COUNT = #self.stored;
local bAdmin = greenCode.Client:IsAdmin();
for i=1, TOPHUD_COUNT do
local TOPHUD = self.stored[i];
if ( TOPHUD and TOPHUD:IsValid() and bAdmin or !TOPHUD("onlyadmin", false) ) then
TOPHUD:Think();
end;
end;
self.alpha = math.Approach(self.alpha, TOPHUD_ALPHA, FrameTime() * 140);
end;
end;
function PLUGIN:HUDPaint()
local POS = 0;
local scrW = ScrW();
local bAdmin = greenCode.Client:IsAdmin();
for k, stored in pairs( self.buffer ) do
local TOPHUD_COUNT = #stored;
for i=1, TOPHUD_COUNT do
local TOPHUD = self.buffer[k][i];
if ( TOPHUD and TOPHUD:IsValid() and bAdmin or !TOPHUD("onlyadmin", false) ) then
local text = TOPHUD:GetText();
local icon = TOPHUD:GetIcon();
POS = POS + greenCode.kernel:GetCachedTextSize("ChatFont", text) + 40;
surface.SetDrawColor( Color(255, 255, 255, self.alpha) )
surface.SetMaterial( icon )
surface.DrawTexturedRect(scrW - POS, 4, 16, 16 );
draw.DrawText(text, "ChatFont", scrW - POS + 25, 5, Color(255,255,255,self.alpha), 0)
end;
end;
end;
end;
greenCode:IncludeDirectory( PLUGIN:GetBaseDir().. "/elements/", false ); | mit |
deepmind/torch-dokx | luasrc/package.lua | 3 | 1337 | local dir = require 'pl.dir'
do
--[[ Information about a package ]]
local Package, parent = torch.class("dokx.Package")
--[[ Create a package object
Parameters:
* `name` - name of the package
* `path` - path of the package
]]
function Package:__init(name, path)
self._name = name
self._path = path
end
function Package:name()
return self._name
end
function Package:path()
return self._path
end
--[[ Return a table of lua files in the package (except those excluded by the config) ]]
function Package:luaFiles(config)
local luaFiles = dir.getallfiles(self._path, "*.lua")
luaFiles = dokx._filterFiles(luaFiles, config.filter, false)
luaFiles = dokx._filterFiles(luaFiles, config.exclude, true)
return luaFiles
end
--[[ Return a table of markdown files in the package (except those excluded by the config) ]]
function Package:mdFiles(config)
local luaFiles = dir.getallfiles(self._path, "*.md")
luaFiles = dokx._filterFiles(luaFiles, config.exclude, true)
return luaFiles
end
--[[ Return a table of image files in the package ]]
function Package:imageFiles(config)
local imageFiles = dir.getallfiles(self._path, "*.png")
return imageFiles
end
end
| bsd-3-clause |
jshackley/darkstar | scripts/zones/Mog_Garden/npcs/GreenThumbMo.lua | 29 | 2393 |
package.loaded["scripts/zones/Mog_Garden/TextIDs"] = nil;
require("scripts/zones/Mog_Garden/TextIDs");
require("scripts/globals/moghouse")
require("scripts/globals/shop");
local BRONZE_PIECE_ITEMID = 2184;
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player, npc, trade)
moogleTrade(player, npc, trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player, npc)
player:startEvent(1016);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player, csid, option)
if (csid == 1016 and option == 0xFFF00FF) then -- Show the Mog House menu..
-- Print the expire time for mog locker if exists..
local lockerLease = getMogLockerExpiryTimestamp(player);
if (lockerLease ~= nil) then
if (lockerLease == -1) then -- Lease expired..
player:messageSpecial(MOGLOCKER_MESSAGE_OFFSET + 2, BRONZE_PIECE_ITEMID);
else
player:messageSpecial(MOGLOCKER_MESSAGE_OFFSET + 1, lockerLease);
end
end
-- Show the mog house menu..
player:sendMenu(1);
elseif (csid == 1016 and option == 0xFFE00FF) then -- Buy/Sell Things
local stock =
{
573, 280, -- Vegetable Seeds
574, 320, -- Fruit Seeds
575, 280, -- Grain Seeds
572, 280, -- Herb Seeds
1236, 1685, -- Cactus Stems
2235, 320, -- Wildgrass Seeds
3986, 1111, -- Chestnut Tree Sap (11th Anniversary Campaign)
3985, 1111, -- Monarch Beetle Saliva (11th Anniversary Campaign)
3984, 1111, -- Golden Seed Pouch (11th Anniversary Campaign)
};
showShop( player, STATIC, stock );
elseif (csid == 1016 and option == 0xFFB00FF) then -- Leave this Mog Garden -> Whence I Came
player:warp(); -- Ghetto for now, the last zone seems to get messed up due to mog house issues.
end
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Dynamis-Buburimu/Zone.lua | 17 | 2365 | -----------------------------------
--
-- Zone: Dynamis-Buburimu
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Dynamis-Buburimu/TextIDs"] = nil;
require("scripts/zones/Dynamis-Buburimu/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;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(143,2 ,-147);
end
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaBuburimu]UniqueID")) then
if (player:isBcnmsFull() == 1) then
if (player:hasStatusEffect(EFFECT_DYNAMIS, 0) == false) then
inst = player:addPlayerToDynamis(1287);
if (inst == 1) then
player:bcnmEnter(1287);
else
cs = 0x0065;
end
else
player:bcnmEnter(1287);
end
else
inst = player:bcnmRegister(1287);
if (inst == 1) then
player:bcnmEnter(1287);
else
cs = 0x0065;
end
end
else
cs = 0x0065;
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 == 0x0065) then
player:setPos(154,-1,-170,190, 118);
end
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Misareaux_Coast/npcs/_0p2.lua | 1 | 2114 | -----------------------------------
-- Area: Misareaux Coast
-- NPC: Dilapidated Gate
-- Entrance to Riverne Site #B01
-- @pos -259 -30 276 178
-----------------------------------
package.loaded["scripts/zones/Misareaux_Coast/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Misareaux_Coast/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == THE_SAVAGE and player:getVar("PromathiaStatus") == 0) then
player:startEvent(0x0008);
elseif (player:getCurrentMission(COP) == ANCIENT_VOWS and player:getVar("PromathiaStatus") == 0) then
player:startEvent(0x0006);
elseif (player:getCurrentMission(COP) == FLAMES_IN_THE_DARKNESS and player:getVar("PromathiaStatus") == 0) then
player:startEvent(0x000C);
elseif (player:getQuestStatus(JEUNO,STORMS_OF_FATE) == QUEST_ACCEPTED and player:getVar('StormsOfFate') == 0) then
player:startEvent(0x022F);
elseif (player:getCurrentMission(COP) > AN_ETERNAL_MELODY or player:hasCompletedMission(COP,THE_LAST_VERSE)) then
player:startEvent(0x0228);
else
player:messageSpecial(DOOR_CLOSED);
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 == 0x0006 or csid == 0x000C) then
player:setVar("PromathiaStatus",1);
elseif (csid == 0x022F) then
player:setVar('StormsOfFate',1);
elseif (csid == 0x0008 and option == 1) then
player:setVar("PromathiaStatus",1);
player:setPos(729,-20,410,88,0x1D); -- Go to Riverne #B01
end
end; | gpl-3.0 |
Shahabambesik/merbot | plugins/sudo.lua | 1 | 3682 | do
local function cb_getdialog(extra, success, result)
vardump(extra)
vardump(result)
end
local function parsed_url(link)
local parsed_link = URL.parse(link)
local parsed_path = URL.parse_path(parsed_link.path)
for k,segment in pairs(parsed_path) do
if segment == 'joinchat' then
invite_link = parsed_path[k+1]:gsub('[ %c].+$', '')
break
end
end
return invite_link
end
local function action_by_reply(extra, success, result)
local hash = parsed_url(result.text)
join = import_chat_link(hash, ok_cb, false)
end
--------------------------------------------------------------------------------
function run(msg, matches)
if not is_sudo(msg.from.peer_id) then
return
end
if matches[1] == 'bin' then
local input = matches[2]:gsub('—', '--')
local header = '<b>$</b> <code>'..input..'</code>\n'
local stdout = io.popen(input):read('*all')
send_api_msg(msg, get_receiver_api(msg), header..'<code>'..stdout..'</code>', true, 'html')
end
if matches[1] == 'bot' then
if matches[2] == 'token' then
if not _config.bot_api then
_config.bot_api = {key = '', uid = '', uname = ''}
end
_config.bot_api.key = matches[3]
_config.bot_api.uid = matches[3]:match('^%d+')
save_config()
reply_msg(msg.id, 'Bot API key has been saved.', ok_cb, true)
end
if matches[2] == 'apiname' then
_config.bot_api.uname = matches[3]:gsub('@', '')
save_config()
reply_msg(msg.id, 'Bot API username has been saved.', ok_cb, true)
end
end
if matches[1] == "block" then
block_user("user#id"..matches[2], ok_cb, false)
if is_mod(matches[2], msg.to.peer_id) then
return "You can't block moderators."
end
if is_admin(matches[2]) then
return "You can't block administrators."
end
block_user("user#id"..matches[2], ok_cb, false)
return "User blocked"
end
if matches[1] == "unblock" then
unblock_user("user#id"..matches[2], ok_cb, false)
return "User unblocked"
end
if matches[1] == "join" then
if msg.reply_id then
get_message(msg.reply_id, action_by_reply, msg)
elseif matches[2] then
local hash = parsed_url(matches[2])
join = import_channel_link(hash, ok_cb, false)
end
end
end
--------------------------------------------------------------------------------
return {
description = 'Various sudo commands.',
usage = {
sudo = {
'<code>!bin [command]</code>',
'Run a system command.',
'',
'<code>!block [user_id]</code>',
'Block user_id to PM.',
'',
'<code>!unblock [user_id]</code>',
'Allowed user_id to PM.',
'',
'<code>!bot restart</code>',
'Restart bot.',
'',
'<code>!bot status</code>',
'Print bot status.',
'',
'<code>!bot token [bot_api_key]</code>',
'Input bot API key.',
'',
'<code>!join</code>',
'Join a group by replying a message containing invite link.',
'',
'<code>!join [invite_link]</code>',
'Join into a group by providing their [invite_link].',
'',
'<code>!version</code>',
'Shows bot version',
},
},
patterns = {
'^[#!/](bin) (.*)$',
'^[#!/](block) (.*)$',
'^[#!/](unblock) (.*)$',
'^[#!/](block) (%d+)$',
'^[#!/](unblock) (%d+)$',
'^[#!/](bot) (%g+) (.*)$',
'^[#!/](join)$',
'^[#!/](join) (.*)$',
},
run = run
}
end
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Southern_San_dOria/npcs/Corua.lua | 30 | 2262 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Corua
-- Only sells when San d'Oria controlls Ronfaure Region
-- @ zone 230
-- @pos -66 2 -11
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/events/harvest_festivals");
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/globals/conquest");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == 1) then
if (trade:hasItemQty(532,1) == true and trade:getItemCount() == 1) then
player:messageSpecial(FLYER_REFUSED);
end
else
onHalloweenTrade(player,trade,npc);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(RONFAURE);
-- player:startEvent(0x0351) - are you the chicks owner
if (RegionOwner ~= SANDORIA) then
player:showText(npc,CORUA_CLOSED_DIALOG);
else
player:showText(npc,CORUA_OPEN_DIALOG);
stock = {0x1125,29, -- San d'Orian Carrot
0x114f,69, -- San d'Orian Grape
0x027f,110, -- Chestnut
0x0262,55} -- San d'Orian Flour
showShop(player,SANDORIA,stock);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Runic_Portal.lua | 17 | 2990 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Runic Portal
-- Aht Urhgan Teleporter to Other Areas
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/besieged");
require("scripts/globals/keyitems");
require("scripts/globals/teleports");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hasAssault, keyitem = hasAssaultOrders(player);
if (hasAssault > 0) then
player:messageSpecial(RUNIC_PORTAL + 9, keyitem);
player:startEvent(hasAssault);
else
if (player:hasKeyItem(RUNIC_PORTAL_USE_PERMIT)) then
player:messageSpecial(RUNIC_PORTAL + 2,RUNIC_PORTAL_USE_PERMIT);
player:startEvent(0x0065,0,player:getNationTeleport(AHTURHGAN));
else
player:messageSpecial(RUNIC_PORTAL);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0065) then
if (option == 101) then
player:delKeyItem(RUNIC_PORTAL_USE_PERMIT);
AzouphIsleStagingPoint(player)
elseif (option == 102) then
player:delKeyItem(RUNIC_PORTAL_USE_PERMIT);
DvuccaIsleStagingPoint(player);
elseif (option == 103) then
player:delKeyItem(RUNIC_PORTAL_USE_PERMIT);
MamoolJaStagingPoint(player);
elseif (option == 104) then
player:delKeyItem(RUNIC_PORTAL_USE_PERMIT);
HalvungStagingPoint(player);
elseif (option == 105) then
player:delKeyItem(RUNIC_PORTAL_USE_PERMIT);
IlrusiAtollStagingPoint(player);
elseif (option == 106) then
player:delKeyItem(RUNIC_PORTAL_USE_PERMIT);
NzyulIsleStagingPoint(player);
end
elseif (csid == 0x0078 and option == 1 ) then--LEUJAOAM_ASSAULT_ORDERS
AzouphIsleStagingPoint(player)
elseif (csid == 0x0079 and option == 1 ) then--MAMMOOL_JA_ASSAULT_ORDERS
MamoolJaStagingPoint(player);
elseif (csid == 0x007A and option == 1 ) then--LEBROS_ASSAULT_ORDERS
HalvungStagingPoint(player);
elseif (csid == 0x007B and option == 1 ) then--PERIQIA_ASSAULT_ORDERS
DvuccaIsleStagingPoint(player);
elseif (csid == 0x007C and option == 1 ) then--ILRUSI_ASSAULT_ORDERS
IlrusiAtollStagingPoint(player);
elseif (csid == 0x007D and option == 1 ) then--NYZUL_ISLE_ASSAULT_ORDERS
NzyulIsleStagingPoint(player);
end
end; | gpl-3.0 |
Victek/wrt1900ac-aa | veriksystems/luci-0.11/applications/luci-statistics/luasrc/model/cbi/luci_statistics/unixsock.lua | 11 | 1500 | --[[
Luci configuration model for statistics - collectd unixsock plugin configuration
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: unixsock.lua 6060 2010-04-13 20:42:26Z jow $
]]--
m = Map("luci_statistics",
translate("Unixsock Plugin Configuration"),
translate(
"The unixsock plugin creates a unix socket which can be used " ..
"to read collected data from a running collectd instance."
))
-- collectd_unixsock config section
s = m:section( NamedSection, "collectd_unixsock", "luci_statistics" )
-- collectd_unixsock.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_unixsock.socketfile (SocketFile)
socketfile = s:option( Value, "SocketFile" )
socketfile.default = "/var/run/collect-query.socket"
socketfile:depends( "enable", 1 )
-- collectd_unixsock.socketgroup (SocketGroup)
socketgroup = s:option( Value, "SocketGroup" )
socketgroup.default = "nobody"
socketgroup.rmempty = true
socketgroup.optional = true
socketgroup:depends( "enable", 1 )
-- collectd_unixsock.socketperms (SocketPerms)
socketperms = s:option( Value, "SocketPerms" )
socketperms.default = "0770"
socketperms.rmempty = true
socketperms.optional = true
socketperms:depends( "enable", 1 )
return m
| gpl-2.0 |
jshackley/darkstar | scripts/globals/items/keen_zaghnal.lua | 37 | 1120 | -----------------------------------------
-- ID: 18067
-- Equip: Keen Zaghnal
-- Enchantment: Accuracy +3
-- Enchantment will wear off if weapon is unequipped.
-- Effect lasts for 30 minutes
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
if (target:getEquipID(SLOT_MAIN) ~= 18067) then
target:delStatusEffect(EFFECT_ACCURACY_BOOST,18067);
end
return 0;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_ACCURACY_BOOST,0,0,1800,18067);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_ACC, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_ACC, 3);
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Bastok_Mines/npcs/Elki.lua | 36 | 2490 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Elki
-- Starts Quests: Hearts of Mythril, The Eleventh's Hour
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
Fame = player:getFameLevel(BASTOK);
Hearts = player:getQuestStatus(BASTOK,HEARTS_OF_MYTHRIL);
HeartsVar = player:getVar("HeartsOfMythril");
Elevenths = player:getQuestStatus(BASTOK,THE_ELEVENTH_S_HOUR);
EleventhsVar = player:getVar("EleventhsHour");
HasToolbox = player:hasKeyItem(0x18);
if (Hearts == QUEST_AVAILABLE) then
player:startEvent(0x0029);
elseif (Hearts == QUEST_ACCEPTED and HeartsVar == 1) then
player:startEvent(0x002a);
elseif (Hearts == QUEST_COMPLETED and Elevenths == QUEST_AVAILABLE and Fame >=2 and player:needToZone() == false) then
player:startEvent(0x002b);
elseif (Elevenths == QUEST_ACCEPTED and HasToolbox) then
player:startEvent(0x002c);
else
player:startEvent(0x001f);
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 == 0x0029 and option == 0) then
player:addQuest(BASTOK,HEARTS_OF_MYTHRIL);
player:addKeyItem(0x17);
player:messageSpecial(KEYITEM_OBTAINED,0x17);
elseif (csid == 0x002a) then
player:addTitle(84);
player:addItem(12840);
player:messageSpecial(ITEM_OBTAINED,12840);
player:completeQuest(BASTOK,HEARTS_OF_MYTHRIL);
player:addFame(BASTOK,BAS_FAME*80);
player:setVar("HeartsOfMythril",0);
player:needToZone(true);
elseif (csid == 0x002b and option == 1) then
player:addQuest(BASTOK,THE_ELEVENTH_S_HOUR);
elseif (csid == 0x002c) then
player:setVar("EleventhsHour",1);
end
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Temenos/mobs/Enhanced_Vulture.lua | 1 | 1440 | -----------------------------------
-- Area: Temenos W T
-- NPC: Enhanced_Vulture
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
GetMobByID(16928959):updateEnmity(target);
GetMobByID(16928960):updateEnmity(target);
GetMobByID(16928961):updateEnmity(target);
GetMobByID(16928962):updateEnmity(target);
GetMobByID(16928963):updateEnmity(target);
GetMobByID(16928964):updateEnmity(target);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
if (IsMobDead(16928959)==true and IsMobDead(16928960)==true and IsMobDead(16928961)==true
and IsMobDead(16928962)==true and IsMobDead(16928963)==true and IsMobDead(16928964)==true) then
GetNPCByID(16928768+17):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+17):setStatus(STATUS_NORMAL);
GetNPCByID(16928770+470):setStatus(STATUS_NORMAL);
end
end;
| gpl-3.0 |
Keithenneu/Dota2-FullOverwrite | bot_antimage.lua | 1 | 2417 | -------------------------------------------------------------------------------
--- AUTHOR: Nostrademous
--- GITHUB REPO: https://github.com/Nostrademous/Dota2-FullOverwrite
-------------------------------------------------------------------------------
local utils = require( GetScriptDirectory().."/utility" )
local dt = require( GetScriptDirectory().."/decision" )
local gHeroVar = require( GetScriptDirectory().."/global_hero_data" )
local ability = require( GetScriptDirectory().."/abilityUse/abilityUse_antimage" )
function setHeroVar(var, value)
local bot = GetBot()
gHeroVar.SetVar(bot:GetPlayerID(), var, value)
end
function getHeroVar(var)
local bot = GetBot()
return gHeroVar.GetVar(bot:GetPlayerID(), var)
end
local SKILL_Q = "antimage_mana_break";
local SKILL_W = "antimage_blink";
local SKILL_E = "antimage_spell_shield";
local SKILL_R = "antimage_mana_void";
local ABILITY1 = "special_bonus_hp_150"
local ABILITY2 = "special_bonus_attack_damage_20"
local ABILITY3 = "special_bonus_attack_speed_20"
local ABILITY4 = "special_bonus_unique_antimage"
local ABILITY5 = "special_bonus_evasion_15"
local ABILITY6 = "special_bonus_all_stats_10"
local ABILITY7 = "special_bonus_agility_25"
local ABILITY8 = "special_bonus_unique_antimage_2"
local AntimageAbilityPriority = {
SKILL_W, SKILL_Q, SKILL_Q, SKILL_E, SKILL_Q,
SKILL_R, SKILL_Q, SKILL_W, SKILL_W, ABILITY1,
SKILL_W, SKILL_R, SKILL_E, SKILL_E, ABILITY4,
SKILL_E, SKILL_R, ABILITY6, ABILITY8
}
local botAM = dt:new()
function botAM:new(o)
o = o or dt:new(o)
setmetatable(o, self)
self.__index = self
return o
end
local amBot = botAM:new{abilityPriority = AntimageAbilityPriority}
function amBot:ConsiderAbilityUse()
return ability.AbilityUsageThink(GetBot())
end
function amBot:GetNukeDamage(bot, target)
return ability.nukeDamage( bot, target )
end
function amBot:QueueNuke(bot, target, actionQueue, engageDist)
return ability.queueNuke( bot, target, actionQueue, engageDist )
end
function amBot:DoHeroSpecificInit(bot)
local mvAbility = bot:GetAbilityByName(SKILL_W)
self:setHeroVar("HasMovementAbility", {mvAbility, mvAbility:GetSpecialValueInt("blink_range")})
self:setHeroVar("HasEscape", {mvAbility, mvAbility:GetSpecialValueInt("blink_range")})
end
function Think()
local bot = GetBot()
amBot:Think(bot)
end
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Temenos/mobs/Pee_Qoho_the_Python.lua | 1 | 1606 | -----------------------------------
-- Area: Temenos
-- NPC:
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if (IsMobDead(16929023)==true and IsMobDead(16929024)==true and IsMobDead(16929025)==true and
IsMobDead(16929026)==true and IsMobDead(16929027)==true and IsMobDead(16929028)==true
) then
mob:setMod(MOD_SLASHRES,1400);
mob:setMod(MOD_PIERCERES,1400);
mob:setMod(MOD_IMPACTRES,1400);
mob:setMod(MOD_HTHRES,1400);
else
mob:setMod(MOD_SLASHRES,300);
mob:setMod(MOD_PIERCERES,300);
mob:setMod(MOD_IMPACTRES,300);
mob:setMod(MOD_HTHRES,300);
end
GetMobByID(16929005):updateEnmity(target);
GetMobByID(16929006):updateEnmity(target);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
if (IsMobDead(16929005)==true and IsMobDead(16929006)==true and IsMobDead(16929007)==true) then
GetNPCByID(16928768+78):setPos(-280,-161,-440);
GetNPCByID(16928768+78):setStatus(STATUS_NORMAL);
GetNPCByID(16928768+473):setStatus(STATUS_NORMAL);
end
end; | gpl-3.0 |
elbamos/nn | SpatialUpSamplingNearest.lua | 13 | 2065 | local SpatialUpSamplingNearest, parent = torch.class('nn.SpatialUpSamplingNearest', 'nn.Module')
--[[
Applies a 2D up-sampling over an input image composed of several input planes.
The upsampling is done using the simple nearest neighbor technique.
The Y and X dimensions are assumed to be the last 2 tensor dimensions. For
instance, if the tensor is 4D, then dim 3 is the y dimension and dim 4 is the x.
owidth = width*scale_factor
oheight = height*scale_factor
--]]
function SpatialUpSamplingNearest:__init(scale)
parent.__init(self)
self.scale_factor = scale
if self.scale_factor < 1 then
error('scale_factor must be greater than 1')
end
if math.floor(self.scale_factor) ~= self.scale_factor then
error('scale_factor must be integer')
end
self.inputSize = torch.LongStorage(4)
self.outputSize = torch.LongStorage(4)
self.usage = nil
end
function SpatialUpSamplingNearest:updateOutput(input)
if input:dim() ~= 4 and input:dim() ~= 3 then
error('SpatialUpSamplingNearest only support 3D or 4D tensors')
end
-- Copy the input size
local xdim = input:dim()
local ydim = input:dim() - 1
for i = 1, input:dim() do
self.inputSize[i] = input:size(i)
self.outputSize[i] = input:size(i)
end
self.outputSize[ydim] = self.outputSize[ydim] * self.scale_factor
self.outputSize[xdim] = self.outputSize[xdim] * self.scale_factor
-- Resize the output if needed
if input:dim() == 3 then
self.output:resize(self.outputSize[1], self.outputSize[2],
self.outputSize[3])
else
self.output:resize(self.outputSize)
end
input.THNN.SpatialUpSamplingNearest_updateOutput(
input:cdata(),
self.output:cdata(),
self.scale_factor
)
return self.output
end
function SpatialUpSamplingNearest:updateGradInput(input, gradOutput)
self.gradInput:resizeAs(input)
input.THNN.SpatialUpSamplingNearest_updateGradInput(
input:cdata(),
gradOutput:cdata(),
self.gradInput:cdata(),
self.scale_factor
)
return self.gradInput
end
| bsd-3-clause |
jshackley/darkstar | scripts/zones/Temenos/npcs/Particle_Gate.lua | 64 | 3548 | -----------------------------------
-- Area: Temenos
-- NPC: Particle_Gate
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/globals/keyitems");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local GateID = npc:getID();
local GateOffset = 16929221;
-- print("GateID " ..GateID);
-- player:PrintToPlayer(npc:getID());
switch (GateID): caseof
{
-- 100-106 : Northern Tower
[GateOffset] = function (x)
player:startEvent(100);
end,
[GateOffset+1] = function (x)
player:startEvent(101);
end,
[GateOffset+2] = function (x)
player:startEvent(102);
end,
[GateOffset+3] = function (x)
player:startEvent(103);
end,
[GateOffset+4] = function (x)
player:startEvent(104);
end,
[GateOffset+5] = function (x)
player:startEvent(105);
end,
[GateOffset+6] = function (x)
player:startEvent(106);
end,
-- 107-113 : Eastern Tower
[GateOffset+7] = function (x)
player:startEvent(107);
end,
[GateOffset+8] = function (x)
player:startEvent(108);
end,
[GateOffset+9] = function (x)
player:startEvent(109);
end,
[GateOffset+10] = function (x)
player:startEvent(110);
end,
[GateOffset+11] = function (x)
player:startEvent(111);
end,
[GateOffset+12] = function (x)
player:startEvent(112);
end,
[GateOffset+13] = function (x)
player:startEvent(113);
end,
-- 114-120 Western Tower
[GateOffset+14] = function (x)
player:startEvent(114);
end,
[GateOffset+15] = function (x)
player:startEvent(115);
end,
[GateOffset+16] = function (x)
player:startEvent(116);
end,
[GateOffset+17] = function (x)
player:startEvent(117);
end,
[GateOffset+18] = function (x)
player:startEvent(118);
end,
[GateOffset+19] = function (x)
player:startEvent(119);
end,
[GateOffset+20] = function (x)
player:startEvent(120);
end,
-- The rest of Temenos
[GateOffset+21] = function (x)
player:startEvent(120);
end,
[GateOffset+22] = function (x)
player:startEvent(120);
end,
[GateOffset+23] = function (x)
player:startEvent(120);
end,
[GateOffset+24] = function (x)
player:startEvent(120);
end,
[GateOffset+25] = function (x)
player:startEvent(120);
end,
}
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Bastok_Mines/npcs/Deegis.lua | 36 | 1768 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Deegis
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,DEEGIS_SHOP_DIALOG);
stock = {
0x30A2, 18360,1, --Padded Cap
0x3088, 9234,1, --Iron Mask
0x3122, 28339,1, --Padded Armor
0x31A2, 15552,1, --Iron Mittens
0x30A1, 1471,2, --Brass Cap
0x3098, 396,2, --Leather Bandana
0x3121, 2236,2, --Brass Harness
0x3118, 604,2, --Leather Vest
0x31A1, 1228,2, --Brass Mittens
0x3198, 324,2, --Leather Gloves
0x30A0, 151,3, --Bronze Cap
0x3120, 230,3, --Bronze Harness
0x3108, 14256,3, --Chainmail
0x31A0, 126,3, --Bronze Mittens
0x3188, 7614,3 --Chain Mittens
}
showNationShop(player, BASTOK, 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 |
jshackley/darkstar | scripts/zones/Caedarva_Mire/npcs/Kwadaaf.lua | 19 | 1350 | -----------------------------------
-- Area: Caedarva Mire
-- NPC: Kwadaaf
-- Type: Entry to Alzadaal Undersea Ruins
-- @pos -639.000 12.323 -260.000 79
-----------------------------------
package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Caedarva_Mire/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(2185,1)) then -- Silver
player:tradeComplete();
player:startEvent(0x00df);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getXPos() < -639) then
player:startEvent(0x00de);
else
player:startEvent(0x00e0);
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 == 0x00df) then
player:setPos(-235,-4,220,0,72);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Yuhtunga_Jungle/mobs/Rose_Garden.lua | 1 | 1644 | -----------------------------------
-- Area: Yuhtunga Jungle
-- MOB: Rose Garden
-----------------------------------
-----------------------------------
function onMobSpawn(mob)
local Voluptuous_Vilma = 17281358;
GetMobByID(Voluptuous_Vilma):setLocalVar("1",os.time() + math.random((36000), (37800)));
end;
function onMobRoam(mob)
local Voluptuous_Vilma = 17281358;
local Voluptuous_Vilma_PH = 0;
local Voluptuous_Vilma_PH_Table =
{
17281357
};
local Voluptuous_Vilma_ToD = GetMobByID(Voluptuous_Vilma):getLocalVar("1");
if (Voluptuous_Vilma_ToD <= os.time()) then
Voluptuous_Vilma_PH = math.random((0), (table.getn(Voluptuous_Vilma_PH_Table)));
if (Voluptuous_Vilma_PH_Table[Voluptuous_Vilma_PH] ~= nil) then
if (GetMobAction(Voluptuous_Vilma) == 0) then
SetServerVariable("Voluptuous_Vilma_PH", Voluptuous_Vilma_PH_Table[Voluptuous_Vilma_PH]);
DeterMob(Voluptuous_Vilma_PH_Table[Voluptuous_Vilma_PH], true);
DeterMob(Voluptuous_Vilma, false);
DespawnMob(Voluptuous_Vilma_PH_Table[Voluptuous_Vilma_PH]);
SpawnMob(Voluptuous_Vilma, "", 0);
end
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer, ally)
local Rose_Garden = 17281357;
local Rose_Garden_PH = GetServerVariable("Rose_Garden_PH");
GetMobByID(Rose_Garden):setLocalVar("1",os.time() + math.random((36000), (37800)));
SetServerVariable("Rose_Garden_PH", 0);
DeterMob(Rose_Garden, true);
DeterMob(Rose_Garden_PH, false);
SpawnMob(Rose_Garden_PH, "", GetMobRespawnTime(Rose_Garden_PH));
end; | gpl-3.0 |
sp3ctum/lean | tests/lua/old/simp1.lua | 6 | 1067 | add_rewrite_rules({"Nat", "add_zerol"})
add_rewrite_rules({"Nat", "add_zeror"})
parse_lean_cmds([[
variable f : Nat -> Nat -> Nat
variable g : Nat -> Nat
variable b : Nat
definition a := 1
theorem a_eq_1 : a = 1
:= refl a
definition c := 1
set_opaque a true
axiom f_id (x : Nat) : f x 1 = 2*x
axiom g_g_x (x : Nat) : (not (x = 0)) -> g (g x) = 0
]])
add_rewrite_rules("a_eq_1")
add_rewrite_rules("f_id")
add_rewrite_rules("eq_id")
-- set_option({"lean", "pp", "implicit"}, true)
e, pr = simplify(parse_lean('fun x, f (f x (0 + a)) (g (b + 0))'))
print(e)
print(pr)
local env = get_environment()
print(env:type_check(pr))
e, pr = simplify(parse_lean('forall x, let d := a + 1 in f x a >= d'))
print(e)
print(pr)
local env = get_environment()
print(env:type_check(pr))
e, pr = simplify(parse_lean('(fun x, f (f x (0 + a)) (g (b + 0))) b'))
print(e)
print(pr)
local env = get_environment()
print(env:type_check(pr))
e, pr = simplify(parse_lean('(fun x y, f x y) = f'))
print(e)
print(pr)
local env = get_environment()
print(env:type_check(pr))
| apache-2.0 |
jshackley/darkstar | scripts/globals/spells/temper.lua | 18 | 1027 | -----------------------------------------
--
-- Spell: Temper
--
-----------------------------------------
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_MULTI_STRIKES;
local enhskill = caster:getSkillLevel(ENHANCING_MAGIC_SKILL);
local final = 0;
local duration = 180;
if (caster:hasStatusEffect(EFFECT_COMPOSURE) == true and caster:getID() == target:getID()) then
duration = duration * 3;
end
if (enhskill<360) then
final = 5;
elseif (enhskill>=360) then
final = math.floor( (enhskill - 300) / 10 );
else
print("Warning: Unknown enhancing magic skill for Temper.");
end
if (final>20) then
final = 20;
end
if (target:addStatusEffect(effect,final,0,duration)) then
spell:setMsg(230);
else
spell:setMsg(75);
end
return effect;
end; | gpl-3.0 |
ByteFun/Starbound_mods | smount/tech/mech/mount68/mount68.lua | 1 | 36459 | function checkCollision(position)
local boundBox = mcontroller.boundBox()
boundBox[1] = boundBox[1] - mcontroller.position()[1] + position[1]
boundBox[2] = boundBox[2] - mcontroller.position()[2] + position[2]
boundBox[3] = boundBox[3] - mcontroller.position()[1] + position[1]
boundBox[4] = boundBox[4] - mcontroller.position()[2] + position[2]
return not world.rectCollision(boundBox)
end
function randomProjectileLine(startPoint, endPoint, stepSize, projectile, chanceToSpawn)
local dist = math.distance(startPoint, endPoint)
local steps = math.floor(dist / stepSize)
local normX = (endPoint[1] - startPoint[1]) / dist
local normY = (endPoint[2] - startPoint[2]) / dist
for i = 0, steps do
local p1 = { normX * i * stepSize + startPoint[1], normY * i * stepSize + startPoint[2]}
local p2 = { normX * (i + 1) * stepSize + startPoint[1] + math.random(-1, 1), normY * (i + 1) * stepSize + startPoint[2] + math.random(-1, 1)}
if math.random() <= chanceToSpawn then
world.spawnProjectile(projectile, math.midPoint(p1, p2), entity.id(), {normX, normY}, false)
end
end
return endPoint
end
function blinkAdjust(position, doPathCheck, doCollisionCheck, doLiquidCheck, doStandCheck)
local blinkCollisionCheckDiameter = tech.parameter("blinkCollisionCheckDiameter")
local blinkVerticalGroundCheck = tech.parameter("blinkVerticalGroundCheck")
local blinkFootOffset = tech.parameter("blinkFootOffset")
if doPathCheck then
local collisionBlocks = world.collisionBlocksAlongLine(mcontroller.position(), position, true, 1)
if #collisionBlocks ~= 0 then
local diff = world.distance(position, mcontroller.position())
diff[1] = diff[1] / math.abs(diff[1])
diff[2] = diff[2] / math.abs(diff[2])
position = {collisionBlocks[1][1] - diff[1], collisionBlocks[1][2] - diff[2]}
end
end
if doCollisionCheck and not checkCollision(position) then
local spaceFound = false
for i = 1, blinkCollisionCheckDiameter * 2 do
if checkCollision({position[1] + i / 2, position[2] + i / 2}) then
position = {position[1] + i / 2, position[2] + i / 2}
spaceFound = true
break
end
if checkCollision({position[1] - i / 2, position[2] + i / 2}) then
position = {position[1] - i / 2, position[2] + i / 2}
spaceFound = true
break
end
if checkCollision({position[1] + i / 2, position[2] - i / 2}) then
position = {position[1] + i / 2, position[2] - i / 2}
spaceFound = true
break
end
if checkCollision({position[1] - i / 2, position[2] - i / 2}) then
position = {position[1] - i / 2, position[2] - i / 2}
spaceFound = true
break
end
end
if not spaceFound then
return nil
end
end
if doStandCheck then
local groundFound = false
for i = 1, blinkVerticalGroundCheck * 2 do
local checkPosition = {position[1], position[2] - i / 2}
if world.pointCollision(checkPosition, false) then
groundFound = true
position = {checkPosition[1], checkPosition[2] + 0.5 - blinkFootOffset}
break
end
end
if not groundFound then
return nil
end
end
if doLiquidCheck and (world.liquidAt(position) or world.liquidAt({position[1], position[2] + blinkFootOffset})) then
return nil
end
if doCollisionCheck and not checkCollision(position) then
return nil
end
return position
end
function findRandomBlinkLocation(doCollisionCheck, doLiquidCheck, doStandCheck)
local randomBlinkTries = tech.parameter("randomBlinkTries")
local randomBlinkDiameter = tech.parameter("randomBlinkDiameter")
for i=1,randomBlinkTries do
local position = mcontroller.position()
position[1] = position[1] + (math.random() * 2 - 1) * randomBlinkDiameter
position[2] = position[2] + (math.random() * 2 - 1) * randomBlinkDiameter
local position = blinkAdjust(position, false, doCollisionCheck, doLiquidCheck, doStandCheck)
if position then
return position
end
end
return nil
end
function init()
self.level = tech.parameter("mechLevel", 6)
self.mechState = "off"
self.mechStateTimer = 0
self.specialLast = false
self.active = false
self.fireTimer = 0
self.fireSecTimer = 0
tech.setVisible(false)
tech.rotateGroup("guns", 0, true)
self.multiJumps = 0
self.lastJump = false
self.mode = "none"
self.timer = 0
self.targetPosition = nil
self.grabbed = false
self.holdingJump = false
self.ranOut = false
self.airDashing = false
self.dashTimer = 0
self.dashDirection = 0
self.dashLastInput = 0
self.dashTapLast = 0
self.dashTapTimer = 0
self.aoeLastInput = 0
self.aoeTapLast = 0
self.aoeTapTimer = 0
self.dashAttackfireTimer = 0
self.dashAttackTimer = 0
self.dashAttackDirection = 0
self.dashAttackLastInput = 0
self.dashAttackTapLast = 0
self.dashAttackTapTimer = 0
self.holdingUp = false
self.holdingDown = false
self.holdingLeft = false
self.holdingRight = false
self.speedMultiplier = 1.1
self.levitateActivated = false
self.mechTimer = 0
self.superJumpTimer = 0
end
function uninit()
if self.active then
local mechTransformPositionChange = tech.parameter("mechTransformPositionChange")
mcontroller.translate({-mechTransformPositionChange[1], -mechTransformPositionChange[2]})
tech.setParentOffset({0, 0})
self.active = false
tech.setVisible(false)
tech.setParentState()
tech.setToolUsageSuppressed(false)
mcontroller.controlFace(nil)
end
end
function input(args)
if self.dashTimer > 0 then
return nil
end
local maximumDoubleTapTime = tech.parameter("maximumDoubleTapTime")
if self.dashTapTimer > 0 then
self.dashTapTimer = self.dashTapTimer - args.dt
end
if args.moves["right"] and self.active then
if self.dashLastInput ~= 1 then
if self.dashTapLast == 1 and self.dashTapTimer > 0 then
self.dashTapLast = 0
self.dashTapTimer = 0
return "dashRight"
else
self.dashTapLast = 1
self.dashTapTimer = maximumDoubleTapTime
end
end
self.dashLastInput = 1
elseif args.moves["left"] and self.active then
if self.dashLastInput ~= -1 then
if self.dashTapLast == -1 and self.dashTapTimer > 0 then
self.dashTapLast = 0
self.dashTapTimer = 0
return "dashLeft"
else
self.dashTapLast = -1
self.dashTapTimer = maximumDoubleTapTime
end
end
self.dashLastInput = -1
else
self.dashLastInput = 0
end
------------------------
local maximumDoubleTapTime2 = tech.parameter("maximumDoubleTapTime2")
if self.aoeTapTimer > 0 then
self.aoeTapTimer = self.aoeTapTimer - args.dt
end
if args.moves["down"] and self.active then
if self.aoeLastInput ~= 1 then
if self.aoeTapLast == 1 and self.aoeTapTimer > 0 then
self.aoeTapLast = 0
self.aoeTapTimer = 0
return "mechSecFire"
else
self.aoeTapLast = 1
self.aoeTapTimer = maximumDoubleTapTime2
end
end
self.aoeLastInput = 1
else
self.aoeLastInput = 0
end
-------------------------
if args.moves["jump"] and mcontroller.jumping() then
self.holdingJump = true
elseif not args.moves["jump"] then
self.holdingJump = false
end
if args.moves["special"] == 1 then
if self.active then
return "mechDeactivate"
else
return "mechActivate"
end
elseif args.moves[""] == 2 and self.active then
return "blink"
elseif args.moves[""] and args.moves[""] and args.moves[""] and not self.levitateActivated and self.active then
return "grab"
elseif args.moves["down"] and args.moves["right"] and not self.levitateActivated and self.active then
return "dashAttackRight"
elseif args.moves["down"] and args.moves["left"] and not self.levitateActivated and self.active then
return "dashAttackLeft"
elseif args.moves["primaryFire"] and self.active then
return "mechFire"
elseif args.moves["altFire"] and self.active then
return "mechAltFire"
elseif args.moves[""] and args.moves[""] and self.active then
return "mechSecFire"
elseif args.moves[""] and not mcontroller.canJump() and not self.holdingJump and self.active then
return "jetpack"
elseif args.moves["jump"] and args.moves["up"] and mcontroller.onGround() and self.active then
return "superjump"
elseif args.moves[""] and not mcontroller.jumping() and not mcontroller.canJump() and not self.lastJump then
self.lastJump = true
return "multiJump"
else
self.lastJump = args.moves["jump"]
end
self.specialLast = args.moves["special"] == 1
--RedOrb
-- if args.moves["left"] then
-- self.holdingLeft = true
-- elseif not args.moves["left"] then
-- self.holdingLeft = false
-- end
-- if args.moves["right"] then
-- self.holdingRight = true
-- elseif not args.moves["right"] then
-- self.holdingRight = false
-- end
-- if args.moves["up"] then
-- self.holdingUp = true
-- elseif not args.moves["up"] then
-- self.holdingUp = false
-- end
-- if args.moves["down"] then
-- self.holdingDown = true
-- elseif not args.moves["down"] then
-- self.holdingDown = false
-- end
-- if not args.moves["jump"] and not args.moves["left"]and not args.moves["right"]and not args.moves["up"]and not args.moves["down"] and not tech.canJump() and not self.holdingJump and self.levitateActivated then
-- return "levitatehover"
-- elseif args.moves["jump"] and not tech.canJump() and not self.holdingJump then
-- return "levitate"
-- elseif args.moves["left"] and args.moves["right"] and not tech.canJump() and self.levitateActivated then
-- return "levitatehover"
-- elseif args.moves["up"] and args.moves["down"] and not tech.canJump() and self.levitateActivated then
-- return "levitatehover"
-- elseif (args.moves["jump"] or args.moves["up"]) and args.moves["left"] and not tech.canJump() and not self.holdingRight and self.levitateActivated then
-- return "levitateleftup"
-- elseif (args.moves["jump"] or args.moves["up"]) and args.moves["right"] and not tech.canJump() and not self.holdingLeft and self.levitateActivated then
-- return "levitaterightup"
-- elseif args.moves["down"] and args.moves["left"] and not tech.canJump() and not self.holdingRight and self.levitateActivated then
-- return "levitateleftdown"
-- elseif args.moves["down"] and args.moves["right"] and not tech.canJump() and not self.holdingLeft and self.levitateActivated then
-- return "levitaterightdown"
-- elseif args.moves["left"] and not tech.canJump() and not self.holdingRight and self.levitateActivated then
-- return "levitateleft"
-- elseif args.moves["right"] and not tech.canJump() and not self.holdingLeft and self.levitateActivated then
-- return "levitateright"
-- elseif args.moves["up"] and not tech.canJump() and not self.holdingDown and self.levitateActivated then
-- return "levitateup"
-- elseif args.moves["down"] and not tech.canJump() and not self.holdingUp and self.levitateActivated then
-- return "levitatedown"
-- else
-- return nil
-- end
--RedOrbEnd
end
function update(args)
tech.burstParticleEmitter("glowParticles")
if self.mechTimer > 0 then
self.mechTimer = self.mechTimer - args.dt
end
local dashControlForce = tech.parameter("dashControlForce")
local dashSpeed = tech.parameter("dashSpeed")
local dashDuration = tech.parameter("dashDuration")
local energyUsageDash = tech.parameter("energyUsageDash")
local usedEnergy = 0
if args.actions["dashRight"] and self.dashTimer <= 0 and status.resource("energy") > energyUsageDash then
self.dashTimer = dashDuration
self.dashDirection = 1
usedEnergy = energyUsageDash
self.airDashing = not mcontroller.onGround()
return tech.consumeTechEnergy(energyUsageDash)
elseif args.actions["dashLeft"] and self.dashTimer <= 0 and status.resource("energy") > energyUsageDash then
self.dashTimer = dashDuration
self.dashDirection = -1
usedEnergy = energyUsageDash
self.airDashing = not mcontroller.onGround()
return tech.consumeTechEnergy(energyUsageDash)
end
if self.dashTimer > 0 then
mcontroller.controlApproachXVelocity(dashSpeed * self.dashDirection, dashControlForce, true)
if self.airDashing then
mcontroller.controlParameters({gravityEnabled = false})
mcontroller.controlApproachYVelocity(0, dashControlForce, true)
end
if self.dashDirection == -1 then
mcontroller.controlFace(-1)
tech.setFlipped(true)
else
mcontroller.controlFace(1)
tech.setFlipped(false)
end
tech.setAnimationState("dashing", "on")
tech.setParticleEmitterActive("dashParticles", true)
self.dashTimer = self.dashTimer - args.dt
else
tech.setAnimationState("dashing", "off")
tech.setParticleEmitterActive("dashParticles", false)
end
local dashAttackControlForce = tech.parameter("dashAttackControlForce")
local dashAttackSpeed = tech.parameter("dashAttackSpeed")
local dashAttackDuration = tech.parameter("dashAttackDuration")
local energyUsageDashAttack = tech.parameter("energyUsageDashAttack")
local diffDash = world.distance(tech.aimPosition(), mcontroller.position())
local aimAngleDash = math.atan(diffDash[2], diffDash[1])
local mechDashFireCycle = tech.parameter("mechDashFireCycle")
local mechDashProjectile = tech.parameter("mechDashProjectile")
local mechDashProjectileConfig = tech.parameter("mechDashProjectileConfig")
local flipDash = aimAngleDash > math.pi / 2 or aimAngleDash < -math.pi / 2
if flipDash then
tech.setFlipped(false)
mcontroller.controlFace(-1)
self.dashAttackDirection = -1
else
tech.setFlipped(true)
mcontroller.controlFace(1)
self.dashAttackDirection = 1
end
if status.resource("energy") > energyUsageDashAttack and args.actions["dashAttackLeft"] or args.actions["dashAttackRight"] then
if self.dashAttackTimer <= 0 then
world.spawnProjectile(mechDashProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontDashGun", "firePoint")), entity.id(), {math.cos(0), math.sin(0)}, false, mechDashProjectileConfig)
self.dashAttackTimer = self.dashAttackTimer + mechDashFireCycle
else
self.dashAttackTimer = self.dashAttackTimer - args.dt
end
mcontroller.controlApproachXVelocity(dashAttackSpeed * self.dashAttackDirection, dashAttackControlForce, true)
tech.setAnimationState("dashingAttack", "on")
tech.setParticleEmitterActive("dashAttackParticles", true)
else
tech.setAnimationState("dashingAttack", "off")
tech.setParticleEmitterActive("dashAttackParticles", false)
end
local energyUsageBlink = tech.parameter("energyUsageBlink")
local blinkMode = tech.parameter("blinkMode")
local blinkOutTime = tech.parameter("blinkOutTime")
local blinkInTime = tech.parameter("blinkInTime")
if args.actions["blink"] and self.mode == "none" and status.resource("energy") > energyUsageBlink then
local blinkPosition = nil
if blinkMode == "random" then
local randomBlinkAvoidCollision = tech.parameter("randomBlinkAvoidCollision")
local randomBlinkAvoidMidair = tech.parameter("randomBlinkAvoidMidair")
local randomBlinkAvoidLiquid = tech.parameter("randomBlinkAvoidLiquid")
blinkPosition =
findRandomBlinkLocation(randomBlinkAvoidCollision, randomBlinkAvoidMidair, randomBlinkAvoidLiquid) or
findRandomBlinkLocation(randomBlinkAvoidCollision, randomBlinkAvoidMidair, false) or
findRandomBlinkLocation(randomBlinkAvoidCollision, false, false)
elseif blinkMode == "cursor" then
blinkPosition = blinkAdjust(tech.aimPosition(), true, true, false, false)
elseif blinkMode == "cursorPenetrate" then
blinkPosition = blinkAdjust(tech.aimPosition(), false, true, false, false)
end
if blinkPosition then
self.targetPosition = blinkPosition
self.mode = "start"
else
-- Make some kind of error noise
end
end
if self.mode == "start" then
mcontroller.setVelocity({0, 0})
self.mode = "out"
self.timer = 0
return tech.consumeTechEnergy(energyUsageBlink)
elseif self.mode == "out" then
tech.setParentDirectives("?multiply=00000000")
tech.setVisible(false)
tech.setAnimationState("blinking", "out")
mcontroller.setVelocity({0, 0})
self.timer = self.timer + args.dt
if self.timer > blinkOutTime then
mcontroller.setPosition(self.targetPosition)
self.mode = "in"
self.timer = 0
end
return 0
elseif self.mode == "in" then
tech.setParentDirectives()
tech.setVisible(true)
tech.setAnimationState("blinking", "in")
mcontroller.setVelocity({0, 0})
self.timer = self.timer + args.dt
if self.timer > blinkInTime then
self.mode = "none"
end
return 0
end
local energyUsageJump = tech.parameter("energyUsageJump")
local multiJumpCount = tech.parameter("multiJumpCount")
if args.actions["multiJump"] and self.multiJumps < multiJumpCount and status.resource("energy") > energyUsageJump then
mcontroller.controlJump(true)
self.multiJumps = self.multiJumps + 1
tech.burstParticleEmitter("multiJumpParticles")
tech.playSound("sound")
return tech.consumeTechEnergy(energyUsageJump)
else
if mcontroller.onGround() or mcontroller.liquidMovement() then
self.multiJumps = 0
end
end
local energyCostPerSecond = tech.parameter("energyCostPerSecond")
local energyCostPerSecondPrim = tech.parameter("energyCostPerSecondPrim")
local energyCostPerSecondSec = tech.parameter("energyCostPerSecondSec")
local energyCostPerSecondAlt = tech.parameter("energyCostPerSecondAlt")
local mechCustomMovementParameters = tech.parameter("mechCustomMovementParameters")
local mechTransformPositionChange = tech.parameter("mechTransformPositionChange")
local parentOffset = tech.parameter("parentOffset")
local mechCollisionTest = tech.parameter("mechCollisionTest")
local mechAimLimit = tech.parameter("mechAimLimit") * math.pi / 180
local mechFrontRotationPoint = tech.parameter("mechFrontRotationPoint")
local mechFrontFirePosition = tech.parameter("mechFrontFirePosition")
local mechBackRotationPoint = tech.parameter("mechBackRotationPoint")
local mechBackFirePosition = tech.parameter("mechBackFirePosition")
local mechFireCycle = tech.parameter("mechFireCycle")
local mechProjectile = tech.parameter("mechProjectile")
local mechProjectileConfig = tech.parameter("mechProjectileConfig")
local mechAltFireCycle = tech.parameter("mechAltFireCycle")
local mechAltProjectile = tech.parameter("mechAltProjectile")
local mechAltProjectileConfig = tech.parameter("mechAltProjectileConfig")
local mechSecFireCycle = tech.parameter("mechSecFireCycle")
local mechSecProjectile = tech.parameter("mechSecProjectile")
local mechSecProjectileConfig = tech.parameter("mechSecProjectileConfig")
local mechGunBeamMaxRange = tech.parameter("mechGunBeamMaxRange")
local mechGunBeamStep = tech.parameter("mechGunBeamStep")
local mechGunBeamSmokeProkectile = tech.parameter("mechGunBeamSmokeProkectile")
local mechGunBeamEndProjectile = tech.parameter("mechGunBeamEndProjectile")
local mechGunBeamUpdateTime = tech.parameter("mechGunBeamUpdateTime")
local mechTransform = tech.parameter("mechTransform")
local mechActiveSide = nil
if tech.setFlipped(true) then
mechActiveSide = "left"
elseif tech.setFlipped(false) then
mechActiveSide = "right"
end
local mechStartupTime = tech.parameter("mechStartupTime")
local mechShutdownTime = tech.parameter("mechShutdownTime")
if not self.active and args.actions["mechActivate"] and self.mechState == "off" then
mechCollisionTest[1] = mechCollisionTest[1] + mcontroller.position()[1]
mechCollisionTest[2] = mechCollisionTest[2] + mcontroller.position()[2]
mechCollisionTest[3] = mechCollisionTest[3] + mcontroller.position()[1]
mechCollisionTest[4] = mechCollisionTest[4] + mcontroller.position()[2]
if not world.rectCollision(mechCollisionTest) then
tech.burstParticleEmitter("mechActivateParticles")
mcontroller.translate(mechTransformPositionChange)
tech.setVisible(true)
tech.setAnimationState("transform", "in")
-- status.modifyResource("health", status.stat("maxHealth") / 20)
tech.setParentState("sit")
tech.setToolUsageSuppressed(true)
self.mechState = "turningOn"
self.mechStateTimer = mechStartupTime
self.active = true
else
-- Make some kind of error noise
end
elseif self.mechState == "turningOn" and self.mechStateTimer <= 0 then
tech.setParentState("sit")
self.mechState = "on"
self.mechStateTimer = 0
elseif (self.active and (args.actions["mechDeactivate"] and self.mechState == "on" or (energyCostPerSecond * args.dt > status.resource("energy")) and self.mechState == "on")) then
self.mechState = "turningOff"
tech.setAnimationState("transform", "out")
self.mechStateTimer = mechShutdownTime
elseif self.mechState == "turningOff" and self.mechStateTimer <= 0 then
tech.burstParticleEmitter("mechDeactivateParticles")
mcontroller.translate({-mechTransformPositionChange[1], -mechTransformPositionChange[2]})
tech.setVisible(false)
tech.setParentState()
tech.setToolUsageSuppressed(false)
tech.setParentOffset({0, 0})
self.mechState = "off"
self.mechStateTimer = 0
self.active = false
end
mcontroller.controlFace(nil)
if self.mechStateTimer > 0 then
self.mechStateTimer = self.mechStateTimer - args.dt
end
if self.active then
local diff = world.distance(tech.aimPosition(), mcontroller.position())
local aimAngle = math.atan(diff[2], diff[1])
local flip = aimAngle > math.pi / 2 or aimAngle < -math.pi / 2
mcontroller.controlParameters(mechCustomMovementParameters)
if flip then
tech.setFlipped(false)
local nudge = tech.transformedPosition({0, 0})
tech.setParentOffset({-parentOffset[1] - nudge[1], parentOffset[2] + nudge[2]})
mcontroller.controlFace(-1)
if aimAngle > 0 then
aimAngle = math.max(aimAngle, math.pi - mechAimLimit)
else
aimAngle = math.min(aimAngle, -math.pi + mechAimLimit)
end
tech.rotateGroup("guns", math.pi + aimAngle)
else
tech.setFlipped(true)
local nudge = tech.transformedPosition({0, 0})
tech.setParentOffset({parentOffset[1] + nudge[1], parentOffset[2] + nudge[2]})
mcontroller.controlFace(1)
if aimAngle > 0 then
aimAngle = math.min(aimAngle, mechAimLimit)
else
aimAngle = math.max(aimAngle, -mechAimLimit)
end
tech.rotateGroup("guns", -aimAngle)
end
if not mcontroller.onGround() then
if mcontroller.velocity()[2] > 0 then
if args.actions["mechFire"] then
tech.setAnimationState("movement", "jumpAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "jumpAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "jumpAttack")
else
tech.setAnimationState("movement", "jump")
end
else
if args.actions["mechFire"] then
tech.setAnimationState("movement", "fallAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "fallAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "fallAttack")
else
tech.setAnimationState("movement", "fall")
end
end
elseif mcontroller.walking() or mcontroller.running() then
if flip and mcontroller.movingDirection() == 1 or not flip and mcontroller.movingDirection() == -1 then
if args.actions["mechFire"] then
tech.setAnimationState("movement", "backWalkAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "backWalkAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "backWalkAttack")
elseif args.actions["dashAttackRight"] then
tech.setAnimationState("movement", "backWalkDash")
elseif args.actions["dashAttackLeft"] then
tech.setAnimationState("movement", "backWalkDash")
else
tech.setAnimationState("movement", "backWalk")
end
else
if args.actions["mechFire"] then
tech.setAnimationState("movement", "walkAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "walkAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "walkAttack")
elseif args.actions["dashAttackRight"] then
tech.setAnimationState("movement", "walkDash")
elseif args.actions["dashAttackLeft"] then
tech.setAnimationState("movement", "walkDash")
else
tech.setAnimationState("movement", "walk")
end
end
else
if args.actions["mechFire"] then
tech.setAnimationState("movement", "idleAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "idleAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "idleAttack")
else
tech.setAnimationState("movement", "idle")
end
end
local energyUsageSuperJump = tech.parameter("energyUsageSuperJump")
local superJumpSpeed = tech.parameter("superjumpSpeed")
local superJumpControlForce = tech.parameter("superjumpControlForce")
local superJumpTime = tech.parameter("superjumpTime")
local superjumpSound = tech.parameter("superjumpSound")
if args.actions["superjump"] and mcontroller.onGround() and self.superJumpTimer <= 0 and status.resource("energy") > energyUsageSuperJump then
tech.playSound("superjumpSound")
self.superJumpTimer = superJumpTime
usedEnergy = energyUsageSuperJump
end
if self.superJumpTimer > 0 then
mcontroller.controlApproachYVelocity(superJumpSpeed, superJumpControlForce)
tech.setParticleEmitterActive("jumpParticles", true)
self.superJumpTimer = self.superJumpTimer - args.dt
return tech.consumeTechEnergy(energyUsageSuperJump)
else
tech.setParticleEmitterActive("jumpParticles", false)
end
local telekinesisProjectile = tech.parameter("telekinesisProjectile")
local telekinesisProjectileConfig = tech.parameter("telekinesisProjectileConfig")
local telekinesisFireCycle = tech.parameter("telekinesisFireCycle")
local energyUsagePerSecondTelekinesis = tech.parameter("energyUsagePerSecondTelekinesis")
local energyUsageTelekinesis = energyUsagePerSecondTelekinesis * args.dt
if self.active and args.actions["grab"] and not self.grabbed then
local monsterIds = world.monsterQuery(tech.aimPosition(), 5)
for i,v in pairs(monsterIds) do
--world.spawnNpc( tech.aimPosition(), "glitch", "lonesurvivor_positionnpc", 2, 1)
world.monsterQuery(tech.aimPosition(),5, { callScript = "lonesurvivor_grab", callScriptArgs = { tech.aimPosition() } })
break
end
self.grabbed = true
elseif self.grabbed and not args.actions["grab"] then
--world.spawnNpc( tech.aimPosition(), "glitch", "lonesurvivor_positionnpc", 3, 1)
world.monsterQuery(tech.aimPosition(),30, { callScript = "lonesurvivor_release", callScriptArgs = { tech.aimPosition() } })
self.grabbed = false
elseif self.active and self.grabbed then
--world.spawnNpc( tech.aimPosition(), "glitch", "lonesurvivor_positionnpc", 1, 1)
world.monsterQuery(tech.aimPosition(),15, { callScript = "lonesurvivor_move", callScriptArgs = { tech.aimPosition() } })
end
if args.actions["grab"] and status.resource("energy") > energyUsageTelekinesis then
if self.fireTimer <= 0 then
world.spawnProjectile(telekinesisProjectile, tech.aimPosition(), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, telekinesisProjectileConfig)
self.fireTimer = self.fireTimer + telekinesisFireCycle
tech.setAnimationState("telekinesis", "telekinesisOn")
else
local oldFireTimer = self.fireTimer
self.fireTimer = self.fireTimer - args.dt
if oldFireTimer > telekinesisFireCycle / 2 and self.fireTimer <= telekinesisFireCycle / 2 then
end
end
return tech.consumeTechEnergy(energyUsageTelekinesis)
end
if args.actions["mechFire"] and status.resource("energy") > energyCostPerSecondPrim then
if self.fireTimer <= 0 then
world.spawnProjectile(mechProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechProjectileConfig)
self.fireTimer = self.fireTimer + mechFireCycle
tech.setAnimationState("frontFiring", "fire")
--tech.setParticleEmitterActive("jetpackParticles3", true)
local startPoint = vec2.add(mcontroller.position(), tech.partPoint("frontGun", "firePoint"))
local endPoint = vec_add(mcontroller.position(), {tech.partPoint("frontDashGun", "firePoint")[1] + mechGunBeamMaxRange * math.cos(aimAngle), tech.partPoint("frontDashGun", "firePoint")[2] + mechGunBeamMaxRange * math.sin(aimAngle) })
local beamCollision = progressiveLineCollision(startPoint, endPoint, mechGunBeamStep)
randomProjectileLine(startPoint, beamCollision, mechGunBeamStep, mechGunBeamSmokeProkectile, 0.08)
else
local oldFireTimer = self.fireTimer
self.fireTimer = self.fireTimer - args.dt
if oldFireTimer > mechFireCycle / 2 and self.fireTimer <= mechFireCycle / 2 then
end
end
return tech.consumeTechEnergy(energyCostPerSecondPrim)
end
if not args.actions["mechFire"] then
--tech.setParticleEmitterActive("jetpackParticles3", false)
end
if args.actions["mechAltFire"] and status.resource("energy") > energyCostPerSecondAlt then
if self.fireTimer <= 0 then
world.spawnProjectile(mechAltProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontAltGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechAltProjectileConfig)
self.fireTimer = self.fireTimer + mechAltFireCycle
tech.setAnimationState("frontAltFiring", "fireAlt")
else
local oldFireTimer = self.fireTimer
self.fireTimer = self.fireTimer - args.dt
if oldFireTimer > mechAltFireCycle / 2 and self.fireTimer <= mechAltFireCycle / 2 then
end
end
return tech.consumeTechEnergy(energyCostPerSecondAlt)
end
if args.actions["mechSecFire"] and status.resource("energy") > energyCostPerSecondSec then
world.spawnProjectile(mechSecProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontSecGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechAltProjectileConfig)
tech.setAnimationState("frontSecFiring", "fireSec")
-- if self.fireSecTimer <= 0 then
-- world.spawnProjectile(mechSecProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontSecGun", "firePoint")), entity.id(), {math.cos(0), math.sin(0)}, false, mechAltProjectileConfig)
-- self.fireSecTimer = self.fireSecTimer + mechSecFireCycle
-- tech.setAnimationState("frontSecFiring", "fireSec")
-- else
-- local oldFireSecTimer = self.fireSecTimer
-- self.fireSecTimer = self.fireSecTimer - args.dt
-- if oldFireSecTimer > mechSecFireCycle / 2 and self.fireSecTimer <= mechSecFireCycle / 2 then
-- end
-- end
return tech.consumeTechEnergy(energyCostPerSecondSec)
end
local jetpackSpeed = tech.parameter("jetpackSpeed")
local jetpackControlForce = tech.parameter("jetpackControlForce")
local energyUsagePerSecond = tech.parameter("energyUsagePerSecond")
local energyUsage = energyUsagePerSecond * args.dt
if status.resource("energy") < energyUsage then
self.ranOut = true
elseif mcontroller.onGround() or mcontroller.liquidMovement() then
self.ranOut = false
end
if args.actions["jetpack"] and not self.ranOut then
tech.setAnimationState("jetpack", "on")
mcontroller.controlApproachYVelocity(jetpackSpeed, jetpackControlForce, true)
return tech.consumeTechEnergy(energyUsage)
else
tech.setAnimationState("jetpack", "off")
return 0
end
-- local levitateSpeed = tech.parameter("levitateSpeed")
-- local levitateControlForce = tech.parameter("levitateControlForce")
-- local energyUsagePerSecondLevitate = tech.parameter("energyUsagePerSecondLevitate")
-- local energyUsagelevitate = energyUsagePerSecondLevitate * args.dt
-- if args.availableEnergy < energyUsagelevitate then
-- self.ranOut = true
-- elseif mcontroller.onGround() or mcontroller.liquidMovement() then
-- self.ranOut = false
-- end
-- if args.actions["levitate"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true)
-- self.levitateActivated = true
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitatehover"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(0, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(0, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateleft"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(0, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(-(levitateSpeed*self.speedMultiplier), levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateleftup"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(-(levitateSpeed*self.speedMultiplier), levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateleftdown"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(-(levitateSpeed)*0.5, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(-(levitateSpeed*self.speedMultiplier), levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateright"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(0, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(levitateSpeed*self.speedMultiplier, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitaterightup"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(levitateSpeed*self.speedMultiplier, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitaterightdown"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(-(levitateSpeed)*0,5, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(levitateSpeed*self.speedMultiplier, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateup"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(0, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitatedown"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(-(levitateSpeed)*0.5, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(0, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- else
-- self.levitateActivated = false
-- tech.setAnimationState("levitate", "off")
-- return 0
-- end
--return energyCostPerSecond * args.dt
end
return 0
end
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Yuhtunga_Jungle/npcs/Mahol_IM.lua | 30 | 3044 | -----------------------------------
-- Area: Yuhtunga Jungle
-- NPC: Mahol, I.M.
-- Outpost Conquest Guards
-- @pos -242.487 -1 -402.772 123
-----------------------------------
package.loaded["scripts/zones/Yuhtunga_Jungle/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Yuhtunga_Jungle/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = ELSHIMOLOWLANDS;
local csid = 0x7ff9;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
BeyondTeam/TeleBeyond | plugins/kickme.lua | 1 | 1456 | local function run(msg, matches)
local hash = 'kick:'..msg.to.id..':'..msg.from.id
if matches[1] == 'kickme' and redis:get(hash) == nil then
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)]['settings']['kickme'] == '❌' then
return reply_msg(msg.id, 'این دستور در این سوپرگروه غیرفعال است.', ok_cb, true)
else
redis:set(hash, "waite")
return reply_msg(msg.id, 'شما از دستور '..msg.text..' استفاده کردید!!\nاگر با درخواست اخراج خود موافقید دستور yes را ارسال کنید\nو برای لغو از دستور no استفاده کنید.', ok_cb, true)
end
end
if msg.text then
if msg.text:match("^yes$") and redis:get(hash) == "waite" then
redis:set(hash, "ok")
elseif msg.text:match("^no$") and redis:get(hash) == "waite" then
send_large_msg(get_receiver(msg), "دستور اخراج لغو شد.")
redis:del(hash, true)
end
end
if redis:get(hash) then
if redis:get(hash) == "ok" then
redis:del(hash, true)
channel_kick("channel#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
return 'یوزرنیم [@'..(msg.from.username or '---')..'] بنابر درخواست خود از گروه ('..msg.to.title..') اخراج شد'
end
end
end
return {
patterns = {
"^[#!/]([Kk]ickme)$",
"no",
"^yes$"
},
run = run,
}
| agpl-3.0 |
jshackley/darkstar | scripts/zones/East_Ronfaure/npcs/Andelain.lua | 19 | 2000 | -----------------------------------
-- Area: East Ronfaure
-- NPC: Andelain
-- Type: Standard NPC
-- @pos 664.231 -12.849 -539.413 101
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/East_Ronfaure/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/East_Ronfaure/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
sermonQuest = player:getQuestStatus(SANDORIA,THE_VICASQUE_S_SERMON);
if (sermonQuest == QUEST_ACCEPTED) then
count = trade:getItemCount();
BluePeas = trade:getItemQty(618);
if (BluePeas == 1 and count == 1 and player:getVar("sermonQuestVar") == 0) then
player:tradeComplete();
player:showText(npc, 7349);
player:startEvent(0x0013);
player:setVar("sermonQuestVar",1);
elseif (BluePeas > 1 and count == BluePeas) then
player:showText(npc, 7352);
player:startEvent(0x0013);
elseif (BluePeas == 1 and count == 1) then
player:showText(npc, 7352,618);
player:startEvent(0x0013);
else
player:showText(npc, 7350);
player:showText(npc, 7351);
player:startEvent(0x0013);
end
else
player:showText(npc, 7350);
player:showText(npc, 7351);
player:startEvent(0x0013);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, 7347);
player:showText(npc, 7348,618);
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 |
deepmind/torch-dokx | tests/testParsing.lua | 2 | 8738 | require 'dokx'
local tester = torch.Tester()
local myTests = {}
local package = "dummyPackageName"
local sourceFile = "dummySourceFile"
local checkTableSize = function(...) dokx._checkTableSize(tester, ...) end
local checkComment = function(...) dokx._checkComment(tester, package, sourceFile, ...) end
local checkWhitespace = function(...) dokx._checkWhitespace(tester, ...) end
local checkFunction = function(...) dokx._checkFunction(tester, package, sourceFile, ...) end
local checkClass = function(...) dokx._checkClass(tester, package, sourceFile, ...) end
-- Unit tests
function myTests:testParseWhitespace()
local parser = dokx.createParser(package, sourceFile)
local testInput = " \n\t "
local result = parser(testInput)
checkTableSize(result, 1)
checkWhitespace(result[1])
end
function myTests:testParseDocumentedFunction()
local parser = dokx.createParser(package, sourceFile)
local testInput = [[-- this is some dummy documentation
function foo()
end
]]
local result = parser(testInput)
checkTableSize(result, 3)
checkComment(result[1], "this is some dummy documentation\n", 2)
checkFunction(result[2], "foo", false, 5)
checkWhitespace(result[3])
end
function myTests:testParseGlobalFunction()
local parser = dokx.createParser(package, sourceFile)
local testInput = [[function foo(a) end]]
local result = parser(testInput)
checkTableSize(result, 1)
checkFunction(result[1], "foo", false, 1, 'a')
end
function myTests:testParseLocalFunction()
local parser = dokx.createParser(package, sourceFile)
local testInput = [[local function foo(a, b) end]]
local result = parser(testInput)
checkTableSize(result, 1)
checkFunction(result[1], "foo", false, 1, 'a, b')
end
function myTests:testParseInstanceMethod()
local parser = dokx.createParser(package, sourceFile)
local testInput = [[function myClass:foo() end]]
local result = parser(testInput)
checkTableSize(result, 1)
checkFunction(result[1], "foo", "myClass", 1)
end
function myTests:testParseClassMethod()
local parser = dokx.createParser(package, sourceFile)
local testInput = [[function myClass.foo() end]]
local result = parser(testInput)
checkTableSize(result, 1)
checkFunction(result[1], "foo", "myClass", 1)
end
function myTests:testParseMustHave()
local parser = dokx.createParser(package, sourceFile)
local testInput = [[myClass:mustHave("step")]]
local result = parser(testInput)
checkTableSize(result, 1)
checkFunction(result[1], "step", "myClass", 1)
end
function myTests:testParseSeparateComments()
local parser = dokx.createParser(package, sourceFile)
local testInput = [=[
--[[ first comment
lorem ipsum
]]
--second comment
]=]
local result = parser(testInput)
checkTableSize(result, 5)
checkWhitespace(result[1])
checkComment(result[2], " first comment\n lorem ipsum\n \n", 4)
checkWhitespace(result[3])
checkComment(result[4], "second comment\n", 6)
checkWhitespace(result[5])
end
function myTests:testParseAdjacentComments()
local parser = dokx.createParser(package, sourceFile)
local testInput = [[
-- first comment
-- second comment
]]
local result = parser(testInput)
checkTableSize(result, 5)
checkWhitespace(result[1])
checkComment(result[2], "first comment\n", 2)
checkWhitespace(result[3])
checkComment(result[4], "second comment\n", 3)
checkWhitespace(result[5])
end
function myTests:testParseClass()
local parser = dokx.createParser(package, sourceFile)
local testInput = [=[--[[
This is a dummy class.
--]]
local MyClass, parent = torch.class('dummyPackageName.MyClass', 'otherPackage.Parent')
]=]
local result = parser(testInput)
checkTableSize(result, 4)
checkComment(result[1], "\n\nThis is a dummy class.\n\n\n", 6)
checkWhitespace(result[2])
checkClass(result[3], "MyClass", "otherPackage.Parent", 7)
checkWhitespace(result[4])
end
function myTests:testParseClassicClass()
local parser = dokx.createParser(package, sourceFile)
local testInput = [=[--[[
This is a dummy class.
--]]
local MyClass, parent = classic.class('dummyPackageName.MyClass', 'otherPackage.Parent')
]=]
local result = parser(testInput)
checkTableSize(result, 4)
checkComment(result[1], "\n\nThis is a dummy class.\n\n\n", 6)
checkWhitespace(result[2])
checkClass(result[3], "MyClass", "otherPackage.Parent", 7)
checkWhitespace(result[4])
end
function myTests:testParseClassicClassWithEllipsis()
local parser = dokx.createParser(package, sourceFile)
local testInput = [=[--[[
This is a dummy class.
--]]
local MyClass, parent = classic.class(..., otherPackage.Parent)
]=]
local result = parser(testInput)
checkTableSize(result, 4)
checkComment(result[1], "\n\nThis is a dummy class.\n\n\n", 6)
checkWhitespace(result[2])
checkClass(result[3], "dummySourceFile", "otherPackage.Parent", 7)
checkWhitespace(result[4])
end
function myTests:testParsePenlightClass()
local parser = dokx.createParser(package, sourceFile)
local testInput = [=[--[[
This is a dummy class.
--]]
local MyClass = class()
]=]
local result = parser(testInput)
checkTableSize(result, 4)
checkComment(result[1], "\n\nThis is a dummy class.\n\n\n", 6)
checkWhitespace(result[2])
checkClass(result[3], "MyClass", false, 7)
checkWhitespace(result[4])
end
function myTests:testParsePenlightClassWithParent()
local parser = dokx.createParser(package, sourceFile)
local testInput = [=[--[[
This is a dummy class.
--]]
local MyClass = class(MyParent)
]=]
local result = parser(testInput)
checkTableSize(result, 4)
checkComment(result[1], "\n\nThis is a dummy class.\n\n\n", 6)
checkWhitespace(result[2])
checkClass(result[3], "MyClass", "MyParent", 7)
checkWhitespace(result[4])
end
function myTests:testFunctionAsAssignment()
local parser = dokx.createParser(package, sourceFile)
local testInput = [[myFunction = function(a, b) end]]
local result = parser(testInput)
checkTableSize(result, 1)
checkFunction(result[1], "myFunction", false, 1)
tester:asserteq(result[1]:args(), "a, b", "function should have expected args")
end
function myTests:testFunctionAsAssignmentWithClass()
local parser = dokx.createParser(package, sourceFile)
local testInput = [[myClass.myFunction = function(a, b) end]]
local result = parser(testInput)
checkTableSize(result, 1)
checkFunction(result[1], "myFunction", "myClass", 1)
tester:asserteq(result[1]:args(), "a, b", "function should have expected args")
end
function myTests:testIgnoreAssignment()
local parser = dokx.createParser(package, sourceFile)
local testInput = [[myFunction = 3]]
local result = parser(testInput)
checkTableSize(result, 0)
end
function myTests:testIgnoreAssignmentString()
local parser = dokx.createParser(package, sourceFile)
local testInput = [[a="function(a, b) return 1 end"]]
local result = parser(testInput)
checkTableSize(result, 0)
end
function myTests:testBadParse()
local parser = dokx.createParser(package, sourceFile)
local testInput = [[a=function)"]]
local result = parser(testInput)
tester:asserteq(result, nil, "result of bad parse should be nil")
end
function myTests:testFunctionAsAssigmentWithDocs()
local parser = dokx.createParser(package, sourceFile)
local testInput = [[
-- a function
module.aFunction = function(x, y)
x = y
z = function() end
local p = function(a)
return 2
end
return z
end
local f = function(z)
end]]
local result = parser(testInput)
checkTableSize(result, 3)
checkComment(result[1], "a function\n", 2)
checkFunction(result[2], "aFunction", "module", 10)
tester:asserteq(result[2]:args(), "x, y", "function should have expected args")
checkWhitespace(result[3])
end
function myTests:testNumberParsing()
local parser = dokx.createParser(package, sourceFile)
local testInput = "return 1.0"
tester:assertne(parser(testInput), nil, "float should parse")
testInput = "return 1."
tester:assertne(parser(testInput), nil, "float with no fractional part should parse")
testInput = "return 1"
tester:assertne(parser(testInput), nil, "integer should parse")
end
function myTests:testInterposingComment()
local parser = dokx.createParser(package, sourceFile)
local testInput = [[
local foo =
-- my very special number
3
bar =
-- another number
4
]]
tester:assertne(parser(testInput), nil, "interposing comment should parse")
end
tester:add(myTests):run()
| bsd-3-clause |
jshackley/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Halbeeya.lua | 34 | 1033 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Halbeeya
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x029E);
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 |
LiberatorUSA/GUCEF | dependencies/Ogre/RenderSystems/GL/premake5.lua | 1 | 16894 | --------------------------------------------------------------------
-- This file was automatically generated by ProjectGenerator
-- which is tooling part the build system designed for GUCEF
-- (Galaxy Unlimited Framework)
-- For the latest info, see http://www.VanvelzenSoftware.com/
--
-- The contents of this file are placed in the public domain. Feel
-- free to make use of it in any way you like.
--------------------------------------------------------------------
--
-- Configuration for module: OgreRenderSystem_GL
project( "OgreRenderSystem_GL" )
configuration( {} )
location( os.getenv( "PM5OUTPUTDIR" ) )
configuration( {} )
targetdir( os.getenv( "PM5TARGETDIR" ) )
configuration( {} )
language( "C++" )
configuration( {} )
kind( "SharedLib" )
configuration( {} )
links( { "Ogre" } )
links( { "Ogre" } )
configuration( {} )
defines( { "OGRE_GLPLUGIN_EXPORTS" } )
links( { "GL", "GLU" } )
links( { "GL", "GLU" } )
links( { "glu32.lib", "opengl32" } )
links( { "glu32.lib", "opengl32" } )
configuration( {} )
vpaths { ["Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"include/OgreGLATIFSInit.h",
"include/OgreGLContext.h",
"include/OgreGLDefaultHardwareBufferManager.h",
"include/OgreGLDepthBuffer.h",
"include/OgreGLFBOMultiRenderTarget.h",
"include/OgreGLFBORenderTexture.h",
"include/OgreGLFrameBufferObject.h",
"include/OgreGLGpuNvparseProgram.h",
"include/OgreGLGpuProgram.h",
"include/OgreGLGpuProgramManager.h",
"include/OgreGLHardwareBufferManager.h",
"include/OgreGLHardwareIndexBuffer.h",
"include/OgreGLHardwareOcclusionQuery.h",
"include/OgreGLHardwarePixelBuffer.h",
"include/OgreGLHardwareVertexBuffer.h",
"include/OgreGLPBRenderTexture.h",
"include/OgreGLPBuffer.h",
"include/OgreGLPixelFormat.h",
"include/OgreGLPlugin.h",
"include/OgreGLPrerequisites.h",
"include/OgreGLRenderSystem.h",
"include/OgreGLRenderTexture.h",
"include/OgreGLRenderToVertexBuffer.h",
"include/OgreGLStateCacheManager.h",
"include/OgreGLSupport.h",
"include/OgreGLTexture.h",
"include/OgreGLTextureManager.h",
"include/OgreGLUniformCache.h",
"include/OgreSDLGLSupport.h",
"include/OgreSDLPrerequisites.h",
"include/OgreSDLWindow.h",
"include/GL/gl.h",
"include/GL/glew.h",
"include/GL/glext.h",
"include/GL/glxew.h",
"include/GL/glxext.h",
"include/GL/glxtokens.h",
"include/GL/wglew.h",
"include/GL/wglext.h",
"src/GLSL/include/OgreGLSLExtSupport.h",
"src/GLSL/include/OgreGLSLGpuProgram.h",
"src/GLSL/include/OgreGLSLLinkProgram.h",
"src/GLSL/include/OgreGLSLLinkProgramManager.h",
"src/GLSL/include/OgreGLSLPreprocessor.h",
"src/GLSL/include/OgreGLSLProgram.h",
"src/GLSL/include/OgreGLSLProgramFactory.h",
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.h",
"src/StateCacheManager/OgreGLNullUniformCacheImp.h",
"src/atifs/include/ATI_FS_GLGpuProgram.h",
"src/atifs/include/Compiler2Pass.h",
"src/atifs/include/ps_1_4.h",
"src/nvparse/_ps1.0_parser.h",
"src/nvparse/_rc1.0_parser.h",
"src/nvparse/_ts1.0_parser.h",
"src/nvparse/_vs1.0_parser.h",
"src/nvparse/macro.h",
"src/nvparse/nvparse.h",
"src/nvparse/nvparse_errors.h",
"src/nvparse/nvparse_externs.h",
"src/nvparse/ps1.0_program.h",
"src/nvparse/rc1.0_combiners.h",
"src/nvparse/rc1.0_final.h",
"src/nvparse/rc1.0_general.h",
"src/nvparse/rc1.0_register.h",
"src/nvparse/ts1.0_inst.h",
"src/nvparse/ts1.0_inst_list.h",
"src/nvparse/vs1.0_inst.h",
"src/nvparse/vs1.0_inst_list.h",
"src/nvparse/winheaders/unistd.h"
} )
configuration( {} )
vpaths { ["Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/OgreGLATIFSInit.cpp",
"src/OgreGLContext.cpp",
"src/OgreGLDefaultHardwareBufferManager.cpp",
"src/OgreGLDepthBuffer.cpp",
"src/OgreGLEngineDll.cpp",
"src/OgreGLFBOMultiRenderTarget.cpp",
"src/OgreGLFBORenderTexture.cpp",
"src/OgreGLFrameBufferObject.cpp",
"src/OgreGLGpuNvparseProgram.cpp",
"src/OgreGLGpuProgram.cpp",
"src/OgreGLGpuProgramManager.cpp",
"src/OgreGLHardwareBufferManager.cpp",
"src/OgreGLHardwareIndexBuffer.cpp",
"src/OgreGLHardwareOcclusionQuery.cpp",
"src/OgreGLHardwarePixelBuffer.cpp",
"src/OgreGLHardwareVertexBuffer.cpp",
"src/OgreGLPBRenderTexture.cpp",
"src/OgreGLPixelFormat.cpp",
"src/OgreGLPlugin.cpp",
"src/OgreGLRenderSystem.cpp",
"src/OgreGLRenderTexture.cpp",
"src/OgreGLRenderToVertexBuffer.cpp",
"src/OgreGLStateCacheManager.cpp",
"src/OgreGLSupport.cpp",
"src/OgreGLTexture.cpp",
"src/OgreGLTextureManager.cpp",
"src/OgreGLUniformCache.cpp",
"src/glew.cpp",
"src/GLSL/src/OgreGLSLExtSupport.cpp",
"src/GLSL/src/OgreGLSLGpuProgram.cpp",
"src/GLSL/src/OgreGLSLLinkProgram.cpp",
"src/GLSL/src/OgreGLSLLinkProgramManager.cpp",
"src/GLSL/src/OgreGLSLPreprocessor.cpp",
"src/GLSL/src/OgreGLSLProgram.cpp",
"src/GLSL/src/OgreGLSLProgramFactory.cpp",
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.cpp",
"src/StateCacheManager/OgreGLNullUniformCacheImp.cpp",
"src/atifs/src/ATI_FS_GLGpuProgram.cpp",
"src/atifs/src/Compiler2Pass.cpp",
"src/atifs/src/ps_1_4.cpp",
"src/nvparse/_ps1.0_lexer.cpp",
"src/nvparse/_ps1.0_parser.cpp",
"src/nvparse/_rc1.0_lexer.cpp",
"src/nvparse/_rc1.0_parser.cpp",
"src/nvparse/_ts1.0_lexer.cpp",
"src/nvparse/_ts1.0_parser.cpp",
"src/nvparse/_vs1.0_lexer.cpp",
"src/nvparse/_vs1.0_parser.cpp",
"src/nvparse/avp1.0_impl.cpp",
"src/nvparse/nvparse.cpp",
"src/nvparse/nvparse_errors.cpp",
"src/nvparse/ps1.0_program.cpp",
"src/nvparse/rc1.0_combiners.cpp",
"src/nvparse/rc1.0_final.cpp",
"src/nvparse/rc1.0_general.cpp",
"src/nvparse/ts1.0_inst.cpp",
"src/nvparse/ts1.0_inst_list.cpp",
"src/nvparse/vcp1.0_impl.cpp",
"src/nvparse/vp1.0_impl.cpp",
"src/nvparse/vs1.0_inst.cpp",
"src/nvparse/vs1.0_inst_list.cpp",
"src/nvparse/vsp1.0_impl.cpp"
} )
configuration( { "ANDROID" } )
vpaths { ["Platform Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.h",
"src/StateCacheManager/OgreGLNullUniformCacheImp.h"
} )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.cpp",
"src/StateCacheManager/OgreGLNullUniformCacheImp.cpp"
} )
configuration( { "EMSCRIPTEN" } )
vpaths { ["Platform Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.h",
"src/StateCacheManager/OgreGLNullUniformCacheImp.h"
} )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.cpp",
"src/StateCacheManager/OgreGLNullUniformCacheImp.cpp"
} )
configuration( { "GLX" } )
vpaths { ["Platform Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"include/GLX/OgreGLXContext.h",
"include/GLX/OgreGLXGLSupport.h",
"include/GLX/OgreGLXRenderTexture.h",
"include/GLX/OgreGLXUtils.h",
"include/GLX/OgreGLXWindow.h",
"src/GLX/OgreGLUtil.h",
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.h",
"src/StateCacheManager/OgreGLNullUniformCacheImp.h"
} )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/GLX/OgreGLXContext.cpp",
"src/GLX/OgreGLXGLSupport.cpp",
"src/GLX/OgreGLXRenderTexture.cpp",
"src/GLX/OgreGLXWindow.cpp",
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.cpp",
"src/StateCacheManager/OgreGLNullUniformCacheImp.cpp"
} )
configuration( { "GTK" } )
vpaths { ["Platform Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"include/gtk/OgreGTKGLSupport.h",
"include/gtk/OgreGTKWindow.h",
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.h",
"src/StateCacheManager/OgreGLNullUniformCacheImp.h",
"src/gtk/OgreGLUtil.h"
} )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.cpp",
"src/StateCacheManager/OgreGLNullUniformCacheImp.cpp",
"src/gtk/OgreGTKGLSupport.cpp",
"src/gtk/OgreGTKWindow.cpp"
} )
configuration( { "IOS" } )
vpaths { ["Platform Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.h",
"src/StateCacheManager/OgreGLNullUniformCacheImp.h"
} )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.cpp",
"src/StateCacheManager/OgreGLNullUniformCacheImp.cpp"
} )
configuration( { "LINUX32" } )
vpaths { ["Platform Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.h",
"src/StateCacheManager/OgreGLNullUniformCacheImp.h"
} )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.cpp",
"src/StateCacheManager/OgreGLNullUniformCacheImp.cpp"
} )
configuration( { "LINUX64" } )
vpaths { ["Platform Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.h",
"src/StateCacheManager/OgreGLNullUniformCacheImp.h"
} )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.cpp",
"src/StateCacheManager/OgreGLNullUniformCacheImp.cpp"
} )
configuration( { "NACL" } )
vpaths { ["Platform Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.h",
"src/StateCacheManager/OgreGLNullUniformCacheImp.h"
} )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.cpp",
"src/StateCacheManager/OgreGLNullUniformCacheImp.cpp"
} )
configuration( { "OSX" } )
vpaths { ["Platform Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"include/OSX/OgreOSXCGLContext.h",
"include/OSX/OgreOSXCarbonContext.h",
"include/OSX/OgreOSXCarbonWindow.h",
"include/OSX/OgreOSXCocoaContext.h",
"include/OSX/OgreOSXCocoaView.h",
"include/OSX/OgreOSXCocoaWindow.h",
"include/OSX/OgreOSXCocoaWindowDelegate.h",
"include/OSX/OgreOSXContext.h",
"include/OSX/OgreOSXGLSupport.h",
"include/OSX/OgreOSXRenderTexture.h",
"include/OSX/OgreOSXWindow.h",
"src/OSX/OgreGLUtil.h",
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.h",
"src/StateCacheManager/OgreGLNullUniformCacheImp.h"
} )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/OSX/OgreOSXCGLContext.cpp",
"src/OSX/OgreOSXCarbonContext.cpp",
"src/OSX/OgreOSXCarbonWindow.cpp",
"src/OSX/OgreOSXContext.cpp",
"src/OSX/OgreOSXRenderTexture.cpp",
"src/OSX/OgreOSXWindow.cpp",
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.cpp",
"src/StateCacheManager/OgreGLNullUniformCacheImp.cpp"
} )
configuration( { "POSIX" } )
vpaths { ["Platform Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.h",
"src/StateCacheManager/OgreGLNullUniformCacheImp.h"
} )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.cpp",
"src/StateCacheManager/OgreGLNullUniformCacheImp.cpp"
} )
configuration( { "SDL" } )
vpaths { ["Platform Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"src/SDL/OgreGLUtil.h",
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.h",
"src/StateCacheManager/OgreGLNullUniformCacheImp.h"
} )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/SDL/OgreSDLGLSupport.cpp",
"src/SDL/OgreSDLWindow.cpp",
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.cpp",
"src/StateCacheManager/OgreGLNullUniformCacheImp.cpp"
} )
configuration( { "SYMBIAN" } )
vpaths { ["Platform Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.h",
"src/StateCacheManager/OgreGLNullUniformCacheImp.h"
} )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.cpp",
"src/StateCacheManager/OgreGLNullUniformCacheImp.cpp"
} )
configuration( { "UNIX" } )
vpaths { ["Platform Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.h",
"src/StateCacheManager/OgreGLNullUniformCacheImp.h"
} )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.cpp",
"src/StateCacheManager/OgreGLNullUniformCacheImp.cpp"
} )
configuration( { "WIN32" } )
vpaths { ["Platform Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"include/Win32/OgreWin32Context.h",
"include/Win32/OgreWin32GLSupport.h",
"include/Win32/OgreWin32Prerequisites.h",
"include/Win32/OgreWin32RenderTexture.h",
"include/Win32/OgreWin32Window.h",
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.h",
"src/StateCacheManager/OgreGLNullUniformCacheImp.h",
"src/Win32/OgreGLUtil.h"
} )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.cpp",
"src/StateCacheManager/OgreGLNullUniformCacheImp.cpp",
"src/Win32/OgreWin32Context.cpp",
"src/Win32/OgreWin32GLSupport.cpp",
"src/Win32/OgreWin32RenderTexture.cpp",
"src/Win32/OgreWin32Window.cpp"
} )
configuration( { "WIN64" } )
vpaths { ["Platform Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.h",
"src/StateCacheManager/OgreGLNullUniformCacheImp.h"
} )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/StateCacheManager/OgreGLNullStateCacheManagerImp.cpp",
"src/StateCacheManager/OgreGLNullUniformCacheImp.cpp"
} )
configuration( {} )
includedirs( { "../../../freetype/include", "../../../freetype/include/freetype", "../../../freetype/include/freetype/config", "../../../freetype/include/freetype/internal", "../../../freetype/include/freetype/internal/services", "../../../freetype/src", "../../../freetype/src/winfonts", "../../OgreMain/include", "../../OgreMain/include/Hash", "../../OgreMain/include/Threading", "../../OgreMain/src", "../../OgreMain/src/nedmalloc", "../../OgreMain/src/stbi", "../../include", "src", "src/GLSL", "src/atifs", "include", "include/GL", "src/GLSL/include", "src/StateCacheManager", "src/atifs/include", "src/nvparse", "src/nvparse/winheaders" } )
configuration( { "ANDROID" } )
includedirs( { "../../OgreMain/include/Android", "src/StateCacheManager" } )
configuration( { "EMSCRIPTEN" } )
includedirs( { "../../OgreMain/include/Emscripten", "src/StateCacheManager" } )
configuration( { "GLX" } )
includedirs( { "../../OgreMain/src/GLX", "include/GLX", "src/GLX", "src/StateCacheManager" } )
configuration( { "GTK" } )
includedirs( { "../../OgreMain/include/gtk", "../../OgreMain/src/gtk", "include/gtk", "src/StateCacheManager", "src/gtk" } )
configuration( { "IOS" } )
includedirs( { "../../OgreMain/include/iOS", "src/StateCacheManager" } )
configuration( { "LINUX32" } )
includedirs( { "src/StateCacheManager" } )
configuration( { "LINUX64" } )
includedirs( { "src/StateCacheManager" } )
configuration( { "NACL" } )
includedirs( { "src/StateCacheManager" } )
configuration( { "OSX" } )
includedirs( { "../../OgreMain/include/OSX", "include/OSX", "src/OSX", "src/StateCacheManager" } )
configuration( { "POSIX" } )
includedirs( { "src/StateCacheManager" } )
configuration( { "SDL" } )
includedirs( { "src/SDL", "src/StateCacheManager" } )
configuration( { "SYMBIAN" } )
includedirs( { "src/StateCacheManager" } )
configuration( { "UNIX" } )
includedirs( { "src/StateCacheManager" } )
configuration( { "WIN32" } )
includedirs( { "../../OgreMain/include/WIN32", "../../OgreMain/src/WIN32", "include/Win32", "src/StateCacheManager", "src/Win32" } )
configuration( { "WIN64" } )
includedirs( { "src/StateCacheManager" } )
| apache-2.0 |
jshackley/darkstar | scripts/zones/West_Ronfaure/npcs/qm3.lua | 34 | 1499 | -----------------------------------
-- Area: West Ronfaure
-- NPC: qm3 (???)
-- Involved in Quest: The Dismayed Customer
-- @pos -399 -10 -438 100
-----------------------------------
package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/zones/West_Ronfaure/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(SANDORIA, THE_DISMAYED_CUSTOMER) == QUEST_ACCEPTED and player:getVar("theDismayedCustomer") == 3) then
player:addKeyItem(GULEMONTS_DOCUMENT);
player:messageSpecial(KEYITEM_OBTAINED, GULEMONTS_DOCUMENT);
player:setVar("theDismayedCustomer", 0);
else
player:messageSpecial(DISMAYED_CUSTOMER);
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 |
samijon/online-anti-spam | plugins/anti_spam.lua | 923 | 3750 |
--An empty table for solving multiple kicking problem(thanks to @topkecleon )
kicktable = {}
do
local TIME_CHECK = 2 -- seconds
local data = load_data(_config.moderation.data)
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
return msg
end
if msg.from.id == our_id then
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
--Load moderation data
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
--Check if flood is one or off
if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then
return msg
end
end
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
local data = load_data(_config.moderation.data)
local NUM_MSG_MAX = 5
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])--Obtain group flood sensitivity
end
end
local max_msg = NUM_MSG_MAX * 1
if msgs > max_msg then
local user = msg.from.id
-- Ignore mods,owner and admins
if is_momod(msg) then
return msg
end
local chat = msg.to.id
local user = msg.from.id
-- Return end if user was kicked before
if kicktable[user] == true then
return
end
kick_user(user, chat)
local name = user_print_name(msg.from)
--save it to log file
savelog(msg.to.id, name.." ["..msg.from.id.."] spammed and kicked ! ")
-- incr it on redis
local gbanspam = 'gban:spam'..msg.from.id
redis:incr(gbanspam)
local gbanspam = 'gban:spam'..msg.from.id
local gbanspamonredis = redis:get(gbanspam)
--Check if user has spammed is group more than 4 times
if gbanspamonredis then
if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then
--Global ban that user
banall_user(msg.from.id)
local gbanspam = 'gban:spam'..msg.from.id
--reset the counter
redis:set(gbanspam, 0)
local username = " "
if msg.from.username ~= nil then
username = msg.from.username
end
local name = user_print_name(msg.from)
--Send this to that chat
send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." Globally banned (spamming)")
local log_group = 1 --set log group caht id
--send it to log group
send_large_msg("chat#id"..log_group, "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)")
end
end
kicktable[user] = true
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function cron()
--clear that table on the top of the plugins
kicktable = {}
end
return {
patterns = {},
cron = cron,
pre_process = pre_process
}
end
| gpl-2.0 |
emadni/telelordteamgimi | plugins/anti_spam.lua | 923 | 3750 |
--An empty table for solving multiple kicking problem(thanks to @topkecleon )
kicktable = {}
do
local TIME_CHECK = 2 -- seconds
local data = load_data(_config.moderation.data)
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
return msg
end
if msg.from.id == our_id then
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
--Load moderation data
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
--Check if flood is one or off
if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then
return msg
end
end
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
local data = load_data(_config.moderation.data)
local NUM_MSG_MAX = 5
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])--Obtain group flood sensitivity
end
end
local max_msg = NUM_MSG_MAX * 1
if msgs > max_msg then
local user = msg.from.id
-- Ignore mods,owner and admins
if is_momod(msg) then
return msg
end
local chat = msg.to.id
local user = msg.from.id
-- Return end if user was kicked before
if kicktable[user] == true then
return
end
kick_user(user, chat)
local name = user_print_name(msg.from)
--save it to log file
savelog(msg.to.id, name.." ["..msg.from.id.."] spammed and kicked ! ")
-- incr it on redis
local gbanspam = 'gban:spam'..msg.from.id
redis:incr(gbanspam)
local gbanspam = 'gban:spam'..msg.from.id
local gbanspamonredis = redis:get(gbanspam)
--Check if user has spammed is group more than 4 times
if gbanspamonredis then
if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then
--Global ban that user
banall_user(msg.from.id)
local gbanspam = 'gban:spam'..msg.from.id
--reset the counter
redis:set(gbanspam, 0)
local username = " "
if msg.from.username ~= nil then
username = msg.from.username
end
local name = user_print_name(msg.from)
--Send this to that chat
send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." Globally banned (spamming)")
local log_group = 1 --set log group caht id
--send it to log group
send_large_msg("chat#id"..log_group, "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)")
end
end
kicktable[user] = true
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function cron()
--clear that table on the top of the plugins
kicktable = {}
end
return {
patterns = {},
cron = cron,
pre_process = pre_process
}
end
| gpl-2.0 |
DarkRainX/ufoai | base/ufos/ui/base.buildinginfo.lua | 2 | 4808 | --!usr/bin/lua
--[[
-- @file
-- @brief Build the building information panel
--]]
--[[
Copyright (C) 2002-2020 UFO: Alien Invasion.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
--]]
--header guard
if (base.build_buildinginfo == nil) then
require("ufox.lua")
require("base.section.lua")
base.build_buildinginfo = function (root_node, base_idx, building_id)
local building_info = root_node:child("building_info")
if (building_info ~= nil) then
-- delete (and later re-build) section
building_info:delete_node()
end
building_info = ufox.build({
name = "building_info",
class = "panel",
size = {root_node:width(), 200},
{
name = "picture",
class = "image",
source = "",
keepratio = true,
pos = {0, 0},
size = {root_node:width(), 90},
contentalign = ufo.ALIGN_CC,
ghost = true,
},
{
name = "building_name",
class = "string",
pos = {5, 100},
size = {root_node:width(), 20},
text = "",
contentalign = ufo.ALIGN_CC,
},
{
name = "cost_label",
class = "string",
pos = {5, 120},
size = {150, 20},
text = "_Costs",
contentalign = ufo.ALIGN_CL,
},
{
name = "cost_string",
class = "string",
pos = {155, 120},
size = {134, 20},
text = "",
contentalign = ufo.ALIGN_CR,
},
{
name = "runningcost_label",
class = "string",
pos = {5, 140},
size = {150, 20},
text = "_Running costs",
contentalign = ufo.ALIGN_CL,
},
{
name = "runningcost_string",
class = "string",
pos = {155, 140},
size = {134, 20},
text = "",
contentalign = ufo.ALIGN_CR,
},
{
name = "buildtime_label",
class = "string",
pos = {5, 160},
size = {150, 20},
text = "_Build time",
contentalign = ufo.ALIGN_CL,
},
{
name = "buildtime_string",
class = "string",
pos = {155, 160},
size = {134, 20},
text = "",
contentalign = ufo.ALIGN_CR,
},
{
name = "depends_label",
class = "string",
pos = {5, 180},
size = {150, 20},
text = "_Depends on",
contentalign = ufo.ALIGN_CL,
},
{
name = "depends_string",
class = "string",
pos = {155, 180},
size = {134, 20},
text = "",
contentalign = ufo.ALIGN_CR,
},
{
name = "show_buildinginfo",
class = "confunc",
--[[
- @brief Passes building information
- @param building_id scripted building id
- @param building_name building name
- @param building_image
- @param fixcost cost to built this building
- @param runningcost monthly maintenance cost of the building
- @param buildtime number of days building this building takes
- @param buildtime_string translated string of buildtime
- @param depends name of the building this one needs in order to work
--]]
on_click = function (sender, building_id, building_name, building_image, fixcost, runningcost, buildtime, buildtime_string, depends)
local panel = sender:parent()
panel:child("picture"):set_source(building_image)
panel:child("building_name"):set_text(string.format("_%s", building_name))
if (tonumber(fixcost) > 0) then
panel:child("cost_string"):set_text(string.format("%d c", fixcost))
else
panel:child("cost_label"):delete_node()
panel:child("cost_string"):delete_node()
end
if (tonumber(runningcost) > 0) then
panel:child("runningcost_string"):set_text(string.format("%d c", runningcost))
else
panel:child("runningcost_label"):delete_node()
panel:child("runningcost_string"):delete_node()
end
if (tonumber(buildtime) > 0) then
panel:child("buildtime_string"):set_text(buildtime_string)
else
panel:child("buildtime_label"):delete_node()
panel:child("buildtime_string"):delete_node()
end
if (depends ~= nil and depends ~= "") then
panel:child("depends_string"):set_text(string.format("_%s", depends))
else
panel:child("depends_label"):delete_node()
panel:child("depends_string"):delete_node()
end
end,
},
}, root_node)
if (root_node.update_height ~= nil) then
root_node:update_height()
end
ufo.cmd(string.format("ui_show_buildinginfo %d %q;", tonumber(base_idx), building_id))
end
--header guard
end
| gpl-2.0 |
jshackley/darkstar | scripts/globals/items/trumpet_shell.lua | 18 | 1266 | -----------------------------------------
-- ID: 5466
-- Item: Trumpet Shell
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity -5
-- Vitality 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,5466);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, -5);
target:addMod(MOD_VIT, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, -5);
target:delMod(MOD_VIT, 4);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Windurst_Waters/npcs/Ten_of_Hearts.lua | 38 | 1045 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Ten of Hearts
-- Type: Standard NPC
-- @zone: 238
-- @pos -49.441 -5.909 226.524
--
-- Auto-Script: Requires Verification (Verfied By Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x006b);
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 |
Shahabambesik/merbot | plugins/music.lua | 1 | 2208 | local function musiclink(msg, musicid)
local value = redis:hget('music:'..msg.to.peer_id, musicid)
if not value then
return
else
value = value
send_api_msg(msg, get_receiver_api(msg), value, true, 'md')
end
end
function sectomin (Sec)
if (tonumber(Sec) == nil) or (tonumber(Sec) == 0) then
return "00:00"
else
Seconds = math.floor(tonumber(Sec))
if Seconds < 1 then Seconds = 1 end
Minutes = math.floor(Seconds / 60)
Seconds = math.floor(Seconds - (Minutes * 60))
if Seconds < 10 then
Seconds = "0"..Seconds
end
if Minutes < 10 then
Minutes = "0"..Minutes
end
return Minutes..':'..Seconds
end
end
function run(msg, matches)
if string.match(msg.text, '[\216-\219][\128-\191]') then
return send_large_msg(get_receiver(msg), 'Please use the English language. ')
end
if matches[1]:lower() == "dl" then
local value = redis:hget('music:'..msg.to.peer_id, matches[2])
if not value then
return 'Music not found.'
else
value = value
send_api_msg(msg, get_receiver_api(msg), value, true, 'md')
end
return
end
local url = http.request("http://api.gpmod.ir/music.search/?q="..URL.escape(matches[2]).."&count=30&sort=2")
local jdat = json:decode(url)
local text , time , num = ''
local hash = 'music:'..msg.to.peer_id
redis:del(hash)
if #jdat.response < 2 then return "No result found." end
for i = 2, #jdat.response do
if 900 > jdat.response[i].duration then
num = i - 1
time = sectomin(jdat.response[i].duration)
text = text..num..'- Artist: '.. jdat.response[i].artist .. ' | '..time..'\nTitle: '..jdat.response[i].title..'\n\n'
redis:hset(hash, num, 'Artist: '.. jdat.response[i].artist .. '\nTitle: '..jdat.response[i].title..' | '..time..'\n\n'.."[Download](http://GPMod.ir/dl.php?q="..jdat.response[i].owner_id.."_"..jdat.response[i].aid..')')
end
end
text = text..'\n----------------------\n*Use the following command to download*.\n\n`!dl <number>`\n\n*(example)*: `!dl 1`\n\n[LionTeam](telegram.me/lionteam)'
send_api_msg(msg, get_receiver_api(msg), text, true, 'md')
end
return {
usage = {'<code>!music [name]</code>\nmusic finder'},
patterns = {
"^[#!/]([Mm][Uu][Ss][Ii][Cc]) (.*)$",
"^[#!/]([dD][Ll]) (.*)$"
},
run = run
}
| gpl-2.0 |
kans/birgo | lib/lua/virgo-init.lua | 1 | 11418 | --[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
-- Bootstrap require system
local native = require('uv_native')
process = {
execPath = native.execpath(),
cwd = getcwd,
argv = argv
}
_G.getcwd = nil
_G.argv = nil
local Emitter = require('core').Emitter
local timer = require('timer')
local env = require('env')
local constants = require('constants')
local uv = require('uv')
local utils = require('utils')
local logging = require('logging')
local fmt = require('string').format
setmetatable(process, Emitter.meta)
function logf(level, ...)
if logging.get_level() < level then
return
end
logging.log(level, fmt(...))
end
logging.critf = function(...)
logf(logging.CRITICAL, ...)
end
logging.errorf = function(...)
logf(logging.ERROR, ...)
end
logging.warnf = function(...)
logf(logging.WARN, ...)
end
logging.infof = function(...)
logf(logging.INFO, ...)
end
logging.debugf = function(...)
logf(logging.DEBUG, ...)
end
-- Load the tty as a pair of pipes
-- But don't hold the event loop open for them
process.stdin = uv.createReadableStdioStream(0)
process.stdout = uv.createWriteableStdioStream(1)
process.stderr = uv.createWriteableStdioStream(2)
local stdout = process.stdout
-- clear some globals
-- This will break lua code written for other lua runtimes
_G.os = nil
_G.math = nil
_G.string = nil
_G.coroutine = nil
_G.jit = nil
_G.bit = nil
_G.debug = nil
_G.table = nil
_G.loadfile = nil
_G.dofile = nil
_G.print = utils.print
_G.p = utils.prettyPrint
_G.debug = utils.debug
_G.debugger = require('virgo-debugger').install(_G.io)
_G.dump_lua = require('virgo-debugger').dump_lua
_G.io = nil
process.version = VERSION
process.versions = {
luvit = VERSION,
uv = native.VERSION_MAJOR .. "." .. native.VERSION_MINOR .. "-" .. UV_VERSION,
luajit = LUAJIT_VERSION,
yajl = YAJL_VERSION,
http_parser = HTTP_VERSION,
}
_G.VERSION = nil
_G.YAJL_VERSION = nil
_G.LUAJIT_VERSION = nil
_G.UV_VERSION = nil
_G.HTTP_VERSION = nil
function process.exit(exit_code)
process:emit('exit', exit_code)
exitProcess(exit_code or 0)
end
function process:addHandlerType(name)
local code = constants[name]
if code then
native.activateSignalHandler(code)
end
end
function process:missingHandlerType(name, ...)
if name == "error" then
error(...)
elseif name == "SIGINT" or name == "SIGTERM" then
process.exit()
end
end
function process.nextTick(callback)
timer.setTimeout(0, callback)
end
-- Load libraries used in this file
-- Load libraries used in this file
local debugm = require('debug')
local native = require('uv_native')
local table = require('table')
local fs = require('fs')
local path = require('path')
local LVFS = VFS
_G.VFS = nil
-- Copy date and binding over from lua os module into luvit os module
local OLD_OS = require('os')
local OS_BINDING = require('os_binding')
package.loaded.os = OS_BINDING
package.preload.os_binding = nil
package.loaded.os_binding = nil
OS_BINDING.date = OLD_OS.date
OS_BINDING.time = OLD_OS.time
-- Ignore sigpipe and exit cleanly on SIGINT and SIGTERM
-- These shouldn't hold open the event loop
if OS_BINDING.type() ~= "win32" then
native.activateSignalHandler(constants.SIGPIPE)
native.activateSignalHandler(constants.SIGINT)
native.activateSignalHandler(constants.SIGTERM)
native.activateSignalHandler(constants.SIGUSR1)
end
-- Hide some stuff behind a metatable
local hidden = {}
setmetatable(_G, {__index=hidden})
local function hide(name)
hidden[name] = _G[name]
_G[name] = nil
end
hide("_G")
hide("exitProcess")
local vfs = LVFS.open()
local path_mapping = {}
if vfs:exists('/path_mapping.lua') then
local mapping_string = vfs:read('/path_mapping.lua')
path_mapping = loadstring(mapping_string, '/path_mapping.lua')()
end
function original_path(filepath)
local ensure_slash = path.posix:join('/', filepath)
return path_mapping[ensure_slash] or filepath
end
-- Replace print
function print(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- A nice global data dumper
function p(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
stdout:write(table.concat(arguments, "\t") .. "\n")
end
hide("printStderr")
-- Like p, but prints to stderr using blocking I/O for better debugging
function debug(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
printStderr(table.concat(arguments, "\t") .. "\n")
end
-- Add global access to the environment variables using a dynamic table
process.env = setmetatable({}, {
__pairs = function (table)
local keys = env.keys()
local index = 0
return function (...)
index = index + 1
local name = keys[index]
if name then
return name, table[name]
end
end
end,
__index = function (table, name)
return env.get(name)
end,
__newindex = function (table, name, value)
if value then
env.set(name, value, 1)
else
env.unset(name)
end
end
})
--Retrieve Process ID from native Luvit function getpid
process.pid = native.getpid()
-- This is called by all the event sources from C
-- The user can override it to hook into event sources
function eventSource(name, fn, ...)
local args = {...}
return assert(xpcall(function ()
return fn(unpack(args))
end, debugm.traceback))
end
errorMeta = {__tostring=function(table) return table.message end}
local global_meta = {__index=_G}
local function partialRealpath(filepath)
-- Do some minimal realpathing
local link
link = fs.lstatSync(filepath).is_symbolic_link and fs.readlinkSync(filepath)
while link do
filepath = path.posix:resolve(path.posix:dirname(filepath), link)
link = fs.lstatSync(filepath).is_symbolic_link and fs.readlinkSync(filepath)
end
return path.posix:normalize(filepath)
end
local function myloadfile(filepath)
if not vfs:exists(filepath) then return end
-- Not done by luvit, we don't have synlinks in the zip file.
-- filepath = partialRealpath(filepath)
if package.loaded[filepath] then
return function ()
return package.loaded[filepath]
end
end
local code = vfs:read(filepath)
-- TODO: find out why inlining assert here breaks the require test
local fn, err = loadstring(code, '@' .. original_path(filepath))
assert(fn, err)
local dirname = path.posix:dirname(filepath)
local realRequire = require
setfenv(fn, setmetatable({
__filename = filepath,
__dirname = dirname,
require = function (filepath)
return realRequire(filepath, dirname)
end,
}, global_meta))
local module = fn()
package.loaded[filepath] = module
return function() return module end
end
local function myloadlib(filepath)
if not vfs:exists(filepath) then return end
filepath = partialRealpath(filepath)
if package.loaded[filepath] then
return function ()
return package.loaded[filepath]
end
end
local name = path.posix:basename(filepath)
if name == "init.luvit" then
name = path.posix:basename(path.posix:dirname(filepath))
end
local base_name = name:sub(1, #name - 6)
package.loaded[filepath] = base_name -- Hook to allow C modules to find their path
local fn, error_message = package.loadlib(filepath, "luaopen_" .. base_name)
if fn then
local module = fn()
package.loaded[filepath] = module
return function() return module end
end
error(error_message)
end
-- tries to load a module at a specified absolute path
local function loadModule(filepath, verbose)
-- First, look for exact file match if the extension is given
local extension = path.posix:extname(filepath)
if extension == ".lua" then
return myloadfile(filepath)
end
if extension == ".luvit" then
return myloadlib(filepath)
end
-- Then, look for module/package.lua config file
if vfs:exists(filepath .. "/package.lua") then
local metadata = loadModule(filepath .. "/package.lua")()
if metadata.main then
return loadModule(path.posix:join(filepath, metadata.main))
end
end
-- Try to load as either lua script or binary extension
local fn = myloadfile(filepath .. ".lua") or myloadfile(filepath .. "/init.lua")
or myloadlib(filepath .. ".luvit") or myloadlib(filepath .. "/init.luvit")
if fn then return fn end
return "\n\tCannot find module " .. filepath
end
-- Remove the cwd based loaders, we don't want them
local builtinLoader = package.loaders[1]
package.loaders = nil
package.path = nil
package.cpath = nil
package.searchpath = nil
package.seeall = nil
package.config = nil
_G.module = nil
function require(filepath, dirname)
if not dirname then dirname = "" end
-- Absolute and relative required modules
local first = filepath:sub(1, 1)
local absolute_path
if first == "/" then
absolute_path = path.posix:normalize(filepath)
elseif first == "." then
absolute_path = path.posix:normalize(path.posix:join(dirname, filepath))
end
if absolute_path then
local loader = loadModule(absolute_path)
if type(loader) == "function" then
return loader()
else
error("Failed to find module '" .. filepath .."'")
end
end
local errors = {}
-- Builtin modules
local module = package.loaded[filepath]
if module then return module end
if filepath:find("^[a-z_]+$") then
local loader = builtinLoader(filepath)
if type(loader) == "function" then
module = loader()
package.loaded[filepath] = module
return module
else
errors[#errors + 1] = loader
end
end
-- Bundled path modules
local dir = dirname .. "/"
repeat
dir = dir:sub(1, dir:find("/[^/]*$") - 1)
local full_path = dir .. "/modules/" .. filepath
local loader = loadModule(dir .. "/modules/" .. filepath)
if type(loader) == "function" then
return loader()
else
errors[#errors + 1] = loader
end
until #dir == 0
error("Failed to find module '" .. filepath .."'" .. table.concat(errors, ""))
end
local virgo_init = {}
function virgo_init.run(name)
local mod = require(name)
mod.run()
-- Stagents/monitoring/tests/agent-protocol/handshake.hello.response.jsonart the event loop
native.run()
-- trigger exit handlers and exit cleanly
process.exit(process.exitCode or 0)
end
function gc()
collectgarbage('collect')
end
function onUSR1()
gc()
end
function onHUP()
logging.rotate()
end
-- Setup GC on USR1
process:on('SIGUSR1', onUSR1)
-- Setup HUP
process:on('SIGHUP', onHUP)
-- Setup GC
local GC_INTERVAL = 5 * 1000 -- milliseconds
local gcInterval = timer.setInterval(GC_INTERVAL, gc)
-- Unref the interval timer. We don't want it to keep the eventloop blocked
gcInterval:unref()
return virgo_init
| apache-2.0 |
jshackley/darkstar | scripts/zones/Cloister_of_Flames/mobs/Ifrit_Prime.lua | 1 | 1778 | -----------------------------------------------------
-- Area: Cloister of Flames
-- MOB: Ifrit Prime
-- Involved in Quest: Trial by Fire
-- Involved in Mission: ASA-4 Sugar Coated Directive
-----------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/status");
-----------------------------------
-- OnMobFight Action
-----------------------------------
function onMobFight(mob, target)
local mobId = mob:getID();
-- ASA-4: Astral Flow Behavior - Guaranteed to Use At Least 5 times before killable, at specified intervals.
if (mob:getBattlefield():getBcnmID() == 547 and GetMobAction(mobId) == ACTION_ATTACK) then
local astralFlows = mob:getLocalVar("astralflows");
if ((astralFlows == 0 and mob:getHPP() <= 80)
or (astralFlows == 1 and mob:getHPP() <= 60)
or (astralFlows == 2 and mob:getHPP() <= 40)
or (astralFlows == 3 and mob:getHPP() <= 20)
or (astralFlows == 4 and mob:getHPP() <= 1)) then
mob:setLocalVar("astralflows",astralFlows + 1);
mob:useMobAbility(592);
if (astralFlows >= 5) then
mob:setUnkillable(false);
end
end
end
end;
-----------------------------------
-- OnMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
-- ASA-4: Avatar is Unkillable Until Its Used Astral Flow At Least 5 times At Specified Intervals
if (mob:getBattlefield():getBcnmID() == 547) then
mob:setLocalVar("astralflows","0");
mob:setUnkillable(true);
end
end;
-----------------------------------
-- OnMobDeath Action
-----------------------------------
function onMobDeath(mob, killer, ally)
end; | gpl-3.0 |
opentibia/server | tools/genenums/enums.lua | 3 | 7174 | -------------------------------------------------------------------
-- OpenTibia - an opensource roleplaying game
----------------------------------------------------------------------
-- This program is free software; you can redistribute it and-or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software Foundation,
-- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
----------------------------------------------------------------------
BeginEnumFile("enums")
enum ("RaceType",
"RACE_NONE",
{"RACE_VENOM ", "venom"},
{"RACE_BLOOD", "blood"},
{"RACE_UNDEAD", "undead"},
{"RACE_FIRE", "fire"},
{"RACE_ENERGY", "energy"}
)
enum ("Direction",
"NORTH = 0",
"EAST = 1",
"SOUTH = 2",
"WEST = 3",
"SOUTHWEST = 4",
"SOUTHEAST = 5",
"NORTHWEST = 6",
"NORTHEAST = 7"
)
enum ({name="CombatType", bitmask=true},
{"COMBAT_NONE", "unknown", null=true},
{"COMBAT_PHYSICALDAMAGE", "physical"},
{"COMBAT_ENERGYDAMAGE", "energy"},
{"COMBAT_EARTHDAMAGE", "earth"},
{"COMBAT_FIREDAMAGE", "fire"},
{"COMBAT_SCRIPTED_HEALTH", "scriptedhealth"},
{"COMBAT_SCRIPTED_MANA", "scriptedmana"},
{"COMBAT_LIFEDRAIN", "lifedrain"},
{"COMBAT_MANADRAIN", "manadrain"},
{"COMBAT_HEALING", "healing"},
{"COMBAT_DROWNDAMAGE", "drown"},
{"COMBAT_ICEDAMAGE", "ice"},
{"COMBAT_HOLYDAMAGE", "holy"},
{"COMBAT_DEATHDAMAGE", "death"}
)
enum ("BlockType",
"BLOCK_NONE",
"BLOCK_DEFENSE",
"BLOCK_ARMOR",
"BLOCK_IMMUNITY"
)
enum ("ViolationAction",
"ACTION_NOTATION = 0",
"ACTION_NAMEREPORT = 1",
"ACTION_BANISHMENT = 2",
"ACTION_BANREPORT = 3",
"ACTION_BANFINAL = 4",
"ACTION_BANREPORTFINAL = 5",
"ACTION_STATEMENT = 6",
"ACTION_DELETION = 7"
)
enum ("SkillType",
{"SKILL_FIST = 0", "fist fighting", "fist"},
{"SKILL_CLUB = 1", "club fighting", "club"},
{"SKILL_SWORD = 2", "sword fighting", "sword"},
{"SKILL_AXE = 3", "axe fighting", "axe"},
{"SKILL_DIST = 4", "distance fighting", "distance"},
{"SKILL_SHIELD = 5", "shielding"},
{"SKILL_FISH = 6", "fishing"}
)
enum ("LevelType",
"LEVEL_FIST = SKILL_FIST",
"LEVEL_CLUB = SKILL_CLUB",
"LEVEL_SWORD = SKILL_SWORD",
"LEVEL_AXE = SKILL_AXE",
"LEVEL_DIST = SKILL_DIST",
"LEVEL_SHIELD = SKILL_SHIELD",
"LEVEL_FISH = SKILL_FISH",
-- Meta-skills, used by some functions
"LEVEL_MAGIC = 7",
"LEVEL_EXPERIENCE = 8"
)
enum ("PlayerStatType",
"STAT_MAXHITPOINTS",
"STAT_MAXMANAPOINTS",
"STAT_SOULPOINTS",
"STAT_MAGICPOINTS"
)
enum ("LossType",
"LOSS_EXPERIENCE = 0",
"LOSS_MANASPENT = 1",
"LOSS_SKILLTRIES = 2",
"LOSS_ITEMS = 3",
"LOSS_CONTAINERS = 4"
)
enum ("PlayerSex",
{"SEX_FEMALE = 0", "female"},
{"SEX_MALE = 1", "male"},
{"SEX_FEMALE_GAMEMASTER = 2", "femalegm"},
{"SEX_MALE_GAMEMASTER = 3", "malegm"},
{"SEX_FEMALE_MANAGER = 4", "femalecm"},
{"SEX_MALE_MANAGER = 5", "malecm"},
{"SEX_FEMALE_GOD = 6", "femalegod"},
{"SEX_MALE_GOD = 7", "malegod"}
)
enum ("ChaseMode",
"CHASEMODE_STANDSTILL",
"CHASEMODE_FOLLOW"
)
enum ("FightMode",
"FIGHTMODE_ATTACK",
"FIGHTMODE_BALANCED",
"FIGHTMODE_DEFENSE"
)
enum ("TradeState",
"TRADE_NONE",
"TRADE_INITIATED",
"TRADE_ACCEPT",
"TRADE_ACKNOWLEDGE",
"TRADE_TRANSFER"
)
enum ("SlotType",
"SLOT_WHEREEVER = 0",
"SLOT_HEAD = 1",
"SLOT_NECKLACE = 2",
"SLOT_BACKPACK = 3",
"SLOT_ARMOR = 4",
"SLOT_RIGHT = 5",
"SLOT_LEFT = 6",
"SLOT_LEGS = 7",
"SLOT_FEET = 8",
"SLOT_RING = 9",
"SLOT_AMMO = 10",
-- Special slot, covers two, not a real slot
"SLOT_HAND = 11",
"SLOT_TWO_HAND = SLOT_HAND",
-- Usual slot iteration begins on HEAD and ends on AMMO slot,
-- Note that iteration over these are INCLUSIVE, so use <=, not !=
"SLOT_FIRST = SLOT_HEAD",
"SLOT_LAST = SLOT_HAND"
)
enum ({name="SlotPosition", bitmask=true},
{"SLOTPOSITION_NONE", "none", null=true},
{"SLOTPOSITION_HEAD = 1", "head"},
{"SLOTPOSITION_NECKLACE = 2", "necklace"},
{"SLOTPOSITION_BACKPACK = 4", "backpack"},
{"SLOTPOSITION_ARMOR = 8", "armor"},
{"SLOTPOSITION_RIGHT = 16", "right-hand"},
{"SLOTPOSITION_LEFT = 32", "left-hand"},
{"SLOTPOSITION_LEGS = 64", "legs"},
{"SLOTPOSITION_FEET = 128", "feet"},
{"SLOTPOSITION_RING = 256", "ring"},
{"SLOTPOSITION_AMMO = 512", "ammo"},
{"SLOTPOSITION_DEPOT = 1024", "depot"},
{"SLOTPOSITION_TWO_HAND = 2048", "two-hand"},
{"SLOTPOSITION_HAND = SLOTPOSITION_LEFT | SLOTPOSITION_RIGHT", "hand"},
{"SLOTPOSITION_WHEREEVER", "any", "anywhere", all = true}
)
enum ({name="TileProp", bitmask=true},
{"TILEPROP_NONE", null=true},
{"TILEPROP_PROTECTIONZONE"},
{"TILEPROP_DEPRECATED"},
{"TILEPROP_NOPVPZONE"},
{"TILEPROP_NOLOGOUT"},
{"TILEPROP_PVPZONE"},
{"TILEPROP_REFRESH"},
--internal usage
{"TILEPROP_POSITIONCHANGE"},
{"TILEPROP_FLOORCHANGE"},
{"TILEPROP_FLOORCHANGE_DOWN"},
{"TILEPROP_FLOORCHANGE_NORTH"},
{"TILEPROP_FLOORCHANGE_SOUTH"},
{"TILEPROP_FLOORCHANGE_EAST"},
{"TILEPROP_FLOORCHANGE_WEST"},
{"TILEPROP_BLOCKSOLID"},
{"TILEPROP_BLOCKPATH"},
{"TILEPROP_VERTICAL"},
{"TILEPROP_HORIZONTAL"},
{"TILEPROP_BLOCKPROJECTILE"},
{"TILEPROP_BLOCKSOLIDNOTMOVEABLE"},
{"TILEPROP_BLOCKPATHNOTMOVEABLE"},
{"TILEPROP_BLOCKPATHNOTFIELD"},
{"TILEPROP_HOUSE_TILE"},
{"TILEPROP_DYNAMIC_TILE"},
{"TILEPROP_INDEXED_TILE"}
)
enum ("ZoneType",
"ZONE_PROTECTION",
"ZONE_NOPVP",
"ZONE_PVP",
"ZONE_NOLOGOUT",
"ZONE_NORMAL"
)
enum ("WorldType",
"WORLD_TYPE_NOPVP",
"WORLD_TYPE_PVP",
"WORLD_TYPE_PVPE"
)
enum ("GameState",
"GAME_STATE_STARTUP",
"GAME_STATE_INIT",
"GAME_STATE_NORMAL",
"GAME_STATE_CLOSED",
"GAME_STATE_SHUTDOWN",
"GAME_STATE_CLOSING"
)
enum ("ServerSaveType",
"SERVER_SAVE_FULL",
"SERVER_SAVE_BINARY",
"SERVER_SAVE_RELATIONAL",
"SERVER_SAVE_NORMAL",
"SERVER_SAVE_SHALLOW"
)
enum ("Script::ListenerType",
-- Not tied to a creature
"ON_SAY_LISTENER",
"ON_USE_ITEM_LISTENER",
"ON_USE_WEAPON_LISTENER",
"ON_EQUIP_ITEM_LISTENER",
"ON_MOVE_CREATURE_LISTENER",
"ON_MOVE_ITEM_LISTENER",
"ON_OPEN_CHANNEL_LISTENER",
"ON_CLOSE_CHANNEL_LISTENER",
"ON_ACCOUNT_LOGIN_LISTENER",
"ON_LOGIN_LISTENER",
"ON_LOGOUT_LISTENER",
"ON_CHANGE_OUTFIT_LISTENER",
"ON_LOOK_LISTENER",
"ON_LOOKED_AT_LISTENER",
"ON_TURN_LISTENER",
"ON_LOAD_LISTENER",
"ON_UNLOAD_LISTENER",
"ON_SPAWN_LISTENER",
"ON_KILLED_LISTENER",
"ON_DEATH_BY_LISTENER",
"ON_KILL_LISTENER",
"ON_DEATH_LISTENER",
"ON_ADVANCE_LISTENER",
"ON_SHOP_PURCHASE_LISTENER",
"ON_SHOP_SELL_LISTENER",
"ON_SHOP_CLOSE_LISTENER",
"ON_TRADE_BEGIN_LISTENER",
"ON_TRADE_END_LISTENER",
"ON_ATTACK_LISTENER",
"ON_DAMAGE_LISTENER",
"ON_CONDITION_LISTENER",
"ON_ACTOR_LOAD_SPELL_LISTENER",
"ON_ACTOR_CAST_SPELL_LISTENER",
-- Creature specific only
"ON_THINK_LISTENER",
"ON_HEAR_LISTENER",
"ON_SPOT_CREATURE_LISTENER",
"ON_LOSE_CREATURE_LISTENER"
)
EndEnumFile()
| gpl-2.0 |
jshackley/darkstar | scripts/globals/items/red_curry_bun_+1.lua | 14 | 2011 | -----------------------------------------
-- ID: 5765
-- Item: red_curry_bun_+1
-- Food Effect: 30 Min, All Races
-----------------------------------------
-- Health 35
-- Strength 7
-- Agility 3
-- Attack % 25 (cap 150)
-- Ranged Atk % 25 (cap 150)
-- Demon Killer 5
-- HP recovered when healing +6
-- MP recovered when healing +3
-----------------------------------------
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,5765);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 35);
target:addMod(MOD_STR, 7);
target:addMod(MOD_AGI, 3);
target:addMod(MOD_FOOD_ATTP, 25);
target:addMod(MOD_FOOD_ATT_CAP, 150);
target:addMod(MOD_FOOD_RATTP, 25);
target:addMod(MOD_FOOD_RATT_CAP, 150);
target:addMod(MOD_DEMON_KILLER, 5);
target:addMod(MOD_HPHEAL, 6);
target:addMod(MOD_MPHEAL, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 35);
target:delMod(MOD_STR, 7);
target:delMod(MOD_AGI, 3);
target:delMod(MOD_FOOD_ATTP, 25);
target:delMod(MOD_FOOD_ATT_CAP, 150);
target:delMod(MOD_FOOD_RATTP, 25);
target:delMod(MOD_FOOD_RATT_CAP, 150);
target:delMod(MOD_DEMON_KILLER, 6);
target:delMod(MOD_HPHEAL, 6);
target:delMod(MOD_MPHEAL, 3);
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Alzadaal_Undersea_Ruins/npcs/qm4.lua | 30 | 1358 | -----------------------------------
-- Area: Alzadaal Undersea Ruins
-- NPC: ??? (Spawn Wulgaru(ZNM T2))
-- @pos -22 -4 204 72
-----------------------------------
package.loaded["scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Alzadaal_Undersea_Ruins/TextIDs");
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local mobID = 17072179;
if (trade:hasItemQty(2597,1) and trade:getItemCount() == 1) then -- Trade Opalus Gem
if (GetMobAction(mobID) == ACTION_NONE) then
player:tradeComplete();
SpawnMob(mobID):updateClaim(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_HAPPENS);
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 |
jshackley/darkstar | scripts/commands/checkmission.lua | 27 | 3863 | ---------------------------------------------------------------------------------------------------
-- func: @checkmission <Log ID> <Player>
-- desc: Prints current MissionID for the given LogID and target Player to the in game chatlog
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "is"
};
function onTrigger(player,logId,target)
if (logId == nil) then
player:PrintToPlayer( "You must enter a valid LogID!" );
player:PrintToPlayer( "@checkmission <Log ID> <Player>" );
return;
end
if (target == nil) then
target = player:getName();
end
local targ = GetPlayerByName(target);
local Log = targ:getCurrentMission(logId)
-- Todo: loop through missionIDs and output mission name, not just a number.
-- Hopefully can use same method to replace this annoying pile of elseif's.
if (targ ~= nil) then
if (logId == 12) then -- Seekers of Adoulin
player:PrintToPlayer( string.format( "Current Seekers of Adoulin Mission ID is: '%s' !", Log ) );
elseif (logId == 11) then -- A Shantotto Ascension
player:PrintToPlayer( string.format( "Current Shantotto Ascension Mission ID is: '%s' !", Log ) );
elseif (logId == 10) then -- A moogle Kupo d'Etat
player:PrintToPlayer( string.format( "Current moogle Kupo dEtat Mission ID is: '%s' !", Log ) );
elseif (logId == 9) then -- A Crystalline Prophecy
player:PrintToPlayer( string.format( "Current Crystalline Prophecy Mission ID is: '%s' !", Log ) );
elseif (logId == 8) then -- Campaign
player:PrintToPlayer( string.format( "Current Campaign OPs ID is: '%s' !", Log ) );
elseif (logId == 7) then -- Assault
player:PrintToPlayer( string.format( "Current Assault Mission ID is: '%s' !", Log ) );
elseif (logId == 6) then -- Chains of Promathia
player:PrintToPlayer( string.format( "Current Chains of Promathia Mission ID is: '%s' !", Log ) );
elseif (logId == 5) then -- Wings of the Goddess
player:PrintToPlayer( string.format( "Current Wings of the Goddess Mission ID is: '%s' !", Log ) );
elseif (logId == 4) then -- Treasures of Aht Urgan
player:PrintToPlayer( string.format( "Current Treasures of Aht Urgan Mission ID is: '%s' !", Log ) );
elseif (logId == 3) then -- Rise of the Zilart
if (Log == 255) then
player:PrintToPlayer( "No current Rise of the Zilart mission." );
else
player:PrintToPlayer( string.format( "Current Rise of the Zilart Mission ID is: '%s' !", Log ) );
end
elseif (logId == 2) then -- Windurst
if (Log == 255) then
player:PrintToPlayer( "No current Windurst mission." );
else
player:PrintToPlayer( string.format( "Current Windurst Mission ID is: '%s' !", Log ) );
end
elseif (logId == 1) then -- Bastok
if (Log == 255) then
player:PrintToPlayer( "No current Bastok mission." );
else
player:PrintToPlayer( string.format( "Current Bastok Mission ID is: '%s' !", Log ) );
end
elseif (logId == 0) then -- San d'Orea
if (Log == 255) then
player:PrintToPlayer( "No current San d'Orea mission." );
else
player:PrintToPlayer( string.format( "Current San dOrea Mission ID is: '%s' !", Log ) );
end
else -- Everything not valid or not currently handled
player:PrintToPlayer("Invalid or unsupported LogID. The LogID must be 0-12.");
end
end
end | gpl-3.0 |
jshackley/darkstar | scripts/zones/Aht_Urhgan_Whitegate/TextIDs.lua | 15 | 4950 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 218; -- You cannot obtain the item. Come back after sorting your inventory.?Prompt?
ITEM_CANNOT_BE_OBTAINEDX = 220; -- You cannot obtain the ?Possible Special Code: 01??Possible Special Code: 05?#?BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?. Try trading again after sorting your inventory.?Prompt?
ITEM_OBTAINED = 221; -- Obtained: <item>
ITEM_OBTAINEDX = 230; -- You obtain ?Numeric Parameter 1? ?Possible Special Code: 01??Speaker Name?)??BAD CHAR: 80??BAD CHAR: 80??BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?!?Prompt?
GIL_OBTAINED = 222; -- Obtained <number> gil
KEYITEM_OBTAINED = 224; -- Obtained key item: <keyitem>
NOT_HAVE_ENOUGH_GIL = 226; -- You do not have enough gil
FISHING_MESSAGE_OFFSET = 882; -- You can't fish here
HOMEPOINT_SET = 1354; -- Home point set!
IMAGE_SUPPORT = 1395; -- Your ?Multiple Choice (Parameter 1)?[fishing/woodworking/smithing/goldsmithing/clothcraft/leatherworking/bonecraft/alchemy/cooking] skills went up ?Multiple Choice (Parameter 2)?[a little/ever so slightly/ever so slightly].?Prompt?
-- Conquest system
SANCTION = 9789; -- You have received the Empire's Sanction.
-- Quest dialogs
ZASSHAL_DIALOG = 10983; -- 'ang about. Looks like the permit you got was the last one I 'ad, so it might take me a bit o' time to scrounge up some more. 'ere, don't gimme that look. I'll be restocked before you know it.
MUSHAYRA_DIALOG = 4952; -- Sorry for all the trouble. Please ignore Hadahda the next time he asks you to do something.
HADAHDA_DIALOG = 4903; -- Hey, think you could help me out?
-- Other Dialogs
ITEM_DELIVERY_DIALOG = 9339; -- You have something you want delivered?
RUNIC_PORTAL = 4572; -- You cannot use the runic portal without the Empire's authorization.
IMAGE_SUPPORT_ACTIVE = 1393; -- You have to wait a bit longer before asking for synthesis image support again.
-- Shop Texts
UGRIHD_PURCHASE_DIALOGUE = 4633; -- Salaheem's Sentinels values your contribution to the success of the company. Please come again!
GAVRIE_SHOP_DIALOG = 9253; -- Remember to take your medicine in small doses... Sometimes you can get a little too much of a good thing!
MALFUD_SHOP_DIALOG = 9254; -- Welcome, welcome! Flavor your meals with Malfud's ingredients!
RUBAHAH_SHOP_DIALOG = 9255; -- Flour! Flooour! Corn! Rice and beans! Get your rice and beans here! If you're looking for grain, you've come to the right place!
MULNITH_SHOP_DIALOG = 9256; -- Drawn in by my shop's irresistible aroma, were you? How would you like some of the Near East's famous skewers to enjoy during your journeys?
SALUHWA_SHOP_DIALOG = 9257; -- Looking for undentable shields? This shop's got the best of 'em! These are absolute must-haves for a mercenary's dangerous work!
DWAGO_SHOP_DIALOG = 9258; -- Buy your goods here...or you'll regret it!
KULHAMARIYO_SHOP_DIALOG = 9259; -- Some fish to savorrr while you enjoy the sights of Aht Urhgan?
KHAFJHIFANM_SHOP_DIALOG = 9260; -- How about a souvenir for back home? There's nothing like dried dates to remind you of good times in Al Zahbi!
HAGAKOFF_SHOP_DIALOG = 9261; -- Welcome! Fill all your destructive needs with my superb weaponry! No good mercenary goes without a good weapon!
BAJAHB_SHOP_DIALOG = 9262; -- Good day! If you want to live long, you'll buy your armor here.
MAZWEEN_SHOP_DIALOG = 9263; -- Magic scrolls! Get your magic scrolls here!
FAYEEWAH_SHOP_DIALOG = 9264; -- Why not sit back a spell and enjoy the rich aroma and taste of a cup of chai?
YAFAAF_SHOP_DIALOG = 9265; -- There's nothing like the mature taste and luxurious aroma of coffee... Would you like a cup
WAHNID_SHOP_DIALOG = 9266; -- All the fishing gear you'll ever need, here in one place!
WAHRAGA_SHOP_DIALOG = 9267; -- Welcome to the Alchemists' Guild.
-- Automaton
AUTOMATON_RENAME = 5818; -- Your automaton has a new name.
AUTOMATON_VALOREDGE_UNLOCK = 9577; -- You obtain the Valoredge X-900 head and frame!
AUTOMATON_SHARPSHOT_UNLOCK = 9582; -- You obtain the Sharpshot Z-500 head and frame!
AUTOMATON_STORMWAKER_UNLOCK = 9587; -- You obtain the Stormwaker Y-700 head and frame!
AUTOMATON_SOULSOOTHER_UNLOCK = 9619; -- You obtain the Soulsoother C-1000 head!
AUTOMATON_SPIRITREAVER_UNLOCK = 9620; -- You obtain the Spiritreaver M-400 head!
AUTOMATON_ATTACHMENT_UNLOCK = 9636; -- You can now equip your automaton with
-- Assault
RYTAAL_MISSION_COMPLETE = 5640; -- Congratulations. You have been awarded Assault Points for the successful completion of your mission.
RYTAAL_MISSION_FAILED = 5641; -- Your mission was not successful; however, the Empire recognizes your contribution and has awarded you Assault Points.
-- Porter Moogle
RETRIEVE_DIALOG_ID = 13502; -- You retrieve a <item> from the porter moogle's care.
| gpl-3.0 |
JoMiro/arcemu | src/scripts/lua/LuaBridge/Stable Scripts/Outland/Auchenai Crypts/BOSS_AuchenaiCrypts_Maladaar.lua | 30 | 1080 | function Maladaar_HealthCheck(Unit)
if Unit:GetHealthPct() < 25 and Didthat == 0 then
Unit:SpawnCreature(18478, 57.4, -390.8, 26.6, 0, 18, 36000000);
Didthat = 1
else
end
end
function Maladaar_SoulSteal(Unit, event, miscunit, misc)
print "Maladaar SoulSteal"
Unit:FullCastSpellOnTarget(36778,Unit:GetRandomPlayer())
Unit:SendChatMessage(11, 0, "I will steal your life...")
end
function Maladaar_Ribbon(Unit, event, miscunit, misc)
print "Maladaar Ribbon"
Unit:FullCastSpellOnTarget(32422,Unit:GetRandomPlayer())
Unit:SendChatMessage(11, 0, "Let's do a good move...")
end
function Maladaar_Fear(Unit, event, miscunit, misc)
print "Maladaar Fear"
Unit:FullCastSpellOnTarget(40453,Unit:GetClosestPlayer())
Unit:SendChatMessage(11, 0, "Let's fear you guys...")
end
function Maladaar(unit, event, miscunit, misc)
print "Maladaar"
unit:RegisterEvent("Maladaar_HealthCheck",1000,1)
unit:RegisterEvent("Maladaar_SoulSteal",8000,0)
unit:RegisterEvent("Maladaar_Ribbon",13000,0)
unit:RegisterEvent("Maladaar_Fear",21000,0)
end
RegisterUnitEvent(18373,1,"Maladaar") | agpl-3.0 |
jshackley/darkstar | scripts/zones/Aydeewa_Subterrane/npcs/qm1.lua | 30 | 1345 | -----------------------------------
-- Area: Aydeewa Subterrane
-- NPC: ??? (Spawn Nosferatu(ZNM T3))
-- @pos -199 8 -62 68
-----------------------------------
package.loaded["scripts/zones/Aydeewa_Subterrane/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aydeewa_Subterrane/TextIDs");
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local mobID = 17056157;
if (trade:hasItemQty(2584,1) and trade:getItemCount() == 1) then -- Trade Pure Blood
if (GetMobAction(mobID) == ACTION_NONE) then
player:tradeComplete();
SpawnMob(mobID):updateClaim(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_HAPPENS);
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 |
msburgess3200/PERP | gamemodes/perp/entities/effects/snow_blizzard/init.lua | 1 | 2319 | /////////////////////////////////////////
// © 2010-2020 D3luX - D3luX-Gaming //
// All rights reserved //
/////////////////////////////////////////
// This material may not be //
// reproduced, displayed, //
// modified or distributed //
// without the express prior //
// written permission of the //
// the copyright holder. //
// D3luX-Gaming.com //
/////////////////////////////////////////
function EFFECT:Init ( data )
self.time = CurTime() + 1;
end
local function snowCollide ( particle, hitPos )
if (GAMEMODE.SnowOnGround) then
particle:SetDieTime(0);
else
particle:SetStartAlpha(255);
particle:SetEndAlpha(0);
end
end
function EFFECT:Emit ( )
local Filter = LocalPlayer();
local PredictSpeed = LocalPlayer():GetVelocity();
if LocalPlayer():InVehicle() then
Filter = {LocalPlayer(), LocalPlayer():GetVehicle()}
PredictSpeed = LocalPlayer():GetVehicle():GetVelocity()
end
if math.Round(PredictSpeed:Length() / 17.6) > 20 then return false; end
//local PredictSpeed = PredictSpeed;
PredictSpeed = Vector(PredictSpeed.x, PredictSpeed.y, 0);
local SpawnPos = GAMEMODE.GetWeatherSpawnPos(PredictSpeed, Filter);
for i = 0, 1200 do
local a = math.random(9999)
local b = math.random(1,180)
local dist = math.random(256,1024)
local X = math.sin(b) * math.sin(a) * dist
local Y = math.sin(b) * math.cos(a) * dist
local offset = Vector(X,Y,0)
local spawnpos = SpawnPos + offset;
local velocity = Vector(math.random(0, 40), math.random(0, 40), math.random(-300, -100));
spawnpos = spawnpos + Vector(velocity.x, velocity.y, 0);
if (GetVectorTraceUp(spawnpos).HitSky) then
local particle = GLOBAL_EMITTER:Add("particle/snow", spawnpos)
if (particle) then
particle:SetVelocity(velocity);
particle:SetLifeTime(0);
particle:SetDieTime(10);
particle:SetStartAlpha(100);
particle:SetEndAlpha(255);
particle:SetStartSize(2);
particle:SetEndSize(2);
particle:SetAirResistance(0);
particle:SetCollide(true);
particle:SetColor(200, 200, 200, 255)
particle:SetCollideCallback(snowCollide);
end
end
end
end
function EFFECT:Think ( )
if (self.time > CurTime()) then
self:Emit();
else
return false;
end
end
function EFFECT:Render ( )
end | mit |
FFXIOrgins/FFXIOrgins | scripts/zones/Ifrits_Cauldron/npcs/qm2.lua | 9 | 1416 | -----------------------------------
-- Area: Ifrit's Cauldron
-- NPC: qm2 (???)
-- Notes: Used to spawn Bomb Queen
-- @pos 18 20 -104 205
-----------------------------------
package.loaded["scripts/zones/Ifrits_Cauldron/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Ifrits_Cauldron/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Trade 3 pinches of Bomb Queen Ash and a Bomb Queen Core and a verification if the nm is already spawned
if(GetMobAction(17617158) == 0 and trade:hasItemQty(1187,3) and trade:hasItemQty(1186,1) and trade:getItemCount() == 4) then
player:tradeComplete();
SpawnMob(17617158,900):updateEnmity(player); -- Spawn Bomb Queen
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);
end; | gpl-3.0 |
anhhung1303/NyuFX | include/0_Extensions.lua | 2 | 30194 | -- BASE
function pack(...)
return arg
end
-- CONVERT
convert = {}
function convert.a_to_ass(a)
if type(a) ~= "number" then
error("number expected", 2)
elseif a < 0 or a > 255 then
return nil
end
return string.format("&H%02x&", 255-a)
end
function convert.ass_to_a(str)
if type(str) ~= "string" then
error("string expected", 2)
end
local a = str:match("&H(%x%x)&")
if not a then
return nil
else
return 255-tonumber(a, 16)
end
end
function convert.rgb_to_ass(r,g,b)
if type(r) ~= "number" or type(g) ~= "number" or type(b) ~= "number" then
error("number, number and number expected", 2)
elseif r < 0 or r > 255 or g < 0 or g > 255 or b < 0 or b > 255 then
return nil
end
return string.format("&H%02x%02x%02x&", b, g, r)
end
function convert.ass_to_rgb(str)
if type(str) ~= "string" then
error("string expected", 2)
end
local b, g, r = str:match("&H(%x%x)(%x%x)(%x%x)&")
if not (b and g and r) then
return nil
else
return tonumber(r, 16), tonumber(g, 16), tonumber(b, 16)
end
end
function convert.shape_to_pixels(shape)
-- Argument check
if type(shape) ~= "string" then
error("string expected", 2)
end
-- Result data
local pixel_palette
local shift_x, shift_y
-- Safe execution
local success = pcall(function()
-- Graphic context
local ctx = tgdi.create_context()
-- Shift shape in valid bitmap section (shifts are 8-fold = subpixel save)
local min_x, min_y
shape:gsub("(%-?%d+)%s+(%-?%d+)", function(x, y)
min_x = min_x and math.min(min_x, x) or x
min_y = min_y and math.min(min_y, y) or y
end)
shift_x, shift_y = min_x >= 0 and min_x % 8 - min_x or 8-(-min_x % 8) - min_x, min_y >= 0 and min_y % 8 - min_y or 8-(-min_y % 8) - min_y
shape = shape:gsub("(%-?%d+)%s+(%-?%d+)", function(x, y)
return string.format("%d %d", x + shift_x, y + shift_y)
end)
-- Get pixels
pixel_palette = ctx:add_path(shape):get_pixels(true)
end)
if not success then
error("invalid shape", 2)
end
-- Convert pixel palette to pixel table with right-shifted positions and return
local pixels, pixels_n = {}, 0
shift_x, shift_y = shift_x / -8, shift_y / -8
for pi, alpha in ipairs(pixel_palette) do
if alpha > 0 then
pixels_n = pixels_n + 1
pixels[pixels_n] = {a = alpha, x = (pi-1) % pixel_palette.width + shift_x, y = math.floor((pi-1) / pixel_palette.width) + shift_y}
end
end
return pixels
end
function convert.text_to_shape(text, style)
-- Flat arguments check
if type(text) ~= "string" or type(style) ~= "table" then
error("string and style table expected", 2)
end
-- Result data
local shape
-- Safe execution
local success = pcall(function()
-- Graphic context
local ctx = tgdi.create_context()
-- Text with spacing
if style.spacing > 0 then
local shape_collection, shape_collection_n = table.create(text:ulen(),0), 0
local current_x = 0
for uchar_i, uchar in text:uchars() do
shape = ctx:add_path(uchar, style.fontname, style.fontsize * 64, style.bold, style.italic, style.underline, style.strikeout, style.encoding):get_path()
ctx:abort_path()
shape = shape:gsub("(%-?%d+)%s+(%-?%d+)", function(x, y)
return string.format("%d %d", x + current_x, y)
end)
shape_collection_n = shape_collection_n + 1
shape_collection[shape_collection_n] = shape
current_x = current_x + ctx:text_extents(uchar, style.fontname, style.fontsize * 64, style.bold, style.italic, style.underline, style.strikeout, style.encoding) + style.spacing * 64
end
shape = table.concat(shape_collection, " ")
-- Text without spacing
else
shape = ctx:add_path(text, style.fontname, style.fontsize * 64, style.bold, style.italic, style.underline, style.strikeout, style.encoding):get_path()
end
-- Scale correctly
local scale_x, scale_y = style.scale_x / 100 / 8, style.scale_y / 100 / 8
shape = shape:gsub("(%-?%d+)%s+(%-?%d+)", function(x, y)
return string.format("%d %d", x * scale_x, y * scale_y)
end)
end)
if not success then
error("invalid text or style table", 2)
end
return shape
end
function convert.text_to_pixels(text, style, off_x, off_y)
-- Flat arguments check
if type(text) ~= "string" or type(style) ~= "table" or
not(
(off_x == nil and off_y == nil) or
(type(off_x) == "number" and type(off_y) == "number")
) then
error("string, style table and optional number and number expected", 2)
elseif off_x and (off_x < 0 or off_x >= 1 or off_y < 0 or off_y >= 1) then
error("offset has to be in range 0<=x<1", 2)
end
-- Result data
local pixels
-- Safe execution
local success = pcall(function()
if not text:find("[^%s]") then
pixels = {}
elseif off_x and (off_x > 0 or off_y > 0) then
off_x, off_y = math.floor(off_x * 8), math.floor(off_y * 8)
pixels = convert.shape_to_pixels(
convert.text_to_shape(text, style):gsub("(%-?%d+)%s+(%-?%d+)", function(x, y)
return string.format("%d %d", x+off_x, y+off_y)
end)
)
else
pixels = convert.shape_to_pixels(convert.text_to_shape(text, style))
end
end)
if not success then
error("invalid text or style table", 2)
end
return pixels
end
function convert.image_to_pixels(image)
if type(image) ~= "string" then
error("string expected", 2)
end
-- Image data
local pixel_palette
-- Safe execution
local success = pcall(function()
-- Get image
pixel_palette = tgdi.load_image(image)
end)
if not success then
error("invalid image", 2)
end
-- Convert pixel palette to RGBA pixel table
local pixels, pixels_n = table.create(pixel_palette.width * pixel_palette.height, 0), 0
if pixel_palette.has_alpha then
for y = 0, pixel_palette.height-1 do
for x = 0, pixel_palette.width-1 do
local i = 1 + y * pixel_palette.width * 4 + x * 4
local a = pixel_palette[i+3]
if a > 0 then
local r = pixel_palette[i]
local g = pixel_palette[i+1]
local b = pixel_palette[i+2]
pixels_n = pixels_n + 1
pixels[pixels_n] = {r = r, g = g, b = b, a = a, x = x, y = y}
end
end
end
else
for y = 0, pixel_palette.height-1 do
for x = 0, pixel_palette.width-1 do
local i = 1 + y * pixel_palette.width * 3 + x * 3
local r = pixel_palette[i]
local g = pixel_palette[i+1]
local b = pixel_palette[i+2]
pixels_n = pixels_n + 1
pixels[pixels_n] = {r = r, g = g, b = b, a = 255, x = x, y = y}
end
end
end
return pixels
end
-- MATH
function math.bezier(pct, p)
if type(pct) ~= "number" or type(p) ~= "table" then
error("number and table expected", 2)
elseif pct < 0 or pct > 1 or #p < 2 then
error("invalid arguments", 2)
end
for i, v in ipairs(p) do
if type(v[1]) ~= "number" or type(v[2]) ~= "number" or (type(v[3]) ~= "number" and type(v[3]) ~= "nil") then
error("invalid table content", 2)
end
end
--Factorial
local function fac(n)
local k = 1
if n > 1 then
for i=2, n do
k = k * i
end
end
return k
end
--Binomial coefficient
local function bin(i, n)
return fac(n) / (fac(i) * fac(n-i))
end
--Bernstein polynom
local function bernstein(pct, i, n)
return bin(i, n) * pct^i * (1 - pct)^(n - i)
end
--Calculate coordinate
local point = {0, 0, 0}
local n = #p - 1
for i=0, n do
local bern = bernstein(pct, i, n)
point[1] = point[1] + p[i+1][1] * bern
point[2] = point[2] + p[i+1][2] * bern
point[3] = point[3] + (p[i+1][3] or 0) * bern
end
return point
end
function math.degree(vec1, vec2)
if type(vec1) ~= "table" or type(vec2) ~= "table" then
error("table and table expected", 2)
elseif type(vec1[1]) ~= "number" or type(vec1[2]) ~= "number" or type(vec1[3]) ~= "number" or
type(vec2[1]) ~= "number" or type(vec2[2]) ~= "number" or type(vec2[3]) ~= "number" then
error("invalid table content", 2)
end
local degree = math.deg(
math.acos(
(vec1[1] * vec2[1] + vec1[2] * vec2[2] + vec1[3] * vec2[3]) /
(math.distance(vec1[1], vec1[2], vec1[3]) * math.distance(vec2[1], vec2[2], vec2[3]))
)
)
return (vec1[1]*vec2[2] - vec1[2]*vec2[1]) < 0 and -degree or degree
end
function math.distance( w, h, d )
if type(w) ~= "number" or type(h) ~= "number" or (type(d) ~= "number" and type(d) ~= "nil") then
error("number, number and optional number expected", 2)
end
if d then
return math.sqrt(w^2 + h^2 + d^2)
else
return math.sqrt(w^2 + h^2)
end
end
function math.ellipse(x, y, w, h, a)
if type(x) ~= "number" or
type(y) ~= "number" or
type(w) ~= "number" or
type(h) ~= "number" or
type(a) ~= "number" then
error("number, number, number, number and number expected", 2)
end
local ra = math.rad(a)
return x + w/2 * math.sin(ra), y + h/2 * math.cos(ra)
end
function math.ortho(vec1, vec2)
if type(vec1) ~= "table" or type(vec2) ~= "table" then
error("table and table expected", 2)
elseif type(vec1[1]) ~= "number" or type(vec1[2]) ~= "number" or type(vec1[3]) ~= "number" or
type(vec2[1]) ~= "number" or type(vec2[2]) ~= "number" or type(vec2[3]) ~= "number" then
error("invalid table content", 2)
end
return {
vec1[2] * vec2[3] - vec1[3] * vec2[2],
vec1[3] * vec2[1] - vec1[1] * vec2[3],
vec1[1] * vec2[2] - vec1[2] * vec2[1]
}
end
function math.randomsteps(start, ends, step)
if type(start) ~= "number" or
type(ends) ~= "number" or
type(step) ~= "number" or
start > ends or
step <= 0 then
error("valid number, number and number expected", 2)
end
return start + math.random(0, math.floor((ends - start) / step)) * step
end
function math.randomway()
return math.random(0,1) * 2 - 1
end
function math.rotate(p, axis, angle)
if type(p) ~= "table" or #p ~= 3 or type(axis) ~= "string" or type(angle) ~= "number" then
error("table, string and number expected", 2)
elseif axis ~= "x" and axis ~= "y" and axis ~= "z" then
error("invalid axis", 2)
elseif type(p[1]) ~= "number" or type(p[2]) ~= "number" or type(p[3]) ~= "number" then
error("invalid table content", 2)
end
local ra = math.rad(angle)
if axis == "x" then
return {
p[1],
math.cos(ra)*p[2] - math.sin(ra)*p[3],
math.sin(ra)*p[2] + math.cos(ra)*p[3]
}
elseif axis == "y" then
return {
math.cos(ra)*p[1] + math.sin(ra)*p[3],
p[2],
-math.sin(ra)*p[1] + math.cos(ra)*p[3]
}
else
return {
math.cos(ra)*p[1] - math.sin(ra)*p[2],
math.sin(ra)*p[1] + math.cos(ra)*p[2],
p[3]
}
end
end
function math.round(num)
if type(num) ~= "number" then
error("number expected", 2)
end
return math.floor(num + 0.5)
end
function math.trim(num, starts, ends)
if type(starts) ~= "number" or
type(ends) ~= "number" or
type(num) ~= "number" then
error("number, number and number expected", 2)
end
return (num < starts and starts) or (num > ends and ends) or num
end
-- SHAPE
shape = {}
function shape.bounding(shape)
if type(shape) ~= "string" or (type(as_region) ~= "boolean" and as_region ~= nil) then
error("string and optional boolean expected", 2)
end
-- Result data
local min_x, min_y, max_x, max_y
-- Safe execution
local success = pcall(function()
-- Graphic context
local ctx = tgdi.create_context()
-- Get bounding
shape = shape:gsub("(%-?%d+)%s+(%-?%d+)", function(x, y)
return string.format("%d %d", x * 8, y * 8)
end)
min_x, min_y, max_x, max_y = ctx:add_path(shape):path_box()
min_x, min_y, max_x, max_y = math.floor(min_x/8), math.floor(min_y/8), math.floor(max_x/8), math.floor(max_y/8)
end)
if not success then
error("invalid shape", 2)
end
return min_x, min_y, max_x, max_y
end
function shape.ellipse(w, h)
if type(w) ~= "number" or type(h) ~= "number" then
error("number and number expected", 2)
end
local w2, h2 = w/2, h/2
return string.format("m %d %d b %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d",
0, h2, -- move
0, h2, 0, 0, w2, 0, -- curve 1
w2, 0, w, 0, w, h2, -- curve 2
w, h2, w, h, w2, h, -- curve 3
w2, h, 0, h, 0, h2 -- curve 4
)
end
function shape.filter(shape, filter)
if type(shape) ~= "string" or type(filter) ~= "function" then
error("string and function expected", 2)
end
local new_shape = shape:gsub("(%-?%d+)%s+(%-?%d+)", function(x, y)
local new_x, new_y = filter(tonumber(x), tonumber(y))
if type(new_x) == "number" and type(new_y) == "number" then
return string.format("%d %d", new_x, new_y)
end
end)
return new_shape
end
function shape.glance(edges, inner_size, outer_size)
if type(edges) ~= "number" or type(inner_size) ~= "number" or type(outer_size) ~= "number" or edges < 2 then
error("valid 3 numbers expected", 2)
end
-- Build shape
local shape, shape_n = {string.format("m 0 %d b", -outer_size)}, 1
local inner_p, outer_p
for i = 1, edges do
--Inner edge
inner_p = math.rotate({0, -inner_size, 0}, "z", ((i-0.5) / edges)*360)
--Outer edge
outer_p = math.rotate({0, -outer_size, 0}, "z", (i / edges)*360)
-- Add curve
shape_n = shape_n + 1
shape[shape_n] = string.format(" %d %d %d %d %d %d", inner_p[1], inner_p[2], inner_p[1], inner_p[2], outer_p[1], outer_p[2])
end
shape = table.concat(shape)
-- Shift to positive numbers
local min_x, min_y = 0, 0
shape:gsub("(%-?%d+)%s+(%-?%d+)", function(x, y)
min_x, min_y = math.min(min_x, x), math.min(min_y, y)
end)
shape = shape:gsub("(%-?%d+)%s+(%-?%d+)", function(x, y)
return string.format("%d %d", x-min_x, y-min_y)
end)
-- Return result
return shape
end
function shape.heart(size, offset)
if type(size) ~= "number" or type(offset) ~= "number" then
error("number and number expected", 2)
end
-- Build shape from template
local shape = string.gsub("m 15 30 b 27 22 30 18 30 14 30 8 22 0 15 10 8 0 0 8 0 14 0 18 3 22 15 30", "%d+", function(num)
num = num / 30 * size
return math.round(num)
end)
-- Shift mid point of heart vertically
shape = shape:gsub("(m %-?%d+ %-?%d+ b %-?%d+ %-?%d+ %-?%d+ %-?%d+ %-?%d+ %-?%d+ %-?%d+ %-?%d+ %-?%d+ %-?%d+ %-?%d+ )(%-?%d+)", function(head, y)
return string.format("%s%d", head, y + offset)
end)
-- Return result
return shape
end
function shape.move(shape, x, y)
if type(shape) ~= "string" or type(x) ~= "number" or type(y) ~= "number" then
error("string, number and number expected", 2)
end
local new_shape = shape:gsub("(%-?%d+)%s+(%-?%d+)", function(px, py)
return string.format("%d %d", px + x, py + y)
end)
return new_shape
end
function shape.rectangle(w, h)
if type(w) ~= "number" or type(h) ~= "number" then
error("number and number expected", 2)
end
return string.format("m 0 0 l %d 0 %d %d 0 %d 0 0", w, w, h, h)
end
function shape.ring(out_r, in_r)
if type(out_r) ~= "number" or type(in_r) ~= "number" or in_r >= out_r then
error("valid number and number expected", 2)
end
local out_r2, in_r2 = out_r*2, in_r*2
local off = out_r - in_r
return string.format("m %d %d b %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d m %d %d b %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d",
0, out_r, -- outer move
0, out_r, 0, 0, out_r, 0, -- outer curve 1
out_r, 0, out_r2, 0, out_r2, out_r, -- outer curve 2
out_r2, out_r, out_r2, out_r2, out_r, out_r2, -- outer curve 3
out_r, out_r2, 0, out_r2, 0, out_r, -- outer curve 4
off, off+in_r, -- inner move
off, off+in_r, off, off+in_r2, off+in_r, off+in_r2, -- inner curve 1
off+in_r, off+in_r2, off+in_r2, off+in_r2, off+in_r2, off+in_r, -- inner curve 2
off+in_r2, off+in_r, off+in_r2, off, off+in_r, off, -- inner curve 3
off+in_r, off, off, off, off, off+in_r -- inner curve 4
)
end
function shape.split(shape, len)
if type(shape) ~= "string" or (type(len) ~= "number" and len ~= nil) then
error("string and optional number expected", 2)
elseif len and len <= 0 then
error("invalid length", 2)
end
-- Curves to lines
local success = pcall(function()
-- Graphic context
local ctx = tgdi.create_context()
-- Flatten path
shape = ctx:add_path(shape):flatten_path():get_path()
end)
if not success then
error("invalid shape", 2)
end
-- Split lines to shorter segments
if len then
local line_mode, last_point = false
shape = shape:gsub("([ml]?)(%s*)(%-?%d+)%s+(%-?%d+)", function(typ, space, x, y)
-- Update line mode
if typ == "m" then
line_mode = false
elseif typ == "l" then
line_mode = true
end
-- Line(s) buffer
local lines
-- LineTo with previous point?
if line_mode and last_point then
local rel_x, rel_y = x-last_point.x, y-last_point.y
local distance = math.distance(rel_x, rel_y)
-- Can split?
if distance > len then
lines = {typ .. space}
local lines_n = 1
local dist_rest = distance % len
for cur_dist = dist_rest > 0 and dist_rest or len, distance, len do
local pct = cur_dist / distance
lines_n = lines_n + 1
lines[lines_n] = string.format("%d %d ", last_point.x + rel_x * pct, last_point.y + rel_y * pct)
end
lines = table.concat(lines):sub(1,-2)
else
lines = string.format("%s%s%d %d", typ, space, x, y)
end
else
lines = string.format("%s%s%d %d", typ, space, x, y)
end
-- Save point for next one
last_point = {x = x, y = y}
-- Return new line(s)
return lines
end)
end
-- Return result
return shape
end
function shape.star(edges, inner_size, outer_size)
if type(edges) ~= "number" or type(inner_size) ~= "number" or type(outer_size) ~= "number" or edges < 2 then
error("valid 3 numbers expected", 2)
end
-- Build shape
local shape, shape_n = {string.format("m 0 %d l", -outer_size)}, 1
local inner_p, outer_p
for i = 1, edges do
-- Inner edge
inner_p = math.rotate({0, -inner_size, 0}, "z", ((i-0.5) / edges)*360)
-- Outer edge
outer_p = math.rotate({0, -outer_size, 0}, "z", (i / edges)*360)
-- Add lines
shape_n = shape_n + 1
shape[shape_n] = string.format(" %d %d %d %d", inner_p[1], inner_p[2], outer_p[1], outer_p[2])
end
shape = table.concat(shape)
-- Shift to positive numbers
local min_x, min_y = 0, 0
shape:gsub("(%-?%d+)%s+(%-?%d+)", function(x, y)
min_x, min_y = math.min(min_x, x), math.min(min_y, y)
end)
shape = shape:gsub("(%-?%d+)%s+(%-?%d+)", function(x, y)
return string.format("%d %d", x-min_x, y-min_y)
end)
-- Return result
return shape
end
function shape.tooutline(shape, size)
if type(shape) ~= "string" or type(size) ~= "number" then
error("string and number expected", 2)
end
-- Collect figures
local figures, figures_n = {}, 0
local figure, figure_n = {}, 0
shape:gsub("(%a?)%s*(%-?%d+)%s+(%-?%d+)", function(typ, x, y)
-- Check point type
if typ ~= "m" and typ ~= "l" and typ ~= "" then
error("shape have to contain only \"moves\" and \"lines\"", 4)
end
-- Last figure finished?
if typ == "m" and figure_n ~= 0 then
-- Enough figure points?
if figure_n < 3 then
error("at least one figure hasn't enough points", 4)
end
-- Save figure
figures_n = figures_n + 1
figures[figures_n] = figure
figure = {}
figure_n = 0
end
-- Add point to current figure
figure_n = figure_n + 1
figure[figure_n] = {x, y}
end)
-- Insert last figure
if figure_n ~= 0 then
-- Enough figure points?
if figure_n < 3 then
error("at least one figure hasn't enough points", 2)
end
-- Save figure
figures_n = figures_n + 1
figures[figures_n] = figure
figure = {}
figure_n = 0
end
-- Remove double points (recreate figures)
for fi = 1, figures_n do
local old_figure, old_figure_n = figures[fi], #figures[fi]
local new_figure, new_figure_n = table.create(old_figure_n, 0), 0
for pi, point in ipairs(old_figure) do
local pre_point
if pi == 1 then
pre_point = old_figure[old_figure_n]
else
pre_point = old_figure[pi-1]
end
if not (point[1] == pre_point[1] and point[2] == pre_point[2]) then
new_figure_n = new_figure_n + 1
new_figure[new_figure_n] = point
end
end
figures[fi] = new_figure
end
-- Vector sizer for local use
local function vec_sizer(vec, size)
local len = math.distance(vec[1], vec[2], vec[3])
if len == 0 then
return {0, 0, 0}
else
return {vec[1] / len * size, vec[2] / len * size, vec[3] / len * size}
end
end
-- Stroke figures
local stroke_figures = {table.create(figures_n, 0),table.create(figures_n, 0)} -- inner + outer
local stroke_subfigures_i = 0
-- Through figures
for fi, figure in ipairs(figures) do
stroke_subfigures_i = stroke_subfigures_i + 1
-- One pass for inner, one for outer outline
for i = 1, 2 do
-- Outline buffer
local outline, outline_n = {}, 0
-- Point iteration order = inner or outer outline
local loop_begin, loop_end, loop_steps
if i == 1 then
loop_begin, loop_end, loop_steps = #figure, 1, -1
else
loop_begin, loop_end, loop_steps = 1, #figure, 1
end
-- Iterate through figure points
for pi = loop_begin, loop_end, loop_steps do
-- Collect current, previous and next point
local point = figure[pi]
local pre_point, post_point
if i == 1 then
if pi == 1 then
pre_point = figure[pi+1]
post_point = figure[#figure]
elseif pi == #figure then
pre_point = figure[1]
post_point = figure[pi-1]
else
pre_point = figure[pi+1]
post_point = figure[pi-1]
end
else
if pi == 1 then
pre_point = figure[#figure]
post_point = figure[pi+1]
elseif pi == #figure then
pre_point = figure[pi-1]
post_point = figure[1]
else
pre_point = figure[pi-1]
post_point = figure[pi+1]
end
end
-- Calculate orthogonal vectors to both neighbour points
local o_vec1 = vec_sizer( math.ortho({point[1]-pre_point[1], point[2]-pre_point[2], 0}, {0, 0, 1}), size )
local o_vec2 = vec_sizer( math.ortho({post_point[1]-point[1], post_point[2]-point[2], 0}, {0, 0, 1}), size )
-- Calculate degree & circumference between orthogonal vectors
local degree = math.degree(o_vec1, o_vec2)
local circ = math.abs(math.rad(degree)) * size
-- Add first edge point
outline_n = outline_n + 1
outline[outline_n] = {math.floor(point[1] + o_vec1[1]), math.floor(point[2] + o_vec1[2])}
-- Round edge needed?
local max_circ = 2
if circ > max_circ then
local circ_rest = circ % max_circ
for cur_circ = circ_rest > 0 and circ_rest or max_circ, circ, max_circ do
local curve_vec = math.rotate(o_vec1, "z", cur_circ / circ * degree)
outline_n = outline_n + 1
outline[outline_n] = {math.floor(point[1] + curve_vec[1]), math.floor(point[2] + curve_vec[2])}
end
end
end
-- Insert inner or outer outline
stroke_figures[i][stroke_subfigures_i] = outline
end
end
-- Convert stroke figures to shape
local stroke_shape, stroke_shape_n = {}, 0
for fi = 1, figures_n do
-- Closed inner outline to shape
local inner_outline = stroke_figures[1][fi]
for pi, point in ipairs(inner_outline) do
stroke_shape_n = stroke_shape_n + 1
stroke_shape[stroke_shape_n] = string.format("%s%d %d", pi == 1 and "m " or pi == 2 and "l " or "", point[1], point[2])
end
stroke_shape_n = stroke_shape_n + 1
stroke_shape[stroke_shape_n] = string.format("%d %d", inner_outline[1][1], inner_outline[1][2])
-- Closed outer outline to shape
local outer_outline = stroke_figures[2][fi]
for pi, point in ipairs(outer_outline) do
stroke_shape_n = stroke_shape_n + 1
stroke_shape[stroke_shape_n] = string.format("%s%d %d", pi == 1 and "m " or pi == 2 and "l " or "", point[1], point[2])
end
stroke_shape_n = stroke_shape_n + 1
stroke_shape[stroke_shape_n] = string.format("%d %d", outer_outline[1][1], outer_outline[1][2])
end
return table.concat(stroke_shape, " ")
end
function shape.triangle(size)
if type(size) ~= "number" then
error("number expected", 2)
end
local h = math.sqrt(3) * size / 2
local base = -h / 6
return string.format("m %d %d l %d %d 0 %d %d %d", size/2, base, size, base+h, base+h, size/2, base)
end
-- STRING
--[[
UTF16 -> UTF8
--------------
U-00000000 EU-0000007F: 0xxxxxxx
U-00000080 EU-000007FF: 110xxxxx 10xxxxxx
U-00000800 EU-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
U-00010000 EU-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
U-00200000 EU-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
U-04000000 EU-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
]]
function string.ucharrange(s, i)
if type(s) ~= "string" or type(i) ~= "number" or i < 1 or i > s:len() then
error("string and valid number expected", 2)
end
local byte = s:byte(i)
if not byte then
return 0
elseif byte < 192 then
return 1
elseif byte < 224 then
return 2
elseif byte < 240 then
return 3
elseif byte < 248 then
return 4
elseif byte < 252 then
return 5
else
return 6
end
end
function string.uchars(s)
if type(s) ~= "string" then
error("string expected", 2)
end
local char_i, s_pos = 0, 1
return function()
if s_pos > s:len() then
return nil
end
local cur_pos = s_pos
s_pos = s_pos + s:ucharrange(s_pos)
char_i = char_i + 1
return char_i, s:sub(cur_pos, s_pos-1)
end
end
function string.ulen(s)
if type(s) ~= "string" then
error("string expected", 2)
end
local n = 0
for _ in s:uchars() do
n = n + 1
end
return n
end
-- TABLE
function table.append(t1, t2)
if type(t1) ~= "table" or type(t2) ~= "table" then
error("table and table expected", 2)
end
local t1_n = #t1
for i, v in pairs(t2) do
if tonumber(i) then
t1_n = t1_n + 1
t1[t1_n] = v
else
t1[i] = v
end
end
return t1
end
function table.copy(old_t)
if type(old_t) ~= "table" then
error("table expected", 2)
end
local new_t = {}
for index, value in pairs(old_t) do
if type(value) == "table" then
new_t[index] = table.copy(value)
else
new_t[index] = value
end
end
return new_t
end
function table.max(t)
if type(t) ~= "table" then
error("table expected", 2)
end
local n = 0
for _ in pairs(t) do
n = n + 1
end
return n
end
function table.tostring(t)
if type(t) ~= "table" then
error("table expected", 2)
end
local result, result_n = {tostring(t)}, 1
local function table_print(t, space)
for i, v in pairs(t) do
if type(i) == "string" then
i = string.format("%q", i)
end
if type(v) == "string" then
v = string.format("%q", v)
end
result_n = result_n + 1
result[result_n] = string.format("%s[%s] = %s", space, tostring(i), tostring(v))
if type(v) == "table" then
table_print(v, space .. "\t")
end
end
end
table_print(t, "\t")
return table.concat(result, "\n")
end
-- UTILS
utils = {}
function utils.distributor(t)
if type(t) ~= "table" or #t < 1 then
error("table expected (not empty)", 2)
end
-- Member functions
local func_t = {}
func_t.__index = func_t
local index = 1
function func_t:get()
if index > #self then index = 1 end
local val = self[index]
index = index + 1
return val
end
-- Return object
return setmetatable(t, func_t)
end
function utils.frames(starts, ends, frame_time)
if type(starts) ~= "number" or type(ends) ~= "number" or type(frame_time) ~= "number" or frame_time <= 0 then
error("number, number and valid number expected", 2)
end
-- Intermediate data
local cur_start_time, i, n = starts, 0, math.ceil((ends - starts) / frame_time)
-- Iterator function
return function()
if cur_start_time >= ends then
return nil
end
local return_start_time = cur_start_time
local return_end_time = return_start_time + frame_time <= ends and return_start_time + frame_time or ends
cur_start_time = return_end_time
i = i + 1
return return_start_time, return_end_time, i, n
end
end
function utils.interpolate(pct, val1, val2, calc)
if type(pct) ~= "number" or
not (
(type(val1) == "number" and type(val2) == "number") or
(type(val1) == "string" and type(val2) == "string")
) or
(type(calc) ~= "string" and type(calc) ~= "number" and type(calc) ~= "nil") then
error("number and 2 numbers or 2 strings and optional string expected", 2)
end
-- Calculate percent value depending on calculation mode
if calc ~= nil then
if type(calc) == "number" then
pct = pct^calc
elseif calc == "curve_up" then
pct = (math.sin( -math.pi/2 + pct * math.pi*2) + 1) / 2
elseif calc == "curve_down" then
pct = 1 - (math.sin( -math.pi/2 + pct * math.pi*2) + 1) / 2
else
error("valid last value expected", 2)
end
end
-- Interpolate numbers
if type(val1) == "number" then
return val1 + (val2 - val1) * pct
-- Interpolate strings
else
-- RGB
local r1, g1, b1 = convert.ass_to_rgb(val1)
local r2, g2, b2 = convert.ass_to_rgb(val2)
if b1 and b2 then
return convert.rgb_to_ass((r2 - r1) * pct + r1, (g2 - g1) * pct + g1, (b2 - b1) * pct + b1)
end
-- Alpha
local a1 = convert.ass_to_a(val1)
local a2 = convert.ass_to_a(val2)
if a1 and a2 then
return convert.a_to_ass((a2 - a1) * pct + a1)
end
-- Invalid string
error("invalid strings", 2)
end
end
function utils.text_extents(text, style)
-- Flat arguments check
if type(text) ~= "string" or type(style) ~= "table" then
error("string and style table expected", 2)
end
-- Result data
local width, height, ascent, descent, internal_lead, external_lead
-- Safe execution
local success = pcall(function()
-- Graphic context
local ctx = tgdi.create_context()
-- Extents with spacing
if style.spacing > 0 and text:ulen() > 0 then
local spaced_width = 0
for uchar_i, uchar in text:uchars() do
width, height, ascent, descent, internal_lead, external_lead =
ctx:text_extents(uchar, style.fontname, style.fontsize * 64, style.bold, style.italic, style.underline, style.strikeout, style.encoding)
spaced_width = spaced_width + width + style.spacing * 64
end
width = spaced_width
-- Extents without spacing
else
width, height, ascent, descent, internal_lead, external_lead =
ctx:text_extents(text, style.fontname, style.fontsize * 64, style.bold, style.italic, style.underline, style.strikeout, style.encoding)
end
-- Scale correctly
local scale_x, scale_y = style.scale_x / 100 / 64, style.scale_y / 100 / 64
width, height, ascent, descent, internal_lead, external_lead =
width * scale_x, height * scale_y, ascent * scale_y, descent * scale_y, internal_lead * scale_y, external_lead * scale_y
end)
if not success then
error("invalid style table", 2)
end
return width, height, ascent, descent, internal_lead, external_lead
end
| lgpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Mamook/npcs/qm2.lua | 15 | 1163 | -----------------------------------
-- Area: Mamook
-- NPC: ??? (Spawn Iriri Samariri(ZNM T2))
-- @pos -118 7 -80 65
-----------------------------------
package.loaded["scripts/zones/Mamook/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mamook/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(trade:hasItemQty(2579,1) and trade:getItemCount() == 1) then -- Trade Samariri Corpsehair
player:tradeComplete();
SpawnMob(17043888,180):updateEnmity(player);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_HAPPENS);
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 |
soroushwilson/wilson1 | plugins/filterword.lua | 8 | 2738 | local function addword(msg, name)
local hash = 'chat:'..msg.to.id..':badword'
redis:hset(hash, name, 'newword')
return "انجام شد"
end
local function get_variables_hash(msg)
return 'chat:'..msg.to.id..':badword'
end
local function list_variablesbad(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'لیست کلمات ممنوع:\n______________________________\n'
for i=1, #names do
text = text..'> '..names[i]..'\n'
end
return text
else
return
end
end
function clear_commandbad(msg, var_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:del(hash, var_name)
return 'پاک شدند'
end
local function list_variables2(msg, value)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
if string.match(value, names[i]) and not is_momod(msg) then
if msg.to.type == 'channel' then
delete_msg(msg.id,ok_cb,false)
else
kick_user(msg.from.id, msg.to.id)
return 'شما به دلیل استفاده از کمله غیر مجاز\nاز ادامه گفتگو در این گروه محروم میشوید'
end
return
end
--text = text..names[i]..'\n'
end
end
end
local function get_valuebad(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
function clear_commandsbad(msg, cmd_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:hdel(hash, cmd_name)
return ''..cmd_name..' پاک شد'
end
local function run(msg, matches)
if matches[2] == '+' then
if not is_momod(msg) then
return 'شما مدیر نیستید'
end
local name = string.sub(matches[3], 1, 50)
local text = addword(msg, name)
return text
end
if matches[1]:lower() == 'filterlist' or matches[1]:lower() == 'لیست فیلتر' then
return list_variablesbad(msg)
elseif matches[1]:lower() == 'clean' or matches[1] == 'حذف' then
if not is_momod(msg) then
return
end
local asd = '1'
return clear_commandbad(msg, asd)
elseif matches[2] == '-' then
if not is_momod(msg) then return '_|_' end
return clear_commandsbad(msg, matches[3])
else
return list_variables2(msg, matches[1])
end
end
return {
patterns = {
"^([Ff]ilter) (.*) (.*)$",
"^[/#!]([Ff]ilter) (.*) (.*)$",
"^[/#!]([Ff]ilterlist)$",
"^([Ff]ilterlist)$",
"^[/#!]([Cc]lean) filterlist$",
"^([Cc]lean) filterlist$",
"^(فیلتر) (.*) (.*)$",
"^(لیست فیلتر)$",
"^(حذف) لیست فیلتر$",
"^(.+)$",
},
run = run
}
| gpl-2.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/RuLude_Gardens/npcs/Muhoho.lua | 34 | 1386 | -----------------------------------
-- Area: Ru'Lud Gardens
-- NPC: Muhoho
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/RuLude_Gardens/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatJeuno = player:getVar("WildcatJeuno");
if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,2) == false) then
player:startEvent(10093);
else
player:startEvent(0x0098);
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 == 10093) then
player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",2,true);
end
end;
| gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/globals/weaponskills/exenterator.lua | 6 | 1862 | -----------------------------------
-- Exenterator
-- Skill level: 357
-- Terpsichore: Aftermath effect varies with TP.
-- In order to obtain Exenterator, the quest Martial Mastery must be completed.
-- Description: Delivers a fourfold attack that lowers enemy's params.accuracy. Effect duration varies with TP.
-- Aligned with the Breeze Gorget, Thunder Gorget & Soil Gorget.
-- Aligned with the Breeze Belt, Thunder Belt & Soil Belt.
-- Notes: Stacks with itself allowing continuous params.acc down
-- params.acc down isn't the same as the spell Blind or sources which are the same as blind allowing both to stack
-- Element: None
-- Modifiers: AGI:20~100%, depending on merit points ugrades.
-- 100%TP 200%TP 300%TP
-- 1.0 1.0 1.0
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 4;
params.ftp100 = 1.0; params.ftp200 = 1.0; params.ftp300 = 1.0;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.85; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1.375;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
if damage > 0 then
local tp = player:getTP();
local duration=(tp/100*30)+90;
if(target:hasStatusEffect(EFFECT_ACCURACY_DOWN) == false) then
target:addStatusEffect(EFFECT_ACCURACY_DOWN, 1, 0,duration);
end
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
joshimoo/Algorithm-Implementations | Selection_Sort/Lua/Yonaba/selection_sort_test.lua | 27 | 1395 | -- Tests for selection_sort.lua
local selection_sort = require 'selection_sort'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
-- Comparison functions
local function le(a,b) return a <= b end
local function ge(a,b) return a >= b end
-- Checks if list is sorted
function is_sorted(list, comp)
comp = comp or le
for i = 2, #list do
if not comp(list[i-1],list[i]) then return false end
end
return true
end
-- Generates a table of n random values
local function gen(n)
local t = {}
for i = 1, n do t[i] = math.random(n) end
return t
end
math.randomseed(os.time())
run('Empty arrays', function()
local t = {}
assert(is_sorted(selection_sort({})))
end)
run('Already sorted array', function()
local t = {1, 2, 3, 4, 5}
assert(is_sorted(selection_sort(t)))
end)
run('Sorting a large array (1e3 values)', function()
local t = gen(1e3)
assert(is_sorted(selection_sort(t)))
assert(is_sorted(selection_sort(t, ge), ge))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
FFXIOrgins/FFXIOrgins | scripts/zones/The_Eldieme_Necropolis/npcs/_5f9.lua | 34 | 1106 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: Shiva's Gate
-- @pos 270 -34 -60 195
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Eldieme_Necropolis/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (npc:getAnimation() == 9) then
player:messageSpecial(SOLID_STONE);
end
return 0;
end;
--
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Sacrarium/npcs/Large_Keyhole.lua | 10 | 1210 | -----------------------------------
-- Area: Sacrarium
-- NPC: Large Keyhole
-- Notes: Used to open R. Gate
-- @pos 100.231 -1.414 51.700 28
-----------------------------------
package.loaded["scripts/zones/Sacrarium/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Sacrarium/TextIDs");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(LARGE_KEYHOLE);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local Timemax=GetServerVariable("SACRARIUM_Coral_Key_trade")+10;
local CurentTime=os.time();
local LargeKeyholeID = npc:getID();
local DoorID = GetNPCByID(LargeKeyholeID):getID() - 2;
if (trade:hasItemQty(1658,1) and trade:getItemCount() == 1) then
if (CurentTime < Timemax)then
GetNPCByID(DoorID):openDoor(15);
SetServerVariable("SACRARIUM_Coral_Key_trade",0);
end
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Selbina/npcs/Melyon.lua | 17 | 3574 | -----------------------------------
-- Area: Selbina
-- NPC: Melyon
-- Starts and Finishes Quest: Only the Best (R)
-- Involved in Quest: Riding on the Clouds
-- @pos 25 -6 6 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(OTHER_AREAS,ONLY_THE_BEST) ~= QUEST_AVAILABLE) then
if(trade:hasItemQty(4366,5) == true and trade:getGil() == 0 and trade:getItemCount() == 5) then
player:startEvent(0x003e); -- La Theine Cabbage x5
elseif(trade:hasItemQty(629,3) == true and trade:getGil() == 0 and trade:getItemCount() == 3) then
player:startEvent(0x003f); -- Millioncorn x3
elseif(trade:hasItemQty(919,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then
player:startEvent(0x0040); -- Boyahda Moss x1
end
end
if(player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_3") == 3) then
if(trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_3",0);
player:tradeComplete();
player:addKeyItem(SOMBER_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SOMBER_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
OnlyTheBest = player:getQuestStatus(OTHER_AREAS,ONLY_THE_BEST);
if (OnlyTheBest == QUEST_AVAILABLE) then
player:startEvent(0x003c,4366,629,919); -- Start quest "Only the Best"
elseif(OnlyTheBest ~= QUEST_AVAILABLE) then
player:startEvent(0x003d,4366,629,919); -- During & after completed quest "Only the Best"
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 == 0x003c and option == 10) then
player:addQuest(OTHER_AREAS,ONLY_THE_BEST);
elseif(csid == 0x003e) then
player:tradeComplete();
player:addGil(100);
player:messageSpecial(GIL_OBTAINED,100);
player:addFame(BASTOK, BAS_FAME*10);
player:addFame(SANDORIA,SAN_FAME*10);
player:addFame(JEUNO, JEUNO_FAME*10);
player:completeQuest(OTHER_AREAS,ONLY_THE_BEST);
elseif(csid == 0x003f) then
player:tradeComplete();
player:addGil(120);
player:messageSpecial(GIL_OBTAINED,120);
player:addFame(BASTOK, BAS_FAME*20);
player:addFame(SANDORIA,SAN_FAME*20);
player:addFame(JEUNO, JEUNO_FAME*20);
player:completeQuest(OTHER_AREAS,ONLY_THE_BEST);
elseif(csid == 0x0040) then
player:tradeComplete();
player:addGil(600);
player:messageSpecial(GIL_OBTAINED,600);
player:addFame(BASTOK, BAS_FAME*30);
player:addFame(SANDORIA,SAN_FAME*30);
player:addFame(JEUNO, JEUNO_FAME*30);
player:completeQuest(OTHER_AREAS,ONLY_THE_BEST);
end
end; | gpl-3.0 |
daofeng2015/luci | protocols/luci-proto-ppp/luasrc/model/network/proto_ppp.lua | 18 | 2363 | -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local netmod = luci.model.network
local _, p
for _, p in ipairs({"ppp", "pptp", "pppoe", "pppoa", "3g", "l2tp", "pppossh"}) do
local proto = netmod:register_protocol(p)
function proto.get_i18n(self)
if p == "ppp" then
return luci.i18n.translate("PPP")
elseif p == "pptp" then
return luci.i18n.translate("PPtP")
elseif p == "3g" then
return luci.i18n.translate("UMTS/GPRS/EV-DO")
elseif p == "pppoe" then
return luci.i18n.translate("PPPoE")
elseif p == "pppoa" then
return luci.i18n.translate("PPPoATM")
elseif p == "l2tp" then
return luci.i18n.translate("L2TP")
elseif p == "pppossh" then
return luci.i18n.translate("PPPoSSH")
end
end
function proto.ifname(self)
return p .. "-" .. self.sid
end
function proto.opkg_package(self)
if p == "ppp" then
return p
elseif p == "3g" then
return "comgt"
elseif p == "pptp" then
return "ppp-mod-pptp"
elseif p == "pppoe" then
return "ppp-mod-pppoe"
elseif p == "pppoa" then
return "ppp-mod-pppoa"
elseif p == "l2tp" then
return "xl2tpd"
elseif p == "pppossh" then
return "pppossh"
end
end
function proto.is_installed(self)
if p == "pppoa" then
return (nixio.fs.glob("/usr/lib/pppd/*/pppoatm.so")() ~= nil)
elseif p == "pppoe" then
return (nixio.fs.glob("/usr/lib/pppd/*/rp-pppoe.so")() ~= nil)
elseif p == "pptp" then
return (nixio.fs.glob("/usr/lib/pppd/*/pptp.so")() ~= nil)
elseif p == "3g" then
return nixio.fs.access("/lib/netifd/proto/3g.sh")
elseif p == "l2tp" then
return nixio.fs.access("/lib/netifd/proto/l2tp.sh")
elseif p == "pppossh" then
return nixio.fs.access("/lib/netifd/proto/pppossh.sh")
else
return nixio.fs.access("/lib/netifd/proto/ppp.sh")
end
end
function proto.is_floating(self)
return (p ~= "pppoe")
end
function proto.is_virtual(self)
return true
end
function proto.get_interfaces(self)
if self:is_floating() then
return nil
else
return netmod.protocol.get_interfaces(self)
end
end
function proto.contains_interface(self, ifc)
if self:is_floating() then
return (netmod:ifnameof(ifc) == self:ifname())
else
return netmod.protocol.contains_interface(self, ifc)
end
end
netmod:register_pattern_virtual("^%s-%%w" % p)
end
| apache-2.0 |
Gael-de-Sailly/minetest-minetestforfun-server | mods/watershed/nodes.lua | 4 | 2134 | minetest.register_alias("watershed:appleleaf", "default:leaves")
minetest.register_alias("watershed:appling", "default:sapling")
minetest.register_alias("watershed:acaciatree", "moretrees:acacia_trunk")
minetest.register_alias("watershed:acacialeaf", "moretrees:acacia_leaves")
minetest.register_alias("watershed:acacialing", "moretrees:acacia_sapling")
minetest.register_alias("watershed:pinetree", "default:pine_tree")
minetest.register_alias("watershed:needles", "default:pine_needles")
minetest.register_alias("watershed:pineling", "default:pine_sapling")
minetest.register_alias("watershed:jungleleaf", "default:jungleleaves")
minetest.register_alias("watershed:jungling", "default:junglesapling")
minetest.register_alias("watershed:dirt", "default:dirt")
minetest.register_alias("watershed:icydirt", "default:dirt_with_grass")
minetest.register_alias("watershed:grass", "default:dirt_with_grass")
minetest.register_alias("watershed:redstone", "default:desert_stone")
minetest.register_alias("watershed:redcobble", "default:desert_cobble")
minetest.register_alias("watershed:stone", "default:stone")
minetest.register_alias("watershed:cactus", "default:cactus")
minetest.register_alias("watershed:goldengrass", "default:dry_shrub")
minetest.register_alias("watershed:drygrass", "default:dirt_with_dry_grass")
minetest.register_alias("watershed:permafrost", "default:dirt")
minetest.register_alias("watershed:freshice", "default:ice")
minetest.register_alias("watershed:cloud", "default:cloud")
minetest.register_alias("watershed:luxore", "default:stone")
minetest.register_alias("watershed:light", "lantern:lamp")
minetest.register_alias("watershed:acaciawood", "moretrees:acacia_wood")
minetest.register_alias("watershed:pinewood", "default:pinewood")
minetest.register_alias("watershed:freshwater", "default:river_water_source")
minetest.register_alias("watershed:freshwaterflow", "default:river_water_flowing")
minetest.register_alias("watershed:lava", "default:lava_source")
minetest.register_alias("watershed:lavaflow", "default:lava_flowing")
-- Items
minetest.register_alias("watershed:luxcrystal", "default:cobble")
| unlicense |
JulianVolodia/awesome | lib/awful/autofocus.lua | 7 | 2314 | ---------------------------------------------------------------------------
--- Autofocus functions.
--
-- When loaded, this module makes sure that there's always a client that will
-- have focus on events such as tag switching, client unmanaging, etc.
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2009 Julien Danjou
-- @release @AWESOME_VERSION@
-- @module awful.autofocus
---------------------------------------------------------------------------
local client = client
local screen = screen
local aclient = require("awful.client")
local atag = require("awful.tag")
local timer = require("gears.timer")
--- Give focus when clients appear/disappear.
--
-- @param obj An object that should have a .screen property.
local function check_focus(obj)
-- When no visible client has the focus...
if not client.focus or not client.focus:isvisible() then
local c = aclient.focus.history.get(obj.screen, 0, aclient.focus.filter)
if c then
c:emit_signal("request::activate", "autofocus.check_focus",
{raise=false})
end
end
end
--- Check client focus (delayed).
-- @param obj An object that should have a .screen property.
local function check_focus_delayed(obj)
timer.delayed_call(check_focus, {screen = obj.screen})
end
--- Give focus on tag selection change.
--
-- @param tag A tag object
local function check_focus_tag(t)
local s = atag.getscreen(t)
if not s then return end
check_focus({ screen = s })
if client.focus and client.focus.screen ~= s then
local c = aclient.focus.history.get(s, 0, aclient.focus.filter)
if c then
c:emit_signal("request::activate", "autofocus.check_focus_tag",
{raise=false})
end
end
end
tag.connect_signal("property::selected", function (t)
timer.delayed_call(check_focus_tag, t)
end)
client.connect_signal("unmanage", check_focus_delayed)
client.connect_signal("tagged", check_focus_delayed)
client.connect_signal("untagged", check_focus_delayed)
client.connect_signal("property::hidden", check_focus_delayed)
client.connect_signal("property::minimized", check_focus_delayed)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
sjznxd/luci-0.11-aa | libs/sgi-wsapi/luasrc/sgi/wsapi.lua | 12 | 1844 | --[[
LuCI - SGI-Module for WSAPI
Description:
Server Gateway Interface for WSAPI
FileId:
$Id: wsapi.lua 2656 2008-07-23 18:52:12Z Cyrus $
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.sgi.wsapi", package.seeall)
local ltn12 = require("luci.ltn12")
require("luci.http")
require("luci.dispatcher")
require("luci.http.protocol")
function run(wsapi_env)
local r = luci.http.Request(
wsapi_env,
ltn12.source.file(wsapi_env.input),
ltn12.sink.file(wsapi_env.error)
)
local res, id, data1, data2 = true, 0, nil, nil
local headers = {}
local status = 200
local x = coroutine.create(luci.dispatcher.httpdispatch)
local active = true
while id < 3 do
res, id, data1, data2 = coroutine.resume(x, r)
if not res then
status = 500
headers["Content-Type"] = "text/plain"
local err = {id}
return status, headers, function() local x = table.remove(err) return x end
end
if id == 1 then
status = data1
elseif id == 2 then
headers[data1] = data2
end
end
local function iter()
local res, id, data = coroutine.resume(x)
if id == 4 and active then
return data
elseif id == 5 then
active = false
return ""
else
return ""
end
if coroutine.status(x) == "dead" then
return nil
end
end
return status, headers, iter
end
| apache-2.0 |
unknownssassss/sudo_meti | plugins/help.lua | 2 | 1993 | local function run(msg, matches)
local group = load_data('bot/group.json')
local addgroup = group[tostring(msg.chat_id)]
if matches[1] == 'help' and is_momod(msg) or is_owner(msg) and addgroup then
pm1 = [[◽Help Bot _STAR_:
by : @SuDo`_`StAr
✨!lock links =>قفل لینک
💀!lock edit =>قفل ویرایش پیام
🔁!lock fwd =>قفل فروارد
💤!lock spam =>قفل اسپم
♎!lock inline =>قفل اینلاین
🚫!lock persian =>قفل فارسی
🔤!lock english => قفل انگلیسی
🔞!lock fosh => قفل فحش
✅!lock username (@) => قفل یوزرنیم
🔹!lock tag (#) =>قفل تگ
⏳!lock tgservice =>قفل سرویس
📱!lock contact =>قفل شماره
🚳!lock game => قفل بازی تحت وب
⛔!mute all => ممنوعیت گپ
🔇!mute audio =>ممنوعیت آهنگ
🔕!mute voice => ممنوعیت صدا
📷!mute photo =>ممنوعیت عکس
👽!mute gifs =>ممنوعیت گیف
📹!mute video =>ممنوعیت فیلم
📦!mute document =>ممنوعیت فایل
💥!mute sticker =>ممنوعیت استیکر
◽️برای لغو لغو قفل ها به جای lock از کلمه unlock استفاده کنید
◽️برای لغو ممنوعیت به جای mute از کلمه unmte استفاده کنید
〰〰〰〰〰〰〰〰〰
◽️Help Owner _STAR_:
📤!promote [id-reply] =>مدیر کردن فرد
📥!demote [id-reply] =>حذف فرداز مدیریت
📝!settings =>تنظیمات
🎩!setlink [link] =>تنظیم لینک گروه
💿!link =>دریافت لینک گروه
📃!setrules [text] =>تنظیم قوانین گروه
🔰!rules =>دریافت قوانین گروه
ℹ!id =>دریافت شناسه عددی خود و گروه
📜!id [reply-username] =>دریافت ایدی عددی فرد
by : @SuDo`_`StAr
]]
tg.sendMessage(msg.chat_id_, 0, 1, pm1, 1, 'md')
end
end
return {
patterns = {
"^[/#!](help)$",
},
run = run
}
| gpl-3.0 |
warriorYosemite/colorBrick | cocos2d/plugin/luabindings/auto/api/lua_cocos2dx_pluginx_auto_api.lua | 146 | 1793 | --------------------------------
-- @module plugin
--------------------------------------------------------
-- the plugin PluginProtocol
-- @field [parent=#plugin] PluginProtocol#PluginProtocol PluginProtocol preloaded module
--------------------------------------------------------
-- the plugin PluginManager
-- @field [parent=#plugin] PluginManager#PluginManager PluginManager preloaded module
--------------------------------------------------------
-- the plugin ProtocolAnalytics
-- @field [parent=#plugin] ProtocolAnalytics#ProtocolAnalytics ProtocolAnalytics preloaded module
--------------------------------------------------------
-- the plugin ProtocolIAP
-- @field [parent=#plugin] ProtocolIAP#ProtocolIAP ProtocolIAP preloaded module
--------------------------------------------------------
-- the plugin ProtocolAds
-- @field [parent=#plugin] ProtocolAds#ProtocolAds ProtocolAds preloaded module
--------------------------------------------------------
-- the plugin ProtocolShare
-- @field [parent=#plugin] ProtocolShare#ProtocolShare ProtocolShare preloaded module
--------------------------------------------------------
-- the plugin ProtocolSocial
-- @field [parent=#plugin] ProtocolSocial#ProtocolSocial ProtocolSocial preloaded module
--------------------------------------------------------
-- the plugin ProtocolUser
-- @field [parent=#plugin] ProtocolUser#ProtocolUser ProtocolUser preloaded module
--------------------------------------------------------
-- the plugin AgentManager
-- @field [parent=#plugin] AgentManager#AgentManager AgentManager preloaded module
--------------------------------------------------------
-- the plugin FacebookAgent
-- @field [parent=#plugin] FacebookAgent#FacebookAgent FacebookAgent preloaded module
return nil
| gpl-3.0 |
subzrk/BadRotations | Libs/DiesalGUI-1.0/Objects/Bar.lua | 6 | 6170 | -- $Id: Bar.lua 60 2016-11-04 01:34:23Z diesal2010 $
local DiesalGUI = LibStub("DiesalGUI-1.0")
-- | Libraries |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local DiesalTools = LibStub("DiesalTools-1.0")
local DiesalStyle = LibStub("DiesalStyle-1.0")
-- ~~| Diesal Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local Colors = DiesalStyle.Colors
local HSL, ShadeColor, TintColor = DiesalTools.HSL, DiesalTools.ShadeColor, DiesalTools.TintColor
-- | Lua Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local type, tonumber, select = type, tonumber, select
local pairs, ipairs, next = pairs, ipairs, next
local min, max = math.min, math.max
-- | WoW Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- | Spinner |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local Type = "Bar"
local Version = 1
-- | Stylesheets |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local Stylesheet = {
['frame-background'] = {
type = 'texture',
layer = 'BACKGROUND',
color = '000000',
alpha = .60,
},
['frame-outline'] = {
type = 'outline',
layer = 'BORDER',
color = 'FFFFFF',
alpha = .02,
position = 1,
},
['frame-inline'] = {
type = 'outline',
layer = 'BORDER',
color = '000000',
alpha = .60,
},
['bar-background'] = {
type = 'texture',
layer = 'BACKGROUND',
gradient = {'VERTICAL',Colors.UI_A100,ShadeColor(Colors.UI_A100,.1)},
position = 0,
},
['bar-inline'] = {
type = 'outline',
layer = 'BORDER',
gradient = {'VERTICAL','FFFFFF','FFFFFF'},
alpha = {.07,.02},
position = 0,
},
['bar-outline'] = {
type = 'texture',
layer = 'ARTWORK',
color = '000000',
alpha = .7,
width = 1,
position = {nil,1,0,0},
},
}
local wireFrame = {
['frame-white'] = {
type = 'outline',
layer = 'OVERLAY',
color = 'ffffff',
},
['bar-green'] = {
type = 'outline',
layer = 'OVERLAY',
color = '55ff00',
},
}
-- | Locals |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local function round(num)
return floor((num + 1/2)/1) * 1
end
-- | Methods |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local methods = {
['OnAcquire'] = function(self)
self:SetStylesheet(Stylesheet)
self:ApplySettings()
-- self:SetStylesheet(wireFrame)
self:Show()
end,
['OnRelease'] = function(self)
end,
['ApplySettings'] = function(self)
self:UpdateSize()
end,
['UpdateSize'] = function(self)
self:SetWidth(self.settings.width)
self:SetHeight(self.settings.height)
self.bar:SetPoint('TOPLEFT',self.settings.padding[1],-self.settings.padding[3])
self.bar:SetPoint('BOTTOMLEFT',self.settings.padding[1],self.settings.padding[4])
self.settings.barWidth = self.settings.width - self.settings.padding[1] - self.settings.padding[2]
self:UpdateBar()
end,
['SetColor'] = function(self, color, colorTop, gradientDirection)
end,
['SetSize'] = function(self, width, height)
width, height = tonumber(width), tonumber(height)
if not width then error('Bar:SetSize(width, height) width to be a number.',0) end
if not height then error('Bar:SetSize(width, height) height to be a number.',0) end
self.settings.width, self.settings.height = width, height
self:UpdateSize()
end,
['SetValue'] = function(self, number, min, max)
number, min, max = tonumber(number), tonumber(min), tonumber(max)
if not number then error('Bar:SetValue(number) number needs to be a number.',0) end
self.settings.min = min or self.settings.min
self.settings.max = max or self.settings.max
self.settings.value = number
self:UpdateBar()
end,
['SetMin'] = function(self, number)
number = tonumber(number)
if not number then error('Bar:SetMin(number) needs to be a number.',0) end
self.settings.min = number
self:UpdateBar()
end,
['SetMax'] = function(self, number)
number = tonumber(number)
if not number then error('Bar:SetMax(number) needs to be a number.',0) end
self.settings.max = number
self:UpdateBar()
end,
['UpdateBar'] = function(self)
local min, max, value, barWidth = self.settings.min, self.settings.max, self.settings.value, self.settings.barWidth
local width = round( (value - min) / (max - min) * barWidth )
if width == 0 then
self.bar:Hide()
else
self.bar:Show()
self.bar:SetWidth(width)
end
end,
['IsVisible'] = function(self)
return self.frame:IsVisible()
end,
}
-- | Constructor |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local function Constructor()
local self = DiesalGUI:CreateObjectBase(Type)
local frame = CreateFrame('Frame',nil,UIParent)
self.frame = frame
-- ~~ Default Settings ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
self.defaults = {
height = 14, -- frame height (not bar)
width = 96, -- frame width (not bar)
padding = {1,1,1,1}, -- left, right, top, bottom (bar padding from frame)
value = 0,
min = 0,
max = 100,
}
-- ~~ Construct ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
frame:SetScript("OnHide",function(this)
self:FireEvent("OnHide")
end)
local bar = self:CreateRegion("Frame", 'bar', frame)
-- ~~ Methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for method, func in pairs(methods) do self[method] = func end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
return self
end
DiesalGUI:RegisterObjectConstructor(Type,Constructor,Version)
| gpl-3.0 |
caidongyun/nginx-openresty-windows | luajit-root/luajit/share/luajit-2.1.0-alpha/jit/dis_x86.lua | 2 | 30214 | ----------------------------------------------------------------------------
-- LuaJIT x86/x64 disassembler module.
--
-- Copyright (C) 2005-2013 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
-- This is a helper module used by the LuaJIT machine code dumper module.
--
-- Sending small code snippets to an external disassembler and mixing the
-- output with our own stuff was too fragile. So I had to bite the bullet
-- and write yet another x86 disassembler. Oh well ...
--
-- The output format is very similar to what ndisasm generates. But it has
-- been developed independently by looking at the opcode tables from the
-- Intel and AMD manuals. The supported instruction set is quite extensive
-- and reflects what a current generation Intel or AMD CPU implements in
-- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3,
-- SSE4.1, SSE4.2, SSE4a and even privileged and hypervisor (VMX/SVM)
-- instructions.
--
-- Notes:
-- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported.
-- * No attempt at optimization has been made -- it's fast enough for my needs.
-- * The public API may change when more architectures are added.
------------------------------------------------------------------------------
local type = type
local sub, byte, format = string.sub, string.byte, string.format
local match, gmatch, gsub = string.match, string.gmatch, string.gsub
local lower, rep = string.lower, string.rep
local bit = require("bit")
local tohex = bit.tohex
-- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on.
local map_opc1_32 = {
--0x
[0]="addBmr","addVmr","addBrm","addVrm","addBai","addVai","push es","pop es",
"orBmr","orVmr","orBrm","orVrm","orBai","orVai","push cs","opc2*",
--1x
"adcBmr","adcVmr","adcBrm","adcVrm","adcBai","adcVai","push ss","pop ss",
"sbbBmr","sbbVmr","sbbBrm","sbbVrm","sbbBai","sbbVai","push ds","pop ds",
--2x
"andBmr","andVmr","andBrm","andVrm","andBai","andVai","es:seg","daa",
"subBmr","subVmr","subBrm","subVrm","subBai","subVai","cs:seg","das",
--3x
"xorBmr","xorVmr","xorBrm","xorVrm","xorBai","xorVai","ss:seg","aaa",
"cmpBmr","cmpVmr","cmpBrm","cmpVrm","cmpBai","cmpVai","ds:seg","aas",
--4x
"incVR","incVR","incVR","incVR","incVR","incVR","incVR","incVR",
"decVR","decVR","decVR","decVR","decVR","decVR","decVR","decVR",
--5x
"pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR",
"popUR","popUR","popUR","popUR","popUR","popUR","popUR","popUR",
--6x
"sz*pushaw,pusha","sz*popaw,popa","boundVrm","arplWmr",
"fs:seg","gs:seg","o16:","a16",
"pushUi","imulVrmi","pushBs","imulVrms",
"insb","insVS","outsb","outsVS",
--7x
"joBj","jnoBj","jbBj","jnbBj","jzBj","jnzBj","jbeBj","jaBj",
"jsBj","jnsBj","jpeBj","jpoBj","jlBj","jgeBj","jleBj","jgBj",
--8x
"arith!Bmi","arith!Vmi","arith!Bmi","arith!Vms",
"testBmr","testVmr","xchgBrm","xchgVrm",
"movBmr","movVmr","movBrm","movVrm",
"movVmg","leaVrm","movWgm","popUm",
--9x
"nop*xchgVaR|pause|xchgWaR|repne nop","xchgVaR","xchgVaR","xchgVaR",
"xchgVaR","xchgVaR","xchgVaR","xchgVaR",
"sz*cbw,cwde,cdqe","sz*cwd,cdq,cqo","call farViw","wait",
"sz*pushfw,pushf","sz*popfw,popf","sahf","lahf",
--Ax
"movBao","movVao","movBoa","movVoa",
"movsb","movsVS","cmpsb","cmpsVS",
"testBai","testVai","stosb","stosVS",
"lodsb","lodsVS","scasb","scasVS",
--Bx
"movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi",
"movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI",
--Cx
"shift!Bmu","shift!Vmu","retBw","ret","$lesVrm","$ldsVrm","movBmi","movVmi",
"enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS",
--Dx
"shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb",
"fp*0","fp*1","fp*2","fp*3","fp*4","fp*5","fp*6","fp*7",
--Ex
"loopneBj","loopeBj","loopBj","sz*jcxzBj,jecxzBj,jrcxzBj",
"inBau","inVau","outBua","outVua",
"callVj","jmpVj","jmp farViw","jmpBj","inBad","inVad","outBda","outVda",
--Fx
"lock:","int1","repne:rep","rep:","hlt","cmc","testb!Bm","testv!Vm",
"clc","stc","cli","sti","cld","std","incb!Bm","incd!Vm",
}
assert(#map_opc1_32 == 255)
-- Map for 1st opcode byte in 64 bit mode (overrides only).
local map_opc1_64 = setmetatable({
[0x06]=false, [0x07]=false, [0x0e]=false,
[0x16]=false, [0x17]=false, [0x1e]=false, [0x1f]=false,
[0x27]=false, [0x2f]=false, [0x37]=false, [0x3f]=false,
[0x60]=false, [0x61]=false, [0x62]=false, [0x63]="movsxdVrDmt", [0x67]="a32:",
[0x40]="rex*", [0x41]="rex*b", [0x42]="rex*x", [0x43]="rex*xb",
[0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb",
[0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb",
[0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb",
[0x82]=false, [0x9a]=false, [0xc4]=false, [0xc5]=false, [0xce]=false,
[0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false,
}, { __index = map_opc1_32 })
-- Map for 2nd opcode byte (0F xx). True CISC hell. Hey, I told you.
-- Prefix dependent MMX/SSE opcodes: (none)|rep|o16|repne, -|F3|66|F2
local map_opc2 = {
--0x
[0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret",
"invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu",
--1x
"movupsXrm|movssXrm|movupdXrm|movsdXrm",
"movupsXmr|movssXmr|movupdXmr|movsdXmr",
"movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm",
"movlpsXmr||movlpdXmr",
"unpcklpsXrm||unpcklpdXrm",
"unpckhpsXrm||unpckhpdXrm",
"movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm",
"movhpsXmr||movhpdXmr",
"$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm",
"hintnopVm","hintnopVm","hintnopVm","hintnopVm",
--2x
"movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil,
"movapsXrm||movapdXrm",
"movapsXmr||movapdXmr",
"cvtpi2psXrMm|cvtsi2ssXrVmt|cvtpi2pdXrMm|cvtsi2sdXrVmt",
"movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr",
"cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm",
"cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm",
"ucomissXrm||ucomisdXrm",
"comissXrm||comisdXrm",
--3x
"wrmsr","rdtsc","rdmsr","rdpmc","sysenter","sysexit",nil,"getsec",
"opc3*38",nil,"opc3*3a",nil,nil,nil,nil,nil,
--4x
"cmovoVrm","cmovnoVrm","cmovbVrm","cmovnbVrm",
"cmovzVrm","cmovnzVrm","cmovbeVrm","cmovaVrm",
"cmovsVrm","cmovnsVrm","cmovpeVrm","cmovpoVrm",
"cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm",
--5x
"movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm",
"rsqrtpsXrm|rsqrtssXrm","rcppsXrm|rcpssXrm",
"andpsXrm||andpdXrm","andnpsXrm||andnpdXrm",
"orpsXrm||orpdXrm","xorpsXrm||xorpdXrm",
"addpsXrm|addssXrm|addpdXrm|addsdXrm","mulpsXrm|mulssXrm|mulpdXrm|mulsdXrm",
"cvtps2pdXrm|cvtss2sdXrm|cvtpd2psXrm|cvtsd2ssXrm",
"cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm",
"subpsXrm|subssXrm|subpdXrm|subsdXrm","minpsXrm|minssXrm|minpdXrm|minsdXrm",
"divpsXrm|divssXrm|divpdXrm|divsdXrm","maxpsXrm|maxssXrm|maxpdXrm|maxsdXrm",
--6x
"punpcklbwPrm","punpcklwdPrm","punpckldqPrm","packsswbPrm",
"pcmpgtbPrm","pcmpgtwPrm","pcmpgtdPrm","packuswbPrm",
"punpckhbwPrm","punpckhwdPrm","punpckhdqPrm","packssdwPrm",
"||punpcklqdqXrm","||punpckhqdqXrm",
"movPrVSm","movqMrm|movdquXrm|movdqaXrm",
--7x
"pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pmu",
"pshiftd!Pmu","pshiftq!Mmu||pshiftdq!Xmu",
"pcmpeqbPrm","pcmpeqwPrm","pcmpeqdPrm","emms|",
"vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$",
nil,nil,
"||haddpdXrm|haddpsXrm","||hsubpdXrm|hsubpsXrm",
"movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr",
--8x
"joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj",
"jsVj","jnsVj","jpeVj","jpoVj","jlVj","jgeVj","jleVj","jgVj",
--9x
"setoBm","setnoBm","setbBm","setnbBm","setzBm","setnzBm","setbeBm","setaBm",
"setsBm","setnsBm","setpeBm","setpoBm","setlBm","setgeBm","setleBm","setgBm",
--Ax
"push fs","pop fs","cpuid","btVmr","shldVmru","shldVmrc",nil,nil,
"push gs","pop gs","rsm","btsVmr","shrdVmru","shrdVmrc","fxsave!Dmp","imulVrm",
--Bx
"cmpxchgBmr","cmpxchgVmr","$lssVrm","btrVmr",
"$lfsVrm","$lgsVrm","movzxVrBmt","movzxVrWmt",
"|popcntVrm","ud2Dp","bt!Vmu","btcVmr",
"bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt",
--Cx
"xaddBmr","xaddVmr",
"cmppsXrmu|cmpssXrmu|cmppdXrmu|cmpsdXrmu","$movntiVmr|",
"pinsrwPrWmu","pextrwDrPmu",
"shufpsXrmu||shufpdXrmu","$cmpxchg!Qmp",
"bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR",
--Dx
"||addsubpdXrm|addsubpsXrm","psrlwPrm","psrldPrm","psrlqPrm",
"paddqPrm","pmullwPrm",
"|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm",
"psubusbPrm","psubuswPrm","pminubPrm","pandPrm",
"paddusbPrm","padduswPrm","pmaxubPrm","pandnPrm",
--Ex
"pavgbPrm","psrawPrm","psradPrm","pavgwPrm",
"pmulhuwPrm","pmulhwPrm",
"|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr",
"psubsbPrm","psubswPrm","pminswPrm","porPrm",
"paddsbPrm","paddswPrm","pmaxswPrm","pxorPrm",
--Fx
"|||lddquXrm","psllwPrm","pslldPrm","psllqPrm",
"pmuludqPrm","pmaddwdPrm","psadbwPrm","maskmovqMrm||maskmovdquXrm$",
"psubbPrm","psubwPrm","psubdPrm","psubqPrm",
"paddbPrm","paddwPrm","padddPrm","ud",
}
assert(map_opc2[255] == "ud")
-- Map for three-byte opcodes. Can't wait for their next invention.
local map_opc3 = {
["38"] = { -- [66] 0f 38 xx
--0x
[0]="pshufbPrm","phaddwPrm","phadddPrm","phaddswPrm",
"pmaddubswPrm","phsubwPrm","phsubdPrm","phsubswPrm",
"psignbPrm","psignwPrm","psigndPrm","pmulhrswPrm",
nil,nil,nil,nil,
--1x
"||pblendvbXrma",nil,nil,nil,
"||blendvpsXrma","||blendvpdXrma",nil,"||ptestXrm",
nil,nil,nil,nil,
"pabsbPrm","pabswPrm","pabsdPrm",nil,
--2x
"||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm",
"||pmovsxwqXrm","||pmovsxdqXrm",nil,nil,
"||pmuldqXrm","||pcmpeqqXrm","||$movntdqaXrm","||packusdwXrm",
nil,nil,nil,nil,
--3x
"||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm",
"||pmovzxwqXrm","||pmovzxdqXrm",nil,"||pcmpgtqXrm",
"||pminsbXrm","||pminsdXrm","||pminuwXrm","||pminudXrm",
"||pmaxsbXrm","||pmaxsdXrm","||pmaxuwXrm","||pmaxudXrm",
--4x
"||pmulddXrm","||phminposuwXrm",
--Fx
[0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt",
},
["3a"] = { -- [66] 0f 3a xx
--0x
[0x00]=nil,nil,nil,nil,nil,nil,nil,nil,
"||roundpsXrmu","||roundpdXrmu","||roundssXrmu","||roundsdXrmu",
"||blendpsXrmu","||blendpdXrmu","||pblendwXrmu","palignrPrmu",
--1x
nil,nil,nil,nil,
"||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru",
nil,nil,nil,nil,nil,nil,nil,nil,
--2x
"||pinsrbXrVmu","||insertpsXrmu","||pinsrXrVmuS",nil,
--4x
[0x40] = "||dppsXrmu",
[0x41] = "||dppdXrmu",
[0x42] = "||mpsadbwXrmu",
--6x
[0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu",
[0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu",
},
}
-- Map for VMX/SVM opcodes 0F 01 C0-FF (sgdt group with register operands).
local map_opcvm = {
[0xc1]="vmcall",[0xc2]="vmlaunch",[0xc3]="vmresume",[0xc4]="vmxoff",
[0xc8]="monitor",[0xc9]="mwait",
[0xd8]="vmrun",[0xd9]="vmmcall",[0xda]="vmload",[0xdb]="vmsave",
[0xdc]="stgi",[0xdd]="clgi",[0xde]="skinit",[0xdf]="invlpga",
[0xf8]="swapgs",[0xf9]="rdtscp",
}
-- Map for FP opcodes. And you thought stack machines are simple?
local map_opcfp = {
-- D8-DF 00-BF: opcodes with a memory operand.
-- D8
[0]="faddFm","fmulFm","fcomFm","fcompFm","fsubFm","fsubrFm","fdivFm","fdivrFm",
"fldFm",nil,"fstFm","fstpFm","fldenvVm","fldcwWm","fnstenvVm","fnstcwWm",
-- DA
"fiaddDm","fimulDm","ficomDm","ficompDm",
"fisubDm","fisubrDm","fidivDm","fidivrDm",
-- DB
"fildDm","fisttpDm","fistDm","fistpDm",nil,"fld twordFmp",nil,"fstp twordFmp",
-- DC
"faddGm","fmulGm","fcomGm","fcompGm","fsubGm","fsubrGm","fdivGm","fdivrGm",
-- DD
"fldGm","fisttpQm","fstGm","fstpGm","frstorDmp",nil,"fnsaveDmp","fnstswWm",
-- DE
"fiaddWm","fimulWm","ficomWm","ficompWm",
"fisubWm","fisubrWm","fidivWm","fidivrWm",
-- DF
"fildWm","fisttpWm","fistWm","fistpWm",
"fbld twordFmp","fildQm","fbstp twordFmp","fistpQm",
-- xx C0-FF: opcodes with a pseudo-register operand.
-- D8
"faddFf","fmulFf","fcomFf","fcompFf","fsubFf","fsubrFf","fdivFf","fdivrFf",
-- D9
"fldFf","fxchFf",{"fnop"},nil,
{"fchs","fabs",nil,nil,"ftst","fxam"},
{"fld1","fldl2t","fldl2e","fldpi","fldlg2","fldln2","fldz"},
{"f2xm1","fyl2x","fptan","fpatan","fxtract","fprem1","fdecstp","fincstp"},
{"fprem","fyl2xp1","fsqrt","fsincos","frndint","fscale","fsin","fcos"},
-- DA
"fcmovbFf","fcmoveFf","fcmovbeFf","fcmovuFf",nil,{nil,"fucompp"},nil,nil,
-- DB
"fcmovnbFf","fcmovneFf","fcmovnbeFf","fcmovnuFf",
{nil,nil,"fnclex","fninit"},"fucomiFf","fcomiFf",nil,
-- DC
"fadd toFf","fmul toFf",nil,nil,
"fsub toFf","fsubr toFf","fdivr toFf","fdiv toFf",
-- DD
"ffreeFf",nil,"fstFf","fstpFf","fucomFf","fucompFf",nil,nil,
-- DE
"faddpFf","fmulpFf",nil,{nil,"fcompp"},
"fsubrpFf","fsubpFf","fdivrpFf","fdivpFf",
-- DF
nil,nil,nil,nil,{"fnstsw ax"},"fucomipFf","fcomipFf",nil,
}
assert(map_opcfp[126] == "fcomipFf")
-- Map for opcode groups. The subkey is sp from the ModRM byte.
local map_opcgroup = {
arith = { "add", "or", "adc", "sbb", "and", "sub", "xor", "cmp" },
shift = { "rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar" },
testb = { "testBmi", "testBmi", "not", "neg", "mul", "imul", "div", "idiv" },
testv = { "testVmi", "testVmi", "not", "neg", "mul", "imul", "div", "idiv" },
incb = { "inc", "dec" },
incd = { "inc", "dec", "callUmp", "$call farDmp",
"jmpUmp", "$jmp farDmp", "pushUm" },
sldt = { "sldt", "str", "lldt", "ltr", "verr", "verw" },
sgdt = { "vm*$sgdt", "vm*$sidt", "$lgdt", "vm*$lidt",
"smsw", nil, "lmsw", "vm*$invlpg" },
bt = { nil, nil, nil, nil, "bt", "bts", "btr", "btc" },
cmpxchg = { nil, "sz*,cmpxchg8bQmp,cmpxchg16bXmp", nil, nil,
nil, nil, "vmptrld|vmxon|vmclear", "vmptrst" },
pshiftw = { nil, nil, "psrlw", nil, "psraw", nil, "psllw" },
pshiftd = { nil, nil, "psrld", nil, "psrad", nil, "pslld" },
pshiftq = { nil, nil, "psrlq", nil, nil, nil, "psllq" },
pshiftdq = { nil, nil, "psrlq", "psrldq", nil, nil, "psllq", "pslldq" },
fxsave = { "$fxsave", "$fxrstor", "$ldmxcsr", "$stmxcsr",
nil, "lfenceDp$", "mfenceDp$", "sfenceDp$clflush" },
prefetch = { "prefetch", "prefetchw" },
prefetcht = { "prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2" },
}
------------------------------------------------------------------------------
-- Maps for register names.
local map_regs = {
B = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh",
"r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" },
B64 = { "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil",
"r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" },
W = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di",
"r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w" },
D = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi",
"r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d" },
Q = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" },
M = { "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7",
"mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext!
X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
"xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" },
}
local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" }
-- Maps for size names.
local map_sz2n = {
B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16,
}
local map_sz2prefix = {
B = "byte", W = "word", D = "dword",
Q = "qword",
M = "qword", X = "xword",
F = "dword", G = "qword", -- No need for sizes/register names for these two.
}
------------------------------------------------------------------------------
-- Output a nicely formatted line with an opcode and operands.
local function putop(ctx, text, operands)
local code, pos, hex = ctx.code, ctx.pos, ""
local hmax = ctx.hexdump
if hmax > 0 then
for i=ctx.start,pos-1 do
hex = hex..format("%02X", byte(code, i, i))
end
if #hex > hmax then hex = sub(hex, 1, hmax)..". "
else hex = hex..rep(" ", hmax-#hex+2) end
end
if operands then text = text.." "..operands end
if ctx.o16 then text = "o16 "..text; ctx.o16 = false end
if ctx.a32 then text = "a32 "..text; ctx.a32 = false end
if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end
if ctx.rex then
local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "")..
(ctx.rexx and "x" or "")..(ctx.rexb and "b" or "")
if t ~= "" then text = "rex."..t.." "..text end
ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false
ctx.rex = false
end
if ctx.seg then
local text2, n = gsub(text, "%[", "["..ctx.seg..":")
if n == 0 then text = ctx.seg.." "..text else text = text2 end
ctx.seg = false
end
if ctx.lock then text = "lock "..text; ctx.lock = false end
local imm = ctx.imm
if imm then
local sym = ctx.symtab[imm]
if sym then text = text.."\t->"..sym end
end
ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text))
ctx.mrm = false
ctx.start = pos
ctx.imm = nil
end
-- Clear all prefix flags.
local function clearprefixes(ctx)
ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false
ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false
ctx.rex = false; ctx.a32 = false
end
-- Fallback for incomplete opcodes at the end.
local function incomplete(ctx)
ctx.pos = ctx.stop+1
clearprefixes(ctx)
return putop(ctx, "(incomplete)")
end
-- Fallback for unknown opcodes.
local function unknown(ctx)
clearprefixes(ctx)
return putop(ctx, "(unknown)")
end
-- Return an immediate of the specified size.
local function getimm(ctx, pos, n)
if pos+n-1 > ctx.stop then return incomplete(ctx) end
local code = ctx.code
if n == 1 then
local b1 = byte(code, pos, pos)
return b1
elseif n == 2 then
local b1, b2 = byte(code, pos, pos+1)
return b1+b2*256
else
local b1, b2, b3, b4 = byte(code, pos, pos+3)
local imm = b1+b2*256+b3*65536+b4*16777216
ctx.imm = imm
return imm
end
end
-- Process pattern string and generate the operands.
local function putpat(ctx, name, pat)
local operands, regs, sz, mode, sp, rm, sc, rx, sdisp
local code, pos, stop = ctx.code, ctx.pos, ctx.stop
-- Chars used: 1DFGIMPQRSTUVWXacdfgijmoprstuwxyz
for p in gmatch(pat, ".") do
local x = nil
if p == "V" or p == "U" then
if ctx.rexw then sz = "Q"; ctx.rexw = false
elseif ctx.o16 then sz = "W"; ctx.o16 = false
elseif p == "U" and ctx.x64 then sz = "Q"
else sz = "D" end
regs = map_regs[sz]
elseif p == "T" then
if ctx.rexw then sz = "Q"; ctx.rexw = false else sz = "D" end
regs = map_regs[sz]
elseif p == "B" then
sz = "B"
regs = ctx.rex and map_regs.B64 or map_regs.B
elseif match(p, "[WDQMXFG]") then
sz = p
regs = map_regs[sz]
elseif p == "P" then
sz = ctx.o16 and "X" or "M"; ctx.o16 = false
regs = map_regs[sz]
elseif p == "S" then
name = name..lower(sz)
elseif p == "s" then
local imm = getimm(ctx, pos, 1); if not imm then return end
x = imm <= 127 and format("+0x%02x", imm)
or format("-0x%02x", 256-imm)
pos = pos+1
elseif p == "u" then
local imm = getimm(ctx, pos, 1); if not imm then return end
x = format("0x%02x", imm)
pos = pos+1
elseif p == "w" then
local imm = getimm(ctx, pos, 2); if not imm then return end
x = format("0x%x", imm)
pos = pos+2
elseif p == "o" then -- [offset]
if ctx.x64 then
local imm1 = getimm(ctx, pos, 4); if not imm1 then return end
local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end
x = format("[0x%08x%08x]", imm2, imm1)
pos = pos+8
else
local imm = getimm(ctx, pos, 4); if not imm then return end
x = format("[0x%08x]", imm)
pos = pos+4
end
elseif p == "i" or p == "I" then
local n = map_sz2n[sz]
if n == 8 and ctx.x64 and p == "I" then
local imm1 = getimm(ctx, pos, 4); if not imm1 then return end
local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end
x = format("0x%08x%08x", imm2, imm1)
else
if n == 8 then n = 4 end
local imm = getimm(ctx, pos, n); if not imm then return end
if sz == "Q" and (imm < 0 or imm > 0x7fffffff) then
imm = (0xffffffff+1)-imm
x = format(imm > 65535 and "-0x%08x" or "-0x%x", imm)
else
x = format(imm > 65535 and "0x%08x" or "0x%x", imm)
end
end
pos = pos+n
elseif p == "j" then
local n = map_sz2n[sz]
if n == 8 then n = 4 end
local imm = getimm(ctx, pos, n); if not imm then return end
if sz == "B" and imm > 127 then imm = imm-256
elseif imm > 2147483647 then imm = imm-4294967296 end
pos = pos+n
imm = imm + pos + ctx.addr
if imm > 4294967295 and not ctx.x64 then imm = imm-4294967296 end
ctx.imm = imm
if sz == "W" then
x = format("word 0x%04x", imm%65536)
elseif ctx.x64 then
local lo = imm % 0x1000000
x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo)
else
x = "0x"..tohex(imm)
end
elseif p == "R" then
local r = byte(code, pos-1, pos-1)%8
if ctx.rexb then r = r + 8; ctx.rexb = false end
x = regs[r+1]
elseif p == "a" then x = regs[1]
elseif p == "c" then x = "cl"
elseif p == "d" then x = "dx"
elseif p == "1" then x = "1"
else
if not mode then
mode = ctx.mrm
if not mode then
if pos > stop then return incomplete(ctx) end
mode = byte(code, pos, pos)
pos = pos+1
end
rm = mode%8; mode = (mode-rm)/8
sp = mode%8; mode = (mode-sp)/8
sdisp = ""
if mode < 3 then
if rm == 4 then
if pos > stop then return incomplete(ctx) end
sc = byte(code, pos, pos)
pos = pos+1
rm = sc%8; sc = (sc-rm)/8
rx = sc%8; sc = (sc-rx)/8
if ctx.rexx then rx = rx + 8; ctx.rexx = false end
if rx == 4 then rx = nil end
end
if mode > 0 or rm == 5 then
local dsz = mode
if dsz ~= 1 then dsz = 4 end
local disp = getimm(ctx, pos, dsz); if not disp then return end
if mode == 0 then rm = nil end
if rm or rx or (not sc and ctx.x64 and not ctx.a32) then
if dsz == 1 and disp > 127 then
sdisp = format("-0x%x", 256-disp)
elseif disp >= 0 and disp <= 0x7fffffff then
sdisp = format("+0x%x", disp)
else
sdisp = format("-0x%x", (0xffffffff+1)-disp)
end
else
sdisp = format(ctx.x64 and not ctx.a32 and
not (disp >= 0 and disp <= 0x7fffffff)
and "0xffffffff%08x" or "0x%08x", disp)
end
pos = pos+dsz
end
end
if rm and ctx.rexb then rm = rm + 8; ctx.rexb = false end
if ctx.rexr then sp = sp + 8; ctx.rexr = false end
end
if p == "m" then
if mode == 3 then x = regs[rm+1]
else
local aregs = ctx.a32 and map_regs.D or ctx.aregs
local srm, srx = "", ""
if rm then srm = aregs[rm+1]
elseif not sc and ctx.x64 and not ctx.a32 then srm = "rip" end
ctx.a32 = false
if rx then
if rm then srm = srm.."+" end
srx = aregs[rx+1]
if sc > 0 then srx = srx.."*"..(2^sc) end
end
x = format("[%s%s%s]", srm, srx, sdisp)
end
if mode < 3 and
(not match(pat, "[aRrgp]") or match(pat, "t")) then -- Yuck.
x = map_sz2prefix[sz].." "..x
end
elseif p == "r" then x = regs[sp+1]
elseif p == "g" then x = map_segregs[sp+1]
elseif p == "p" then -- Suppress prefix.
elseif p == "f" then x = "st"..rm
elseif p == "x" then
if sp == 0 and ctx.lock and not ctx.x64 then
x = "CR8"; ctx.lock = false
else
x = "CR"..sp
end
elseif p == "y" then x = "DR"..sp
elseif p == "z" then x = "TR"..sp
elseif p == "t" then
else
error("bad pattern `"..pat.."'")
end
end
if x then operands = operands and operands..", "..x or x end
end
ctx.pos = pos
return putop(ctx, name, operands)
end
-- Forward declaration.
local map_act
-- Fetch and cache MRM byte.
local function getmrm(ctx)
local mrm = ctx.mrm
if not mrm then
local pos = ctx.pos
if pos > ctx.stop then return nil end
mrm = byte(ctx.code, pos, pos)
ctx.pos = pos+1
ctx.mrm = mrm
end
return mrm
end
-- Dispatch to handler depending on pattern.
local function dispatch(ctx, opat, patgrp)
if not opat then return unknown(ctx) end
if match(opat, "%|") then -- MMX/SSE variants depending on prefix.
local p
if ctx.rep then
p = ctx.rep=="rep" and "%|([^%|]*)" or "%|[^%|]*%|[^%|]*%|([^%|]*)"
ctx.rep = false
elseif ctx.o16 then p = "%|[^%|]*%|([^%|]*)"; ctx.o16 = false
else p = "^[^%|]*" end
opat = match(opat, p)
if not opat then return unknown(ctx) end
-- ctx.rep = false; ctx.o16 = false
--XXX fails for 66 f2 0f 38 f1 06 crc32 eax,WORD PTR [esi]
--XXX remove in branches?
end
if match(opat, "%$") then -- reg$mem variants.
local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end
opat = match(opat, mrm >= 192 and "^[^%$]*" or "%$(.*)")
if opat == "" then return unknown(ctx) end
end
if opat == "" then return unknown(ctx) end
local name, pat = match(opat, "^([a-z0-9 ]*)(.*)")
if pat == "" and patgrp then pat = patgrp end
return map_act[sub(pat, 1, 1)](ctx, name, pat)
end
-- Get a pattern from an opcode map and dispatch to handler.
local function dispatchmap(ctx, opcmap)
local pos = ctx.pos
local opat = opcmap[byte(ctx.code, pos, pos)]
pos = pos + 1
ctx.pos = pos
return dispatch(ctx, opat)
end
-- Map for action codes. The key is the first char after the name.
map_act = {
-- Simple opcodes without operands.
[""] = function(ctx, name, pat)
return putop(ctx, name)
end,
-- Operand size chars fall right through.
B = putpat, W = putpat, D = putpat, Q = putpat,
V = putpat, U = putpat, T = putpat,
M = putpat, X = putpat, P = putpat,
F = putpat, G = putpat,
-- Collect prefixes.
[":"] = function(ctx, name, pat)
ctx[pat == ":" and name or sub(pat, 2)] = name
if ctx.pos - ctx.start > 5 then return unknown(ctx) end -- Limit #prefixes.
end,
-- Chain to special handler specified by name.
["*"] = function(ctx, name, pat)
return map_act[name](ctx, name, sub(pat, 2))
end,
-- Use named subtable for opcode group.
["!"] = function(ctx, name, pat)
local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end
return dispatch(ctx, map_opcgroup[name][((mrm-(mrm%8))/8)%8+1], sub(pat, 2))
end,
-- o16,o32[,o64] variants.
sz = function(ctx, name, pat)
if ctx.o16 then ctx.o16 = false
else
pat = match(pat, ",(.*)")
if ctx.rexw then
local p = match(pat, ",(.*)")
if p then pat = p; ctx.rexw = false end
end
end
pat = match(pat, "^[^,]*")
return dispatch(ctx, pat)
end,
-- Two-byte opcode dispatch.
opc2 = function(ctx, name, pat)
return dispatchmap(ctx, map_opc2)
end,
-- Three-byte opcode dispatch.
opc3 = function(ctx, name, pat)
return dispatchmap(ctx, map_opc3[pat])
end,
-- VMX/SVM dispatch.
vm = function(ctx, name, pat)
return dispatch(ctx, map_opcvm[ctx.mrm])
end,
-- Floating point opcode dispatch.
fp = function(ctx, name, pat)
local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end
local rm = mrm%8
local idx = pat*8 + ((mrm-rm)/8)%8
if mrm >= 192 then idx = idx + 64 end
local opat = map_opcfp[idx]
if type(opat) == "table" then opat = opat[rm+1] end
return dispatch(ctx, opat)
end,
-- REX prefix.
rex = function(ctx, name, pat)
if ctx.rex then return unknown(ctx) end -- Only 1 REX prefix allowed.
for p in gmatch(pat, ".") do ctx["rex"..p] = true end
ctx.rex = true
end,
-- Special case for nop with REX prefix.
nop = function(ctx, name, pat)
return dispatch(ctx, ctx.rex and pat or "nop")
end,
}
------------------------------------------------------------------------------
-- Disassemble a block of code.
local function disass_block(ctx, ofs, len)
if not ofs then ofs = 0 end
local stop = len and ofs+len or #ctx.code
ofs = ofs + 1
ctx.start = ofs
ctx.pos = ofs
ctx.stop = stop
ctx.imm = nil
ctx.mrm = false
clearprefixes(ctx)
while ctx.pos <= stop do dispatchmap(ctx, ctx.map1) end
if ctx.pos ~= ctx.start then incomplete(ctx) end
end
-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len).
local function create(code, addr, out)
local ctx = {}
ctx.code = code
ctx.addr = (addr or 0) - 1
ctx.out = out or io.write
ctx.symtab = {}
ctx.disass = disass_block
ctx.hexdump = 16
ctx.x64 = false
ctx.map1 = map_opc1_32
ctx.aregs = map_regs.D
return ctx
end
local function create64(code, addr, out)
local ctx = create(code, addr, out)
ctx.x64 = true
ctx.map1 = map_opc1_64
ctx.aregs = map_regs.Q
return ctx
end
-- Simple API: disassemble code (a string) at address and output via out.
local function disass(code, addr, out)
create(code, addr, out):disass()
end
local function disass64(code, addr, out)
create64(code, addr, out):disass()
end
-- Return register name for RID.
local function regname(r)
if r < 8 then return map_regs.D[r+1] end
return map_regs.X[r-7]
end
local function regname64(r)
if r < 16 then return map_regs.Q[r+1] end
return map_regs.X[r-15]
end
-- Public module functions.
return {
create = create,
create64 = create64,
disass = disass,
disass64 = disass64,
regname = regname,
regname64 = regname64
}
| bsd-2-clause |
FFXIOrgins/FFXIOrgins | scripts/zones/Dynamis-Jeuno/mobs/Goblin_Statue.lua | 17 | 5156 | -----------------------------------
-- Area: Dynamis Jeuno
-- NPC: Goblin Statue
-- Map1 Position: http://images3.wikia.nocookie.net/__cb20090312005127/ffxi/images/b/bb/Jeu1.jpg
-- Map2 Position: http://images4.wikia.nocookie.net/__cb20090312005155/ffxi/images/3/31/Jeu2.jpg
-- Vanguard Position: http://faranim.livejournal.com/39860.html
-----------------------------------
package.loaded["scripts/zones/Dynamis-Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Jeuno/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
local X = mob:getXPos();
local Y = mob:getYPos();
local Z = mob:getZPos();
local spawnList = jeunoList;
if(mob:getStatPoppedMobs() == false) then
mob:setStatPoppedMobs(true);
for nb = 1, table.getn(spawnList), 2 do
if(mob:getID() == spawnList[nb]) then
for nbi = 1, table.getn(spawnList[nb + 1]), 1 do
if((nbi % 2) == 0) then X=X+2; Z=Z+2; else X=X-2; Z=Z-2; end
local mobNBR = spawnList[nb + 1][nbi];
if(mobNBR <= 20) then
if(mobNBR == 0) then mobNBR = math.random(1,15); end -- Spawn random Vanguard (TEMPORARY)
local DynaMob = getDynaMob(target,mobNBR,1);
--printf("Goblin Statue => mob %u \n",DynaMob);
if(DynaMob ~= nil) then
-- Spawn Mob
SpawnMob(DynaMob):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(DynaMob):setPos(X,Y,Z);
GetMobByID(DynaMob):setSpawn(X,Y,Z);
-- Spawn Pet for BST, DRG, and SMN
if(mobNBR == 9 or mobNBR == 15) then
SpawnMob(DynaMob + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(DynaMob + 1):setPos(X,Y,Z);
GetMobByID(DynaMob + 1):setSpawn(X,Y,Z);
end
end
elseif(mobNBR > 20) then
SpawnMob(mobNBR):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
local MJob = GetMobByID(mobNBR):getMainJob();
if(MJob == 9 or MJob == 15) then
-- Spawn Pet for BST, DRG, and SMN
SpawnMob(mobNBR + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(mobNBR + 1):setPos(X,Y,Z);
GetMobByID(mobNBR + 1):setSpawn(X,Y,Z);
end
end
end
end
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
mobID = mob:getID();
-- HP Bonus: 005 011 016 023 026 031 040 057 063 065 068 077 079 080 082 083 084 093 102 119 | 123 126 128
if(mobID == 17547534 or mobID == 17547540 or mobID == 17547545 or mobID == 17547552 or mobID == 17547555 or mobID == 17547560 or mobID == 17547569 or mobID == 17547586 or
mobID == 17547592 or mobID == 17547594 or mobID == 17547597 or mobID == 17547606 or mobID == 17547608 or mobID == 17547609 or mobID == 17547612 or mobID == 17547613 or
mobID == 17547622 or mobID == 17547631 or mobID == 17547647 or mobID == 17547651 or mobID == 17547654 or mobID == 17547656) then
killer:restoreHP(3000);
killer:messageBasic(024,(killer:getMaxHP()-killer:getHP()));
-- MP Bonus: 009 012 017 024 025 030 039 044 056 062 064 067 076 078 081 082 085 094 095 101 118 | 122 127 129 150
elseif(mobID == 17547538 or mobID == 17547541 or mobID == 17547546 or mobID == 17547553 or mobID == 17547554 or mobID == 17547559 or mobID == 17547568 or mobID == 17547573 or
mobID == 17547585 or mobID == 17547591 or mobID == 17547593 or mobID == 17547596 or mobID == 17547605 or mobID == 17547607 or mobID == 17547610 or mobID == 17547611 or
mobID == 17547614 or mobID == 17547623 or mobID == 17547624 or mobID == 17547630 or mobID == 17547646 or mobID == 17547650 or mobID == 17547655 or mobID == 17547657 or
mobID == 17547678) then
killer:restoreMP(3000);
killer:messageBasic(025,(killer:getMaxMP()-killer:getMP()));
end
-- Spawn 089-097 when statue 044 is defeated
if(mobID == 17547573) then
for nbx = 17547618, 17547626, 1 do SpawnMob(nbx); end
end
-- Spawn 114-120 when statue 064 is defeated
if(mobID == 17547593) then
for nbx = 17547642, 17547648, 1 do SpawnMob(nbx); end
local spawn = {17547265,17547608,17547609,17547610,17547611,17547612,17547613,17547614,17547615,17547616,17547617};
for nbi = 1, table.getn(spawn), 1 do
SpawnMob(spawn[nbi]);
end
end
-- Spawn 098-100 when statue 073 074 075 are defeated
if((mobID == 17547602 or mobID == 17547603 or mobID == 17547604) and
GetMobAction(17547602) ~= 16 and GetMobAction(17547603) ~= 16 and GetMobAction(17547604) ~= 16) then
SpawnMob(17547627); -- 098
SpawnMob(17547628); -- 099
SpawnMob(17547629); -- 100
end
-- Spawn 101-112 when statue Center of 098 099 100 is defeated
if(mobID == 17547628) then
for nbx = 17547630, 17547641, 1 do SpawnMob(nbx); end
end
end; | gpl-3.0 |
daofeng2015/luci | applications/luci-app-coovachilli/luasrc/model/cbi/coovachilli_network.lua | 79 | 1459 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local sys = require"luci.sys"
local ip = require "luci.ip"
m = Map("coovachilli")
-- tun
s1 = m:section(TypedSection, "tun")
s1.anonymous = true
s1:option( Flag, "usetap" )
s1:option( Value, "tundev" ).optional = true
s1:option( Value, "txqlen" ).optional = true
net = s1:option( Value, "net" )
for _, route in ipairs(ip.routes({ family = 4, type = 1 })) do
if route.dest:prefix() > 0 and route.dest:prefix() < 32 then
net:value( route.dest:string() )
end
end
s1:option( Value, "dynip" ).optional = true
s1:option( Value, "statip" ).optional = true
s1:option( Value, "dns1" ).optional = true
s1:option( Value, "dns2" ).optional = true
s1:option( Value, "domain" ).optional = true
s1:option( Value, "ipup" ).optional = true
s1:option( Value, "ipdown" ).optional = true
s1:option( Value, "conup" ).optional = true
s1:option( Value, "condown" ).optional = true
-- dhcp config
s2 = m:section(TypedSection, "dhcp")
s2.anonymous = true
dif = s2:option( Value, "dhcpif" )
for _, nif in ipairs(sys.net.devices()) do
if nif ~= "lo" then dif:value(nif) end
end
s2:option( Value, "dhcpmac" ).optional = true
s2:option( Value, "lease" ).optional = true
s2:option( Value, "dhcpstart" ).optional = true
s2:option( Value, "dhcpend" ).optional = true
s2:option( Flag, "eapolenable" )
return m
| apache-2.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Castle_Oztroja/npcs/_47x.lua | 17 | 1245 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _47x (Handle)
-- Notes: Opens door _477
-- @pos -99 -71 -41 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Castle_Oztroja/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local DoorID = npc:getID() - 1;
local DoorA = GetNPCByID(DoorID):getAnimation();
if(player:getZPos() > -45) then
if(DoorA == 9 and npc:getAnimation() == 9) then
npc:openDoor(6.5);
-- Should be a ~1 second delay here before the door opens
GetNPCByID(DoorID):openDoor(4.5);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
xToken/CompMod | lua/CompMod/Balance/Balance_Marine_Structures.lua | 1 | 1205 | -- Natural Selection 2 Competitive Mod
-- Source located at - https://github.com/xToken/CompMod
-- lua\CompMod\Balance\Balance_Marine_Structures.lua
-- - Dragon
kCommandStationCost = 15 -- Default is 15
kExtractorCost = 10 -- Default is 10
kInfantryPortalCost = 20 -- Default is 20
kArmoryCost = 10 -- Default is 10
kArmsLabCost = 20 -- Default is 15
kPrototypeLabCost = 40 -- Default is 40
kSentryCost = 5 -- Default is 5
kPowerNodeCost = 15 -- Default is 0
kRoboticsFactoryCost = 10 -- Default is 10
kObservatoryCost = 15 -- Increased from 10
kPhaseGateCost = 15 -- Default is 15
kPowerPointBuildTime = 5
-- Extractor Build Time
kExtractorBuildTime = 15 -- Increased from 11
kMACCost = 8 -- Increased from 5
kARCDamage = 450 -- Default is 450
kARCUpgradedDamage = 550
kARCSpeed = 2.0 -- Default is 2.0
kARCUpgradedSpeed = 3.0
kARCCombatMoveSpeed = 0.8 -- Default is 0.8
kARCUpgradedCombatMoveSpeed = 1.8
kARCDamageType = kDamageType.StructuresOnly
kARCBuildTime = 10
kArmsLabBuildTime = 12 -- Decreased from 17
kExtractorHealth = 2400 -- Default is 2400
kExtractorArmor = 850 -- Default is 1050 | mit |
FFXIOrgins/FFXIOrgins | scripts/zones/Southern_San_dOria_[S]/npcs/Crochepallade.lua | 36 | 1043 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Crochepallade -- Name is Moogle for some reason
-- @zone 80
-- @pos -46 2 -8
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0149);
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.