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 |
|---|---|---|---|---|---|
ArashFaceBook/Virus | plugins/trivia.lua | 647 | 6784 | do
-- Trivia plugin developed by Guy Spronck
-- Returns the chat hash for storing information
local function get_hash(msg)
local hash = nil
if msg.to.type == 'chat' then
hash = 'chat:'..msg.to.id..':trivia'
end
if msg.to.type == 'user' then
hash = 'user:'..msg.from.id..':trivia'
end
return hash
end
-- Sets the question variables
local function set_question(msg, question, answer)
local hash =get_hash(msg)
if hash then
redis:hset(hash, "question", question)
redis:hset(hash, "answer", answer)
redis:hset(hash, "time", os.time())
end
end
-- Returns the current question
local function get_question( msg )
local hash = get_hash(msg)
if hash then
local question = redis:hget(hash, 'question')
if question ~= "NA" then
return question
end
end
return nil
end
-- Returns the answer of the last question
local function get_answer(msg)
local hash = get_hash(msg)
if hash then
return redis:hget(hash, 'answer')
else
return nil
end
end
-- Returns the time of the last question
local function get_time(msg)
local hash = get_hash(msg)
if hash then
return redis:hget(hash, 'time')
else
return nil
end
end
-- This function generates a new question if available
local function get_newquestion(msg)
local timediff = 601
if(get_time(msg)) then
timediff = os.time() - get_time(msg)
end
if(timediff > 600 or get_question(msg) == nil)then
-- Let's show the answer if no-body guessed it right.
if(get_question(msg)) then
send_large_msg(get_receiver(msg), "The question '" .. get_question(msg) .."' has not been answered. \nThe answer was '" .. get_answer(msg) .."'")
end
local url = "http://jservice.io/api/random/"
local b,c = http.request(url)
local query = json:decode(b)
if query then
local stringQuestion = ""
if(query[1].category)then
stringQuestion = "Category: " .. query[1].category.title .. "\n"
end
if query[1].question then
stringQuestion = stringQuestion .. "Question: " .. query[1].question
set_question(msg, query[1].question, query[1].answer:lower())
return stringQuestion
end
end
return 'Something went wrong, please try again.'
else
return 'Please wait ' .. 600 - timediff .. ' seconds before requesting a new question. \nUse !triviaquestion to see the current question.'
end
end
-- This function generates a new question when forced
local function force_newquestion(msg)
-- Let's show the answer if no-body guessed it right.
if(get_question(msg)) then
send_large_msg(get_receiver(msg), "The question '" .. get_question(msg) .."' has not been answered. \nThe answer was '" .. get_answer(msg) .."'")
end
local url = "http://jservice.io/api/random/"
local b,c = http.request(url)
local query = json:decode(b)
if query then
local stringQuestion = ""
if(query[1].category)then
stringQuestion = "Category: " .. query[1].category.title .. "\n"
end
if query[1].question then
stringQuestion = stringQuestion .. "Question: " .. query[1].question
set_question(msg, query[1].question, query[1].answer:lower())
return stringQuestion
end
end
return 'Something went wrong, please try again.'
end
-- This function adds a point to the player
local function give_point(msg)
local hash = get_hash(msg)
if hash then
local score = tonumber(redis:hget(hash, msg.from.id) or 0)
redis:hset(hash, msg.from.id, score+1)
end
end
-- This function checks for a correct answer
local function check_answer(msg, answer)
if(get_answer(msg)) then -- Safety for first time use
if(get_answer(msg) == "NA")then
-- Question has not been set, give a new one
--get_newquestion(msg)
return "No question set, please use !trivia first."
elseif (get_answer(msg) == answer:lower()) then -- Question is set, lets check the answer
set_question(msg, "NA", "NA") -- Correct, clear the answer
give_point(msg) -- gives out point to player for correct answer
return msg.from.print_name .. " has answered correctly! \nUse !trivia to get a new question."
else
return "Sorry " .. msg.from.print_name .. ", but '" .. answer .. "' is not the correct answer!"
end
else
return "No question set, please use !trivia first."
end
end
local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
local function get_user_score(msg, user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local hash = 'chat:'..msg.to.id..':trivia'
user_info.score = tonumber(redis:hget(hash, user_id) or 0)
user_info.name = user_print_name(user)..' ('..user_id..')'
return user_info
end
-- Function to print score
local function trivia_scores(msg)
if msg.to.type == 'chat' then
-- Users on chat
local hash = 'chat:'..msg.to.id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_user_score(msg, user_id, msg.to.id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.score and b.score then
return a.score > b.score
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.score..'\n'
end
return text
else
return "This function is only available in group chats."
end
end
local function run(msg, matches)
if(matches[1] == "!triviascore" or matches[1] == "!triviascores") then
-- Output all scores
return trivia_scores(msg)
elseif(matches[1] == "!triviaquestion")then
return "Question: " .. get_question(msg)
elseif(matches[1] == "!triviaskip") then
if is_sudo(msg) then
return force_newquestion(msg)
end
elseif(matches[1] ~= "!trivia") then
return check_answer(msg, matches[1])
end
return get_newquestion(msg)
end
return {
description = "Trivia plugin for Telegram",
usage = {
"!trivia to obtain a new question.",
"!trivia [answer] to answer the question.",
"!triviaquestion to show the current question.",
"!triviascore to get a scoretable of all players.",
"!triviaskip to skip a question (requires sudo)"
},
patterns = {"^!trivia (.*)$",
"^!trivia$",
"^!triviaquestion$",
"^!triviascore$",
"^!triviascores$",
"^!triviaskip$"},
run = run
}
end
| gpl-2.0 |
TheAnswer/FirstTest | bin/scripts/creatures/objects/endor/npcs/gundula/gundulaElder.lua | 1 | 4574 | --Copyright (C) 2008 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
gundulaElder = Creature:new {
objectName = "gundulaElder", -- Lua Object Name
creatureType = "NPC",
faction = "gundula_tribe",
factionPoints = 20,
gender = "",
speciesName = "gundula_elder",
stfName = "mob/creature_names",
objectCRC = 1805137364,
socialGroup = "gundula_tribe",
level = 56,
combatFlags = ATTACKABLE_FLAG + ENEMY_FLAG,
healthMax = 13000,
healthMin = 11000,
strength = 0,
constitution = 0,
actionMax = 13000,
actionMin = 11000,
quickness = 0,
stamina = 0,
mindMax = 13000,
mindMin = 11000,
focus = 0,
willpower = 0,
height = 1, -- Size of creature
armor = 0, -- 0 = None; 1 = Light; 2 = Medium; 3 = Heavy
kinetic = 0,
energy = 30,
electricity = 60,
stun = 0,
blast = 0,
heat = 0,
cold = 60,
acid = 0,
lightsaber = 0,
accuracy = 0,
healer = 0,
pack = 1,
herd = 0,
stalker = 0,
killer = 0,
ferocity = 0,
aggressive = 0,
invincible = 0,
attackCreatureOnSight = "", -- Enter socialGroups
weapon = "object/weapon/creature/shared_creature_default_weapon.iff", -- File path to weapon -> object\xxx\xxx\xx
weaponName = "Creature Defualt", -- Name ex. 'a Vibrolance'
weaponTemp = "creature_default_weapon", -- Weapon Template ex. 'lance_vibrolance'
weaponClass = "UnarmedMeleeWeapon", -- Weapon Class ex. 'PolearmMeleeWeapon'
weaponEquipped = 0,
weaponMinDamage = 420,
weaponMaxDamage = 550,
weaponAttackSpeed = 2,
weaponDamageType = "KINETIC", -- ELECTRICITY, KINETIC, etc
weaponArmorPiercing = "NONE", -- LIGHT, NONE, MEDIUM, HEAVY
alternateWeapon = "", -- File path to weapon -> object\xxx\xxx\xx
alternateWeaponName = "", -- Name ex. 'a Vibrolance'
alternateWeaponTemp = "", -- Weapon Template ex. 'lance_vibrolance'
alternateWeaponClass = "", -- Weapon Class ex. 'PolearmMeleeWeapon'
alternateWeaponEquipped = 0,
alternateWeaponMinDamage = 0,
alternateWeaponMaxDamage = 0,
alternateWeaponAttackSpeed = 0,
alternateWeaponDamageType = "", -- ELECTRICITY, KINETIC, etc
alternateWeaponArmorPiercing = "", -- LIGHT, NONE, MEDIUM, HEAVY
internalNPCDamageModifier = 0.3, -- Damage Modifier to other NPC's
lootGroup = "0", -- Group it belongs to for loot
tame = 0,
datapadItemCRC = 0,
mountCRC = 0,
mountSpeed = 0,
mountAcceleration = 0,
milk = 0,
boneType = "",
boneMax = 0,
hideType = "",
hideMax = 0,
meatType = "",
meatMax = 0,
skills = { "gundulaAttack1" },
respawnTimer = 180,
behaviorScript = "", -- Link to the behavior script for this object
}
Creatures:addCreature(gundulaElder, 1805137364) -- Add to Global Table
| lgpl-3.0 |
minexew/zeroDB | AddOns/zeroDB/ui/TabView.lua | 1 | 2354 |
zeroDB = zeroDB or {}
zeroDB.TabView = {}
local tab_inactive = 'Interface\\AddOns\\zeroDB\\assets\\tab_inactive'
local tab_active = 'Interface\\AddOns\\zeroDB\\assets\\tab_active'
function zeroDB.TabView:new(options)
local o = options
setmetatable(o, self)
self.__index = self
self = o
local sample_tab = options.tabs[1][1]
local point, relativeTo, relativePoint, xOffset, yOffset = sample_tab:GetPoint(1)
self.x = xOffset
self.y = yOffset
self.tab_width = sample_tab:GetWidth()
self.active_tab = nil
self.num_tabs = table.getn(self.tabs)
for i = 1, self.num_tabs do
self.tabs[i][2]:Hide()
self.tabs[i][1]:SetNormalTexture(tab_inactive)
if self.tabs[i].title then
getglobal(self.tabs[i][1]:GetName()..'_Text'):SetText(self.tabs[i].title)
end
local index = i
self.tabs[i][1]:SetScript("OnClick", function() self:activate_tab(index) end)
end
if self.num_tabs > 0 then
self:activate_tab(1)
end
self:set_visibility(nil)
return self
end
function zeroDB.TabView:activate_tab(index)
if self.active_tab then
self.tabs[self.active_tab][1]:SetNormalTexture(tab_inactive)
self.tabs[self.active_tab][2]:Hide()
end
self.tabs[index][1]:SetNormalTexture(tab_active)
self.tabs[index][2]:Show()
self.active_tab = index
end
function zeroDB.TabView:set_visibility(visible)
local x = self.x
local y = self.y
local num_visible_tabs = 0
local last_visible_tab_index = nil
for i = 1, self.num_tabs do
if not visible or visible[i] then
self.tabs[i][1]:SetPoint("TOPLEFT", x, y)
self.tabs[i][1]:Show()
x = x + self.tab_width
num_visible_tabs = num_visible_tabs + 1
last_visible_tab_index = i
if not self.active_tab then
self:activate_tab(i)
end
else
if self.active_tab == i then
self.tabs[i][1]:SetNormalTexture(tab_inactive)
self.tabs[i][2]:Hide()
self.active_tab = nil
end
self.tabs[i][1]:Hide()
end
end
if not self.active_tab and last_visible_tab_index then
self:activate_tab(last_visible_tab_index)
end
return num_visible_tabs
end
| gpl-3.0 |
Modified-MW-DF/modified-MDF | MWDF Project/Dwarf Fortress/hack/scripts/modtools/outside-only.lua | 2 | 3629 | -- enables outside only and inside only buildings
--author expwnent
local usage = [====[
modtools/outside-only
=====================
This allows you to specify certain custom buildings as outside only, or inside
only. If the player attempts to build a building in an inappropriate location,
the building will be destroyed.
Arguments::
-clear
clears the list of registered buildings
-checkEvery n
set how often existing buildings are checked for whether they
are in the appropriate location to n ticks
-type [EITHER, OUTSIDE_ONLY, INSIDE_ONLY]
specify what sort of restriction to put on the building
-building name
specify the id of the building
]====]
local eventful = require 'plugins.eventful'
local utils = require 'utils'
buildingType = buildingType or utils.invert({'EITHER','OUTSIDE_ONLY','INSIDE_ONLY'})
registeredBuildings = registeredBuildings or {}
checkEvery = checkEvery or 100
timeoutId = timeoutId or nil
eventful.enableEvent(eventful.eventType.UNLOAD,1)
eventful.onUnload.outsideOnly = function()
registeredBuildings = {}
checkEvery = 100
timeoutId = nil
end
local function destroy(building)
if #building.jobs > 0 and building.jobs[0] and building.jobs[0].job_type == df.job_type.DestroyBuilding then
return
end
local b = dfhack.buildings.deconstruct(building)
if b then
--TODO: print an error message to the user so they know
return
end
-- building.flags.almost_deleted = 1
end
local function checkBuildings()
local toDestroy = {}
local function forEach(building)
if building:getCustomType() < 0 then
--TODO: support builtin building types if someone wants
return
end
local pos = df.coord:new()
pos.x = building.centerx
pos.y = building.centery
pos.z = building.z
local outside = dfhack.maps.getTileBlock(pos).designation[pos.x%16][pos.y%16].outside
local def = df.global.world.raws.buildings.all[building:getCustomType()]
local btype = registeredBuildings[def.code]
if btype then
-- print('outside: ' .. outside==true .. ', type: ' .. btype)
end
if not btype or btype == buildingType.EITHER then
registeredBuildings[def.code] = nil
return
elseif btype == buildingType.OUTSIDE_ONLY then
if outside then
return
end
else
if not outside then
return
end
end
table.insert(toDestroy,building)
end
for _,building in ipairs(df.global.world.buildings.all) do
forEach(building)
end
for _,building in ipairs(toDestroy) do
destroy(building)
end
if timeoutId then
dfhack.timeout_active(timeoutId,nil)
timeoutId = nil
end
timeoutId = dfhack.timeout(checkEvery, 'ticks', checkBuildings)
end
eventful.enableEvent(eventful.eventType.BUILDING, 100)
eventful.onBuildingCreatedDestroyed.outsideOnly = function(buildingId)
checkBuildings()
end
validArgs = validArgs or utils.invert({
'help',
'clear',
'checkEvery',
'building',
'type'
})
local args = utils.processArgs({...}, validArgs)
if args.help then
print(usage)
return
end
if args.clear then
registeredBuildings = {}
end
if args.checkEvery then
if not tonumber(args.checkEvery) then
error('Invalid checkEvery.')
end
checkEvery = tonumber(args.checkEvery)
end
if not args.building then
return
end
if not args['type'] then
print 'outside-only: please specify type'
return
end
if not buildingType[args['type']] then
error('Invalid building type: ' .. args['type'])
end
registeredBuildings[args.building] = buildingType[args['type']]
checkBuildings()
| mit |
PAPAGENO-devels/papageno | test/benchmarks/Lua/lua-regression-test/WoW/ContainerFrame.lua | 1 | 24456 | NUM_CONTAINER_FRAMES = 12;
NUM_BAG_FRAMES = 4;
MAX_CONTAINER_ITEMS = 36;
NUM_CONTAINER_COLUMNS = 4;
ROWS_IN_BG_TEXTURE = 6;
MAX_BG_TEXTURES = 2;
BG_TEXTURE_HEIGHT = 512;
CONTAINER_WIDTH = 192;
CONTAINER_SPACING = 0;
VISIBLE_CONTAINER_SPACING = 3;
CONTAINER_OFFSET_Y = 70;
CONTAINER_OFFSET_X = 0;
CONTAINER_SCALE = 0.90;
function ContainerFrame_OnLoad()
this:RegisterEvent("BAG_UPDATE");
this:RegisterEvent("BAG_CLOSED");
this:RegisterEvent("BAG_OPEN");
this:RegisterEvent("BAG_UPDATE_COOLDOWN");
this:RegisterEvent("ITEM_LOCK_CHANGED");
this:RegisterEvent("UPDATE_INVENTORY_ALERTS");
ContainerFrame1.bagsShown = 0;
ContainerFrame1.bags = {};
end
function ContainerFrame_OnEvent()
if ( event == "BAG_UPDATE" ) then
if ( this:IsShown() and this:GetID() == arg1 ) then
ContainerFrame_Update(this);
end
elseif ( event == "BAG_CLOSED" ) then
if ( this:GetID() == arg1 ) then
this:Hide();
end
elseif ( event == "BAG_OPEN" ) then
if ( this:GetID() == arg1 ) then
this:Show();
end
elseif ( event == "ITEM_LOCK_CHANGED" or event == "BAG_UPDATE_COOLDOWN" or event == "UPDATE_INVENTORY_ALERTS" ) then
if ( this:IsShown() ) then
ContainerFrame_Update(this);
end
end
end
function ToggleBag(id)
if ( IsOptionFrameOpen() ) then
return;
end
local size = GetContainerNumSlots(id);
if ( size > 0 or id == KEYRING_CONTAINER ) then
local containerShowing;
for i=1, NUM_CONTAINER_FRAMES, 1 do
local frame = getglobal("ContainerFrame"..i);
if ( frame:IsShown() and frame:GetID() == id ) then
containerShowing = i;
frame:Hide();
end
end
if ( not containerShowing ) then
ContainerFrame_GenerateFrame(ContainerFrame_GetOpenFrame(), size, id);
end
end
end
function ToggleBackpack()
if ( IsOptionFrameOpen() ) then
return;
end
if ( IsBagOpen(0) ) then
for i=1, NUM_CONTAINER_FRAMES, 1 do
local frame = getglobal("ContainerFrame"..i);
if ( frame:IsShown() ) then
frame:Hide();
end
end
else
ToggleBag(0);
end
end
function ContainerFrame_OnHide()
if ( this:GetID() == 0 ) then
MainMenuBarBackpackButton:SetChecked(0);
else
local bagButton = getglobal("CharacterBag"..(this:GetID() - 1).."Slot");
if ( bagButton ) then
bagButton:SetChecked(0);
else
-- If its a bank bag then update its highlight
UpdateBagButtonHighlight(this:GetID());
end
end
ContainerFrame1.bagsShown = ContainerFrame1.bagsShown - 1;
-- Remove the closed bag from the list and collapse the rest of the entries
local index = 1;
while ContainerFrame1.bags[index] do
if ( ContainerFrame1.bags[index] == this:GetName() ) then
local tempIndex = index;
while ContainerFrame1.bags[tempIndex] do
if ( ContainerFrame1.bags[tempIndex + 1] ) then
ContainerFrame1.bags[tempIndex] = ContainerFrame1.bags[tempIndex + 1];
else
ContainerFrame1.bags[tempIndex] = nil;
end
tempIndex = tempIndex + 1;
end
end
index = index + 1;
end
updateContainerFrameAnchors();
if ( this:GetID() == KEYRING_CONTAINER ) then
UpdateMicroButtons();
PlaySound("KeyRingClose");
else
PlaySound("igBackPackClose");
end
end
function ContainerFrame_OnShow()
if ( this:GetID() == 0 ) then
MainMenuBarBackpackButton:SetChecked(1);
elseif ( this:GetID() <= NUM_BAG_SLOTS ) then
local button = getglobal("CharacterBag"..(this:GetID() - 1).."Slot");
if ( button ) then
button:SetChecked(1);
end
else
UpdateBagButtonHighlight(this:GetID());
end
ContainerFrame1.bagsShown = ContainerFrame1.bagsShown + 1;
if ( this:GetID() == KEYRING_CONTAINER ) then
UpdateMicroButtons();
PlaySound("KeyRingOpen");
else
PlaySound("igBackPackOpen");
end
end
function OpenBag(id)
if ( not CanOpenPanels() ) then
if ( UnitIsDead("player") ) then
NotWhileDeadError();
end
return;
end
local size = GetContainerNumSlots(id);
if ( size > 0 ) then
local containerShowing;
for i=1, NUM_CONTAINER_FRAMES, 1 do
local frame = getglobal("ContainerFrame"..i);
if ( frame:IsShown() and frame:GetID() == id ) then
containerShowing = i;
end
end
if ( not containerShowing ) then
ContainerFrame_GenerateFrame(ContainerFrame_GetOpenFrame(), size, id);
end
end
end
function CloseBag(id)
for i=1, NUM_CONTAINER_FRAMES, 1 do
local containerFrame = getglobal("ContainerFrame"..i);
if ( containerFrame:IsShown() and (containerFrame:GetID() == id) ) then
containerFrame:Hide();
return;
end
end
end
function IsBagOpen(id)
for i=1, NUM_CONTAINER_FRAMES, 1 do
local containerFrame = getglobal("ContainerFrame"..i);
if ( containerFrame:IsShown() and (containerFrame:GetID() == id) ) then
return i;
end
end
return nil;
end
function OpenBackpack()
if ( not CanOpenPanels() ) then
if ( UnitIsDead("player") ) then
NotWhileDeadError();
end
return;
end
for i=1, NUM_CONTAINER_FRAMES, 1 do
local containerFrame = getglobal("ContainerFrame"..i);
if ( containerFrame:IsShown() and (containerFrame:GetID() == 0) ) then
ContainerFrame1.backpackWasOpen = 1;
return;
else
ContainerFrame1.backpackWasOpen = nil;
end
end
if ( not ContainerFrame1.backpackWasOpen ) then
ToggleBackpack();
end
end
function CloseBackpack()
for i=1, NUM_CONTAINER_FRAMES, 1 do
local containerFrame = getglobal("ContainerFrame"..i);
if ( containerFrame:IsShown() and (containerFrame:GetID() == 0) and (ContainerFrame1.backpackWasOpen == nil) ) then
containerFrame:Hide();
return;
end
end
end
function ContainerFrame_GetOpenFrame()
for i=1, NUM_CONTAINER_FRAMES, 1 do
local frame = getglobal("ContainerFrame"..i);
if ( not frame:IsShown() ) then
return frame;
end
-- If all frames open return the last frame
if ( i == NUM_CONTAINER_FRAMES ) then
frame:Hide();
return frame;
end
end
end
function ContainerFrame_Update(frame)
local id = frame:GetID();
local name = frame:GetName();
local texture, itemCount, locked, quality, readable;
for j=1, frame.size, 1 do
local itemButton = getglobal(name.."Item"..j);
texture, itemCount, locked, quality, readable = GetContainerItemInfo(id, itemButton:GetID());
SetItemButtonTexture(itemButton, texture);
SetItemButtonCount(itemButton, itemCount);
SetItemButtonDesaturated(itemButton, locked, 0.5, 0.5, 0.5);
if ( texture ) then
ContainerFrame_UpdateCooldown(id, itemButton);
itemButton.hasItem = 1;
else
getglobal(name.."Item"..j.."Cooldown"):Hide();
itemButton.hasItem = nil;
end
itemButton.readable = readable;
--local normalTexture = getglobal(name.."Item"..j.."NormalTexture");
--if ( quality and quality ~= -1) then
-- local color = getglobal("ITEM_QUALITY".. quality .."_COLOR");
-- normalTexture:SetVertexColor(color.r, color.g, color.b);
--else
-- normalTexture:SetVertexColor(TOOLTIP_DEFAULT_COLOR.r, TOOLTIP_DEFAULT_COLOR.g, TOOLTIP_DEFAULT_COLOR.b);
--end
local showSell = nil;
if ( GameTooltip:IsOwned(itemButton) ) then
if ( texture ) then
local hasCooldown, repairCost = GameTooltip:SetBagItem(itemButton:GetParent():GetID(),itemButton:GetID());
--[[if ( hasCooldown ) then
itemButton.updateTooltip = TOOLTIP_UPDATE_TIME;
else
itemButton.updateTooltip = nil;
end
]]
if ( InRepairMode() and (repairCost > 0) ) then
GameTooltip:AddLine(TEXT(REPAIR_COST), "", 1, 1, 1);
SetTooltipMoney(GameTooltip, repairCost);
GameTooltip:Show();
elseif ( MerchantFrame:IsShown() and not locked) then
showSell = 1;
end
else
GameTooltip:Hide();
end
if ( showSell ) then
ShowContainerSellCursor(itemButton:GetParent():GetID(), itemButton:GetID());
elseif ( readable ) then
ShowInspectCursor();
else
ResetCursor();
end
end
end
end
function ContainerFrame_UpdateCooldown(container, button)
local cooldown = getglobal(button:GetName().."Cooldown");
local start, duration, enable = GetContainerItemCooldown(container, button:GetID());
CooldownFrame_SetTimer(cooldown, start, duration, enable);
if ( duration > 0 and enable == 0 ) then
SetItemButtonTextureVertexColor(button, 0.4, 0.4, 0.4);
end
end
function ContainerFrame_GenerateFrame(frame, size, id)
frame.size = size;
local name = frame:GetName();
local bgTextureTop = getglobal(name.."BackgroundTop");
local bgTextureMiddle = getglobal(name.."BackgroundMiddle1");
local bgTextureBottom = getglobal(name.."BackgroundBottom");
local columns = NUM_CONTAINER_COLUMNS;
local rows = ceil(size / columns);
-- if size = 0 then its the backpack
if ( id == 0 ) then
getglobal(name.."MoneyFrame"):Show();
-- Set Backpack texture
bgTextureTop:SetTexture("Interface\\ContainerFrame\\UI-BackpackBackground");
bgTextureTop:SetHeight(256);
bgTextureTop:SetTexCoord(0, 1, 0, 1);
-- Hide unused textures
for i=1, MAX_BG_TEXTURES do
getglobal(name.."BackgroundMiddle"..i):Hide();
end
bgTextureBottom:Hide();
frame:SetHeight(240);
else
-- Not the backpack
-- Set whether or not its a bank bag
local bagTextureSuffix = "";
if ( id > NUM_BAG_FRAMES ) then
bagTextureSuffix = "-Bank";
elseif ( id == KEYRING_CONTAINER ) then
bagTextureSuffix = "-Keyring";
end
-- Set textures
bgTextureTop:SetTexture("Interface\\ContainerFrame\\UI-Bag-Components"..bagTextureSuffix);
for i=1, MAX_BG_TEXTURES do
getglobal(name.."BackgroundMiddle"..i):SetTexture("Interface\\ContainerFrame\\UI-Bag-Components"..bagTextureSuffix);
getglobal(name.."BackgroundMiddle"..i):Hide();
end
bgTextureBottom:SetTexture("Interface\\ContainerFrame\\UI-Bag-Components"..bagTextureSuffix);
-- Hide the moneyframe since its not the backpack
getglobal(name.."MoneyFrame"):Hide();
local bgTextureCount, height;
local rowHeight = 41;
-- Subtract one, since the top texture contains one row already
local remainingRows = rows-1;
-- See if the bag needs the texture with two slots at the top
local isPlusTwoBag;
if ( mod(size,columns) == 2 ) then
isPlusTwoBag = 1;
end
-- Bag background display stuff
if ( isPlusTwoBag ) then
bgTextureTop:SetTexCoord(0, 1, 0.189453125, 0.330078125);
bgTextureTop:SetHeight(72);
else
if ( rows == 1 ) then
-- If only one row chop off the bottom of the texture
bgTextureTop:SetTexCoord(0, 1, 0.00390625, 0.16796875);
bgTextureTop:SetHeight(86);
else
bgTextureTop:SetTexCoord(0, 1, 0.00390625, 0.18359375);
bgTextureTop:SetHeight(94);
end
end
-- Calculate the number of background textures we're going to need
bgTextureCount = ceil(remainingRows/ROWS_IN_BG_TEXTURE);
local middleBgHeight = 0;
-- If one row only special case
if ( rows == 1 ) then
bgTextureBottom:SetPoint("TOP", bgTextureMiddle:GetName(), "TOP", 0, 0);
bgTextureBottom:Show();
-- Hide middle bg textures
for i=1, MAX_BG_TEXTURES do
getglobal(name.."BackgroundMiddle"..i):Hide();
end
else
-- Try to cycle all the middle bg textures
local firstRowPixelOffset = 9;
local firstRowTexCoordOffset = 0.353515625;
for i=1, bgTextureCount do
bgTextureMiddle = getglobal(name.."BackgroundMiddle"..i);
if ( remainingRows > ROWS_IN_BG_TEXTURE ) then
-- If more rows left to draw than can fit in a texture then draw the max possible
height = ( ROWS_IN_BG_TEXTURE*rowHeight ) + firstRowTexCoordOffset;
bgTextureMiddle:SetHeight(height);
bgTextureMiddle:SetTexCoord(0, 1, firstRowTexCoordOffset, ( height/BG_TEXTURE_HEIGHT + firstRowTexCoordOffset) );
bgTextureMiddle:Show();
remainingRows = remainingRows - ROWS_IN_BG_TEXTURE;
middleBgHeight = middleBgHeight + height;
else
-- If not its a huge bag
bgTextureMiddle:Show();
height = remainingRows*rowHeight-firstRowPixelOffset;
bgTextureMiddle:SetHeight(height);
bgTextureMiddle:SetTexCoord(0, 1, firstRowTexCoordOffset, ( height/BG_TEXTURE_HEIGHT + firstRowTexCoordOffset) );
middleBgHeight = middleBgHeight + height;
end
end
-- Position bottom texture
bgTextureBottom:SetPoint("TOP", bgTextureMiddle:GetName(), "BOTTOM", 0, 0);
bgTextureBottom:Show();
end
-- Set the frame height
frame:SetHeight(bgTextureTop:GetHeight()+bgTextureBottom:GetHeight()+middleBgHeight);
end
frame:SetWidth(CONTAINER_WIDTH);
frame:SetID(id);
getglobal(frame:GetName().."PortraitButton"):SetID(id);
--Special case code for keyrings
if ( id == KEYRING_CONTAINER ) then
getglobal(frame:GetName().."Name"):SetText(KEYRING);
SetPortraitToTexture(frame:GetName().."Portrait", "Interface\\ContainerFrame\\KeyRing-Bag-Icon");
else
getglobal(frame:GetName().."Name"):SetText(GetBagName(id));
SetBagPortaitTexture(getglobal(frame:GetName().."Portrait"), id);
end
for j=1, size, 1 do
local index = size - j + 1;
local itemButton =getglobal(name.."Item"..j);
itemButton:SetID(index);
-- Set first button
if ( j == 1 ) then
-- Anchor the first item differently if its the backpack frame
if ( id == 0 ) then
itemButton:SetPoint("BOTTOMRIGHT", name, "BOTTOMRIGHT", -12, 30);
else
itemButton:SetPoint("BOTTOMRIGHT", name, "BOTTOMRIGHT", -12, 9);
end
else
if ( mod((j-1), columns) == 0 ) then
itemButton:SetPoint("BOTTOMRIGHT", name.."Item"..(j - columns), "TOPRIGHT", 0, 4);
else
itemButton:SetPoint("BOTTOMRIGHT", name.."Item"..(j - 1), "BOTTOMLEFT", -5, 0);
end
end
local texture, itemCount, locked, quality, readable = GetContainerItemInfo(id, index);
SetItemButtonTexture(itemButton, texture);
SetItemButtonCount(itemButton, itemCount);
SetItemButtonDesaturated(itemButton, locked, 0.5, 0.5, 0.5);
if ( texture ) then
ContainerFrame_UpdateCooldown(id, itemButton);
itemButton.hasItem = 1;
else
getglobal(name.."Item"..j.."Cooldown"):Hide();
itemButton.hasItem = nil;
end
itemButton.readable = readable;
itemButton:Show();
end
for j=size + 1, MAX_CONTAINER_ITEMS, 1 do
getglobal(name.."Item"..j):Hide();
end
-- Add the bag to the baglist
ContainerFrame1.bags[ContainerFrame1.bagsShown + 1] = frame:GetName();
updateContainerFrameAnchors();
frame:Show();
end
function updateContainerFrameAnchors()
-- Adjust the start anchor for bags depending on the multibars
local shrinkFrames, frame;
local xOffset = CONTAINER_OFFSET_X;
local yOffset = CONTAINER_OFFSET_Y;
local screenHeight = GetScreenHeight();
local containerScale = CONTAINER_SCALE;
local freeScreenHeight = screenHeight - yOffset;
local index = 1;
local column = 0;
local uiScale = 1;
if ( GetCVar("useUiScale") == "1" ) then
uiScale = GetCVar("uiscale") + 0;
if ( uiScale > containerScale ) then
containerScale = uiScale * containerScale;
end
end
while ContainerFrame1.bags[index] do
frame = getglobal(ContainerFrame1.bags[index]);
frame:SetScale(1);
-- freeScreenHeight determines when to start a new column of bags
if ( index == 1 ) then
-- First bag
frame:SetPoint("BOTTOMRIGHT", frame:GetParent(), "BOTTOMRIGHT", -xOffset, yOffset );
elseif ( freeScreenHeight < frame:GetHeight() ) then
-- Start a new column
column = column + 1;
freeScreenHeight = screenHeight - yOffset;
frame:SetPoint("BOTTOMRIGHT", frame:GetParent(), "BOTTOMRIGHT", -(column * CONTAINER_WIDTH) - xOffset, yOffset );
else
-- Anchor to the previous bag
frame:SetPoint("BOTTOMRIGHT", ContainerFrame1.bags[index - 1], "TOPRIGHT", 0, CONTAINER_SPACING);
end
if ( frame:GetLeft() < ( BankFrame:GetRight() - 45 ) ) then
if ( frame:GetTop() > ( BankFrame:GetBottom() + 50 ) ) then
shrinkFrames = 1;
break;
end
end
freeScreenHeight = freeScreenHeight - frame:GetHeight() - VISIBLE_CONTAINER_SPACING;
index = index + 1;
end
if ( shrinkFrames ) then
screenHeight = screenHeight / containerScale;
xOffset = xOffset / containerScale;
yOffset = yOffset / containerScale;
freeScreenHeight = screenHeight - yOffset;
index = 1;
column = 0;
while ContainerFrame1.bags[index] do
frame = getglobal(ContainerFrame1.bags[index]);
frame:SetScale(containerScale);
if ( index == 1 ) then
-- First bag
frame:SetPoint("BOTTOMRIGHT", frame:GetParent(), "BOTTOMRIGHT", -xOffset, yOffset );
elseif ( freeScreenHeight < frame:GetHeight() ) then
-- Start a new column
column = column + 1;
freeScreenHeight = screenHeight - yOffset;
frame:SetPoint("BOTTOMRIGHT", frame:GetParent(), "BOTTOMRIGHT", -(column * CONTAINER_WIDTH) - xOffset, yOffset );
else
-- Anchor to the previous bag
frame:SetPoint("BOTTOMRIGHT", ContainerFrame1.bags[index - 1], "TOPRIGHT", 0, CONTAINER_SPACING);
end
freeScreenHeight = freeScreenHeight - frame:GetHeight() - VISIBLE_CONTAINER_SPACING;
index = index + 1;
end
end
-- This is used to position the unit tooltip
--[[
local oldContainerPosition = OPEN_CONTAINER_POSITION;
if ( index == 1 ) then
DEFAULT_TOOLTIP_POSITION = -13;
else
DEFAULT_TOOLTIP_POSITION = -((column + 1) * CONTAINER_WIDTH) - xOffset;
end
if ( DEFAULT_TOOLTIP_POSITION ~= oldContainerPosition and GameTooltip.default and GameTooltip:IsShown() ) then
GameTooltip:SetPoint("BOTTOMRIGHT", "UIParent", "BOTTOMRIGHT", DEFAULT_TOOLTIP_POSITION, 64);
end
]]
end
function ContainerFrameItemButton_OnLoad()
this:RegisterForClicks("LeftButtonUp", "RightButtonUp");
this:RegisterForDrag("LeftButton");
this.SplitStack = function(button, split)
SplitContainerItem(button:GetParent():GetID(), button:GetID(), split);
end
end
function ContainerFrameItemButton_OnClick(button, ignoreModifiers)
if ( button == "LeftButton" ) then
if ( IsControlKeyDown() and not ignoreModifiers ) then
DressUpItemLink(GetContainerItemLink(this:GetParent():GetID(), this:GetID()));
elseif ( IsShiftKeyDown() and not ignoreModifiers ) then
if ( ChatFrameEditBox:IsShown() ) then
ChatFrameEditBox:Insert(GetContainerItemLink(this:GetParent():GetID(), this:GetID()));
else
local texture, itemCount, locked = GetContainerItemInfo(this:GetParent():GetID(), this:GetID());
if ( not locked ) then
this.SplitStack = function(button, split)
SplitContainerItem(button:GetParent():GetID(), button:GetID(), split);
end
OpenStackSplitFrame(this.count, this, "BOTTOMRIGHT", "TOPRIGHT");
end
end
else
PickupContainerItem(this:GetParent():GetID(), this:GetID());
StackSplitFrame:Hide();
end
else
if ( IsControlKeyDown() and not ignoreModifiers ) then
return;
elseif ( IsShiftKeyDown() and MerchantFrame:IsShown() and not ignoreModifiers ) then
this.SplitStack = function(button, split)
SplitContainerItem(button:GetParent():GetID(), button:GetID(), split);
MerchantItemButton_OnClick("LeftButton");
end
OpenStackSplitFrame(this.count, this, "BOTTOMRIGHT", "TOPRIGHT");
elseif ( MerchantFrame:IsShown() and MerchantFrame.selectedTab == 2 ) then
-- Don't sell the item if the buyback tab is selected
return;
else
UseContainerItem(this:GetParent():GetID(), this:GetID());
StackSplitFrame:Hide();
end
end
end
function ContainerFrameItemButton_OnEnter(button)
if ( not button ) then
button = this;
end
local x;
x = button:GetRight();
if ( x >= ( GetScreenWidth() / 2 ) ) then
GameTooltip:SetOwner(button, "ANCHOR_LEFT");
else
GameTooltip:SetOwner(button, "ANCHOR_RIGHT");
end
-- Keyring specific code
if ( this:GetParent():GetID() == KEYRING_CONTAINER ) then
GameTooltip:SetInventoryItem("player", KeyRingButtonIDToInvSlotID(this:GetID()));
CursorUpdate();
return;
end
local hasCooldown, repairCost = GameTooltip:SetBagItem(button:GetParent():GetID(),button:GetID());
--[[
Commented out to make dressup cursor work.
if ( hasCooldown ) then
button.updateTooltip = TOOLTIP_UPDATE_TIME;
else
button.updateTooltip = nil;
end
]]
if ( InRepairMode() and (repairCost and repairCost > 0) ) then
GameTooltip:AddLine(TEXT(REPAIR_COST), "", 1, 1, 1);
SetTooltipMoney(GameTooltip, repairCost);
GameTooltip:Show();
elseif ( MerchantFrame:IsShown() and MerchantFrame.selectedTab == 1 ) then
ShowContainerSellCursor(button:GetParent():GetID(),button:GetID());
elseif ( this.readable or (IsControlKeyDown() and button.hasItem) ) then
ShowInspectCursor();
else
ResetCursor();
end
end
function ContainerFrameItemButton_OnUpdate(elapsed)
--[[
Might hurt performance, but need to always update the cursor now
if ( not this.updateTooltip ) then
return;
end
this.updateTooltip = this.updateTooltip - elapsed;
if ( this.updateTooltip > 0 ) then
return;
end
]]
if ( GameTooltip:IsOwned(this) ) then
ContainerFrameItemButton_OnEnter();
end
end
function OpenAllBags(forceOpen)
if ( not UIParent:IsVisible() ) then
return;
end
local bagsOpen = 0;
local totalBags = 1;
for i=1, NUM_CONTAINER_FRAMES, 1 do
local containerFrame = getglobal("ContainerFrame"..i);
local bagButton = getglobal("CharacterBag"..(i -1).."Slot");
if ( (i <= NUM_BAG_FRAMES) and GetContainerNumSlots(bagButton:GetID() - CharacterBag0Slot:GetID() + 1) > 0) then
totalBags = totalBags + 1;
end
if ( containerFrame:IsShown() ) then
containerFrame:Hide();
if ( containerFrame:GetID() ~= KEYRING_CONTAINER ) then
bagsOpen = bagsOpen + 1;
end
end
end
if ( bagsOpen >= totalBags and not forceOpen ) then
return;
else
ToggleBackpack();
ToggleBag(1);
ToggleBag(2);
ToggleBag(3);
ToggleBag(4);
if ( BankFrame:IsVisible() ) then
ToggleBag(5);
ToggleBag(6);
ToggleBag(7);
ToggleBag(8);
ToggleBag(9);
ToggleBag(10);
end
end
end
function CloseAllBags()
CloseBackpack();
for i=1, NUM_CONTAINER_FRAMES, 1 do
CloseBag(i);
end
end
--KeyRing functions
function KeyRingItemButton_OnClick(button)
if ( button == "LeftButton" ) then
if ( IsControlKeyDown() and not this.isBag ) then
DressUpItemLink(GetContainerItemLink(KEYRING_CONTAINER, this:GetID()));
elseif ( IsShiftKeyDown() and not this.isBag ) then
if ( ChatFrameEditBox:IsVisible() ) then
ChatFrameEditBox:Insert(GetContainerItemLink(KEYRING_CONTAINER, this:GetID()));
else
local texture, itemCount, locked = GetContainerItemInfo(KEYRING_CONTAINER, this:GetID());
if ( not locked ) then
OpenStackSplitFrame(this.count, this, "BOTTOMLEFT", "TOPLEFT");
end
end
else
PickupContainerItem(KEYRING_CONTAINER, this:GetID());
end
else
if ( IsControlKeyDown() and not this.isBag ) then
return;
elseif ( IsShiftKeyDown() and not this.isBag ) then
local texture, itemCount, locked = GetContainerItemInfo(KEYRING_CONTAINER, this:GetID());
if ( not locked ) then
OpenStackSplitFrame(this.count, this, "BOTTOMLEFT", "TOPLEFT");
end
else
UseContainerItem(KEYRING_CONTAINER, this:GetID());
end
end
end
function PutKeyInKeyRing()
local texture;
local emptyKeyRingSlot;
for i=1, GetKeyRingSize() do
texture = GetContainerItemInfo(KEYRING_CONTAINER, i);
if ( not texture ) then
emptyKeyRingSlot = i;
break;
end
end
if ( emptyKeyRingSlot ) then
PickupContainerItem(KEYRING_CONTAINER, emptyKeyRingSlot);
else
UIErrorsFrame:AddMessage(NO_EMPTY_KEYRING_SLOTS, 1.0, 0.1, 0.1, 1.0);
end
end
function ToggleKeyRing()
if ( IsOptionFrameOpen() ) then
return;
end
local shownContainerID = IsBagOpen(KEYRING_CONTAINER);
if ( shownContainerID ) then
getglobal("ContainerFrame"..shownContainerID):Hide();
else
ContainerFrame_GenerateFrame(ContainerFrame_GetOpenFrame(), GetKeyRingSize(), KEYRING_CONTAINER);
-- Stop keyring button pulse
SetButtonPulse(KeyRingButton, 0, 1);
end
end
function GetKeyRingSize()
local level = UnitLevel("player");
local size;
if ( level > 60 ) then
size = 16;
elseif ( level >= 50 ) then
size = 12;
elseif ( level >= 40 ) then
size = 8;
else
size = 4;
end
return size;
end | gpl-2.0 |
TheAnswer/FirstTest | bin/scripts/items/objects/clothing/pants/pants8.lua | 1 | 2280 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
pants8 = Clothing:new {
objectName = "Striped Slacks",
templateName = "pants_s08",
objectCRC = "597357025",
objectType = PANTS,
itemMask = HUMANOIDS,
equipped = "0"
} | lgpl-3.0 |
karolhrdina/malamute | bindings/lua_ffi/test.lua | 4 | 1640 | #!/usr/bin/lua5.2
--[[
Copyright (c) the Contributors as noted in the AUTHORS file.
This file is part of the Malamute Project.
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
]]
local malamute = require ("malamute_ffi")
local mlm = malamute.mlm
local ffi = malamute.ffi
-- FIXME: test expects broker running as third party service
-- w/o czmq ffi bindings we won't get zactor available
local endpoint = "ipc://@/malamute"
local r = 0
local client = mlm.mlm_client_new ()
assert (client ~= nil)
r = mlm.mlm_client_connect (client, endpoint, 1000, "client")
assert (r == 0)
r = mlm.mlm_client_set_producer (client, "STREAM")
assert (r == 0)
local consumer = mlm.mlm_client_new ()
assert (consumer ~= nil)
r = mlm.mlm_client_connect (consumer, endpoint, 1000, "consumer")
assert (r == 0)
r = mlm.mlm_client_set_consumer (consumer, "STREAM", ".*")
assert (r == 0)
r = mlm.mlm_client_sendx (client, "SUBJECT", "Wine", "from", "Burgundy", ffi.NULL);
assert (r == 0)
-- FIXME: minimal czmq bindings to show at least something on cmdline
local msg = mlm.mlm_client_recv (consumer)
assert (msg ~= nil)
ffi.cdef [[
void zmsg_print (zmsg_t *self);
void zmsg_destroy (zmsg_t **self_p);
]]
local czmq = ffi.load ("czmq")
czmq.zmsg_print (msg)
local msg_p = ffi.new ("zmsg_t*[1]", msg)
czmq.zmsg_destroy (msg_p)
local client_p = ffi.new ("mlm_client_t*[1]", client)
mlm.mlm_client_destroy (client_p)
local consumer_p = ffi.new ("mlm_client_t*[1]", consumer)
mlm.mlm_client_destroy (consumer_p)
| mpl-2.0 |
yav/language-lua | lua-5.3.1-tests/sort.lua | 3 | 7591 | -- $Id: sort.lua,v 1.32 2015/03/04 13:09:38 roberto Exp $
print "testing (parts of) table library"
print "testing unpack"
local unpack = table.unpack
local maxI = math.maxinteger
local minI = math.mininteger
local function checkerror (msg, f, ...)
local s, err = pcall(f, ...)
assert(not s and string.find(err, msg))
end
checkerror("wrong number of arguments", table.insert, {}, 2, 3, 4)
local x,y,z,a,n
a = {}; lim = _soft and 200 or 2000
for i=1, lim do a[i]=i end
assert(select(lim, unpack(a)) == lim and select('#', unpack(a)) == lim)
x = unpack(a)
assert(x == 1)
x = {unpack(a)}
assert(#x == lim and x[1] == 1 and x[lim] == lim)
x = {unpack(a, lim-2)}
assert(#x == 3 and x[1] == lim-2 and x[3] == lim)
x = {unpack(a, 10, 6)}
assert(next(x) == nil) -- no elements
x = {unpack(a, 11, 10)}
assert(next(x) == nil) -- no elements
x,y = unpack(a, 10, 10)
assert(x == 10 and y == nil)
x,y,z = unpack(a, 10, 11)
assert(x == 10 and y == 11 and z == nil)
a,x = unpack{1}
assert(a==1 and x==nil)
a,x = unpack({1,2}, 1, 1)
assert(a==1 and x==nil)
do
local maxi = (1 << 31) - 1 -- maximum value for an int (usually)
local mini = -(1 << 31) -- minimum value for an int (usually)
checkerror("too many results", unpack, {}, 0, maxi)
checkerror("too many results", unpack, {}, 1, maxi)
checkerror("too many results", unpack, {}, 0, maxI)
checkerror("too many results", unpack, {}, 1, maxI)
checkerror("too many results", unpack, {}, mini, maxi)
checkerror("too many results", unpack, {}, -maxi, maxi)
checkerror("too many results", unpack, {}, minI, maxI)
unpack({}, maxi, 0)
unpack({}, maxi, 1)
unpack({}, maxI, minI)
pcall(unpack, {}, 1, maxi + 1)
local a, b = unpack({[maxi] = 20}, maxi, maxi)
assert(a == 20 and b == nil)
a, b = unpack({[maxi] = 20}, maxi - 1, maxi)
assert(a == nil and b == 20)
local t = {[maxI - 1] = 12, [maxI] = 23}
a, b = unpack(t, maxI - 1, maxI); assert(a == 12 and b == 23)
a, b = unpack(t, maxI, maxI); assert(a == 23 and b == nil)
a, b = unpack(t, maxI, maxI - 1); assert(a == nil and b == nil)
t = {[minI] = 12.3, [minI + 1] = 23.5}
a, b = unpack(t, minI, minI + 1); assert(a == 12.3 and b == 23.5)
a, b = unpack(t, minI, minI); assert(a == 12.3 and b == nil)
a, b = unpack(t, minI + 1, minI); assert(a == nil and b == nil)
end
do -- length is not an integer
local t = setmetatable({}, {__len = function () return 'abc' end})
assert(#t == 'abc')
checkerror("object length is not an integer", table.insert, t, 1)
end
print "testing pack"
a = table.pack()
assert(a[1] == nil and a.n == 0)
a = table.pack(table)
assert(a[1] == table and a.n == 1)
a = table.pack(nil, nil, nil, nil)
assert(a[1] == nil and a.n == 4)
-- testing move
do
local function eqT (a, b)
for k, v in pairs(a) do assert(b[k] == v) end
for k, v in pairs(b) do assert(a[k] == v) end
end
local a = table.move({10,20,30}, 1, 3, 2) -- move forward
eqT(a, {10,10,20,30})
a = table.move({10,20,30}, 2, 3, 1) -- move backward
eqT(a, {20,30,30})
a = table.move({10,20,30}, 1, 3, 1, {}) -- move
eqT(a, {10,20,30})
a = table.move({10,20,30}, 1, 0, 3, {}) -- do not move
eqT(a, {})
a = table.move({10,20,30}, 1, 10, 1) -- move to the same place
eqT(a, {10,20,30})
a = table.move({[maxI - 2] = 1, [maxI - 1] = 2, [maxI] = 3},
maxI - 2, maxI, -10, {})
eqT(a, {[-10] = 1, [-9] = 2, [-8] = 3})
a = table.move({[minI] = 1, [minI + 1] = 2, [minI + 2] = 3},
minI, minI + 2, -10, {})
eqT(a, {[-10] = 1, [-9] = 2, [-8] = 3})
a = table.move({45}, 1, 1, maxI)
eqT(a, {45, [maxI] = 45})
a = table.move({[maxI] = 100}, maxI, maxI, minI)
eqT(a, {[minI] = 100, [maxI] = 100})
a = table.move({[minI] = 100}, minI, minI, maxI)
eqT(a, {[minI] = 100, [maxI] = 100})
a = setmetatable({}, {
__index = function (_,k) return k * 10 end,
__newindex = error})
local b = table.move(a, 1, 10, 3, {})
eqT(a, {})
eqT(b, {nil,nil,10,20,30,40,50,60,70,80,90,100})
b = setmetatable({""}, {
__index = error,
__newindex = function (t,k,v)
t[1] = string.format("%s(%d,%d)", t[1], k, v)
end})
table.move(a, 10, 13, 3, b)
assert(b[1] == "(3,100)(4,110)(5,120)(6,130)")
local stat, msg = pcall(table.move, b, 10, 13, 3, b)
assert(not stat and msg == b)
end
do
-- for very long moves, just check initial accesses and interrupt
-- move with an error
local function checkmove (f, e, t, x, y)
local pos1, pos2
local a = setmetatable({}, {
__index = function (_,k) pos1 = k end,
__newindex = function (_,k) pos2 = k; error() end, })
local st, msg = pcall(table.move, a, f, e, t)
assert(not st and not msg and pos1 == x and pos2 == y)
end
checkmove(1, maxI, 0, 1, 0)
checkmove(0, maxI - 1, 1, maxI - 1, maxI)
checkmove(minI, -2, 0, -2, maxI - 1)
checkmove(minI + 1, -1, 1, -1, maxI)
end
checkerror("too many", table.move, {}, 0, maxI, 1)
checkerror("too many", table.move, {}, -1, maxI - 1, 1)
checkerror("too many", table.move, {}, minI, -1, 1)
checkerror("too many", table.move, {}, minI, maxI, 1)
checkerror("wrap around", table.move, {}, 1, maxI, 2)
checkerror("wrap around", table.move, {}, 1, 2, maxI)
checkerror("wrap around", table.move, {}, minI, -2, 2)
print"testing sort"
-- test checks for invalid order functions
local function check (t)
local function f(a, b) assert(a and b); return true end
checkerror("invalid order function", table.sort, t, f)
end
check{1,2,3,4}
check{1,2,3,4,5}
check{1,2,3,4,5,6}
function check (a, f)
f = f or function (x,y) return x<y end;
for n = #a, 2, -1 do
assert(not f(a[n], a[n-1]))
end
end
a = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"}
table.sort(a)
check(a)
function perm (s, n)
n = n or #s
if n == 1 then
local t = {unpack(s)}
table.sort(t)
check(t)
else
for i = 1, n do
s[i], s[n] = s[n], s[i]
perm(s, n - 1)
s[i], s[n] = s[n], s[i]
end
end
end
perm{}
perm{1}
perm{1,2}
perm{1,2,3}
perm{1,2,3,4}
perm{2,2,3,4}
perm{1,2,3,4,5}
perm{1,2,3,3,5}
perm{1,2,3,4,5,6}
perm{2,2,3,3,5,6}
limit = 30000
if _soft then limit = 5000 end
a = {}
for i=1,limit do
a[i] = math.random()
end
local x = os.clock()
table.sort(a)
print(string.format("Sorting %d elements in %.2f sec.", limit, os.clock()-x))
check(a)
x = os.clock()
table.sort(a)
print(string.format("Re-sorting %d elements in %.2f sec.", limit, os.clock()-x))
check(a)
a = {}
for i=1,limit do
a[i] = math.random()
end
x = os.clock(); i=0
table.sort(a, function(x,y) i=i+1; return y<x end)
print(string.format("Invert-sorting other %d elements in %.2f sec., with %i comparisons",
limit, os.clock()-x, i))
check(a, function(x,y) return y<x end)
table.sort{} -- empty array
for i=1,limit do a[i] = false end
x = os.clock();
table.sort(a, function(x,y) return nil end)
print(string.format("Sorting %d equal elements in %.2f sec.", limit, os.clock()-x))
check(a, function(x,y) return nil end)
for i,v in pairs(a) do assert(not v or i=='n' and v==limit) end
A = {"álo", "\0first :-)", "alo", "then this one", "45", "and a new"}
table.sort(A)
check(A)
table.sort(A, function (x, y)
load(string.format("A[%q] = ''", x), "")()
collectgarbage()
return x<y
end)
tt = {__lt = function (a,b) return a.val < b.val end}
a = {}
for i=1,10 do a[i] = {val=math.random(100)}; setmetatable(a[i], tt); end
table.sort(a)
check(a, tt.__lt)
check(a)
print"OK"
| bsd-3-clause |
TheAnswer/FirstTest | bin/scripts/creatures/objects/talus/npcs/fedDub/fedDubSupporter.lua | 1 | 4557 | --Copyright (C) 2008 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
fedDubSupporter = Creature:new {
objectName = "fedDubSupporter", -- Lua Object Name
creatureType = "NPC",
faction = "fed_dub",
factionPoints = 20,
gender = "",
speciesName = "fed_dub_supporter",
stfName = "mob/creature_names",
objectCRC = 1386145364,
socialGroup = "fed_dub",
level = 8,
combatFlags = ATTACKABLE_FLAG + ENEMY_FLAG,
healthMax = 495,
healthMin = 405,
strength = 0,
constitution = 0,
actionMax = 495,
actionMin = 405,
quickness = 0,
stamina = 0,
mindMax = 495,
mindMin = 405,
focus = 0,
willpower = 0,
height = 1, -- Size of creature
armor = 0, -- 0 = None; 1 = Light; 2 = Medium; 3 = Heavy
kinetic = 0,
energy = 0,
electricity = 0,
stun = -1,
blast = 0,
heat = 0,
cold = 0,
acid = 0,
lightsaber = 0,
accuracy = 0,
healer = 0,
pack = 1,
herd = 1,
stalker = 0,
killer = 0,
ferocity = 0,
aggressive = 0,
invincible = 0,
attackCreatureOnSight = "", -- Enter socialGroups
weapon = "object/weapon/creature/shared_creature_default_weapon.iff", -- File path to weapon -> object\xxx\xxx\xx
weaponName = "Creature Defualt", -- Name ex. 'a Vibrolance'
weaponTemp = "creature_default_weapon", -- Weapon Template ex. 'lance_vibrolance'
weaponClass = "UnarmedMeleeWeapon", -- Weapon Class ex. 'PolearmMeleeWeapon'
weaponEquipped = 0,
weaponMinDamage = 70,
weaponMaxDamage = 75,
weaponAttackSpeed = 2,
weaponDamageType = "KINETIC", -- ELECTRICITY, KINETIC, etc
weaponArmorPiercing = "NONE", -- LIGHT, NONE, MEDIUM, HEAVY
alternateWeapon = "", -- File path to weapon -> object\xxx\xxx\xx
alternateWeaponName = "", -- Name ex. 'a Vibrolance'
alternateWeaponTemp = "", -- Weapon Template ex. 'lance_vibrolance'
alternateWeaponClass = "", -- Weapon Class ex. 'PolearmMeleeWeapon'
alternateWeaponEquipped = 0,
alternateWeaponMinDamage = 0,
alternateWeaponMaxDamage = 0,
alternateWeaponAttackSpeed = 0,
alternateWeaponDamageType = "", -- ELECTRICITY, KINETIC, etc
alternateWeaponArmorPiercing = "", -- LIGHT, NONE, MEDIUM, HEAVY
internalNPCDamageModifier = 0.3, -- Damage Modifier to other NPC's
lootGroup = "0", -- Group it belongs to for loot
tame = 0,
datapadItemCRC = 0,
mountCRC = 0,
mountSpeed = 0,
mountAcceleration = 0,
milk = 0,
boneType = "",
boneMax = 0,
hideType = "",
hideMax = 0,
meatType = "",
meatMax = 0,
skills = { "fedDubAttack1" },
respawnTimer = 180,
behaviorScript = "", -- Link to the behavior script for this object
}
Creatures:addCreature(fedDubSupporter, 1386145364) -- Add to Global Table
| lgpl-3.0 |
Andrettin/Wyrmsun | scripts/items.lua | 1 | 15372 | -- _________ __ __
-- / _____// |_____________ _/ |______ ____ __ __ ______
-- \_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/
-- / \| | | | \// __ \| | / __ \_/ /_/ > | /\___ \
-- /_______ /|__| |__| (____ /__| (____ /\___ /|____//____ >
-- \/ \/ \//_____/ \/
-- ______________________ ______________________
-- T H E W A R B E G I N S
-- Stratagus - A free fantasy real time strategy game engine
--
-- (c) Copyright 2015-2022 by Andrettin
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
DefineUnitType("unit-template-item", {
Name = "Item",
Template = true,
Image = {"file", "neutral/items/sack.png", "size", {16, 14}},
Animations = "animations-item",
NeutralMinimapColor = {255, 255, 0},
HitPoints = 1,
DrawLevel = 30,
TileSize = {1, 1}, BoxSize = {32, 32},
Missile = "missile-none",
Priority = 0,
Domain = "land",
NumDirections = 1,
Item = true,
ButtonPopup = "popup_item",
Sounds = {
"selected", "click"
}
} )
DefineUnitType("unit-short-sword", {
Name = "Short Sword",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "germanic/items/broad_bronze_sword.png", "size", {32, 32}},
Icon = "icon-germanic-short-sword",
ItemClass = "sword",
ButtonIcons = {
{"stand-ground", "icon-germanic-stand-ground"}
},
BasicDamage = 0
} )
DefineUnitType("unit-goblin-short-sword", {
Parent = "unit-short-sword",
Image = {"file", "teuton/items/long_iron_sword.png", "size", {32, 32}},
Icon = "icon-goblin-short-sword",
ButtonIcons = {
{"stand-ground", "icon-goblin-stand-ground"}
}
} )
DefineUnitType("unit-broad-sword", {
Name = "Broad Sword",
Parent = "unit-template-item",
Costs = {"copper", 200},
Image = {"file", "germanic/items/broad_bronze_sword.png", "size", {32, 32}},
Icon = "icon-germanic-broad-sword",
ItemClass = "sword",
ButtonIcons = {
{"stand-ground", "icon-germanic-stand-ground"}
},
BasicDamage = 2
} )
DefineUnitType("unit-goblin-broad-sword", {
Parent = "unit-broad-sword",
Image = {"file", "teuton/items/long_iron_sword.png", "size", {32, 32}},
Icon = "icon-goblin-broad-sword",
ButtonIcons = {
{"stand-ground", "icon-goblin-stand-ground"}
}
} )
DefineUnitType("unit-spatha", {
Name = "Spatha",
Parent = "unit-template-item",
Costs = {"copper", 400},
Image = {"file", "teuton/items/long_iron_sword.png", "size", {32, 32}},
Icon = "icon-teuton-spatha",
ItemClass = "sword",
ButtonIcons = {
{"stand-ground", "icon-germanic-stand-ground"}
},
BasicDamage = 4
} )
DefineUnitType("unit-frankish-spatha", {
Name = "Spatha",
Parent = "unit-spatha",
Icon = "icon-frankish-spatha"
} )
DefineUnitType("unit-goblin-long-sword", {
Name = "Long Sword",
Parent = "unit-spatha",
Icon = "icon-goblin-long-sword",
ButtonIcons = {
{"stand-ground", "icon-goblin-stand-ground"}
}
} )
DefineUnitType("unit-thrusting-sword", {
Name = "Thrusting Sword",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "germanic/items/broad_bronze_sword.png", "size", {32, 32}},
Icon = "icon-gnomish-thrusting-sword-1",
ItemClass = "thrusting_sword",
ButtonIcons = {
{"stand-ground", "icon-germanic-stand-ground"}
},
BasicDamage = 0
} )
DefineUnitType("unit-battle-axe", {
Name = "Battle Axe",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "neutral/items/axe.png", "size", {32, 32}},
Icon = "icon-dwarven-battle-axe",
ItemClass = "axe",
ButtonIcons = {
{"stand-ground", "icon-dwarven-stand-ground"}
},
BasicDamage = 0
} )
DefineUnitType("unit-broad-axe", {
Name = "Broad Axe",
Parent = "unit-template-item",
Costs = {"copper", 200},
Image = {"file", "neutral/items/axe.png", "size", {32, 32}},
Icon = "icon-dwarven-broad-axe",
ItemClass = "axe",
ButtonIcons = {
{"stand-ground", "icon-dwarven-stand-ground"}
},
BasicDamage = 2
} )
DefineUnitType("unit-great-axe", {
Name = "Great Axe",
Parent = "unit-template-item",
Costs = {"copper", 400},
Image = {"file", "neutral/items/axe.png", "size", {32, 32}},
Icon = "icon-dwarven-great-axe",
ItemClass = "axe",
ButtonIcons = {
{"stand-ground", "icon-dwarven-stand-ground"}
},
BasicDamage = 4
} )
DefineUnitType("unit-club", {
Name = "Club",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "neutral/items/club.png", "size", {32, 32}},
Icon = "icon-club",
ItemClass = "mace",
BasicDamage = 0
} )
DefineUnitType("unit-hammer", {
Name = "Hammer",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "neutral/items/hammer.png", "size", {32, 32}},
Icon = "hammer",
ItemClass = "mace",
BasicDamage = 0
} )
DefineUnitType("unit-runesmiths-hammer", {
Name = "Runesmith's Hammer",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "neutral/items/hammer.png", "size", {32, 32}},
Icon = "icon-dwarven-runesmiths-hammer",
ItemClass = "mace",
BasicDamage = 0
} )
DefineUnitType("unit-mining-pick", {
Name = "Mining Pick",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "neutral/items/mining_pick.png", "size", {32, 32}},
Icon = "icon-mining-pick",
ItemClass = "mace",
BasicDamage = 0
} )
DefineUnitType("unit-short-spear", {
Name = "Short Spear",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "neutral/items/spear.png", "size", {32, 32}},
Icon = "icon-spear",
ItemClass = "spear",
BasicDamage = 0
} )
DefineUnitType("unit-long-spear", {
Name = "Long Spear",
Parent = "unit-template-item",
Costs = {"copper", 200},
Image = {"file", "neutral/items/spear.png", "size", {32, 32}},
Icon = "icon-long-spear",
ItemClass = "spear",
BasicDamage = 2
} )
DefineUnitType("unit-pike", {
Name = "Pike",
Parent = "unit-template-item",
Costs = {"copper", 400},
Image = {"file", "neutral/items/spear.png", "size", {32, 32}},
Icon = "icon-pike",
ItemClass = "spear",
BasicDamage = 4
} )
DefineUnitType("unit-pilum", {
Name = "Pilum",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "latin/items/pilum.png", "size", {48, 48}},
Icon = "icon-latin-pilum",
ItemClass = "javelin",
BasicDamage = 0
} )
DefineUnitType("unit-throwing-axe", {
Name = "Throwing Axe",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "neutral/items/axe.png", "size", {32, 32}},
Icon = "icon-dwarven-throwing-axe",
ItemClass = "throwing_axe",
ButtonIcons = {
{"stand-ground", "icon-dwarven-stand-ground"}
},
BasicDamage = 0
} )
DefineUnitType("unit-sharp-throwing-axe", {
Name = "Sharp Throwing Axe",
Parent = "unit-template-item",
Costs = {"copper", 200},
Image = {"file", "neutral/items/axe.png", "size", {32, 32}},
Icon = "icon-dwarven-sharp-throwing-axe",
ItemClass = "throwing_axe",
ButtonIcons = {
{"stand-ground", "icon-dwarven-stand-ground"}
},
BasicDamage = 2
} )
DefineUnitType("unit-bearded-throwing-axe", {
Name = "Bearded Throwing Axe",
Parent = "unit-template-item",
Costs = {"copper", 400},
Image = {"file", "neutral/items/axe.png", "size", {32, 32}},
Icon = "icon-dwarven-bearded-throwing-axe",
ItemClass = "throwing_axe",
ButtonIcons = {
{"stand-ground", "icon-dwarven-stand-ground"}
},
BasicDamage = 4
} )
DefineUnitType("unit-hand-cannon", {
Name = "Hand Cannon",
Parent = "unit-template-item",
Costs = {"copper", 400},
Image = {"file", "teuton/items/hand_cannon.png", "size", {16, 16}},
Icon = "icon-teuton-hand-cannon",
ItemClass = "gun",
BasicDamage = 0
} )
DefineUnitType("unit-wooden-shield", {
Name = "Wooden Shield",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "dwarf/items/round_shield.png", "size", {14, 14}},
Icon = "icon-germanic-wooden-oblong-shield",
ItemClass = "shield",
Armor = 0
} )
DefineUnitType("unit-goblin-wooden-shield", {
Parent = "unit-wooden-shield",
Icon = "icon-goblin-wooden-shield"
} )
DefineUnitType("unit-bronze-shield", {
Name = "Bronze Shield",
Parent = "unit-template-item",
Costs = {"copper", 200},
Image = {"file", "germanic/items/bronze_shield.png", "size", {32, 32}},
Icon = "icon-germanic-bronze-shield",
ItemClass = "shield",
Armor = 2
} )
DefineUnitType("unit-goblin-rimmed-shield", {
Name = "Rimmed Shield",
Parent = "unit-template-item",
Costs = {"copper", 200},
Image = {"file", "dwarf/items/round_shield.png", "size", {14, 14}},
Icon = "icon-goblin-rimmed-shield",
ItemClass = "shield",
Armor = 2
} )
DefineUnitType("unit-iron-shield", {
Name = "Iron Shield",
Parent = "unit-template-item",
Costs = {"copper", 400},
Image = {"file", "teuton/items/saxon_shield.png", "size", {32, 32}},
Icon = "saxon_iron_shield",
ItemClass = "shield",
Armor = 4
} )
DefineUnitType("unit-goblin-embossed-shield", {
Name = "Embossed Shield",
Parent = "unit-template-item",
Costs = {"copper", 400},
Image = {"file", "dwarf/items/round_shield.png", "size", {14, 14}},
Icon = "icon-goblin-embossed-shield",
ItemClass = "shield",
Armor = 4
} )
DefineUnitType("unit-kite-shield", {
Name = "Kite Shield",
Parent = "unit-template-item",
Costs = {"copper", 400},
Image = {"file", "teuton/items/saxon_shield.png", "size", {32, 32}},
Icon = "heater_shield",
ItemClass = "shield",
Armor = 4
} )
--[[
DefineUnitType("unit-suebi-shield", {
Name = "Suebi Shield",
Parent = "unit-template-item",
Image = {"file", "suebi/items/suebi_shield.png", "size", {32, 32}},
Icon = "saxon_iron_shield", -- each base item type needs to have its own icon
ItemClass = "shield",
Armor = 4
} )
--]]
DefineUnitType("unit-round-shield", {
Name = "Round Shield",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "dwarf/items/round_shield.png", "size", {14, 14}},
Icon = "icon-dwarven-shield-1",
ItemClass = "shield",
Armor = 0
} )
DefineUnitType("unit-brising-round-shield", {
Name = "Brising Round Shield",
Parent = "unit-round-shield",
Image = {"file", "dlcs/brising_faction_flair/graphics/items/brising_round_shield.png", "size", {14, 14}},
Icon = "icon-brising-round-shield"
} )
DefineUnitType("unit-joruvellir-wooden-shield", {
Name = "Joruvellir Wooden Shield",
Parent = "unit-round-shield",
Icon = "icon-joruvellir-shield"
} )
DefineUnitType("unit-heater-shield", {
Name = "Heater Shield",
Parent = "unit-template-item",
Costs = {"copper", 200},
Image = {"file", "dwarf/items/round_shield.png", "size", {14, 14}},
Icon = "icon-dwarven-shield-2",
ItemClass = "shield",
Armor = 2
} )
DefineUnitType("unit-thrymgjol-shield", {
Name = "Thrymgjol Shield",
Parent = "unit-template-item",
Costs = {"copper", 400},
Image = {"file", "dwarf/items/round_shield.png", "size", {14, 14}},
Icon = "icon-dwarven-shield-3",
ItemClass = "shield",
Armor = 4
} )
DefineUnitType("unit-horn", {
Name = "Horn",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "germanic/items/bronze_lur.png", "size", {17, 15}},
Icon = "icon-germanic-bronze-lur",
ItemClass = "horn"
} )
DefineUnitType("unit-boots", {
Name = "Boots",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "neutral/items/boots.png", "size", {32, 32}},
Icon = "icon-dwarven-boots",
ItemClass = "boots",
Speed = 0
} )
DefineUnitType("unit-wool-shoes", {
Name = "Wool Shoes",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "neutral/items/boots.png", "size", {32, 32}},
Icon = "icon-gnomish-boots",
ItemClass = "boots",
Speed = 0
} )
DefineUnitType("unit-furry-wool-shoes", {
Name = "Furry Wool Shoes",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "neutral/items/boots.png", "size", {32, 32}},
Icon = "icon-gnomish-boots-fur",
ItemClass = "boots",
Speed = 0
} )
DefineUnitType("unit-amulet", {
Name = "Amulet",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "neutral/items/amulet.png", "size", {32, 32}},
Icon = "icon-amulet",
ItemClass = "amulet"
} )
DefineUnitType("unit-ring", {
Name = "Ring",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "neutral/items/ring.png", "size", {32, 32}},
Icon = "icon-ring",
ItemClass = "ring"
} )
DefineUnitType("unit-arrows", {
Name = "Arrows",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "neutral/items/arrow.png", "size", {32, 32}},
Icon = "icon-germanic-arrow",
ItemClass = "arrows",
NumDirections = 8,
BasicDamage = 0
} )
DefineUnitType("unit-barbed-arrows", {
Name = "Barbed Arrows",
Parent = "unit-template-item",
Costs = {"copper", 200},
Image = {"file", "neutral/items/arrow.png", "size", {32, 32}},
Icon = "icon-germanic-barbed-arrow",
ItemClass = "arrows",
NumDirections = 8,
BasicDamage = 2
} )
DefineUnitType("unit-bodkin-arrows", {
Name = "Bodkin Arrows",
Parent = "unit-template-item",
Costs = {"copper", 400},
Image = {"file", "neutral/items/arrow.png", "size", {32, 32}},
Icon = "icon-bodkin-arrow",
ItemClass = "arrows",
NumDirections = 8,
BasicDamage = 4
} )
DefineUnitType("unit-scroll", {
Name = "Scroll",
Parent = "unit-template-item",
Costs = {"copper", 100},
Image = {"file", "neutral/items/scroll.png", "size", {32, 32}},
Icon = "icon-scroll",
ItemClass = "scroll",
Sounds = {
"used", "scroll"
}
} )
DefineUnitType("unit-book", {
Name = "Book",
Parent = "unit-template-item",
Costs = {"copper", 500},
Image = {"file", "neutral/items/book.png", "size", {32, 32}},
Icon = "icon-book-red",
ItemClass = "book",
Sounds = {
"used", "scroll"
}
} )
DefineUnitType("unit-cheese", {
Name = "Cheese",
Parent = "unit-template-item",
Image = {"file", "neutral/items/cheese.png", "size", {15, 12}},
Icon = "icon-cheese",
ItemClass = "food",
Costs = {"time", 50, "copper", 25},
Dairy = true,
HitPointHealing = 5,
Sounds = {
"used", "eat"
}
} )
DefineUnitType("unit-carrots", {
Name = "Carrots",
Parent = "unit-template-item",
Image = {"file", "neutral/items/carrots.png", "size", {18, 12}},
Icon = "icon-carrots",
ItemClass = "food",
Costs = {"time", 50, "copper", 25},
HitPointHealing = 5,
Vegetable = true,
Sounds = {
"used", "eat"
}
} )
DefineUnitType("unit-wyrm-heart", {
Name = "Wyrm Heart",
Parent = "unit-template-item",
Image = {"file", "neutral/items/wyrm_heart.png", "size", {16, 16}},
Icon = "icon-wyrm-heart",
ItemClass = "food",
HitPointHealing = 60,
Flesh = true,
Sounds = {
"used", "eat"
}
} )
-- Shem (piece of parchment with secret symbols used to animate golems); according to Prague legends, used to animate the golem Josef
| gpl-2.0 |
TheAnswer/FirstTest | bin/scripts/creatures/objects/yavin4/creatures/spinedPuc.lua | 1 | 4646 | --Copyright (C) 2008 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
spinedPuc = Creature:new {
objectName = "spinedPuc", -- Lua Object Name
creatureType = "ANIMAL",
gender = "",
speciesName = "spined_puc",
stfName = "mob/creature_names",
objectCRC = 307007655,
socialGroup = "Spined Puc",
level = 14,
combatFlags = ATTACKABLE_FLAG + ENEMY_FLAG + AGGRESSIVE_FLAG,
healthMax = 2400,
healthMin = 2000,
strength = 0,
constitution = 0,
actionMax = 2400,
actionMin = 2000,
quickness = 0,
stamina = 0,
mindMax = 2400,
mindMin = 2000,
focus = 0,
willpower = 0,
height = 1, -- Size of creature
armor = 0, -- 0 = None; 1 = Light; 2 = Medium; 3 = Heavy
kinetic = 0,
energy = 0,
electricity = 0,
stun = 0,
blast = 0,
heat = 0,
cold = 0,
acid = 0,
lightsaber = 0,
accuracy = 200,
healer = 0,
pack = 1,
herd = 0,
stalker = 0,
killer = 1,
ferocity = 0,
aggressive = 1,
invincible = 0,
meleeDefense = 1,
rangedDefense = 1,
attackCreatureOnSight = "", -- Enter socialGroups
weapon = "object/weapon/creature/shared_creature_default_weapon.iff", -- File path to weapon -> object\xxx\xxx\xx
weaponName = "Creature Defualt", -- Name ex. 'a Vibrolance'
weaponTemp = "creature_default_weapon", -- Weapon Template ex. 'lance_vibrolance'
weaponClass = "UnarmedMeleeWeapon", -- Weapon Class ex. 'PolearmMeleeWeapon'
weaponEquipped = 0,
weaponMinDamage = 150,
weaponMaxDamage = 160,
weaponAttackSpeed = 2,
weaponDamageType = "KINETIC", -- ELECTRICITY, KINETIC, etc
weaponArmorPiercing = "NONE", -- LIGHT, NONE, MEDIUM, HEAVY
alternateWeapon = "", -- File path to weapon -> object\xxx\xxx\xx
alternateWeaponName = "", -- Name ex. 'a Vibrolance'
alternateWeaponTemp = "", -- Weapon Template ex. 'lance_vibrolance'
alternateWeaponClass = "", -- Weapon Class ex. 'PolearmMeleeWeapon'
alternateweaponEquipped = 0,
alternateWeaponMinDamage = 0,
alternateWeaponMaxDamage = 0,
alternateWeaponAttackSpeed = 0,
alternateWeaponDamageType = "", -- ELECTRICITY, KINETIC, etc
alternateWeaponArmorPiercing = "", -- LIGHT, NONE, MEDIUM, HEAVY
internalNPCDamageModifier = 0.3, -- Damage Modifier to other NPC's
lootGroup = "0", -- Group it belongs to for loot
tame = 0.25, -- Likely hood to be tamed
datapadItemCRC = 4255586723,
mountCRC = 0,
mountSpeed = 0,
mountAcceleration = 0,
milk = 0,
boneType = "",
boneMax = 20,
hideType = "hide_leathery_yavin4",
hideMax = 6,
meatType = "meat_reptilian_yavin4",
meatMax = 6,
skills = { "spinedPucAttack1" },
respawnTimer = 60,
behaviorScript = "" -- Link to the behavior script for this object
}
Creatures:addCreature(spinedPuc, 307007655) -- Add to Global Table
| lgpl-3.0 |
moltafet35/seeck | 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 |
TheAnswer/FirstTest | bin/scripts/creatures/objects/tatooine/creatures/worrtGutbuster.lua | 1 | 4720 | --Copyright (C) 2008 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
worrtGutbuster = Creature:new {
objectName = "worrtGutbuster", -- Lua Object Name
creatureType = "ANIMAL",
gender = "",
speciesName = "worrt_gutbuster",
stfName = "mob/creature_names",
objectCRC = 714826259,
socialGroup = "Worrt",
level = 16,
combatFlags = ATTACKABLE_FLAG + ENEMY_FLAG + AGGRESSIVE_FLAG,
healthMax = 3500,
healthMin = 2900,
strength = 0,
constitution = 0,
actionMax = 3500,
actionMin = 2900,
quickness = 0,
stamina = 0,
mindMax = 3500,
mindMin = 2900,
focus = 0,
willpower = 0,
height = 1, -- Size of creature
armor = 0, -- 0 = None; 1 = Light; 2 = Medium; 3 = Heavy
kinetic = 0,
energy = 0,
electricity = 10,
stun = -1,
blast = 0,
heat = 0,
cold = 0,
acid = 0,
lightsaber = 0,
accuracy = 0,
healer = 0,
pack = 1,
herd = 0,
stalker = 0,
killer = 0,
ferocity = 0,
aggressive = 1,
invincible = 0,
meleeDefense = 1,
rangedDefense = 1,
attackCreatureOnSight = "", -- Enter socialGroups
weapon = "object/weapon/creature/shared_creature_default_weapon.iff", -- File path to weapon -> object\xxx\xxx\xx
weaponName = "Creature Defualt", -- Name ex. 'a Vibrolance'
weaponTemp = "creature_default_weapon", -- Weapon Template ex. 'lance_vibrolance'
weaponClass = "UnarmedMeleeWeapon", -- Weapon Class ex. 'PolearmMeleeWeapon'
weaponEquipped = 0,
weaponMinDamage = 160,
weaponMaxDamage = 170,
weaponAttackSpeed = 2,
weaponDamageType = "KINETIC", -- ELECTRICITY, KINETIC, etc
weaponArmorPiercing = "NONE", -- LIGHT, NONE, MEDIUM, HEAVY
alternateWeapon = "", -- File path to weapon -> object\xxx\xxx\xx
alternateWeaponName = "", -- Name ex. 'a Vibrolance'
alternateWeaponTemp = "", -- Weapon Template ex. 'lance_vibrolance'
alternateWeaponClass = "", -- Weapon Class ex. 'PolearmMeleeWeapon'
alternateWeaponEquipped = 0,
alternateWeaponMinDamage = 0,
alternateWeaponMaxDamage = 0,
alternateWeaponAttackSpeed = 0,
alternateWeaponDamageType = "", -- ELECTRICITY, KINETIC, etc
alternateWeaponArmorPiercing = "", -- LIGHT, NONE, MEDIUM, HEAVY
internalNPCDamageModifier = 0.3, -- Damage Modifier to other NPC's
lootGroup = "0", -- Group it belongs to for loot
tame = 0.05, -- Likely hood to be tamed
datapadItemCRC = 2024101379,
mountCRC = 0,
mountSpeed = 0,
mountAcceleration = 0,
milk = 0,
boneType = "bone_mammal_tatooine",
boneMax = 4,
hideType = "hide_leathery_tatooine",
hideMax = 9,
meatType = "meat_reptilian_tatooine",
meatMax = 9,
skills = { "worrtAttack1" },
-- skills = { " Stun attack", "", "" }
respawnTimer = 60,
behaviorScript = "", -- Link to the behavior script for this object
}
Creatures:addCreature(worrtGutbuster, 714826259) -- Add to Global Table
| lgpl-3.0 |
raffomania/MAVE | src/core/resources.lua | 1 | 1205 | Resources = class("Resources")
function Resources:initialize()
self.imageQueue = {}
self.musicQueue = {}
self.soundQueue = {}
self.fontQueue= {}
self.images = {}
self.music = {}
self.sounds = {}
self.fonts = {}
end
function Resources:addImage(name, src)
self.imageQueue[name] = src
end
function Resources:addMusic(name, src)
self.musicQueue[name] = src
end
function Resources:addSound(name, src)
self.soundQueue[name] = src
end
function Resources:addFont(name, src, size)
self.fontQueue[name] = {src, size}
end
function Resources:load(threaded)
for name, pair in pairs(self.fontQueue) do
self.fonts[name] = love.graphics.newFont(pair[1], pair[2])
self.fontQueue[name] = nil
end
for name, src in pairs(self.musicQueue) do
self.music[name] = love.audio.newSource(src)
self.musicQueue[name] = nil
end
for name, src in pairs(self.soundQueue) do
self.sounds[name] = love.audio.newSource(src)
self.soundQueue[name] = nil
end
for name, src in pairs(self.imageQueue) do
self.images[name] = love.graphics.newImage(src)
self.imageQueue[name] = nil
end
end | gpl-3.0 |
perusio/lua-uri | test/_generic.lua | 2 | 24889 | require "uri-test"
local URI = require "uri"
module("test.generic", lunit.testcase, package.seeall)
function test_normalize_percent_encoding ()
-- Don't use unnecessary percent encoding for unreserved characters.
test_norm("x:ABCDEFGHIJKLM", "x:%41%42%43%44%45%46%47%48%49%4A%4b%4C%4d")
test_norm("x:NOPQRSTUVWXYZ", "x:%4E%4f%50%51%52%53%54%55%56%57%58%59%5A")
test_norm("x:abcdefghijklm", "x:%61%62%63%64%65%66%67%68%69%6A%6b%6C%6d")
test_norm("x:nopqrstuvwxyz", "x:%6E%6f%70%71%72%73%74%75%76%77%78%79%7A")
test_norm("x:0123456789", "x:%30%31%32%33%34%35%36%37%38%39")
test_norm("x:-._~", "x:%2D%2e%5F%7e")
-- Keep percent encoding for other characters in US-ASCII.
test_norm_already("x:%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F")
test_norm_already("x:%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F")
test_norm_already("x:%20%21%22%23%24%25%26%27%28%29%2A%2B%2C")
test_norm_already("x:%2F")
test_norm_already("x:%3A%3B%3C%3D%3E%3F%40")
test_norm_already("x:%5B%5C%5D%5E")
test_norm_already("x:%60")
test_norm_already("x:%7B%7C%7D")
test_norm_already("x:%7F")
-- Normalize hex digits in percent encoding to uppercase.
test_norm("x:%0A%0B%0C%0D%0E%0F", "x:%0a%0b%0c%0d%0e%0f")
test_norm("x:%AA%BB%CC%DD%EE%FF", "x:%aA%bB%cC%dD%eE%fF")
-- Keep percent encoding, and normalize hex digit case, for all characters
-- outside US-ASCII.
for i = 0x80, 0xFF do
test_norm_already(string.format("x:%%%02X", i))
test_norm(string.format("x:%%%02X", i), string.format("x:%%%02x", i))
end
end
function test_bad_percent_encoding ()
assert_error("double percent", function () URI:new("x:foo%%2525") end)
assert_error("no hex digits", function () URI:new("x:foo%") end)
assert_error("no hex digits 2nd time", function () URI:new("x:f%20o%") end)
assert_error("1 hex digit", function () URI:new("x:foo%2") end)
assert_error("1 hex digit 2nd time", function () URI:new("x:f%20o%2") end)
assert_error("bad hex digit 1", function () URI:new("x:foo%G2bar") end)
assert_error("bad hex digit 2", function () URI:new("x:foo%2Gbar") end)
assert_error("bad hex digit both", function () URI:new("x:foo%GGbar") end)
end
function test_scheme ()
test_norm_already("foo:")
test_norm_already("foo:-+.:")
test_norm_already("foo:-+.0123456789:")
test_norm_already("x:")
test_norm("example:FooBar:Baz", "ExAMplE:FooBar:Baz")
local uri = assert(URI:new("Foo-Bar:Baz%20Quux"))
is("foo-bar", uri:scheme())
end
function test_change_scheme ()
local uri = assert(URI:new("x-foo://example.com/blah"))
is("x-foo://example.com/blah", tostring(uri))
is("x-foo", uri:scheme())
is("uri", uri._NAME)
-- x-foo -> x-bar
is("x-foo", uri:scheme("x-bar"))
is("x-bar", uri:scheme())
is("x-bar://example.com/blah", tostring(uri))
is("uri", uri._NAME)
-- x-bar -> http
is("x-bar", uri:scheme("http"))
is("http", uri:scheme())
is("http://example.com/blah", tostring(uri))
is("uri.http", uri._NAME)
-- http -> x-foo
is("http", uri:scheme("x-foo"))
is("x-foo", uri:scheme())
is("x-foo://example.com/blah", tostring(uri))
is("uri", uri._NAME)
end
function test_change_scheme_bad ()
local uri = assert(URI:new("x-foo://foo@bar/"))
-- Try changing the scheme to something invalid
assert_error("bad scheme '-x-foo'", function () uri:scheme("-x-foo") end)
assert_error("bad scheme 'x,foo'", function () uri:scheme("x,foo") end)
assert_error("bad scheme 'x:foo'", function () uri:scheme("x:foo") end)
assert_error("bad scheme 'x-foo:'", function () uri:scheme("x-foo:") end)
-- Change to valid scheme, but where the rest of the URI is not valid for it
assert_error("bad HTTP URI", function () uri:scheme("http") end)
-- Original URI should be left unchanged
is("x-foo://foo@bar/", tostring(uri))
is("x-foo", uri:scheme())
is("uri", uri._NAME)
end
function test_auth_userinfo ()
local uri = assert(URI:new("X://a-zA-Z09!$:&%40@FOO.com:80/"))
is("x://a-zA-Z09!$:&%40@foo.com:80/", tostring(uri))
is("x", uri:scheme())
is("a-zA-Z09!$:&%40", uri:userinfo())
is("foo.com", uri:host())
is(80, uri:port())
end
function test_auth_userinfo_bad ()
is_bad_uri("bad character in userinfo", "x-a://foo^bar@example.com/")
end
function test_auth_set_userinfo ()
local uri = assert(URI:new("X-foo://user:pass@FOO.com:80/"))
is("user:pass", uri:userinfo("newuserinfo"))
is("newuserinfo", uri:userinfo())
is("x-foo://newuserinfo@foo.com:80/", tostring(uri))
-- Userinfo should be supplied already percent-encoded, but the percent
-- encoding should be normalized.
is("newuserinfo", uri:userinfo("foo%3abar%3A:%78"))
is("foo%3Abar%3A:x", uri:userinfo())
-- It should be OK to use more than one colon in userinfo for generic URIs,
-- although not for ones which specificly divide it into username:password.
is("foo%3Abar%3A:x", uri:userinfo("foo:bar:baz::"))
is("foo:bar:baz::", uri:userinfo())
end
function test_auth_set_bad_userinfo ()
local uri = assert(URI:new("X-foo://user:pass@FOO.com:80/"))
assert_error("/ in userinfo", function () uri:userinfo("foo/bar") end)
assert_error("@ in userinfo", function () uri:userinfo("foo@bar") end)
is("user:pass", uri:userinfo())
is("x-foo://user:pass@foo.com:80/", tostring(uri))
end
function test_auth_reg_name ()
local uri = assert(URI:new("x://azAZ0-9--foo.bqr_baz~%20!$;/"))
-- TODO - %20 should probably be rejected. Apparently only UTF-8 pctenc
-- should be produced, so after unescaping unreserved chars there should
-- be nothing left percent encoded other than valid UTF-8 sequences. If
-- that's right I could safely decode the host before returning it.
is("azaz0-9--foo.bqr_baz~%20!$;", uri:host())
end
function test_auth_ip4 ()
local uri = assert(URI:new("x://0.0.0.0/path"))
is("0.0.0.0", uri:host())
uri = assert(URI:new("x://192.168.0.1/path"))
is("192.168.0.1", uri:host())
uri = assert(URI:new("x://255.255.255.255/path"))
is("255.255.255.255", uri:host())
end
function test_auth_ip4_or_reg_name_bad ()
is_bad_uri("bad character in host part", "x://foo:bar/")
end
function test_auth_ip6 ()
-- The example addresses in here are all from RFC 4291 section 2.2, except
-- that they get normalized to lowercase here in the results.
local uri = assert(URI:new("x://[ABCD:EF01:2345:6789:ABCD:EF01:2345:6789]"))
is("[abcd:ef01:2345:6789:abcd:ef01:2345:6789]", uri:host())
uri = assert(URI:new("x://[ABCD:EF01:2345:6789:ABCD:EF01:2345:6789]/"))
is("[abcd:ef01:2345:6789:abcd:ef01:2345:6789]", uri:host())
uri = assert(URI:new("x://[ABCD:EF01:2345:6789:ABCD:EF01:2345:6789]:"))
is("[abcd:ef01:2345:6789:abcd:ef01:2345:6789]", uri:host())
uri = assert(URI:new("x://[ABCD:EF01:2345:6789:ABCD:EF01:2345:6789]:/"))
is("[abcd:ef01:2345:6789:abcd:ef01:2345:6789]", uri:host())
uri = assert(URI:new("x://[ABCD:EF01:2345:6789:ABCD:EF01:2345:6789]:0/"))
is("[abcd:ef01:2345:6789:abcd:ef01:2345:6789]", uri:host())
uri = assert(URI:new("x://y:z@[ABCD:EF01:2345:6789:ABCD:EF01:2345:6789]:80/"))
is("[abcd:ef01:2345:6789:abcd:ef01:2345:6789]", uri:host())
uri = assert(URI:new("x://[2001:DB8:0:0:8:800:200C:417A]/"))
is("[2001:db8:0:0:8:800:200c:417a]", uri:host())
uri = assert(URI:new("x://[FF01:0:0:0:0:0:0:101]/"))
is("[ff01:0:0:0:0:0:0:101]", uri:host())
uri = assert(URI:new("x://[ff01::101]/"))
is("[ff01::101]", uri:host())
uri = assert(URI:new("x://[0:0:0:0:0:0:0:1]/"))
is("[0:0:0:0:0:0:0:1]", uri:host())
uri = assert(URI:new("x://[::1]/"))
is("[::1]", uri:host())
uri = assert(URI:new("x://[0:0:0:0:0:0:0:0]/"))
is("[0:0:0:0:0:0:0:0]", uri:host())
uri = assert(URI:new("x://[0:0:0:0:0:0:13.1.68.3]/"))
is("[0:0:0:0:0:0:13.1.68.3]", uri:host())
uri = assert(URI:new("x://[::13.1.68.3]/"))
is("[::13.1.68.3]", uri:host())
uri = assert(URI:new("x://[0:0:0:0:0:FFFF:129.144.52.38]/"))
is("[0:0:0:0:0:ffff:129.144.52.38]", uri:host())
uri = assert(URI:new("x://[::FFFF:129.144.52.38]/"))
is("[::ffff:129.144.52.38]", uri:host())
-- These try all the cominations of abbreviating using '::'.
uri = assert(URI:new("x://[08:19:2a:3B:4c:5D:6e:7F]/"))
is("[08:19:2a:3b:4c:5d:6e:7f]", uri:host())
uri = assert(URI:new("x://[::19:2a:3B:4c:5D:6e:7F]/"))
is("[::19:2a:3b:4c:5d:6e:7f]", uri:host())
uri = assert(URI:new("x://[::2a:3B:4c:5D:6e:7F]/"))
is("[::2a:3b:4c:5d:6e:7f]", uri:host())
uri = assert(URI:new("x://[::3B:4c:5D:6e:7F]/"))
is("[::3b:4c:5d:6e:7f]", uri:host())
uri = assert(URI:new("x://[::4c:5D:6e:7F]/"))
is("[::4c:5d:6e:7f]", uri:host())
uri = assert(URI:new("x://[::5D:6e:7F]/"))
is("[::5d:6e:7f]", uri:host())
uri = assert(URI:new("x://[::6e:7F]/"))
is("[::6e:7f]", uri:host())
uri = assert(URI:new("x://[::7F]/"))
is("[::7f]", uri:host())
uri = assert(URI:new("x://[::]/"))
is("[::]", uri:host())
uri = assert(URI:new("x://[08::]/"))
is("[08::]", uri:host())
uri = assert(URI:new("x://[08:19::]/"))
is("[08:19::]", uri:host())
uri = assert(URI:new("x://[08:19:2a::]/"))
is("[08:19:2a::]", uri:host())
uri = assert(URI:new("x://[08:19:2a:3B::]/"))
is("[08:19:2a:3b::]", uri:host())
uri = assert(URI:new("x://[08:19:2a:3B:4c::]/"))
is("[08:19:2a:3b:4c::]", uri:host())
uri = assert(URI:new("x://[08:19:2a:3B:4c:5D::]/"))
is("[08:19:2a:3b:4c:5d::]", uri:host())
uri = assert(URI:new("x://[08:19:2a:3B:4c:5D:6e::]/"))
is("[08:19:2a:3b:4c:5d:6e::]", uri:host())
-- Try extremes of good IPv4 addresses mapped to IPv6.
uri = assert(URI:new("x://[::FFFF:0.0.0.0]/path"))
is("[::ffff:0.0.0.0]", uri:host())
uri = assert(URI:new("x://[::ffff:255.255.255.255]/path"))
is("[::ffff:255.255.255.255]", uri:host())
end
function test_auth_ip6_bad ()
is_bad_uri("empty brackets", "x://[]")
is_bad_uri("just colon", "x://[:]")
is_bad_uri("3 colons only", "x://[:::]")
is_bad_uri("3 colons at start", "x://[:::1234]")
is_bad_uri("3 colons at end", "x://[1234:::]")
is_bad_uri("3 colons in middle", "x://[1234:::5678]")
is_bad_uri("non-hex char", "x://[ABCD:EF01:2345:6789:ABCD:EG01:2345:6789]")
is_bad_uri("chunk too big",
"x://[ABCD:EF01:2345:6789:ABCD:EFF01:2345:6789]")
is_bad_uri("too many chunks",
"x://[ABCD:EF01:2345:6789:ABCD:EF01:2345:6789:1]")
is_bad_uri("not enough chunks", "x://[ABCD:EF01:2345:6789:ABCD:EF01:2345]")
is_bad_uri("too many chunks with ellipsis in middle",
"x://[ABCD:EF01:2345:6789:ABCD::EF01:2345:6789]")
is_bad_uri("too many chunks with ellipsis at end",
"x://[ABCD:EF01:2345:6789:ABCD:EF01:2345:6789::]")
is_bad_uri("too many chunks with ellipsis at start",
"x://[::ABCD:EF01:2345:6789:ABCD:EF01:2345:6789]")
is_bad_uri("two elipses, middle and end",
"x://[EF01:2345::6789:ABCD:EF01:2345::]")
is_bad_uri("two elipses, start and middle",
"x://[::EF01:2345::6789:ABCD:EF01:2345]")
is_bad_uri("two elipses, both ends",
"x://[::EF01:2345:6789:ABCD:EF01:2345::]")
is_bad_uri("two elipses, both middle",
"x://[EF01:2345::6789:ABCD:::EF01:2345]")
is_bad_uri("extra colon at start",
"x://[:ABCD:EF01:2345:6789:ABCD:EF01:2345:6789]")
is_bad_uri("missing chunk at start",
"x://[:EF01:2345:6789:ABCD:EF01:2345:6789]")
is_bad_uri("extra colon at end",
"x://[ABCD:EF01:2345:6789:ABCD:EF01:2345:6789:]")
is_bad_uri("missing chunk at end",
"x://[ABCD:EF01:2345:6789:ABCD:EF01:2345:]")
-- Bad IPv4 addresses mapped to IPv6.
is_bad_uri("octet 1 too big", "x://[::FFFF:256.2.3.4]/")
is_bad_uri("octet 2 too big", "x://[::FFFF:1.256.3.4]/")
is_bad_uri("octet 3 too big", "x://[::FFFF:1.2.256.4]/")
is_bad_uri("octet 4 too big", "x://[::FFFF:1.2.3.256]/")
is_bad_uri("octet 1 leading zeroes", "x://[::FFFF:01.2.3.4]/")
is_bad_uri("octet 2 leading zeroes", "x://[::FFFF:1.02.3.4]/")
is_bad_uri("octet 3 leading zeroes", "x://[::FFFF:1.2.03.4]/")
is_bad_uri("octet 4 leading zeroes", "x://[::FFFF:1.2.3.04]/")
is_bad_uri("only 2 octets", "x://[::FFFF:1.2]/")
is_bad_uri("only 3 octets", "x://[::FFFF:1.2.3]/")
is_bad_uri("5 octets", "x://[::FFFF:1.2.3.4.5]/")
end
function test_auth_ipvfuture ()
local uri = assert(URI:new("x://[v123456789ABCdef.foo=bar]/"))
is("[v123456789abcdef.foo=bar]", uri:host())
end
function test_auth_ipvfuture_bad ()
is_bad_uri("missing dot", "x://[v999]")
is_bad_uri("missing hex num", "x://[v.foo]")
is_bad_uri("missing bit after dot", "x://[v999.]")
is_bad_uri("bad character in hex num", "x://[v99g.foo]")
is_bad_uri("bad character after dot", "x://[v999.foo:bar]")
end
function test_auth_set_host ()
local uri = assert(URI:new("x-a://host/path"))
is("host", uri:host("FOO.BAR"))
is("x-a://foo.bar/path", tostring(uri))
is("foo.bar", uri:host("[::6e:7F]"))
is("x-a://[::6e:7f]/path", tostring(uri))
is("[::6e:7f]", uri:host("[v7F.foo=BAR]"))
is("x-a://[v7f.foo=bar]/path", tostring(uri))
is("[v7f.foo=bar]", uri:host(""))
is("x-a:///path", tostring(uri))
is("", uri:host(nil))
is(nil, uri:host())
is("x-a:/path", tostring(uri))
end
function test_auth_set_host_bad ()
local uri = assert(URI:new("x-a://host/path"))
assert_error("bad char in host", function () uri:host("foo^bar") end)
assert_error("invalid IPv6 host", function () uri:host("[::3G]") end)
assert_error("invalid IPvFuture host", function () uri:host("[v7.]") end)
is("host", uri:host())
is("x-a://host/path", tostring(uri))
-- There must be a hsot when there is a userinfo or port.
uri = assert(URI:new("x-a://foo@/"))
assert_error("userinfo but no host", function () uri:host(nil) end)
is("x-a://foo@/", tostring(uri))
uri = assert(URI:new("x-a://:123/"))
assert_error("port but no host", function () uri:host(nil) end)
is("x-a://:123/", tostring(uri))
end
function test_auth_port ()
local uri = assert(URI:new("x://localhost:0/path"))
is(0, uri:port())
uri = assert(URI:new("x://localhost:0"))
is(0, uri:port())
uri = assert(URI:new("x://foo:bar@localhost:0"))
is(0, uri:port())
uri = assert(URI:new("x://localhost:00/path"))
is(0, uri:port())
uri = assert(URI:new("x://localhost:00"))
is(0, uri:port())
uri = assert(URI:new("x://foo:bar@localhost:00"))
is(0, uri:port())
uri = assert(URI:new("x://localhost:54321/path"))
is(54321, uri:port())
uri = assert(URI:new("x://localhost:54321"))
is(54321, uri:port())
uri = assert(URI:new("x://foo:bar@localhost:54321"))
is(54321, uri:port())
uri = assert(URI:new("x://foo:bar@localhost:"))
is(nil, uri:port())
uri = assert(URI:new("x://foo:bar@localhost:/"))
is(nil, uri:port())
uri = assert(URI:new("x://foo:bar@localhost"))
is(nil, uri:port())
uri = assert(URI:new("x://foo:bar@localhost/"))
is(nil, uri:port())
end
function test_auth_set_port ()
-- Test unusual but valid values for port.
local uri = assert(URI:new("x://localhost/path"))
is(nil, uri:port("12345")) -- string
is(12345, uri:port())
is("x://localhost:12345/path", tostring(uri))
uri = assert(URI:new("x://localhost/path"))
is(nil, uri:port(12345.0)) -- float
is(12345, uri:port())
is("x://localhost:12345/path", tostring(uri))
end
function test_auth_set_port_without_host ()
local uri = assert(URI:new("x:///path"))
is(nil, uri:port(80))
is(80, uri:port())
is("", uri:host())
is("x://:80/path", tostring(uri))
uri = assert(URI:new("x:/path"))
is(nil, uri:port(80))
is(80, uri:port())
is("", uri:host())
is("x://:80/path", tostring(uri))
end
function test_auth_set_port_bad ()
local uri = assert(URI:new("x://localhost:54321/path"))
assert_error("negative port number", function () uri:port(-23) end)
assert_error("port not integer", function () uri:port(23.00001) end)
assert_error("string not number", function () uri:port("x") end)
assert_error("string not all number", function () uri:port("x23") end)
assert_error("string negative number", function () uri:port("-23") end)
assert_error("string empty", function () uri:port("") end)
is(54321, uri:port())
is("x://localhost:54321/path", tostring(uri))
end
function test_path ()
local uri = assert(URI:new("x:"))
is("", uri:path())
uri = assert(URI:new("x:?"))
is("", uri:path())
uri = assert(URI:new("x:#"))
is("", uri:path())
uri = assert(URI:new("x:/"))
is("/", uri:path())
uri = assert(URI:new("x://"))
is("", uri:path())
uri = assert(URI:new("x://?"))
is("", uri:path())
uri = assert(URI:new("x://#"))
is("", uri:path())
uri = assert(URI:new("x:///"))
is("/", uri:path())
uri = assert(URI:new("x:////"))
is("//", uri:path())
uri = assert(URI:new("x:foo"))
is("foo", uri:path())
uri = assert(URI:new("x:/foo"))
is("/foo", uri:path())
uri = assert(URI:new("x://foo"))
is("", uri:path())
uri = assert(URI:new("x://foo?"))
is("", uri:path())
uri = assert(URI:new("x://foo#"))
is("", uri:path())
uri = assert(URI:new("x:///foo"))
is("/foo", uri:path())
uri = assert(URI:new("x:////foo"))
is("//foo", uri:path())
uri = assert(URI:new("x://foo/"))
is("/", uri:path())
uri = assert(URI:new("x://foo/bar"))
is("/bar", uri:path())
end
function test_path_bad ()
is_bad_uri("bad character in path", "x-a://host/^/")
end
function test_set_path_without_auth ()
local uri = assert(URI:new("x:blah"))
is("blah", uri:path("frob%25%3a%78/%2F"))
is("frob%25%3Ax/%2F", uri:path("/foo/bar"))
is("/foo/bar", uri:path("//foo//bar"))
is("/%2Ffoo//bar", uri:path("x ?#\"\0\127\255"))
is("x%20%3F%23%22%00%7F%FF", uri:path(""))
is("", uri:path(nil))
is("", uri:path())
is("x:", tostring(uri))
end
function test_set_path_with_auth ()
local uri = assert(URI:new("x://host/wibble"))
is("/wibble", uri:path("/foo/bar"))
is("/foo/bar", uri:path("//foo//bar"))
is("//foo//bar", uri:path(nil))
is("", uri:path(""))
is("", uri:path())
is("x://host", tostring(uri))
end
function test_set_path_bad ()
local uri = assert(URI:new("x://host/wibble"))
tostring(uri)
assert_error("with authority, path must start with /",
function () uri:path("foo") end)
assert_error("bad %-encoding, % at end", function () uri:path("foo%") end)
assert_error("bad %-encoding, %2 at end", function () uri:path("foo%2") end)
assert_error("bad %-encoding, %gf", function () uri:path("%gf") end)
assert_error("bad %-encoding, %fg", function () uri:path("%fg") end)
is("/wibble", uri:path())
is("x://host/wibble", tostring(uri))
end
function test_query ()
local uri = assert(URI:new("x:?"))
is("", uri:query())
uri = assert(URI:new("x:"))
is(nil, uri:query())
uri = assert(URI:new("x:/foo"))
is(nil, uri:query())
uri = assert(URI:new("x:/foo#"))
is(nil, uri:query())
uri = assert(URI:new("x:/foo#bar?baz"))
is(nil, uri:query())
uri = assert(URI:new("x:/foo?"))
is("", uri:query())
uri = assert(URI:new("x://foo?"))
is("", uri:query())
uri = assert(URI:new("x://foo/?"))
is("", uri:query())
uri = assert(URI:new("x:/foo?bar"))
is("bar", uri:query())
uri = assert(URI:new("x:?foo?bar?"))
is("foo?bar?", uri:query())
uri = assert(URI:new("x:?foo?bar?#quux?frob"))
is("foo?bar?", uri:query())
uri = assert(URI:new("x://foo/bar%3Fbaz?"))
is("", uri:query())
uri = assert(URI:new("x:%3F?foo"))
is("%3F", uri:path())
is("foo", uri:query())
end
function test_query_bad ()
is_bad_uri("bad character in query", "x-a://host/path/?foo^bar")
end
function test_set_query ()
local uri = assert(URI:new("x://host/path"))
is(nil, uri:query("foo/bar?baz"))
is("x://host/path?foo/bar?baz", tostring(uri))
is("foo/bar?baz", uri:query(""))
is("x://host/path?", tostring(uri))
is("", uri:query("foo^bar#baz"))
is("x://host/path?foo%5Ebar%23baz", tostring(uri))
is("foo%5Ebar%23baz", uri:query(nil))
is(nil, uri:query())
is("x://host/path", tostring(uri))
end
function test_fragment ()
local uri = assert(URI:new("x:"))
is(nil, uri:fragment())
uri = assert(URI:new("x:#"))
is("", uri:fragment())
uri = assert(URI:new("x://#"))
is("", uri:fragment())
uri = assert(URI:new("x:///#"))
is("", uri:fragment())
uri = assert(URI:new("x:////#"))
is("", uri:fragment())
uri = assert(URI:new("x:#foo"))
is("foo", uri:fragment())
uri = assert(URI:new("x:%23#foo"))
is("%23", uri:path())
is("foo", uri:fragment())
uri = assert(URI:new("x:?foo?bar?#quux?frob"))
is("quux?frob", uri:fragment())
end
function test_fragment_bad ()
is_bad_uri("bad character in fragment", "x-a://host/path/#foo^bar")
end
function test_set_fragment ()
local uri = assert(URI:new("x://host/path"))
is(nil, uri:fragment("foo/bar#baz"))
is("x://host/path#foo/bar%23baz", tostring(uri))
is("foo/bar%23baz", uri:fragment(""))
is("x://host/path#", tostring(uri))
is("", uri:fragment("foo^bar?baz"))
is("x://host/path#foo%5Ebar?baz", tostring(uri))
is("foo%5Ebar?baz", uri:fragment(nil))
is(nil, uri:fragment())
is("x://host/path", tostring(uri))
end
function test_bad_usage ()
assert_error("missing uri arg", function () URI:new() end)
assert_error("nil uri arg", function () URI:new(nil) end)
end
function test_clone_with_new ()
-- Test cloning with as many components set as possible.
local uri = assert(URI:new("x-foo://user:pass@bar.com:123/blah?q#frag"))
tostring(uri)
local clone = URI:new(uri)
assert_table(clone)
is("x-foo://user:pass@bar.com:123/blah?q#frag", tostring(uri))
is("x-foo://user:pass@bar.com:123/blah?q#frag", tostring(clone))
is("uri", getmetatable(uri)._NAME)
is("uri", getmetatable(clone)._NAME)
-- Test cloning with less stuff specified, but not in the base class.
uri = assert(URI:new("http://example.com/"))
clone = URI:new(uri)
assert_table(clone)
is("http://example.com/", tostring(uri))
is("http://example.com/", tostring(clone))
is("uri.http", getmetatable(uri)._NAME)
is("uri.http", getmetatable(clone)._NAME)
end
function test_set_uri ()
local uri = assert(URI:new("x-foo://user:pass@bar.com:123/blah?q#frag"))
is("x-foo://user:pass@bar.com:123/blah?q#frag",
uri:uri("http://example.com:81/blah2?q2#frag2"))
is("http://example.com:81/blah2?q2#frag2", uri:uri())
is("uri.http", getmetatable(uri)._NAME)
is("http", uri:scheme())
is("q2", uri:query())
is("http://example.com:81/blah2?q2#frag2", uri:uri("Urn:X-FOO:bar"))
is("uri.urn", getmetatable(uri)._NAME)
is("x-foo", uri:nid())
is("urn:x-foo:bar", tostring(uri))
end
function test_set_uri_bad ()
local uri = assert(URI:new("x-foo://user:pass@bar.com:123/blah?q#frag"))
assert_error("can't set URI to nil", function () uri:uri(nil) end)
assert_error("invalid authority", function () uri:uri("foo://@@") end)
is("x-foo://user:pass@bar.com:123/blah?q#frag", uri:uri())
is("uri", getmetatable(uri)._NAME)
is("x-foo", uri:scheme())
end
function test_eq ()
local uri1str, uri2str = "x-a://host/foo", "x-a://host/bar"
local uri1obj, uri2obj = assert(URI:new(uri1str)), assert(URI:new(uri2str))
assert_true(URI.eq(uri1str, uri1str), "str == str")
assert_false(URI.eq(uri1str, uri2str), "str ~= str")
assert_true(URI.eq(uri1str, uri1obj), "str == obj")
assert_false(URI.eq(uri1str, uri2obj), "str ~= obj")
assert_true(URI.eq(uri1obj, uri1str), "obj == str")
assert_false(URI.eq(uri1obj, uri2str), "obj ~= str")
assert_true(URI.eq(uri1obj, uri1obj), "obj == obj")
assert_false(URI.eq(uri1obj, uri2obj), "obj ~= obj")
end
function test_eq_bad_uri ()
-- Check that an exception is thrown when 'eq' is given a bad URI string,
-- and also that it's not just the error from trying to call the 'uri'
-- method on nil, because that won't be very helpful to the caller.
local ok, err = pcall(URI.eq, "^", "x-a://x/")
assert_false(ok)
assert_not_match("a nil value", err)
ok, err = pcall(URI.eq, "x-a://x/", "^")
assert_false(ok)
assert_not_match("a nil value", err)
end
-- vi:ts=4 sw=4 expandtab
| mit |
Novaes/ouro | src/lib/low-matrixtestharness.lua | 1 | 7264 | local ffi = require("ffi")
if ffi.os == "Windows" then
return
end
local adjust = 0
function CalcTime(fn)
local begin = terralib.currenttimeinseconds()
local current
local times = 0
repeat
fn()
current = terralib.currenttimeinseconds()
times = times + 1
until times == 10
-- until current - begin > 0.2
return (current - begin - adjust*times) / times
end
local MTH = {}
function assertmm(CR,C,A,B,M,N,K)
for m=0, M - 1 do
for n=0, N - 1 do
CR[m*N + n] = 0
for k=0, K - 1 do
CR[m*N + n] = CR[m*N + n] + A[m*K + k] * B[k*N + n]
end
if CR[m*N + n] ~= C[m*N + n] then return false end
end
end
return true
end
-- find a standard convolution and make it here
-- void cblas_dgemm(int, int,
-- int, const int M, const int N,
-- const int K, const double alpha, const double *A,
-- const int lda, const double *B, const int ldb,
-- const double beta, double *C, const int ldc);
-- ]]
-- local function referenceconv(M,N,K,L,A,B,C)
-- --acc.cblas_dgemm(101,111,111,M,N,K,1.0,A,K,B,N,0.0,C,N)
-- end
function asserteq(C,CR,rows,cols,depth)
local dim = rows * cols
for d=0,depth-1 do
local base = dim * d
for i=0,rows-1 do
for j=0,cols-1 do
if(C[base + i*cols + j] ~= CR[base + i*cols + j]) then
return false
end
end
end
end
return true
end
function printMatrix(m,rows,columns,depth)
local dim = rows * columns
if depth > 1 then
-- print each output
for d=0,depth-1 do
local base = dim * d
for i=0,rows-1 do
for j=0,columns-1 do
io.write(" " .. m[base + i*columns + j])
end
io.write("\n")
end
io.write("\n")
end
else
-- usual matrix print
for i=0,rows-1 do
for j=0,columns-1 do
io.write(" " .. m[i*columns + j])
end
io.write("\n")
end
end
io.write("\n")
end
function generateTestSet(A,Me,Ne,cx,cy,Bs,K,L,NF)
for i = cx, Me - cx - 1 do
for j = cy, Ne - cy - 1 do
A[i*Ne + j] = math.random(1,9)
end
end
for pos=0,NF -1 do
local filter = {}
for i=1, K*L do
filter[i] = math.random(1,9)
end
createFilter(filter,K,L,Bs,pos)
end
-- An option for a three kernels sequence
-- createFilter({1,2,1,
-- 0,0,0,
-- -1,-2,-1},K,L,Bs,0) -- edge detection (Sobel)
-- createFilter({0,-1,0,
-- -1,5,-1,
-- 0,-1,0},K,L,Bs,1) -- sharpen
-- createFilter({0,0,0,
-- 0,1,0,
-- 0,0,0},K,L,Bs,2) -- indentity
end
function createFilter(filter,rows,columns,m,pos)
local base = pos * rows * columns
for i=0,rows-1 do
for j=0,rows-1 do
m[base + i*columns + j] = filter[i*columns + j + 1]
-- io.write(m[i*columns + j])
end
-- io.write("\n")
end
-- io.write("\n")
return m
end
function naiveConvolve(out, inp, Me, Ne, kernel, K, L,depth)
local kCenterX, kCenterY = math.floor(K/2), math.floor(L/2)
local dimKer = K*L
local e = 0
for d=0,depth-1 do
local baseKer = dimKer * d
for i= kCenterX, Me-kCenterX -1 do -- added border to compare with my result
for j=kCenterY, Ne-kCenterY -1 do
out[e] = 0
for m=0,K-1 do
for n=0,L-1 do
--boundaries
local ii = i + (m - kCenterY)
local jj = j + (n - kCenterX)
if ii >= 0 and ii< Me and jj>=0 and jj<Ne then
local tmp = out[e]
out[e] = tmp + inp[ii*Ne + jj] * kernel[baseKer + m*L + n]
end
end
end
e = e + 1
end
end
end
end
function MTH.timefunctions(typstring,M,N,K,L,depth,...)
local ctyp = typstring.."[?] __attribute__((aligned(64)))"
local cx,cy = math.floor(K/2), math.floor(L/2)
local Me, Ne = M+2*cx, N+2*cy
local A = ffi.new(ctyp,Me*Ne)
local Bs = ffi.new(ctyp,K*L*depth)
local CR = ffi.new(ctyp,M*N*depth)
generateTestSet(A,Me,Ne,cx,cy,Bs,K,L,depth)
-- Setup GEMM
local Mlow, Nlow = M*N, K*L
local Klow, Llow = K*L, depth
-- result will be Mlow * Llow due to the matrix multiplication
local AA = ffi.new(ctyp,Mlow*Nlow)
local BB = ffi.new(ctyp,Klow*Llow)
local CC = ffi.new(ctyp,Mlow*Llow)
local fns = {...}
local Cfns = {}
-- initialize: fill the matrix C with -1
for i,fn in ipairs(fns) do
local Cs = ffi.new(ctyp,M*N*depth)
for j = 0, M * N * depth - 1 do
Cs[j] = 0
end
Cfns[i] = Cs
end
-- compute;
local results = {}
local checked = false
local time
-- loop over all tested functions, so if you have more
-- than one time and checked will have multiple values (put them inside)
for i,fn in ipairs(fns) do
local Cs = Cfns[i] -- 3D
local tocall = function() fn(Me,Ne,K,L,M,N,A,Bs,Cs,depth,AA,BB,CC) end
--tocall()
time = CalcTime(tocall)
results[i] = M*N*K*L*depth*2.0*1e-9 / time -- gflop
-- Print in case detailed analysis
-- print("Image:")
-- printMatrix(A,Me,Ne,0)
-- print("Kernels:")
-- printMatrix(Bs,K,L,depth)
-- print("Outputs")
-- printMatrix(Cs,M,N,depth)
-- Check correctness to any of the function tested
-- In this case I'm testing only the convolution
-- CHECK CORRECTNESS
naiveConvolve(CR,A,Me,Ne,Bs,K,L,depth)
checked = asserteq(Cs,CR,M,N,depth)
if checked == false then break end
-- print("Naive")
-- printMatrix(CR,M,N,depth)
-- Print in case detailed analysis
if i ~= 1 then
local C0 = Cs[1]
local C1 = Cs[i]
local c = 0
for m = 0, M-1 do
for n = 0, N-1 do
if C0[c]~= C1[c] then
return false
end
c = c + 1
end
end
end
end
return time,checked,results
end
function MTH.timefunctionsGEMM(typstring,M,K,N,...)
local ctyp = typstring.."[?] __attribute__((aligned(64)))"
local A,B = ffi.new(ctyp,M*K), ffi.new(ctyp,K*N)
print("M:" .. M .. " K:" .. K .. " N:" .. N)
for m = 0, M-1 do
for k = 0, K-1 do
A[m*K + k] = math.random(0,9)
end
end
for k = 0, K-1 do
for n = 0, N-1 do
B[k*N + n] = math.random(0,9)
end
end
local fns = {...}
local Cs = {}
for i,fn in ipairs(fns) do
local C = ffi.new(ctyp,M*N)
for j = 0, M * N - 1 do
C[j] = -1
end
Cs[i] = C
end
local results = {}
local check = false
for i,fn in ipairs(fns) do
local C = Cs[i]
local tocall = function() fn(M,K,N,A,B,C) end
tocall()
results[i] = M*N*K*2.0*1e-9 / CalcTime(tocall)
local CR = ffi.new(ctyp,M*N)
check = assertmm(CR,C,A,B,M,N,K)
-- printMatrix(A,M,K,0)
-- printMatrix(B,K,N,0)
-- printMatrix(C,M,N,0)
-- printMatrix(CR,M,N,0)
if i ~= 1 then
local C0 = Cs[1]
local C1 = Cs[i]
local c = 0
for m = 0, M-1 do
for n = 0, N-1 do
if C0[c]~= C1[c] then
return false
end
c = c + 1
end
end
end
end
return check,results
end
return MTH
| mit |
FTBpro/count-von-count | lib/redis/voncount.lua | 1 | 5526 | -------------- Function to simulate inheritance -------------------------------------
-- local function inheritsFrom( baseClass )
-- local new_class = {}
-- local class_mt = { __index = new_class }
-- if baseClass then
-- setmetatable( new_class, { __index = baseClass } )
-- end
-- return new_class
-- end
---------- Array methods ---------------------------
local function concatToArray(a1, a2)
for i = 1, #a2 do
a1[#a1 + 1] = a2[i]
end
return a1
end
local function flattenArray(arr)
local flat = {}
for i = 1, #arr do
if type(arr[i]) == "table" then
local inner_flatten = flattenArray(arr[i])
concatToArray(flat, inner_flatten)
else
flat[#flat + 1] = arr[i]
end
end
return flat
end
local function dupArray(arr)
local dup = {}
for i = 1, #arr do
dup[i] = arr[i]
end
return dup
end
-----------------------------------------------------
-------------- Base Class ---------------------------------------------------------
local Base = {}
function Base:new(_obj_type, ids, _type)
local redis_key = _obj_type
for k, id in ipairs(ids) do
redis_key = redis_key .. "_" .. id
end
local baseObj = { redis_key = redis_key, _type = _type, _ids = ids, _obj_type = _obj_type }
self.__index = self
return setmetatable(baseObj, self)
end
function Base:count(key, num)
local allKeys = flattenArray({ key })
for i, curKey in ipairs(allKeys) do
if self._type == "set" then
redis.call("ZINCRBY", self.redis_key, num, curKey)
else
redis.call("HINCRBY", self.redis_key, curKey, num)
end
end
end
function Base:expire(ttl)
if redis.call("TTL", self.redis_key) == -1 then
redis.call("EXPIRE", self.redis_key, ttl)
end
end
----------------- Custom Methods -------------------------
function Base:conditionalCount(should_count, key)
if should_count ~= "0" and should_count ~= "false" then
self:count(key, 1)
end
end
function Base:countIfExist(value, should_count, key)
if value and value ~= "" and value ~= "null" and value ~= "nil" then
self:conditionalCount(should_count, key)
end
end
function Base:sevenDaysCount(should_count, key)
if should_count ~= "0" and should_count ~= "false" then
local first_day = tonumber(self._ids[3])
for day = 0, 6, 1 do
local curDayObjIds = dupArray(self._ids)
if (first_day + day) > 365 then
curDayObjIds[4] = string.format("%03d", (tonumber(curDayObjIds[4]) + 1) )
end
local curDayObj = Base:new(self._obj_type, curDayObjIds, self._type)
curDayObj:count(key, 1)
curDayObj:expire(1209600) -- expire in 2 weeks
end
end
end
function Base:countAndSetIf(should_count, countKey, redisKey, setKey)
if should_count ~= "0" and should_count ~= "false" then
self:count(countKey, 1)
local setCount = redis.call("ZCOUNT", self.redis_key, "-inf", "+inf")
redis.call("HSET", redisKey, setKey, setCount)
end
end
----------------------------------------------------------
------------- Helper Methods ------------------------
-- return an array with all the values in tbl that match the given keys array
local function getValueByKeys(tbl, keys)
local values = {}
if type(keys) == "table" then
for i, key in ipairs(keys) do
table.insert(values, tbl[key])
end
else
table.insert(values, tbl[keys])
end
return values
end
-- parse key and replace "place holders" with their value from tbl.
-- matching replace values in tbl can be arrays, in such case an array will be returned with all the possible keys combinations
local function addValuesToKey(tbl, key)
local rslt = { key }
local match = key:match("{[%w_]*}")
while match do
local subStrings = flattenArray({ tbl[match:sub(2, -2)] })
local tempResult = {}
for i, subStr in ipairs(subStrings) do
local dup = dupArray(rslt)
for j, existingKey in ipairs(dup) do
local curKey = existingKey:gsub(match, subStr)
dup[j] = curKey
end
concatToArray(tempResult, dup)
end
rslt = tempResult
if #rslt > 0 then
match = rslt[1]:match("{[%w_]*}")
else
match = nil
end
end
if #rslt == 1 then
return rslt[1]
else
return rslt
end
end
--------------------------------------------------
local mode = ARGV[2] or "live"
local arg = ARGV[1]
local params = cjson.decode(arg)
local config = cjson.decode(redis.call("get", "von_count_config_".. mode))
local action = params["action"]
local defaultMethod = { change = 1, custom_functions = {} }
local action_config = config[action]
if action_config then
for obj_type, methods in pairs(action_config) do
for i, defs in ipairs(methods) do
setmetatable(defs, { __index = defaultMethod })
local ids = getValueByKeys(params, defs["id"])
local _type = defs["type"] or "hash"
local obj = Base:new(obj_type, ids, _type)
if defs["count"] then
local key = addValuesToKey(params, defs["count"])
local change = defs["change"]
obj:count(key, change)
end
for j, custom_function in ipairs(defs["custom_functions"]) do
local function_name = custom_function["name"]
local args = {}
for z, arg in ipairs(custom_function["args"]) do
local arg_value = addValuesToKey(params, arg)
table.insert(args, arg_value)
end
obj[function_name](obj, unpack(args))
end
if defs["expire"] then
obj:expire(defs["expire"])
end
end
end
end
| mit |
TheAnswer/FirstTest | bin/scripts/slashcommands/admin/harmless.lua | 1 | 2429 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
HarmlessSlashCommand = {
name = "harmless",
alternativeNames = "",
animation = "",
invalidStateMask = 2097152, --glowingJedi,
invalidPostures = "",
target = 2,
targeType = 1,
disabled = 0,
maxRangeToTarget = 0,
--adminLevel = 0,
addToCombatQueue = 0,
}
AddHarmlessSlashCommand(HarmlessSlashCommand)
| lgpl-3.0 |
TheAnswer/FirstTest | bin/scripts/creatures/objects/corellia/npcs/monumenter/monumenterMarauder.lua | 1 | 4568 | --Copyright (C) 2008 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
monumenterMarauder = Creature:new {
objectName = "monumenterMarauder", -- Lua Object Name
creatureType = "NPC",
faction = "monumenter",
factionPoints = 20,
gender = "",
speciesName = "monumenter_marauder",
stfName = "mob/creature_names",
objectCRC = 00000000000,
socialGroup = "monumenter",
level = 13,
combatFlags = ATTACKABLE_FLAG + ENEMY_FLAG,
healthMax = 1900,
healthMin = 1500,
strength = 0,
constitution = 0,
actionMax = 1900,
actionMin = 1500,
quickness = 0,
stamina = 0,
mindMax = 1900,
mindMin = 1500,
focus = 0,
willpower = 0,
height = 1, -- Size of creature
armor = 0, -- 0 = None; 1 = Light; 2 = Medium; 3 = Heavy
kinetic = 0,
energy = 0,
electricity = 0,
stun = -1,
blast = 0,
heat = 0,
cold = 0,
acid = 0,
lightsaber = 0,
accuracy = 0,
healer = 0,
pack = 1,
herd = 0,
stalker = 0,
killer = 0,
ferocity = 0,
aggressive = 0,
invincible = 0,
attackCreatureOnSight = "", -- Enter socialGroups
weapon = "object/weapon/ranged/pistol/shared_pistol_dl44.iff", -- File path to weapon -> object\xxx\xxx\xx
weaponName = "DL44 Pistol", -- Name ex. 'a Vibrolance'
weaponTemp = "pistol_dl44", -- Weapon Template ex. 'lance_vibrolance'
weaponClass = "PistolRangedWeapon", -- Weapon Class ex. 'PolearmMeleeWeapon'
weaponEquipped = 1,
weaponMinDamage = 140,
weaponMaxDamage = 150,
weaponAttackSpeed = 2,
weaponDamageType = "ENERGY", -- ELECTRICITY, KINETIC, etc
weaponArmorPiercing = "NONE", -- LIGHT, NONE, MEDIUM, HEAVY
alternateWeapon = "", -- File path to weapon -> object\xxx\xxx\xx
alternateWeaponName = "", -- Name ex. 'a Vibrolance'
alternateWeaponTemp = "", -- Weapon Template ex. 'lance_vibrolance'
alternateWeaponClass = "", -- Weapon Class ex. 'PolearmMeleeWeapon'
alternateWeaponEquipped = 0,
alternateWeaponMinDamage = 0,
alternateWeaponMaxDamage = 0,
alternateweaponAttackSpeed = 2,
alternateWeaponDamageType = "", -- ELECTRICITY, KINETIC, etc
alternateweaponArmorPiercing = "NONE", -- LIGHT, NONE, MEDIUM, HEAVY
internalNPCDamageModifier = 0.3, -- Damage Modifier to other NPC's
lootGroup = "0", -- Group it belongs to for loot
tame = 0,
datapadItemCRC = 0,
mountCRC = 0,
mountSpeed = 0,
mountAcceleration = 0,
milk = 0,
boneType = "",
boneMax = 0,
hideType = "",
hideMax = 0,
meatType = "",
meatMax = 0,
skills = { "monumenterAttack1" },
respawnTimer = 180,
behaviorScript = "", -- Link to the behavior script for this object
}
Creatures:addCreature(monumenterMarauder, 00000000000) -- Add to Global Table
| lgpl-3.0 |
niedbalski/mongrel2 | examples/bbs/bbs.lua | 96 | 4552 | local strict = require 'strict'
local m2 = require 'mongrel2'
local ui = require 'ui'
local engine = require 'engine'
local db = require 'db'
local function new_user(conn, req, user, password)
req = ui.prompt(conn, req, 'new_user')
while req.data.msg ~= password do
req = ui.prompt(conn, req, 'repeat_pass')
end
db.register_user(user, password)
ui.screen(conn, req, 'welcome_newbie')
end
local function read_long_message(conn, req, user)
local msg = {}
ui.screen(conn, req, 'leave_msg')
req = ui.ask(conn, req, 'From: ' .. user .. '\n---', '')
while req.data.msg ~= '.' and #msg < 24 do
table.insert(msg, req.data.msg)
req = ui.ask(conn, req, '', '')
end
return msg
end
local function message_iterator(db, i)
if i > 0 then
return i-1, db.message_read(i-1)
end
end
local function messages(db)
local count = assert(db.message_count())
return message_iterator, db, count
end
local function list_all_messages(conn, req)
for i, msg in messages(db) do
ui.display(conn, req, ('---- #%d -----'):format(i))
ui.display(conn, req, msg .. '\n')
if i == 0 then
ui.ask(conn, req, "No more messages; Enter for MAIN MENU.", '> ')
else
req = ui.ask(conn, req, "Enter, or Q to stop reading.", '> ')
if req.data.msg:upper() == 'Q' then
ui.display(conn, req, "Done reading.")
break
end
end
end
end
local MAINMENU = {
['1'] = function(conn, req, user)
local msg = read_long_message(conn, req, user)
db.post_message(user, msg)
ui.screen(conn, req, 'posted')
end,
['2'] = function(conn, req, user)
ui.screen(conn, req, 'read_msg')
local count = assert(db.message_count())
if count == 0 then
ui.display(conn, req, "There are no messages!")
else
list_all_messages(conn, req)
end
end,
['3'] = function (conn, req, user)
req = ui.ask(conn, req, 'Who do you want to send it to?', '> ')
local to = req.data.msg
local exists = assert(db.user_exists(to))
if exists then
local msg = read_long_message(conn, req, user)
db.send_to(to, user, msg)
ui.display(conn, req, "Message sent to " .. to)
else
ui.display(conn, req, 'Sorry, that user does not exit.')
end
end,
['4'] = function(conn, req, user)
local count = assert(db.inbox_count(user))
if count == 0 then
ui.display(conn, req, 'No messages for you. Try back later.')
return
end
while db.inbox_count(user) > 0 do
local msg = assert(db.read_inbox(user))
ui.display(conn, req, msg)
ui.ask(conn, req, "Enter to continue.", '> ')
end
end,
['Q'] = function(conn, req, user)
ui.exit(conn, req, 'bye')
end
}
local function m2bbs(conn)
local req = coroutine.yield() -- Wait for data
ui.screen(conn, req, 'welcome')
-- Have the user log in
req = ui.prompt(conn, req, 'name')
local user = req.data.msg
req = ui.prompt(conn, req, 'password')
local password = req.data.msg
print('login attempt', user, password)
local exists, error = db.user_exists(user)
if error then
print("ERROR:", error)
ui.display(conn, req, 'We had an error, sorry. Try again.')
return
elseif not exists then
new_user(conn, req, user, password)
elseif not db.auth_user(user, password) then
ui.exit(conn, req, 'bad_pass')
return
end
-- Display the MoTD and wait for the user to hit Enter.
ui.prompt(conn, req, 'motd')
repeat
req = ui.prompt(conn, req, 'menu')
local selection = MAINMENU[req.data.msg:upper()]
print("message:", req.data.msg)
if selection then
selection(conn, req, user)
else
ui.screen(conn, req, 'menu_error')
end
until req.data.msg:upper() == "Q"
end
do
-- Load configuration properties
local config = {}
setfenv(assert(loadfile('config.lua')), config)()
-- Connect to the Mongrel2 server
print("connecting", config.sender_id, config.sub_addr, config.pub_addr)
local ctx = mongrel2.new(config.io_threads)
local conn = ctx:new_connection(config.sender_id, config.sub_addr, config.pub_addr)
-- Run the BBS engine
engine.run(conn, m2bbs)
end
| bsd-3-clause |
TheAnswer/FirstTest | bin/scripts/slashcommands/skills/saberDervish.lua | 1 | 2575 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
SaberDervishSlashCommand = {
name = "saberdervish",
alternativeNames = "",
animation = "",
invalidStateMask = 3894805544, --aiming, berzerk, tumbling, frozen, swimming, glowingJedi, ridingMount, pilotingShip, shipOperations, shipGunner,
invalidPostures = "3,5,6,7,8,9,10,11,12,13,14,",
target = 1,
targeType = 2,
disabled = 0,
maxRangeToTarget = 0,
--adminLevel = 0,
addToCombatQueue = 1,
}
AddSaberDervishSlashCommand(SaberDervishSlashCommand)
| lgpl-3.0 |
TheAnswer/FirstTest | bin/scripts/items/bluefrog/slicingTools.lua | 1 | 2198 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
slicingTools = {armorUpgradeKit, weaponUpgradeKit, precisionLaserKnife, flowAnalyzerNode, molecularClamp}
addBFItemSet("Slicing Tools" , slicingTools); | lgpl-3.0 |
wangfakang/ABTestingGateway | lib/abtesting/utils/redis.lua | 26 | 1554 | local modulename = "abtestingRedis"
local _M = {}
_M._VERSION = '0.0.1'
local redis = require('resty.redis')
_M.new = function(self, conf)
self.host = conf.host
self.port = conf.port
self.uds = conf.uds
self.timeout = conf.timeout
self.dbid = conf.dbid
self.poolsize = conf.poolsize
self.idletime = conf.idletime
local red = redis:new()
return setmetatable({redis = red}, { __index = _M } )
end
_M.connectdb = function(self)
local uds = self.uds
local host = self.host
local port = self.port
local dbid = self.dbid
local red = self.redis
if not uds and not (host and port) then
return nil, 'no uds or tcp avaliable provided'
end
if not dbid then dbid = 0 end
local timeout = self.timeout
if not timeout then
timeout = 1000 -- 10s
end
red:set_timeout(timeout)
local ok, err
if uds then
ok, err = red:connect('unix:'..uds)
if ok then return red:select(dbid) end
end
if host and port then
ok, err = red:connect(host, port)
if ok then return red:select(dbid) end
end
return ok, err
end
_M.keepalivedb = function(self)
local pool_max_idle_time = self.idletime --毫秒
local pool_size = self.poolsize --连接池大小
if not pool_size then pool_size = 1000 end
if not pool_max_idle_time then pool_max_idle_time = 90000 end
return self.redis:set_keepalive(pool_max_idle_time, pool_size)
end
return _M
| mit |
TheAnswer/FirstTest | bin/scripts/crafting/objects/draftschematics/artisan/domesticArtsIiiBasicDesserts/caramelizedPkneb.lua | 1 | 4078 | --Copyright (C) 2009 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
caramelizedPkneb = Object:new {
objectName = "Caramelized Pkneb",
stfName = "pkneb",
stfFile = "food_name",
objectCRC = 223277237,
groupName = "craftArtisanDomesticGroupC", -- Group schematic is awarded in (See skills table)
craftingToolTab = 4, -- (See DraftSchemticImplementation.h)
complexity = 4,
size = 1,
xpType = "crafting_general",
xp = 80,
assemblySkill = "general_assembly",
experimentingSkill = "general_experimentation",
ingredientTemplateNames = "craft_food_ingredients_n, craft_food_ingredients_n, craft_food_ingredients_n, craft_food_ingredients_n",
ingredientTitleNames = "carbosyrup, sweet_meat, bone_fragments, additive",
ingredientSlotType = "1, 0, 0, 3",
resourceTypes = "object/tangible/component/food/shared_ingredient_carbosyrup.iff, meat, bone, object/tangible/food/crafted/additive/shared_additive_light.iff",
resourceQuantities = "1, 20, 20, 1",
combineTypes = "1, 0, 0, 1",
contribution = "100, 100, 100, 100",
numberExperimentalProperties = "1, 1, 1, 2, 2, 2, 2",
experimentalProperties = "XX, XX, XX, PE, OQ, FL, OQ, DR, PE, DR, OQ",
experimentalWeights = "1, 1, 1, 2, 1, 2, 1, 1, 3, 3, 1",
experimentalGroupTitles = "null, null, null, exp_nutrition, exp_flavor, exp_quantity, exp_filling",
experimentalSubGroupTitles = "null, null, hitpoints, nutrition, flavor, quantity, filling",
experimentalMin = "0, 0, 1000, 75, 60, 60, 80",
experimentalMax = "0, 0, 1000, 120, 120, 100, 120",
experimentalPrecision = "0, 0, 0, 0, 0, 0, 0",
tanoAttributes = "objecttype=8202:objectcrc=128351778:stfFile=food_name:stfName=pkneb:stfDetail=:itemmask=65535::",
blueFrogAttributes = "",
blueFrogEnabled = False,
customizationOptions = "",
customizationDefaults = "",
customizationSkill = "clothing_customization"
}
DraftSchematics:addDraftSchematic(caramelizedPkneb, 223277237)--- Add to global DraftSchematics table
| lgpl-3.0 |
TheAnswer/FirstTest | bin/scripts/slashcommands/skills/creatureAreaDisease.lua | 1 | 2596 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
CreatureAreaDiseaseSlashCommand = {
name = "creatureareadisease",
alternativeNames = "",
animation = "",
invalidStateMask = 3894870032, --alert, immobilized, frozen, swimming, glowingJedi, ridingMount, pilotingShip, shipOperations, shipGunner,
invalidPostures = "5,6,7,8,9,10,11,12,13,14,4,",
target = 1,
targeType = 2,
disabled = 0,
maxRangeToTarget = 0,
--adminLevel = 0,
addToCombatQueue = 1,
}
AddCreatureAreaDiseaseSlashCommand(CreatureAreaDiseaseSlashCommand)
| lgpl-3.0 |
TheAnswer/FirstTest | bin/scripts/crafting/objects/draftschematics/tailor/masterTailor/revealingFleshwrap.lua | 1 | 3957 | --Copyright (C) 2009 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
revealingFleshwrap = Object:new {
objectName = "Revealing Fleshwrap",
stfName = "bodysuit_s06",
stfFile = "wearables_name",
objectCRC = 3890717293,
groupName = "craftClothingMaster", -- Group schematic is awarded in (See skills table)
craftingToolTab = 8, -- (See DraftSchemticImplementation.h)
complexity = 21,
size = 3,
xpType = "crafting_clothing_general",
xp = 900,
assemblySkill = "clothing_assembly",
experimentingSkill = "clothing_experimentation",
ingredientTemplateNames = "craft_clothing_ingredients_n, craft_clothing_ingredients_n, craft_clothing_ingredients_n",
ingredientTitleNames = "highly_elastic_skin_fabric, jewelry_setting, hardware",
ingredientSlotType = "0, 1, 1",
resourceTypes = "petrochem_inert_polymer, object/tangible/component/clothing/shared_jewelry_setting.iff, object/tangible/component/clothing/shared_metal_fasteners.iff",
resourceQuantities = "300, 2, 4",
combineTypes = "0, 1, 1",
contribution = "100, 100, 100",
numberExperimentalProperties = "1, 1, 1, 1",
experimentalProperties = "XX, XX, XX, XX",
experimentalWeights = "1, 1, 1, 1",
experimentalGroupTitles = "null, null, null, null",
experimentalSubGroupTitles = "null, null, sockets, hitpoints",
experimentalMin = "0, 0, 0, 1000",
experimentalMax = "0, 0, 0, 1000",
experimentalPrecision = "0, 0, 0, 0",
tanoAttributes = "objecttype=16777219:objectcrc=707325039:stfFile=wearables_name:stfName=bodysuit_s06:stfDetail=:itemmask=62974::",
blueFrogAttributes = "",
blueFrogEnabled = False,
customizationOptions = "/private/index_color_1",
customizationDefaults = "207",
customizationSkill = "clothing_customization"
}
DraftSchematics:addDraftSchematic(revealingFleshwrap, 3890717293)--- Add to global DraftSchematics table
| lgpl-3.0 |
TheAnswer/FirstTest | bin/scripts/crafting/objects/draftschematics/artisan/masterArtisan/vehicleCustomizationKit.lua | 1 | 4074 | --Copyright (C) 2009 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
vehicleCustomizationKit = Object:new {
objectName = "Vehicle Customization Kit",
stfName = "vehicle_customization_kit",
stfFile = "item_n",
objectCRC = 4170918716,
groupName = "craftArtisanVehicle", -- Group schematic is awarded in (See skills table)
craftingToolTab = 16, -- (See DraftSchemticImplementation.h)
complexity = 12,
size = 1,
xpType = "crafting_general",
xp = 40,
assemblySkill = "general_assembly",
experimentingSkill = "general_experimentation",
ingredientTemplateNames = "craft_item_ingredients_n, craft_droid_ingredients_n, craft_droid_ingredients_n, craft_item_ingredients_n, craft_droid_ingredients_n",
ingredientTitleNames = "assembly_enclosure, thermal_shielding, colors, electronic_control_unit, color_stowage",
ingredientSlotType = "0, 0, 0, 2, 2",
resourceTypes = "metal, mineral, mineral, object/tangible/component/item/shared_electronic_control_unit.iff, object/tangible/component/droid/shared_droid_storage_compartment.iff",
resourceQuantities = "12, 9, 6, 1, 1",
combineTypes = "0, 0, 0, 1, 1",
contribution = "100, 100, 100, 100, 100",
numberExperimentalProperties = "1, 1, 1, 2",
experimentalProperties = "XX, XX, XX, CD, OQ",
experimentalWeights = "1, 1, 1, 1, 1",
experimentalGroupTitles = "null, null, null, exp_quality",
experimentalSubGroupTitles = "null, null, hit_points, charges",
experimentalMin = "0, 0, 1000, 1",
experimentalMax = "0, 0, 1000, 10",
experimentalPrecision = "0, 0, 0, 0",
tanoAttributes = "objecttype=32768:objectcrc=3528062501:stfFile=item_n:stfName=vehicle_customization_kit:stfDetail=:itemmask=65535::",
blueFrogAttributes = "",
blueFrogEnabled = False,
customizationOptions = "",
customizationDefaults = "",
customizationSkill = "clothing_customization"
}
DraftSchematics:addDraftSchematic(vehicleCustomizationKit, 4170918716)--- Add to global DraftSchematics table
| lgpl-3.0 |
TheAnswer/FirstTest | bin/scripts/crafting/objects/draftschematics/scout/trappingIiRefinedDesign/stinkBomb.lua | 1 | 3653 | --Copyright (C) 2009 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
stinkBomb = Object:new {
objectName = "Stink Bomb",
stfName = "trap_state_def_1",
stfFile = "item_n",
objectCRC = 1618982847,
groupName = "craftScoutTrapGroupB", -- Group schematic is awarded in (See skills table)
craftingToolTab = 524288, -- (See DraftSchemticImplementation.h)
complexity = 7,
size = 1,
xpType = "trapping",
xp = 30,
assemblySkill = "general_assembly",
experimentingSkill = "general_experimentation",
ingredientTemplateNames = "craft_item_ingredients_n, craft_item_ingredients_n",
ingredientTitleNames = "trap_housing, musk",
ingredientSlotType = "0, 0",
resourceTypes = "bone, hide",
resourceQuantities = "10, 5",
combineTypes = "0, 0",
contribution = "100, 100",
numberExperimentalProperties = "1, 1, 1, 1",
experimentalProperties = "XX, XX, XX, XX",
experimentalWeights = "1, 1, 1, 1",
experimentalGroupTitles = "null, null, null, null",
experimentalSubGroupTitles = "null, null, hitpoints, quality",
experimentalMin = "0, 0, 1000, 1",
experimentalMax = "0, 0, 1000, 100",
experimentalPrecision = "0, 0, 0, 0",
tanoAttributes = "objecttype=8212:objectcrc=750361076:stfFile=item_n:stfName=trap_state_def_1:stfDetail=:itemmask=65535::",
blueFrogAttributes = "",
blueFrogEnabled = False,
customizationOptions = "",
customizationDefaults = "",
customizationSkill = "clothing_customization"
}
DraftSchematics:addDraftSchematic(stinkBomb, 1618982847)--- Add to global DraftSchematics table
| lgpl-3.0 |
DarkstarProject/darkstar | scripts/globals/spells/huton_san.lua | 12 | 1384 | -----------------------------------------
-- Spell: Huton: San
-- Deals wind damage to an enemy and lowers its resistance against ice.
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/magic")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
--doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus)
local duration = 15 + caster:getMerit(dsp.merit.HUTON_EFFECT) -- T1 bonus debuff duration
local bonusAcc = 0
local bonusMab = caster:getMerit(dsp.merit.HUTON_EFFECT) -- T1 mag atk
if(caster:getMerit(dsp.merit.HUTON_SAN) ~= 0) then -- T2 mag atk/mag acc, don't want to give a penalty to entities that can cast this without merits
bonusMab = bonusMab + caster:getMerit(dsp.merit.HUTON_SAN) - 5 -- merit gives 5 power but no bonus with one invest, thus subtract 5
bonusAcc = bonusAcc + caster:getMerit(dsp.merit.HUTON_SAN) - 5
end
local params = {}
params.dmg = 134
params.multiplier = 1.5
params.hasMultipleTargetReduction = false
params.resistBonus = bonusAcc
params.mabBonus = bonusMab
dmg = doNinjutsuNuke(caster, target, spell, params)
handleNinjutsuDebuff(caster,target,spell,30,duration,dsp.mod.ICERES)
return dmg
end | gpl-3.0 |
AbolDalton/kia | plugins/stats.lua | 1 | 3998 | do
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(receiver, chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false)
return --text
end
local function chat_stats2(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nGroups: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == 'Yalda' then -- Put everything you like :)
local about = _config.about_text
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /optima ")
return about
end
if matches[1]:lower() == "statslist" then
if not is_momod(msg) then
return "For mods only !"
end
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats2(chat_id)
end
if matches[1]:lower() == "stats" then
if not matches[2] then
if not is_momod(msg) then
return "For mods only !"
end
if msg.to.type == 'chat' or msg.to.type == 'channel' then
local receiver = get_receiver(msg)
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats(receiver, chat_id)
else
return
end
end
if matches[2] == "Yalda" then -- Put everything you like :)
if not is_admin1(msg) then
return "For admins only !"
else
return bot_stats()
end
end
if matches[2] == "group" then
if not is_admin1(msg) then
return "For admins only !"
else
return chat_stats(matches[3])
end
end
end
end
return {
patterns = {
"^[#!/]([Ss]tats)$",
"^[#!/]([Ss]tatslist)$",
"^[#!/]([Ss]tats) (group) (%d+)",
"^[#!/]([Ss]tats) (Yalda)",
"^[#!/](Yalda)"
},
run = run
}
end
| gpl-2.0 |
Fenix-XI/Fenix | scripts/zones/Kazham/npcs/Rauteinot.lua | 26 | 3159 | -----------------------------------
-- Area: Kazham
-- NPC: Rauteinot
-- Starts and Finishes Quest: Missionary Man
-- @zone 250
-- @pos -42 -10 -89
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getVar("MissionaryManVar") == 1 and trade:hasItemQty(1146,1) == true and trade:getItemCount() == 1) then
player:startEvent(0x008b); -- Trading elshimo marble
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
MissionaryMan = player:getQuestStatus(OUTLANDS,MISSIONARY_MAN);
MissionaryManVar = player:getVar("MissionaryManVar");
if (MissionaryMan == QUEST_AVAILABLE and player:getFameLevel(KAZHAM) >= 3) then
player:startEvent(0x0089,0,1146); -- Start quest "Missionary Man"
elseif (MissionaryMan == QUEST_ACCEPTED and MissionaryManVar == 1) then
player:startEvent(0x008a,0,1146); -- During quest (before trade marble) "Missionary Man"
elseif (MissionaryMan == QUEST_ACCEPTED and (MissionaryManVar == 2 or MissionaryManVar == 3)) then
player:startEvent(0x008c); -- During quest (after trade marble) "Missionary Man"
elseif (MissionaryMan == QUEST_ACCEPTED and MissionaryManVar == 4) then
player:startEvent(0x008d); -- Finish quest "Missionary Man"
elseif (MissionaryMan == QUEST_COMPLETED) then
player:startEvent(0x008e); -- New standard dialog
else
player:startEvent(0x0088); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0089 and option == 1) then
player:addQuest(OUTLANDS,MISSIONARY_MAN);
player:setVar("MissionaryManVar",1);
elseif (csid == 0x008b) then
player:setVar("MissionaryManVar",2);
player:addKeyItem(RAUTEINOTS_PARCEL);
player:messageSpecial(KEYITEM_OBTAINED,RAUTEINOTS_PARCEL);
player:tradeComplete();
elseif (csid == 0x008d) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4728);
else
player:setVar("MissionaryManVar",0);
player:delKeyItem(SUBLIME_STATUE_OF_THE_GODDESS);
player:addItem(4728);
player:messageSpecial(ITEM_OBTAINED,4728);
player:addFame(WINDURST,30);
player:completeQuest(OUTLANDS,MISSIONARY_MAN);
end
end
end; | gpl-3.0 |
GameDevStudios/MrBallGuy2 | assets/libs/loveframes/objects/internal/multichoice/multichoicelist.lua | 8 | 10372 | --[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2013 Kenny Shields --
--]]------------------------------------------------
-- multichoicelist class
local newobject = loveframes.NewObject("multichoicelist", "loveframes_object_multichoicelist", true)
--[[---------------------------------------------------------
- func: initialize()
- desc: initializes the object
--]]---------------------------------------------------------
function newobject:initialize(object)
self.type = "multichoicelist"
self.parent = loveframes.base
self.list = object
self.x = object.x
self.y = object.y + self.list.height
self.width = self.list.width
self.height = 0
self.clickx = 0
self.clicky = 0
self.padding = self.list.listpadding
self.spacing = self.list.listspacing
self.buttonscrollamount = object.buttonscrollamount
self.mousewheelscrollamount = object.mousewheelscrollamount
self.offsety = 0
self.offsetx = 0
self.extrawidth = 0
self.extraheight = 0
self.canremove = false
self.dtscrolling = self.list.dtscrolling
self.internal = true
self.vbar = false
self.children = {}
self.internals = {}
for k, v in ipairs(object.choices) do
local row = loveframes.objects["multichoicerow"]:new()
row:SetText(v)
self:AddItem(row)
end
table.insert(loveframes.base.internals, self)
-- apply template properties to the object
loveframes.templates.ApplyToObject(self)
end
--[[---------------------------------------------------------
- func: update(deltatime)
- desc: updates the object
--]]---------------------------------------------------------
function newobject:update(dt)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
local alwaysupdate = self.alwaysupdate
if not visible then
if not alwaysupdate then
return
end
end
local width = love.graphics.getWidth()
local height = love.graphics.getHeight()
local x, y = love.mouse.getPosition()
local selfcol = loveframes.util.BoundingBox(x, self.x, y, self.y, 1, self.width, 1, self.height)
local parent = self.parent
local base = loveframes.base
local upadte = self.Update
local internals = self.internals
local children = self.children
-- move to parent if there is a parent
if parent ~= base then
self.x = parent.x + self.staticx
self.y = parent.y + self.staticy
end
if self.x < 0 then
self.x = 0
end
if self.x + self.width > width then
self.x = width - self.width
end
if self.y < 0 then
self.y = 0
end
if self.y + self.height > height then
self.y = height - self.height
end
for k, v in ipairs(internals) do
v:update(dt)
end
for k, v in ipairs(children) do
v:update(dt)
v:SetClickBounds(self.x, self.y, self.width, self.height)
v.y = (v.parent.y + v.staticy) - self.offsety
v.x = (v.parent.x + v.staticx) - self.offsetx
end
if upadte then
upadte(self, dt)
end
end
--[[---------------------------------------------------------
- func: draw()
- desc: draws the object
--]]---------------------------------------------------------
function newobject:draw()
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
local x = self.x
local y = self.y
local width = self.width
local height = self.height
local stencilfunc = function() love.graphics.rectangle("fill", x, y, width, height) end
local loveversion = love._version
local skins = loveframes.skins.available
local skinindex = loveframes.config["ACTIVESKIN"]
local defaultskin = loveframes.config["DEFAULTSKIN"]
local selfskin = self.skin
local skin = skins[selfskin] or skins[skinindex]
local drawfunc = skin.DrawMultiChoiceList or skins[defaultskin].DrawMultiChoiceList
local drawoverfunc = skin.DrawOverMultiChoiceList or skins[defaultskin].DrawOverMultiChoiceList
local draw = self.Draw
local drawcount = loveframes.drawcount
local internals = self.internals
local children = self.children
-- set the object's draw order
self:SetDrawOrder()
if draw then
draw(self)
else
drawfunc(self)
end
for k, v in ipairs(internals) do
v:draw()
end
if loveversion == "0.8.0" then
local stencil = love.graphics.newStencil(stencilfunc)
love.graphics.setStencil(stencil)
else
love.graphics.setStencil(stencilfunc)
end
for k, v in ipairs(children) do
local col = loveframes.util.BoundingBox(self.x, v.x, self.y, v.y, self.width, v.width, self.height, v.height)
if col then
v:draw()
end
end
love.graphics.setStencil()
if not draw then
drawoverfunc(self)
end
end
--[[---------------------------------------------------------
- func: mousepressed(x, y, button)
- desc: called when the player presses a mouse button
--]]---------------------------------------------------------
function newobject:mousepressed(x, y, button)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
local selfcol = loveframes.util.BoundingBox(x, self.x, y, self.y, 1, self.width, 1, self.height)
local toplist = self:IsTopList()
local internals = self.internals
local children = self.children
local scrollamount = self.mousewheelscrollamount
if not selfcol and self.canremove and button == "l" then
self:Close()
end
if self.vbar and toplist then
local bar = internals[1].internals[1].internals[1]
local dtscrolling = self.dtscrolling
if dtscrolling then
local dt = love.timer.getDelta()
if button == "wu" then
bar:Scroll(-scrollamount * dt)
elseif button == "wd" then
bar:Scroll(scrollamount * dt)
end
else
if button == "wu" then
bar:Scroll(-scrollamount)
elseif button == "wd" then
bar:Scroll(scrollamount)
end
end
end
for k, v in ipairs(internals) do
v:mousepressed(x, y, button)
end
for k, v in ipairs(children) do
v:mousepressed(x, y, button)
end
end
--[[---------------------------------------------------------
- func: mousereleased(x, y, button)
- desc: called when the player releases a mouse button
--]]---------------------------------------------------------
function newobject:mousereleased(x, y, button)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
local internals = self.internals
local children = self.children
self.canremove = true
for k, v in ipairs(internals) do
v:mousereleased(x, y, button)
end
for k, v in ipairs(children) do
v:mousereleased(x, y, button)
end
end
--[[---------------------------------------------------------
- func: AddItem(object)
- desc: adds an item to the object
--]]---------------------------------------------------------
function newobject:AddItem(object)
if object.type ~= "multichoicerow" then
return
end
object.parent = self
table.insert(self.children, object)
self:CalculateSize()
self:RedoLayout()
end
--[[---------------------------------------------------------
- func: RemoveItem(object)
- desc: removes an item from the object
--]]---------------------------------------------------------
function newobject:RemoveItem(object)
local children = self.children
for k, v in ipairs(children) do
if v == object then
table.remove(children, k)
end
end
self:CalculateSize()
self:RedoLayout()
end
--[[---------------------------------------------------------
- func: CalculateSize()
- desc: calculates the size of the object's children
--]]---------------------------------------------------------
function newobject:CalculateSize()
self.height = self.padding
if self.list.listheight then
self.height = self.list.listheight
else
for k, v in ipairs(self.children) do
self.height = self.height + (v.height + self.spacing)
end
end
if self.height > love.graphics.getHeight() then
self.height = love.graphics.getHeight()
end
local numitems = #self.children
local height = self.height
local padding = self.padding
local spacing = self.spacing
local itemheight = self.padding
local vbar = self.vbar
local children = self.children
for k, v in ipairs(children) do
itemheight = itemheight + v.height + spacing
end
self.itemheight = (itemheight - spacing) + padding
if self.itemheight > height then
self.extraheight = self.itemheight - height
if not vbar then
local scroll = loveframes.objects["scrollbody"]:new(self, "vertical")
table.insert(self.internals, scroll)
self.vbar = true
end
else
if vbar then
self.internals[1]:Remove()
self.vbar = false
self.offsety = 0
end
end
end
--[[---------------------------------------------------------
- func: RedoLayout()
- desc: used to redo the layour of the object
--]]---------------------------------------------------------
function newobject:RedoLayout()
local children = self.children
local padding = self.padding
local spacing = self.spacing
local starty = padding
local vbar = self.vbar
if #children > 0 then
for k, v in ipairs(children) do
v.staticx = padding
v.staticy = starty
if vbar then
v.width = (self.width - self.internals[1].width) - padding * 2
self.internals[1].staticx = self.width - self.internals[1].width
self.internals[1].height = self.height
else
v.width = self.width - padding * 2
end
starty = starty + v.height
starty = starty + spacing
end
end
end
--[[---------------------------------------------------------
- func: SetPadding(amount)
- desc: sets the object's padding
--]]---------------------------------------------------------
function newobject:SetPadding(amount)
self.padding = amount
end
--[[---------------------------------------------------------
- func: SetSpacing(amount)
- desc: sets the object's spacing
--]]---------------------------------------------------------
function newobject:SetSpacing(amount)
self.spacing = amount
end
--[[---------------------------------------------------------
- func: Close()
- desc: closes the object
--]]---------------------------------------------------------
function newobject:Close()
self:Remove()
self.list.haslist = false
end | gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Western_Adoulin/npcs/Kipligg.lua | 11 | 2005 | -----------------------------------
-- Area: Western Adoulin
-- NPC: Kipligg
-- Type: Standard NPC and Mission NPC,
-- Involved with Missions: '...Into the Fire', 'Done and Delivered'
-- !pos -32 0 22 256
-----------------------------------
require("scripts/globals/missions");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local SOA_Mission = player:getCurrentMission(SOA);
if (SOA_Mission < dsp.mission.id.soa.LIFE_ON_THE_FRONTIER) then
-- Dialogue prior to joining colonization effort
player:startEvent(571);
elseif (SOA_Mission == dsp.mission.id.soa.INTO_THE_FIRE) then
-- Finishes SOA Mission: '...Into the Fire'
player:startEvent(155);
elseif ((SOA_Mission >= dsp.mission.id.soa.MELVIEN_DE_MALECROIX) and (SOA_Mission <= dsp.mission.id.soa.COURIER_CATASTROPHE)) then
-- Reminds player where to go for SOA Mission: 'Melvien de Malecroix'
player:startEvent(162);
elseif (SOA_Mission == dsp.mission.id.soa.DONE_AND_DELIVERED) then
-- Finishes SOA Mission: 'Done and Delivered'
player:startEvent(157);
elseif (SOA_Mission == dsp.mission.id.soa.MINISTERIAL_WHISPERS) then
-- Reminds player where to go for SOA Mission: 'Ministerial Whispers'
player:startEvent(163);
else
-- Dialogue after joining colonization effort
player:startEvent(589);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 155) then
-- Finishes SOA Mission: '...Into the Fire'
player:completeMission(SOA, dsp.mission.id.soa.INTO_THE_FIRE);
player:addMission(SOA, dsp.mission.id.soa.MELVIEN_DE_MALECROIX);
elseif (csid == 157) then
-- Finishes SOA Mission: 'Done and Delivered'
player:completeMission(SOA, dsp.mission.id.soa.DONE_AND_DELIVERED);
player:addMission(SOA, dsp.mission.id.soa.MINISTERIAL_WHISPERS);
end
end;
| gpl-3.0 |
kashif/optim | rprop.lua | 9 | 3301 | --[[ A plain implementation of RPROP
ARGS:
- `opfunc` : a function that takes a single input (X), the point of
evaluation, and returns f(X) and df/dX
- `x` : the initial point
- `state` : a table describing the state of the optimizer; after each
call the state is modified
- `state.stepsize` : initial step size, common to all components
- `state.etaplus` : multiplicative increase factor, > 1 (default 1.2)
- `state.etaminus` : multiplicative decrease factor, < 1 (default 0.5)
- `state.stepsizemax` : maximum stepsize allowed (default 50)
- `state.stepsizemin` : minimum stepsize allowed (default 1e-6)
- `state.niter` : number of iterations (default 1)
RETURN:
- `x` : the new x vector
- `f(x)` : the function, evaluated before the update
(Martin Riedmiller, Koray Kavukcuoglu 2013)
--]]
function optim.rprop(opfunc, x, config, state)
if config == nil and state == nil then
print('no state table RPROP initializing')
end
-- (0) get/update state
local config = config or {}
local state = state or config
local stepsize = config.stepsize or 0.1
local etaplus = config.etaplus or 1.2
local etaminus = config.etaminus or 0.5
local stepsizemax = config.stepsizemax or 50.0
local stepsizemin = config.stepsizemin or 1E-06
local niter = config.niter or 1
local hfx = {}
for i=1,niter do
-- (1) evaluate f(x) and df/dx
local fx,dfdx = opfunc(x)
-- init temp storage
if not state.delta then
state.delta = dfdx.new(dfdx:size()):zero()
state.stepsize = dfdx.new(dfdx:size()):fill(stepsize)
state.sign = dfdx.new(dfdx:size())
state.psign = torch.ByteTensor(dfdx:size())
state.nsign = torch.ByteTensor(dfdx:size())
state.zsign = torch.ByteTensor(dfdx:size())
state.dminmax = torch.ByteTensor(dfdx:size())
end
-- sign of derivative from last step to this one
torch.cmul(state.sign, dfdx, state.delta)
torch.sign(state.sign, state.sign)
-- get indices of >0, <0 and ==0 entries
state.sign.gt(state.psign, state.sign, 0)
state.sign.lt(state.nsign, state.sign, 0)
state.sign.eq(state.zsign, state.sign, 0)
-- get step size updates
state.sign[state.psign] = etaplus
state.sign[state.nsign] = etaminus
state.sign[state.zsign] = 1
-- update stepsizes with step size updates
state.stepsize:cmul(state.sign)
-- threshold step sizes
-- >50 => 50
state.stepsize.gt(state.dminmax, state.stepsize, stepsizemax)
state.stepsize[state.dminmax] = stepsizemax
-- <1e-6 ==> 1e-6
state.stepsize.lt(state.dminmax, state.stepsize, stepsizemin)
state.stepsize[state.dminmax] = stepsizemin
-- for dir<0, dfdx=0
-- for dir>=0 dfdx=dfdx
dfdx[state.nsign] = 0
-- state.sign = sign(dfdx)
torch.sign(state.sign,dfdx)
-- update weights
x:addcmul(-1,state.sign,state.stepsize)
-- update state.dfdx with current dfdx
state.delta:copy(dfdx)
table.insert(hfx,fx)
end
-- return x*, f(x) before optimization
return x,hfx
end
| bsd-3-clause |
Fenix-XI/Fenix | scripts/zones/Sealions_Den/bcnms/warriors_path.lua | 1 | 2484 | -----------------------------------
-- Area: Sealion's Den
-- Name: warriors_path
-- bcnmID : 993
-----------------------------------
package.loaded["scripts/zones/Sealions_Den/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Sealions_Den/TextIDs");
-----------------------------------
--Tarutaru
--Tenzen group 860 3875
--Makki-Chebukki (RNG) , 16908311 16908315 16908319 group 853 2492
--Kukki-Chebukki (BLM) 16908312 16908316 16908320 group 852 2293
--Cherukiki (WHM). 16908313 16908317 16908321 group 851 710
--instance 1 @pos -780 -103 -90
--instance 2 @pos -140 -23 -450
--instance 3 @pos 500 56 -810
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
player:addExp(1000);
--player:addCurrency("mweya_plasm",250);
if (player:getCurrentMission(COP) == THE_WARRIOR_S_PATH) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0);
player:setVar("PromathiaStatus",0);
player:completeMission(COP,THE_WARRIOR_S_PATH);
player:addMission(COP,GARDEN_OF_ANTIQUITY);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,1);
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 0x7d01) then
player:setPos(-25,-1 ,-620 ,208 ,33);-- al'taieu
player:addTitle(THE_CHEBUKKIS_WORST_NIGHTMARE);
end
end; | gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Temple_of_Uggalepih/npcs/Worn_Book.lua | 9 | 1643 | -----------------------------------
-- Area: Temple of Uggalepih
-- NPC: Worn Book
-- Getting "Old Rusty Key (keyitem)"
-- !pos 59 0 19 159
-----------------------------------
local ID = require("scripts/zones/Temple_of_Uggalepih/IDs")
require("scripts/globals/keyitems")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
if player:hasKeyItem(dsp.ki.OLD_RUSTY_KEY) or player:hasKeyItem(dsp.ki.PAINTBRUSH_OF_SOULS) then
player:messageSpecial(ID.text.NO_REASON_TO_INVESTIGATE)
else
local offset = npc:getID() - ID.npc.BOOK_OFFSET
player:startEvent(61 + offset)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
local book = player:getCharVar("paintbrushOfSouls_book")
if csid == 61 and option == 1 and (book == 0 or book == 2 or book == 4 or book == 6) then
player:setCharVar("paintbrushOfSouls_book", book + 1)
elseif csid == 62 and option == 1 and (book == 0 or book == 1 or book == 4 or book == 5) then
player:setCharVar("paintbrushOfSouls_book", book + 2)
elseif csid == 63 and option == 1 and (book == 0 or book == 1 or book == 2 or book == 3) then
player:setCharVar("paintbrushOfSouls_book", book + 4)
end
if player:getCharVar("paintbrushOfSouls_book") == 7 then
player:messageSpecial(ID.text.FALLS_FROM_THE_BOOK, dsp.ki.OLD_RUSTY_KEY)
player:addKeyItem(dsp.ki.OLD_RUSTY_KEY)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.OLD_RUSTY_KEY)
player:setCharVar("paintbrushOfSouls_book", 0)
end
end
| gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Bastok_Markets/npcs/Harmodios.lua | 9 | 1815 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Harmodios
-- Standard Merchant NPC
-- !pos -79.928 -4.824 -135.114 235
-----------------------------------
local ID = require("scripts/zones/Bastok_Markets/IDs")
require("scripts/globals/quests")
require("scripts/globals/shop")
function onTrigger(player,npc)
local WildcatBastok = player:getCharVar("WildcatBastok")
if player:getQuestStatus(BASTOK,dsp.quest.id.bastok.LURE_OF_THE_WILDCAT) == QUEST_ACCEPTED and not player:getMaskBit(WildcatBastok,10) then
player:startEvent(430)
elseif player:getCharVar("comebackQueenCS") == 1 then
player:startEvent(490)
else
local stock =
{
17347, 990, 1, -- Piccolo
17344, 219, 2, -- Cornette
17353, 43, 2, -- Maple Harp
5041, 69120, 2, -- Scroll of Vital Etude
5042, 66240, 2, -- Scroll of Swift Etude
5043, 63360, 2, -- Scroll of Sage Etude
5044, 56700, 2, -- Scroll of Logical Etude
5039, 79560, 2, -- Scroll of Herculean Etude
5040, 76500, 2, -- Scroll of Uncanny Etude
17351, 4644, 3, -- Gemshorn
17345, 43, 3, -- Flute
5045, 54000, 3, -- Scroll of Bewitching Etude
}
player:showText(npc, ID.text.HARMODIOS_SHOP_DIALOG)
dsp.shop.nation(player, stock, dsp.nation.BASTOK)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if csid == 430 then
player:setMaskBit(player:getCharVar("WildcatBastok"),"WildcatBastok",10,true)
elseif csid == 490 then
player:startEvent(491)
elseif csid == 491 then
player:setCharVar("comebackQueenCS", 2)
end
end
| gpl-3.0 |
DarkstarProject/darkstar | scripts/globals/items/red_curry_bun.lua | 11 | 1876 | -----------------------------------------
-- ID: 5759
-- Item: red_curry_bun
-- Food Effect: 30 Min, All Races
-----------------------------------------
-- TODO: Group effects
-- Health 25
-- Strength 7
-- Agility 1
-- Intelligence -2
-- Attack % 23 (cap 150)
-- Ranged Atk % 23 (cap 150)
-- Demon Killer 4
-- Resist Sleep +3
-- HP recovered when healing +2
-- MP recovered when healing +1
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,1800,5759)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.HP, 25)
target:addMod(dsp.mod.STR, 7)
target:addMod(dsp.mod.AGI, 1)
target:addMod(dsp.mod.INT, -2)
target:addMod(dsp.mod.FOOD_ATTP, 23)
target:addMod(dsp.mod.FOOD_ATT_CAP, 150)
target:addMod(dsp.mod.FOOD_RATTP, 23)
target:addMod(dsp.mod.FOOD_RATT_CAP, 150)
target:addMod(dsp.mod.DEMON_KILLER, 4)
target:addMod(dsp.mod.SLEEPRES, 3)
target:addMod(dsp.mod.HPHEAL, 2)
target:addMod(dsp.mod.MPHEAL, 1)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.HP, 25)
target:delMod(dsp.mod.STR, 7)
target:delMod(dsp.mod.AGI, 1)
target:delMod(dsp.mod.INT, -2)
target:delMod(dsp.mod.FOOD_ATTP, 23)
target:delMod(dsp.mod.FOOD_ATT_CAP, 150)
target:delMod(dsp.mod.FOOD_RATTP, 23)
target:delMod(dsp.mod.FOOD_RATT_CAP, 150)
target:delMod(dsp.mod.DEMON_KILLER, 4)
target:delMod(dsp.mod.SLEEPRES, 3)
target:delMod(dsp.mod.HPHEAL, 2)
target:delMod(dsp.mod.MPHEAL, 1)
end | gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Kazham/npcs/Kakapp.lua | 9 | 2736 | -----------------------------------
-- Area: Kazham
-- NPC: Kakapp
-- Standard Info NPC
-----------------------------------
function onTrade(player,npc,trade)
-- item IDs
-- 483 Broken Mithran Fishing Rod
-- 22 Workbench
-- 1008 Ten of Coins
-- 1157 Sands of Silence
-- 1158 Wandering Bulb
-- 904 Giant Fish Bones
-- 4599 Blackened Toad
-- 905 Wyvern Skull
-- 1147 Ancient Salt
-- 4600 Lucky Egg
local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, dsp.quest.id.outlands.THE_OPO_OPO_AND_I);
local progress = player:getCharVar("OPO_OPO_PROGRESS");
local failed = player:getCharVar("OPO_OPO_FAILED");
local goodtrade = trade:hasItemQty(905,1);
local badtrade = (trade:hasItemQty(483,1) or trade:hasItemQty(22,1) or trade:hasItemQty(1008,1) or trade:hasItemQty(1157,1) or trade:hasItemQty(1158,1) or trade:hasItemQty(4599,1) or trade:hasItemQty(904,1) or trade:hasItemQty(1147,1) or trade:hasItemQty(4600,1));
if (OpoOpoAndIStatus == QUEST_ACCEPTED) then
if progress == 7 or failed == 8 then
if goodtrade then
player:startEvent(226);
elseif badtrade then
player:startEvent(236);
end
end
end
end;
function onTrigger(player,npc)
local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, dsp.quest.id.outlands.THE_OPO_OPO_AND_I);
local progress = player:getCharVar("OPO_OPO_PROGRESS");
local failed = player:getCharVar("OPO_OPO_FAILED");
local retry = player:getCharVar("OPO_OPO_RETRY");
if (OpoOpoAndIStatus == QUEST_ACCEPTED) then
if retry >= 1 then -- has failed on future npc so disregard previous successful trade
player:startEvent(204);
elseif (progress == 7 or failed == 8) then
player:startEvent(213); -- asking for wyvern skull
elseif (progress >= 8 or failed >= 9) then
player:startEvent(249); -- happy with wyvern skull
end
else
player:startEvent(204);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 226) then -- correct trade, onto next opo
if player:getCharVar("OPO_OPO_PROGRESS") == 7 then
player:tradeComplete();
player:setCharVar("OPO_OPO_PROGRESS",8);
player:setCharVar("OPO_OPO_FAILED",0);
else
player:setCharVar("OPO_OPO_FAILED",9);
end
elseif (csid == 236) then -- wrong trade, restart at first opo
player:setCharVar("OPO_OPO_FAILED",1);
player:setCharVar("OPO_OPO_RETRY",8);
end
end;
| gpl-3.0 |
DarkstarProject/darkstar | scripts/globals/items/windurst_taco.lua | 11 | 1348 | -----------------------------------------
-- ID: 5172
-- Item: windurst_taco
-- Food Effect: 30Min, All Races
-----------------------------------------
-- MP 20
-- Vitality -1
-- Agility 5
-- MP Recovered While Healing 1
-- Ranged Accuracy % 8 (cap 10)
-- Ranged Attack +1
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,1800,5172)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.MP, 20)
target:addMod(dsp.mod.VIT, -1)
target:addMod(dsp.mod.AGI, 5)
target:addMod(dsp.mod.MPHEAL, 1)
target:addMod(dsp.mod.RATT, 1)
target:addMod(dsp.mod.FOOD_RACCP, 8)
target:addMod(dsp.mod.FOOD_RACC_CAP, 10)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.MP, 20)
target:delMod(dsp.mod.VIT, -1)
target:delMod(dsp.mod.AGI, 5)
target:delMod(dsp.mod.MPHEAL, 1)
target:delMod(dsp.mod.RATT, 1)
target:delMod(dsp.mod.FOOD_RACCP, 8)
target:delMod(dsp.mod.FOOD_RACC_CAP, 10)
end
| gpl-3.0 |
mrrigealijan/nnso | plugins/filter.lua | 6 | 3623 | local function save_filter(msg, name, value)
local hash = nil
if msg.to.type == 'channel' then
hash = 'chat:'..msg.to.id..':filters'
end
if msg.to.type == 'user' then
return 'SUPERGROUPS only'
end
if hash then
redis:hset(hash, name, value)
return "Successfull!"
end
end
local function get_filter_hash(msg)
if msg.to.type == 'channel' then
return 'chat:'..msg.to.id..':filters'
end
end
local function list_filter(msg)
if msg.to.type == 'user' then
return 'SUPERGROUPS only'
end
local hash = get_filter_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'Sencured Wordes:\n\n'
for i=1, #names do
text = text..'➡️ '..names[i]..'\n'
end
return text
end
end
local function get_filter(msg, var_name)
local hash = get_filter_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if value == 'msg' then
delete_msg(msg.id, ok_cb, false)
return 'WARNING!\nDon\'nt Use it!'
elseif value == 'kick' then
send_large_msg('channel#id'..msg.to.id, "BBye xD")
channel_kick_user('channel#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, true)
delete_msg(msg.id, ok_cb, false)
end
end
end
local function get_filter_act(msg, var_name)
local hash = get_filter_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if value == 'msg' then
return 'Warning'
elseif value == 'kick' then
return 'Kick YOU'
elseif value == 'none' then
return 'Out of filter'
end
end
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
if matches[1] == "ilterlist" then
return list_filter(msg)
elseif matches[1] == "ilter" and matches[2] == "war1324jadlkhrou2aisn" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "You Are Not MOD"
else
local value = 'msg'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "in" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "You Are Not MOD"
else
local value = 'kick'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "out" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "You Are Not MOD"
else
local value = 'none'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "clean" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "You Are Not MOD"
else
local value = 'none'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "about" then
return get_filter_act(msg, matches[3]:lower())
else
if is_sudo(msg) then
return
elseif is_admin(msg) then
return
elseif is_momod(msg) then
return
elseif tonumber(msg.from.id) == tonumber(our_id) then
return
else
return get_filter(msg, msg.text:lower())
end
end
end
return {
patterns = {
"^[!/][Ff](ilter) (.+) (.*)$",
"^[!/][Ff](ilterlist)$",
"(.*)",
},
run = run
}
| gpl-2.0 |
DarkstarProject/darkstar | scripts/globals/spells/embrava.lua | 11 | 1070 | --------------------------------------
-- Spell: Embrava
-- Consumes 20% of your maximum MP. Gradually restores
-- target party member's HP and MP and increases attack speed.
--------------------------------------
require("scripts/globals/magic")
require("scripts/globals/msg")
require("scripts/globals/status")
--------------------------------------
function onMagicCastingCheck(caster, target, spell)
return 0
end
function onSpellCast(caster, target, spell)
-- If Tabula Rasa wears before spell goes off, no Embrava for you!
if not caster:hasStatusEffect(dsp.effect.TABULA_RASA) then
spell:setMsg(dsp.msg.basic.MAGIC_CANNOT_CAST)
return 0
end
-- Skill caps at 500
local skill = math.min(caster:getSkillLevel(dsp.skill.ENHANCING_MAGIC), 500)
local duration = calculateDuration(90, spell:getSkillType(), spell:getSpellGroup(), caster, target)
duration = calculateDurationForLvl(duration, 5, target:getMainLvl())
target:addStatusEffect(dsp.effect.EMBRAVA, skill, 0, duration)
return dsp.effect.EMBRAVA
end | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Bastok_Mines/npcs/Leonie.lua | 13 | 1060 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Leonie
-- Type: Room Renters
-- @zone: 234
-- @pos 118.871 -0.004 -83.916
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
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:startEvent(0x0238);
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 |
Fenix-XI/Fenix | scripts/zones/Port_Bastok/npcs/Gudav.lua | 12 | 1990 | -----------------------------------
-- Area: Port Bastok
-- NPC: Gudav
-- Starts Quests: A Foreman's Best Friend
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(13096,1) and trade:getItemCount() == 1) then
if (player:getQuestStatus(BASTOK,A_FOREMAN_S_BEST_FRIEND) == QUEST_ACCEPTED) then
player:tradeComplete();
player:startEvent(0x0070);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getMainLvl() >= 7 and player:getQuestStatus(BASTOK,A_FOREMAN_S_BEST_FRIEND) == QUEST_AVAILABLE) then
player:startEvent(0x006e);
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 == 0x006e) then
player:addQuest(BASTOK,A_FOREMAN_S_BEST_FRIEND);
elseif (csid == 0x0070) then
if (player:hasKeyItem(MAP_OF_THE_GUSGEN_MINES) == false) then
player:addKeyItem(MAP_OF_THE_GUSGEN_MINES);
player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_GUSGEN_MINES);
end
player:addFame(BASTOK,60);
player:completeQuest(BASTOK,A_FOREMAN_S_BEST_FRIEND);
end
end; | gpl-3.0 |
DarkstarProject/darkstar | scripts/globals/items/serving_of_medicinal_quus.lua | 11 | 1095 | -----------------------------------------
-- ID: 4294
-- Item: serving_of_medicinal_quus
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Dexterity 1
-- Mind -1
-- Ranged ACC % 7
-- Ranged ACC Cap 15
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,14400,4294)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.DEX, 1)
target:addMod(dsp.mod.MND, -1)
target:addMod(dsp.mod.FOOD_RACCP, 7)
target:addMod(dsp.mod.FOOD_RACC_CAP, 15)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.DEX, 1)
target:delMod(dsp.mod.MND, -1)
target:delMod(dsp.mod.FOOD_RACCP, 7)
target:delMod(dsp.mod.FOOD_RACC_CAP, 15)
end
| gpl-3.0 |
parapluu/encore | src/runtime/pony/premake4.lua | 1 | 5198 | -- premake.override is a premake5 feature.
-- We use this approach to improve Visual Studio Support for Windows.
-- The goal is to force C++ compilation for non-*.cpp/cxx/cc file extensions.
-- By doing this properly, we avoid a MSVC warning about overiding /TC
-- with /TP.
if premake.override then
local force_cpp = { }
function cppforce(inFiles)
for _, val in ipairs(inFiles) do
for _, fname in ipairs(os.matchfiles(val)) do
table.insert(force_cpp, path.getabsolute(fname))
end
end
end
premake.override(premake.vstudio.vc2010, "additionalCompileOptions", function(base, cfg, condition)
if cfg.abspath then
if table.contains(force_cpp, cfg.abspath) then
_p(3,'<CompileAs %s>CompileAsCpp</CompileAs>', condition)
end
end
return base(cfg, condition)
end)
end
if os.execute("clang -v") == 0 then
premake.gcc.cc = 'clang'
premake.gcc.cxx = 'clang++'
end
function use_flto()
buildoptions {
"-O3",
"-flto",
}
linkoptions {
"-flto",
"-fuse-ld=gold",
}
end
function c_lib()
kind "StaticLib"
language "C"
configuration "not windows"
buildoptions "-std=gnu11"
configuration "Release or Profile"
if(macosx or linux) then
use_flto()
else
if(optimize) then
optimize "Speed"
else
flags "OptimizeSpeed"
end
end
configuration "*"
end
solution "ponyrt"
configurations {"Debug", "Release"}
configuration "not windows"
buildoptions {
"-mcx16",
"-pthread",
"-std=gnu11",
"-march=native",
"-Wunused-parameter",
"-Wno-error=deprecated-declarations",
}
linkoptions {
"-lm",
"-pthread"
}
configuration "*"
includedirs {
"../closure",
"../array",
"../encore",
"../future",
"../task",
"../adt",
"../party",
"libponyrt",
"../common",
"../dtrace",
}
flags {
"ExtraWarnings",
"FatalWarnings",
"Symbols"
}
configuration "Debug"
targetdir "bin/debug"
objdir "obj/debug"
configuration "Release"
targetdir "bin/release"
objdir "obj/release"
defines "NDEBUG"
configuration "macosx"
-- set these to suppress clang warning about -pthread being unused
buildoptions "-Qunused-arguments"
linkoptions "-Qunused-arguments"
configuration "windows"
if(architecture) then
architecture "x64"
end
linkoptions "/NODEFAULTLIB:msvcrt.lib"
if(cppforce) then
cppforce { "**.c" }
end
configuration "not windows"
if(table.contains(_ARGS, "dtrace")) then
defines "USE_DYNAMIC_TRACE"
os.execute("echo '#define USE_DYNAMIC_TRACE' > ../../../release/inc/dtrace_enabled.h")
if os.execute("dtrace -h -s ../common/encore_probes.d -o ../common/encore_probes.h") ~= 0 then
print("Error generating encore DTrace headers. Stop");
os.exit(1)
end
if os.execute("dtrace -h -s ../common/dtrace_probes.d -o ../common/dtrace_probes.h") ~= 0 then
print("Error generating ponyc DTrace headers. Stop");
os.exit(1)
end
if os.is("linux") then
os.execute("dtrace -G -s ../common/encore_probes.d -o ../common/encore_probes.o")
os.execute("dtrace -G -s ../common/dtrace_probes.d -o ../common/dtrace_probes.o")
project "ponyrt"
configuration "Debug"
postbuildcommands {
'ar -rcs bin/debug/libponyrt.a ../common/encore_probes.o',
'ar -rcs bin/debug/libponyrt.a ../common/dtrace_probes.o'
}
configuration "Release"
postbuildcommands {
'ar -rcs bin/release/libponyrt.a ../common/encore_probes.o',
'ar -rcs bin/release/libponyrt.a ../common/dtrace_probes.o',
}
end
else
os.execute("cat /dev/null > ../../../release/inc/dtrace_enabled.h")
end
project "ponyrt"
c_lib()
includedirs {
"./libponyrt/",
}
files {
"./libponyrt/**.h",
"./libponyrt/**.c"
}
project "encore"
c_lib()
files {
"../encore/encore.h",
"../encore/encore.c"
}
project "array"
c_lib()
files {
"../array/array.h",
"../array/array.c"
}
project "tuple"
c_lib()
files {
"../tuple/tuple.h",
"../tuple/tuple.c"
}
project "range"
c_lib()
files {
"../range/range.h",
"../range/range.c"
}
project "task"
c_lib()
files {
"../task/task.h",
"../task/task.c"
}
project "optiontype"
c_lib()
links { "encore" }
files {
"../adt/option.h",
"../adt/option.c"
}
project "closure"
c_lib()
files {
"../closure/closure.h",
"../closure/closure.c"
}
project "party"
c_lib()
links { "future", "array" }
files {
"../party/**.h",
"../party/**.c"
}
project "future"
c_lib()
links { "closure", "array" }
files {
"../future/future.c",
}
project "stream"
c_lib()
links { "future" }
files {
"../stream/stream.h",
"../stream/stream.c"
}
-- -- project "set"
-- -- kind "StaticLib"
-- -- language "C"
-- -- links { "closure" }
-- -- includedirs { "../closure" }
-- -- files {
-- -- "../set/set.c"
-- -- }
| bsd-3-clause |
chuanli11/MGANs | code/release_MGAN.lua | 1 | 1453 | -- a script for releasing the generator: it basically concatenates the encoder part of VGG to the generator.
require 'torch'
require 'nn'
require 'optim'
require 'cutorch'
require 'cunn'
require 'image'
loadcaffe_wrap = paths.dofile('lib/loadcaffe_wrapper.lua')
util = paths.dofile('lib/util.lua')
local opt = {}
opt.model_name = '../Dataset/VG_Alpilles_ImageNet100/MGAN/epoch_5_netG.t7'
opt.release_name = '../Dataset/VG_Alpilles_ImageNet100/VG_Alpilles_ImageNet100_epoch5.t7'
---*********************************************************************************************************************
-- DO NOT CHANGE AFTER THIS LINE
---*********************************************************************************************************************
opt.vgg_proto_file = '../Dataset/model/VGG_ILSVRC_19_layers_deploy.prototxt'
opt.vgg_model_file = '../Dataset/model/VGG_ILSVRC_19_layers.caffemodel'
opt.vgg_backend = 'nn'
opt.netEnco_vgg_Outputlayer = 21
opt.gpu = 0
local net_vgg = loadcaffe_wrap.load(opt.vgg_proto_file, opt.vgg_model_file, opt.vgg_backend, opt.netEnco_vgg_Outputlayer)
local net_deco = util.load(opt.model_name, opt.gpu)
print(net_deco)
local net_release = nn.Sequential()
for i_layer = 1, opt.netEnco_vgg_Outputlayer do
net_release:add(net_vgg:get(i_layer))
end
for i_layer = 1, net_deco:size() do
net_release:add(net_deco:get(i_layer))
end
print(net_release)
util.save(opt.release_name, net_release, opt.gpu)
| mit |
Fenix-XI/Fenix | scripts/globals/items/blacksmiths_belt.lua | 18 | 1175 | -----------------------------------------
-- ID: 15445
-- Item: Blacksmith's Belt
-- Enchantment: Synthesis image support
-- 2Min, All Races
-----------------------------------------
-- Enchantment: Synthesis image support
-- Duration: 2Min
-- Smithing Skill +3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_SMITHING_IMAGERY) == true) then
result = 237;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_SMITHING_IMAGERY,3,0,120);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_SKILL_SMT, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_SKILL_SMT, 1);
end; | gpl-3.0 |
marcel-sch/luci | modules/luci-mod-admin-full/luasrc/model/cbi/admin_status/processes.lua | 75 | 1236 | -- 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.
f = SimpleForm("processes", translate("Processes"), translate("This list gives an overview over currently running system processes and their status."))
f.reset = false
f.submit = false
t = f:section(Table, luci.sys.process.list())
t:option(DummyValue, "PID", translate("PID"))
t:option(DummyValue, "USER", translate("Owner"))
t:option(DummyValue, "COMMAND", translate("Command"))
t:option(DummyValue, "%CPU", translate("CPU usage (%)"))
t:option(DummyValue, "%MEM", translate("Memory usage (%)"))
hup = t:option(Button, "_hup", translate("Hang Up"))
hup.inputstyle = "reload"
function hup.write(self, section)
null, self.tag_error[section] = luci.sys.process.signal(section, 1)
end
term = t:option(Button, "_term", translate("Terminate"))
term.inputstyle = "remove"
function term.write(self, section)
null, self.tag_error[section] = luci.sys.process.signal(section, 15)
end
kill = t:option(Button, "_kill", translate("Kill"))
kill.inputstyle = "reset"
function kill.write(self, section)
null, self.tag_error[section] = luci.sys.process.signal(section, 9)
end
return f | apache-2.0 |
crunchuser/prosody-modules | mod_auth_external/mod_auth_external.lua | 31 | 4708 | --
-- Prosody IM
-- Copyright (C) 2010 Waqas Hussain
-- Copyright (C) 2010 Jeff Mitchell
-- Copyright (C) 2013 Mikael Nordfeldth
-- Copyright (C) 2013 Matthew Wild, finally came to fix it all
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local lpty = assert(require "lpty", "mod_auth_external requires lpty: https://code.google.com/p/prosody-modules/wiki/mod_auth_external#Installation");
local usermanager = require "core.usermanager";
local new_sasl = require "util.sasl".new;
local server = require "net.server";
local have_async, async = pcall(require, "util.async");
local log = module._log;
local host = module.host;
local script_type = module:get_option_string("external_auth_protocol", "generic");
local command = module:get_option_string("external_auth_command", "");
local read_timeout = module:get_option_number("external_auth_timeout", 5);
local blocking = module:get_option_boolean("external_auth_blocking", not(have_async and server.event and lpty.getfd));
local auth_processes = module:get_option_number("external_auth_processes", 1);
assert(script_type == "ejabberd" or script_type == "generic", "Config error: external_auth_protocol must be 'ejabberd' or 'generic'");
assert(not host:find(":"), "Invalid hostname");
if not blocking then
log("debug", "External auth in non-blocking mode, yay!")
waiter, guard = async.waiter, async.guarder();
elseif auth_processes > 1 then
log("warn", "external_auth_processes is greater than 1, but we are in blocking mode - reducing to 1");
auth_processes = 1;
end
local ptys = {};
local pty_options = { throw_errors = false, no_local_echo = true, use_path = false };
for i = 1, auth_processes do
ptys[i] = lpty.new(pty_options);
end
local curr_process = 0;
function send_query(text)
curr_process = (curr_process%auth_processes)+1;
local pty = ptys[curr_process];
local finished_with_pty
if not blocking then
finished_with_pty = guard(pty); -- Prevent others from crossing this line while we're busy
end
if not pty:hasproc() then
local status, ret = pty:exitstatus();
if status and (status ~= "exit" or ret ~= 0) then
log("warn", "Auth process exited unexpectedly with %s %d, restarting", status, ret or 0);
return nil;
end
local ok, err = pty:startproc(command);
if not ok then
log("error", "Failed to start auth process '%s': %s", command, err);
return nil;
end
log("debug", "Started auth process");
end
pty:send(text);
if blocking then
return pty:read(read_timeout);
else
local response;
local wait, done = waiter();
server.addevent(pty:getfd(), server.event.EV_READ, function ()
response = pty:read();
done();
return -1;
end);
wait();
finished_with_pty();
return response;
end
end
function do_query(kind, username, password)
if not username then return nil, "not-acceptable"; end
local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password);
local len = #query
if len > 1000 then return nil, "policy-violation"; end
if script_type == "ejabberd" then
local lo = len % 256;
local hi = (len - lo) / 256;
query = string.char(hi, lo)..query;
elseif script_type == "generic" then
query = query..'\n';
end
local response, err = send_query(query);
if not response then
log("warn", "Error while waiting for result from auth process: %s", err or "unknown error");
elseif (script_type == "ejabberd" and response == "\0\2\0\0") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "0") then
return nil, "not-authorized";
elseif (script_type == "ejabberd" and response == "\0\2\0\1") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "1") then
return true;
else
log("warn", "Unable to interpret data from auth process, %s", (response:match("^error:") and response) or ("["..#response.." bytes]"));
return nil, "internal-server-error";
end
end
local host = module.host;
local provider = {};
function provider.test_password(username, password)
return do_query("auth", username, password);
end
function provider.set_password(username, password)
return do_query("setpass", username, password);
end
function provider.user_exists(username)
return do_query("isuser", username);
end
function provider.create_user(username, password) return nil, "Account creation/modification not available."; end
function provider.get_sasl_handler()
local testpass_authentication_profile = {
plain_test = function(sasl, username, password, realm)
return usermanager.test_password(username, realm, password), true;
end,
};
return new_sasl(host, testpass_authentication_profile);
end
module:provides("auth", provider);
| mit |
Fenix-XI/Fenix | scripts/globals/items/dish_of_spaghetti_vongole_rosso_+1.lua | 18 | 1650 | -----------------------------------------
-- ID: 5198
-- Item: Dish of Spaghetti Vongole Rosso +1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health % 20
-- Health Cap 95
-- Vitality 2
-- Mind -1
-- Defense % 25
-- Defense Cap 35
-- Store TP 6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5198);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 20);
target:addMod(MOD_FOOD_HP_CAP, 95);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_MND, -1);
target:addMod(MOD_FOOD_DEFP, 25);
target:addMod(MOD_FOOD_DEF_CAP, 35);
target:addMod(MOD_STORETP, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 20);
target:delMod(MOD_FOOD_HP_CAP, 95);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_MND, -1);
target:delMod(MOD_FOOD_DEFP, 25);
target:delMod(MOD_FOOD_DEF_CAP, 35);
target:delMod(MOD_STORETP, 6);
end;
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/LaLoff_Amphitheater/bcnms/ark_angels_1.lua | 28 | 3110 | -----------------------------------
-- Area: LaLoff Amphitheater
-- Name: Ark Angels 1 (Hume)
-----------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
require("scripts/globals/missions");
require("scripts/globals/keyitems");
-----------------------------------
-- Death cutscenes:
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); -- Hume
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); -- taru
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,2,0); -- mithra
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0); -- elvan
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,0); -- galka
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,5,0); -- divine might
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,6,0); -- skip ending cs
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
--print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:hasCompletedMission(ZILART,ARK_ANGELS)) then
player:startEvent(0x7d01,instance:getEntrance(),instance:getFastestTime(),1,instance:getTimeInside(),180,0,1); -- winning CS (allow player to skip)
else
player:startEvent(0x7d01,instance:getEntrance(),instance:getFastestTime(),1,instance:getTimeInside(),180,0,0); -- winning CS (allow player to skip)
end
elseif (leavecode == 4) then
player:startEvent(0x7d02, 0, 0, 0, 0, 0, instance:getEntrance(), 180); -- player lost
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
local AAKeyitems = (player:hasKeyItem(SHARD_OF_ARROGANCE) and player:hasKeyItem(SHARD_OF_COWARDICE)
and player:hasKeyItem(SHARD_OF_ENVY) and player:hasKeyItem(SHARD_OF_RAGE));
if (csid == 0x7d01) then
if (player:getCurrentMission(ZILART) == ARK_ANGELS and player:getVar("ZilartStatus") == 1) then
player:addKeyItem(SHARD_OF_APATHY);
player:messageSpecial(KEYITEM_OBTAINED,SHARD_OF_APATHY);
if (AAKeyitems == true) then
player:completeMission(ZILART,ARK_ANGELS);
player:addMission(ZILART,THE_SEALED_SHRINE);
player:setVar("ZilartStatus",0);
end
end
end
end; | gpl-3.0 |
DarkstarProject/darkstar | scripts/globals/mobskills/vitriolic_spray.lua | 11 | 1113 | ---------------------------------------------
-- Vitriolic Spray
-- Family: Wamouracampa
-- Description: Expels a caustic stream at targets in a fan-shaped area of effect. Additional effect: Burn
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadow
-- Range: Cone
-- Notes: Burn is 10-30/tic
---------------------------------------------
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 = dsp.effect.BURN
local power = math.random(10,30)
MobStatusEffectMove(mob, target, typeEffect, power, 3, 60)
local dmgmod = 1
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*2.7,dsp.magic.ele.FIRE,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.FIRE,MOBPARAM_WIPE_SHADOWS)
target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.FIRE)
return dmg
end
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/FeiYin/npcs/Grounds_Tome.lua | 30 | 1074 | -----------------------------------
-- Area: Fei'Yin
-- NPC: Grounds Tome
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/groundsofvalor");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
startGov(GOV_EVENT_FEIYIN,player);
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
updateGov(player,csid,option,711,712,713,714,715,716,717,718,0,0);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
finishGov(player,csid,option,711,712,713,714,715,716,717,718,0,0,GOV_MSG_FEIYIN);
end;
| gpl-3.0 |
Fenix-XI/Fenix | scripts/globals/mobskills/glittering_ruby.lua | 27 | 1144 | ---------------------------------------------------
-- Glittering Ruby
---------------------------------------------------
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)
--randomly give str/dex/vit/agi/int/mnd/chr (+12)
local effect = math.random();
local effectid = EFFECT_STR_BOOST;
if (effect<=0.14) then --STR
effectid = EFFECT_STR_BOOST;
elseif (effect<=0.28) then --DEX
effectid = EFFECT_DEX_BOOST;
elseif (effect<=0.42) then --VIT
effectid = EFFECT_VIT_BOOST;
elseif (effect<=0.56) then --AGI
effectid = EFFECT_AGI_BOOST;
elseif (effect<=0.7) then --INT
effectid = EFFECT_INT_BOOST;
elseif (effect<=0.84) then --MND
effectid = EFFECT_MND_BOOST;
else --CHR
effectid = EFFECT_CHR_BOOST;
end
target:addStatusEffect(effectid,math.random(12,14),0,90);
skill:setMsg(MSG_BUFF);
return effectid;
end
| gpl-3.0 |
oTibia/UnderLight-AK47 | data/creaturescripts/scripts/look.lua | 2 | 1324 | --example of an onLook function event
function onLook(cid, target, itemid)
if itemid == 1988 then --backpack
if target ~= nil then
doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, "You are looking to a very beautiful backpack.")
else
--target nil means looking at an object in shop npc window, so it will work for backpacks at shop windows
doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, "You can buy this backpack for a very cheap price.")
end
return false --don't use default description
end
if target ~= nil then
if target.type == 1 and getPlayerName(target.uid) == "Zeus" then
doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, "You are looking to the sexy Zeus ;)")
elseif target.type == 3 then
doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, "That is a NPC. His name is "..getCreatureName(target.uid)..".")
elseif target.type == 2 then
doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, "This is a monster. It wants to kill you, muahahaha!")
elseif target.itemid == 2676 then
--as target isn't nil, it won't appear for bananas inside of a npc window shop
doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, "Yummy banana!")
else
return true --use default description
end
else
return true --use default description
end
return false --don't use default description
end | gpl-2.0 |
eugeneia/snabbswitch | src/program/snsh/snsh.lua | 4 | 4449 | -- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local lib = require("core.lib")
local usage = require("program.snsh.README_inc")
local long_opts = {
["package-path"] = "P",
eval = "e",
load = "l",
program = "p",
test = "t",
interactive = "i",
debug = "d",
jit = "j",
sigquit = "q",
help = "h",
}
function run (parameters)
local profiling = false
local traceprofiling = false
local start_repl = false
local noop = true -- are we doing nothing?
local program -- should we run a different program?
-- Table of functions implementing command-line arguments
local opt = {}
function opt.h (arg) print(usage) main.exit(0) end
function opt.l (arg) require(arg) noop = false end
function opt.t (arg) require(arg).selftest() noop = false end
function opt.q (arg) hook_sigquit(arg) end
function opt.d (arg) _G.developer_debug = true end
function opt.p (arg) program = arg end
function opt.i (arg) start_repl = true noop = false end
function opt.j (arg)
if arg:match("^v") then
local file = arg:match("^v=(.*)")
if file == '' then file = nil end
require("jit.v").start(file)
elseif arg:match("^p") then
local opts, file = arg:match("^p=([^,]*),?(.*)")
if file == '' then file = nil end
require("jit.p").start(opts, file)
profiling = true
elseif arg:match("^dump") then
local opts, file = arg:match("^dump=([^,]*),?(.*)")
if file == '' then file = nil end
require("jit.dump").on(opts, file)
elseif arg:match("^tprof") then
require("lib.traceprof.traceprof").start()
traceprofiling = true
end
end
function opt.e (arg)
local thunk, error = loadstring(arg)
if thunk then thunk() else print(error) end
noop = false
end
function opt.P (arg)
package.path = arg
end
-- Execute command line arguments
parameters = lib.dogetopt(parameters, opt, "hl:p:t:die:j:P:q:", long_opts)
if program then
local mod = (("program.%s.%s"):format(program, program))
require(mod).run(parameters)
elseif #parameters > 0 then
run_script(parameters)
elseif noop then
print(usage)
main.exit(1)
end
if start_repl then repl() end
if profiling then require("jit.p").stop() end
if traceprofiling then
require("lib.traceprof.traceprof").stop()
end
end
function run_script (parameters)
local command = table.remove(parameters, 1)
main.parameters = parameters -- make remaining args available to script
dofile(command)
end
-- This is a simple REPL similar to LuaJIT's built-in REPL. It can only
-- read single-line statements but does support the `=<expr>' syntax.
function repl ()
local line = nil
local function eval_line ()
if line:sub(0,1) == "=" then
-- Evaluate line as expression.
print(loadstring("return "..line:sub(2))())
else
-- Evaluate line as statement
local load = loadstring(line)
if load then load() end
end
end
repeat
io.stdout:write("Snabb> ")
io.stdout:flush()
line = io.stdin:read("*l")
if line then
local status, err = pcall(eval_line)
if not status then
io.stdout:write(("Error in %s\n"):format(err))
end
io.stdout:flush()
end
until not line
end
-- Cause SIGQUIT to enter the REPL.
-- SIGQUIT can be triggered interactively with `Control \' in a terminal.
function hook_sigquit (action)
if action ~= 'repl' then
print("ignoring unrecognized SIGQUIT action: " .. action)
os.exit(1)
end
local S = require("syscall")
local fd = S.signalfd("quit", "nonblock") -- handle SIGQUIT via fd
S.sigprocmask("block", "quit") -- block traditional handler
local timer = require("core.timer")
timer.activate(timer.new("sigquit-repl",
function ()
if (#S.util.signalfd_read(fd) > 0) then
print("[snsh: SIGQUIT caught - entering REPL]")
repl()
end
end,
1e4,
'repeating'))
end
| apache-2.0 |
Fenix-XI/Fenix | scripts/globals/weaponskills/hard_slash.lua | 11 | 1603 | -----------------------------------
-- Hard Slash
-- Great Sword weapon skill
-- Skill level: 5
-- Delivers a single-hit attack. Damage varies with TP.
-- Modifiers: STR:30%
-- 100%TP 200%TP 300%TP
-- 1.5 1.75 2.0
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.numHits = 1;
-- ftp damage mods (for Damage Varies with TP; lines are calculated in the function
params.ftp100 = 1.5; params.ftp200 = 1.75; params.ftp300 = 2.0;
-- wscs are in % so 0.2=20%
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
-- critical mods, again in % (ONLY USE FOR params.critICAL HIT VARIES WITH TP)
params.crit100 = 0.0; params.crit200=0.0; params.crit300=0.0;
params.canCrit = false;
-- accuracy mods (ONLY USE FOR accURACY VARIES WITH TP) , should be the acc at those %s NOT the penalty values. Leave 0 if acc doesnt vary with tp.
params.acc100 = 0; params.acc200=0; params.acc300=0;
-- attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default.
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 1.0;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
tcatm/luci | applications/luci-app-wshaper/luasrc/model/cbi/wshaper.lua | 56 | 1848 | -- Copyright 2011 Manuel Munz <freifunk at somakoma dot de>
-- Licensed to the public under the Apache License 2.0.
require("luci.tools.webadmin")
m = Map("wshaper", translate("Wondershaper"),
translate("Wondershaper shapes traffic to ensure low latencies for interactive traffic even when your " ..
"internet connection is highly saturated."))
s = m:section(NamedSection, "settings", "wshaper", translate("Wondershaper settings"))
s.anonymous = true
network = s:option(ListValue, "network", translate("Interface"))
luci.tools.webadmin.cbi_add_networks(network)
uplink = s:option(Value, "uplink", translate("Uplink"), translate("Upstream bandwidth in kbit/s"))
uplink.optional = false
uplink.datatype = "uinteger"
uplink.default = "240"
uplink = s:option(Value, "downlink", translate("Downlink"), translate("Downstream bandwidth in kbit/s"))
uplink.optional = false
uplink.datatype = "uinteger"
uplink.default = "200"
nopriohostsrc = s:option(DynamicList, "nopriohostsrc", translate("Low priority hosts (Source)"), translate("Host or Network in CIDR notation."))
nopriohostsrc.optional = true
nopriohostsrc.datatype = ipaddr
nopriohostsrc.placeholder = "10.0.0.1/32"
nopriohostdst = s:option(DynamicList, "nopriohostdst", translate("Low priority hosts (Destination)"), translate("Host or Network in CIDR notation."))
nopriohostdst.optional = true
nopriohostdst.datatype = ipaddr
nopriohostdst.placeholder = "10.0.0.1/32"
noprioportsrc = s:option(DynamicList, "noprioportsrc", translate("Low priority source ports"))
noprioportsrc.optional = true
noprioportsrc.datatype = "range(0,65535)"
noprioportsrc.placeholder = "21"
noprioportdst = s:option(DynamicList, "noprioportdst", translate("Low priority destination ports"))
noprioportdst.optional = true
noprioportdst.datatype = "range(0,65535)"
noprioportdst.placeholder = "21"
return m
| apache-2.0 |
mozilla-services/data-pipeline | heka/sandbox/filters/firefox_executive_report.lua | 4 | 9338 | -- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
--[[
Firefox Executive Report
*Example Heka Configuration*
.. code-block:: ini
[FirefoxExecutiveReport]
type = "SandboxFilter"
filename = "lua_filters/firefox_executive_report.lua"
message_matcher = "Logger == 'fx' && Type == 'executive_summary' && Fields[vendor] == 'Mozilla' && Fields[app] == 'Firefox'"
output_limit = 0
memory_limit = 0
ticker_interval = 0
preserve_data = false
timer_event_on_shutdown = true
[FirefoxExecutiveReport.config]
items = 100000000
# rollup_interval = "day" # day|week|month
# rollup_os = "Windows" # this will rollup the Windows OS versions (set the message_matcher accordingly)
# finalize_on_exit = false # forces the current interval (most likely incomplete data) to be rolled up
--]]
_PRESERVATION_VERSION = 2
fx = require "fx" -- this must be global when we are pulling in other fx submodules
require "fx.executive_report"
require "math"
require "os"
require "string"
require "table"
local DAYS = 31
local WEEKS = 52
local MONTHS = 12
local DAY_OFFSET = 4 -- start the week on Sunday and correct for the Unix epoch landing on a Thursday
local SEC_IN_DAY = 60 * 60 * 24
local SEC_IN_WEEK = SEC_IN_DAY * 7
local items = read_config("items") or 1000
local rollup_os = read_config("rollup_os")
local rollup_interval = read_config("rollup_interval") or "day"
local finalize_on_exit = read_config("finalize_on_exit")
local floor = math.floor
local date = os.date
local format = string.format
fx_cids = fx.executive_report.new(items)
intervals = {}
current_day = -1
current_interval = -1
current_interval_ts = -1
local get_os_id
local get_os_name
if rollup_os == "Windows" then
get_os_id = function() return fx.get_os_win_id(read_message("Fields[osVersion]")) end
get_os_name = fx.get_os_win_name
else
get_os_id = function() return fx.get_os_id(read_message("Fields[os]")) end
get_os_name = fx.get_os_name
end
local function get_row(interval, time_t_fmt, time_t)
local country = fx.get_country_id(read_message("Fields[country]"))
local channel = fx.get_channel_id(read_message("Fields[channel]"))
local _os = get_os_id()
local partition = format("%d,%d,%d", country, channel, _os)
local r = interval[partition]
if not r then
local time_str = date(time_t_fmt, time_t)
-- date, actives, hours, inactives, new_records, five_of_seven, total_records, crashes, default, google, bing, yahoo, other
r = {time_str, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
interval[partition] = r
end
return r, country, channel, _os
end
local function update_row(r, cid, country, channel, _os, dow)
local dflt = fx.get_boolean_value(read_message("Fields[default]"))
local pct = read_message("Fields[profileCreationTimestamp]")
if type(pct) ~= "number" then pct = 0 end
fx_cids:add(cid, country, channel, _os, dow, dflt, pct >= current_interval_ts)
local doc_type = read_message("Fields[docType]")
if doc_type == "main" then
r[3] = r[3] + (tonumber(read_message("Fields[hours]")) or 0)
r[10] = r[10] + (tonumber(read_message("Fields[google]")) or 0)
r[11] = r[11] + (tonumber(read_message("Fields[bing]")) or 0)
r[12] = r[12] + (tonumber(read_message("Fields[yahoo]")) or 0)
r[13] = r[13] + (tonumber(read_message("Fields[other]")) or 0)
elseif doc_type == "crash" then
local num_crashes = read_message("Fields[crashes]")
-- If field is missing, assume one crash per record.
if num_crashes == nil then
num_crashes = 1
end
-- If field contains an unexpected value, assume zero crashes.
if type(num_crashes) ~= "number" or num_crashes < 0 then
num_crashes = 0
end
r[8] = r[8] + num_crashes
end
end
local function clear_intervals(s, e, size)
for i = s + 1, e do
local idx = i % size + 1
intervals[idx] = {}
end
current_interval = e
end
local function set_day_interval_ts(day)
current_interval_ts = day * SEC_IN_DAY * 1e9
end
local function update_day(ts, cid, day)
if current_interval == -1 then
current_interval = day
set_day_interval_ts(day)
end
local delta = day - current_interval
if delta > 0 and delta < DAYS then
fx_cids:report(intervals[current_interval % DAYS + 1])
clear_intervals(current_interval, day, DAYS)
set_day_interval_ts(day)
elseif delta >= DAYS then
error(string.format("data gap over %d days", DAYS))
end
local t = intervals[day % DAYS + 1]
local r, country, channel, _os = get_row(t, "%Y-%m-%d", ts / 1e9)
if r then
update_row(r, cid, country, channel, _os, 0)
end
end
local function set_week_interval_ts(week)
current_interval_ts = (week * SEC_IN_WEEK - (SEC_IN_DAY * DAY_OFFSET)) * 1e9
end
local function update_week(_, cid, day)
local week = floor((day + DAY_OFFSET) / 7)
if current_interval == -1 then
current_interval = week
set_week_interval_ts(week)
end
local delta = week - current_interval
if delta > 0 and delta < WEEKS then
fx_cids:report(intervals[current_interval % WEEKS + 1])
clear_intervals(current_interval, week, WEEKS)
set_week_interval_ts(week)
elseif delta >= WEEKS then
error(string.format("data gap over %d weeks", WEEKS))
end
local interval = intervals[week % WEEKS + 1]
local r, country, channel, _os = get_row(interval, "%Y-%m-%d", week * SEC_IN_WEEK - (DAY_OFFSET * SEC_IN_DAY))
if r then
-- The use of submission date changes the meaning of the day of the week
-- calculation, it now represents the days the user interacted with the
-- telemetry system. The V2 analysis reported on the user provided date
-- which is activityTimestamp in the executive summary.
-- See: https://docs.google.com/document/d/1mLP4DY-FIQHof6Nxh2ioVQ-ZvvlnIZ_6yLqYp8idXG4
update_row(r, cid, country, channel, _os, (day + DAY_OFFSET) % 7)
end
end
local function set_month_interval_ts(year, month)
current_interval_ts = os.time({year = year, month = month, day = 1}) * 1e9
end
local function update_month(ts, cid, _, day_changed)
local month = current_interval
local t
if current_interval == -1 or day_changed then
t = date("*t", ts / 1e9)
month = (tonumber(t.year) - 1) * 12 + tonumber(t.month)
if current_interval == -1 then
current_interval = month
set_month_interval_ts(t.year, t.month)
end
end
local delta = month - current_interval
if delta > 0 and delta < MONTHS then
fx_cids:report(intervals[current_interval % MONTHS + 1])
clear_intervals(current_interval, month, MONTHS)
set_month_interval_ts(t.year, t.month)
elseif delta >= MONTHS then
error(string.format("data gap over %d months", MONTHS))
end
local t = intervals[month % MONTHS + 1]
local r, country, channel, _os = get_row(t, "%Y-%m-01", ts / 1e9)
if r then
update_row(r, cid, country, channel, _os, 0)
end
end
local update_interval
if rollup_interval == "day" then
for i=1, DAYS do
intervals[i] = {}
end
update_interval = update_day
elseif rollup_interval == "week" then
for i=1, WEEKS do
intervals[i] = {}
end
update_interval = update_week
elseif rollup_interval == "month" then
for i=1, MONTHS do
intervals[i] = {}
end
update_interval = update_month
else
error("invalid rollup_interval: " .. rollup_interval)
end
----
function process_message()
local ts = read_message("Timestamp") -- use the submission date https://docs.google.com/document/d/1mLP4DY-FIQHof6Nxh2ioVQ-ZvvlnIZ_6yLqYp8idXG4
local cid = read_message("Fields[clientId]")
if type(cid) == "string" then
local day = floor(ts / (SEC_IN_DAY * 1e9))
local day_changed = day ~= current_day
if day < current_day then
error("data is in the past, this report doesn't back fill")
end
current_day = day
update_interval(ts, cid, day, day_changed)
end
return 0
end
function timer_event(ns)
if current_interval == -1 then return end
if finalize_on_exit then
fx_cids:report(intervals[current_interval % #intervals + 1])
end
add_to_payload("geo,channel,os,date,actives,hours,inactives,new_records,five_of_seven,total_records,crashes,default,google,bing,yahoo,other\n")
local country, channel, _os
for i,t in ipairs(intervals) do
for k,v in pairs(t) do
country, channel, _os = k:match("(%d+),(%d+),(%d+)")
add_to_payload(fx.get_country_name(tonumber(country)), ",",
fx.get_channel_name(tonumber(channel)), ",",
get_os_name(tonumber(_os)), ",",
table.concat(v, ","), "\n")
end
end
inject_payload("csv", rollup_interval)
end
| mpl-2.0 |
Fenix-XI/Fenix | scripts/zones/Southern_San_dOria_[S]/npcs/Achtelle.lua | 38 | 1029 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Achtelle
-- @zone 80
-- @pos 108 2 -11
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--player:startEvent(0x01FE); Event doesnt work but this is her default dialogue, threw in something below til it gets fixed
player:showText(npc, 13454); -- (Couldn't find default dialogue) How very good to see you again!
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 |
Fenix-XI/Fenix | scripts/zones/Southern_San_dOria_[S]/npcs/Achtelle1.lua | 38 | 1029 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Achtelle
-- @zone 80
-- @pos 108 2 -11
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--player:startEvent(0x01FE); Event doesnt work but this is her default dialogue, threw in something below til it gets fixed
player:showText(npc, 13454); -- (Couldn't find default dialogue) How very good to see you again!
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 |
wangg12/fbcunn | examples/imagenet/opts.lua | 8 | 2711 | --
-- Copyright (c) 2014, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
local M = { }
function M.parse(arg)
local defaultDir = paths.concat(os.getenv('HOME'), 'fbcunn_imagenet')
local cmd = torch.CmdLine()
cmd:text()
cmd:text('Torch-7 Imagenet Training script')
cmd:text()
cmd:text('Options:')
------------ General options --------------------
cmd:option('-cache',
defaultDir ..'/imagenet_runs',
'subdirectory in which to save/log experiments')
cmd:option('-data',
defaultDir .. '/imagenet_raw_images/256',
'Home of ImageNet dataset')
cmd:option('-manualSeed', 2, 'Manually set RNG seed')
cmd:option('-GPU', 1, 'Default preferred GPU')
cmd:option('-nGPU', 1, 'Number of GPUs to use by default')
cmd:option('-backend', 'cudnn', 'Options: cudnn | fbcunn | cunn')
------------- Data options ------------------------
cmd:option('-nDonkeys', 2, 'number of donkeys to initialize (data loading threads)')
------------- Training options --------------------
cmd:option('-nEpochs', 55, 'Number of total epochs to run')
cmd:option('-epochSize', 10000, 'Number of batches per epoch')
cmd:option('-epochNumber', 1, 'Manual epoch number (useful on restarts)')
cmd:option('-batchSize', 128, 'mini-batch size (1 = pure stochastic)')
cmd:option('-testBatchSize', 12, 'mini-batch size for testing')
---------- Optimization options ----------------------
cmd:option('-LR', 0.0, 'learning rate; if set, overrides default LR/WD recipe')
cmd:option('-momentum', 0.9, 'momentum')
cmd:option('-weightDecay', 5e-4, 'weight decay')
---------- Model options ----------------------------------
cmd:option('-netType', 'alexnet', 'Options: alexnet | overfeat')
cmd:option('-retrain', 'none', 'provide path to model to retrain with')
cmd:option('-optimState', 'none', 'provide path to an optimState to reload from')
cmd:text()
local opt = cmd:parse(arg or {})
-- add commandline specified options
opt.save = paths.concat(opt.cache,
cmd:string('alexnet12', opt,
{retrain=true, optimState=true, cache=true, data=true}))
-- add date/time
opt.save = paths.concat(opt.save, ',' .. os.date():gsub(' ',''))
return opt
end
return M
| bsd-3-clause |
erics1989/lurk | terrain.lua | 1 | 8498 |
-- terrain data
_database = _database or {}
_database.terrain_question = {
name = "?",
bcolor = { 32, 32, 32 },
color = { 64, 64, 64 },
character = "?",
sprite = { file = "resource/sprite/Interface.png", x = 2, y = 3 },
}
_database.terrain_dot = {
name = "dirt",
bcolor = color_constants.base03,
color = { 88, 110, 117 },
character = ".",
sprite = { file = "resource/sprite/Terrain_Objects.png", x = 8, y = 0 },
sense = true,
stand = true
}
_database.terrain_foliage = {
name = "foliage",
bcolor = color_constants.base03,
color = { 133, 153, 0 },
character = ",",
sprite = { file = "resource/sprite/Terrain_Objects.png", x = 0, y = 10 },
sense = true, stand = true, burn = true, plant = true,
}
_database.terrain_dense_foliage = {
name = "dense foliage",
bcolor = color_constants.base03,
color = { 133, 153, 0 },
character = ";",
sprite = { file = "resource/sprite/Terrain_Objects.png", x = 1, y = 10 },
sense = true, stand = true, burn = true, plant = true,
person_terrain_postact = function (person, terrain)
if not person.status_cover_foliage then
local status = game.data_init("status_cover_foliage")
game.person_status_enter(person, status)
end
end,
object_terrain_postact = function (object, terrain)
if not object.status_cover_foliage then
local status = game.data_init("status_cover_foliage")
game.object_status_enter(object, status)
end
end
}
_database.terrain_tree = {
name = "tree",
bcolor = color_constants.base03,
color = { 133, 153, 0 },
character = "&",
sprite = { file = "resource/sprite/Terrain_Objects.png", x = 3, y = 10 },
stand = true, burn = true, plant = true,
person_terrain_postact = function (person, terrain)
if not person.status_cover_tree then
local status = game.data_init("status_cover_tree")
game.person_status_enter(person, status)
end
end,
object_terrain_postact = function (object, terrain)
if not object.status_cover_tree then
local status = game.data_init("status_cover_tree")
game.object_status_enter(object, status)
end
end
}
_database.terrain_fire = {
name = "fire",
bcolor = color_constants.base03,
color = { 203, 75, 22 },
character = "^",
sprite = { file = "resource/sprite/FX_General.png", x = 12, y = 1 },
sprite2 = { file = "resource/sprite/FX_General.png", x = 13, y = 1 },
sense = true, stand = true, fire = true,
init = function (terrain)
terrain.counters = 8
end,
act = function (terrain)
if _state.turn % 2 == 0 then
local f = function (space)
return game.data(space.terrain).burn
end
spaces = List.filter(Hex.adjacent(terrain.space), f)
for _, space in ipairs(spaces) do
game.terrain_exit(space.terrain)
game.terrain_enter(
game.data_init("terrain_fire"),
space
)
end
end
terrain.counters = terrain.counters - 1
if terrain.counters == 0 then
local space = terrain.space
game.terrain_exit(terrain)
game.terrain_enter(
game.data_init("terrain_dot"),
space
)
else
table.insert(_state.map.events, terrain)
end
end,
person_terrain_postact = function (person, terrain)
if game.person_sense(_state.hero, person) then
local str = string.format(
game.data(person).plural and
"%s burn." or
"%s burns.",
grammar.cap(grammar.the(game.data(person).name))
)
game.print(str)
end
game.person_damage(person, 1)
end
}
_database.terrain_water = {
name = "water",
bcolor = color_constants.blue,
color = { 88, 110, 117 },
character = "~",
sprite = { file = "resource/sprite/Terrain_Objects.png", x = 8, y = 0 },
sense = true, stand = true, water = true,
person_terrain_postact = function (person, terrain)
if not person.status_underwater then
local status = game.data_init("status_underwater")
game.person_status_enter(person, status)
end
end,
object_terrain_postact = function (object, terrain)
if not object.status_underwater then
local status = game.data_init("status_underwater")
game.object_status_enter(object, status)
end
end
}
_database.terrain_water2 = {
name = "water",
bcolor = color_constants.blue,
color = color_constants.green,
character = "~",
sprite = { file = "resource/sprite/Terrain_Objects.png", x = 0, y = 11 },
sprite2 = { file = "resource/sprite/Terrain_Objects.png", x = 1, y = 11 },
sense = true, stand = true, water = true,
person_terrain_postact = function (person, terrain)
if not person.status_underwater then
local status = game.data_init("status_underwater")
game.person_status_enter(person, status)
end
end,
object_terrain_postact = function (object, terrain)
if not object.status_underwater then
local status = game.data_init("status_underwater")
game.object_status_enter(object, status)
end
end
}
_database.terrain_stone = {
name = "stone",
bcolor = { 131, 148, 150 },
color = { 88, 110, 117 },
character = "#",
sprite = { file = "resource/sprite/Terrain.png", x = 12, y = 0 },
}
_database.terrain_stairs_up = {
name = "stairs",
bcolor = { 0, 43, 54 },
color = { 255, 255, 255 },
character = "<",
sprite = { file = "resource/sprite/Terrain.png", x = 15, y = 1 },
sense = true,
stand = true,
on_person_relocate = function (person, terrain)
if person == _state.hero then
_state.hero.stairs = function ()
game.print("You ascend the stairs.")
local stairs_dn = List.filter(
_state.map.spaces,
function (space)
return space.terrain.id == "terrain_stairs_dn"
end
)
game.person_enter(_state.hero, stairs_dn[1])
end
end
end
}
_database.terrain_stairs_dn = {
name = "stairs",
bcolor = { 0, 43, 54 },
color = { 255, 255, 255 },
character = ">",
sprite = { file = "resource/sprite/Terrain.png", x = 14, y = 1 },
sense = true,
stand = true,
on_person_relocate = function (person, terrain)
if person == _state.hero then
_state.hero.stairs = function ()
game.print("You ascend the stairs.")
local stairs_up = List.filter(
_state.map.spaces,
function (space)
return space.terrain.id == "terrain_stairs_up"
end
)
game.person_enter(_state.hero, stairs_up[1])
end
end
end
}
_database.terrain_chasm = {
name = "chasm",
bcolor = color_constants.min,
color = color_constants.base03,
character = " ",
sense = true, stand = true,
enter = function (terrain)
game.print("You fall into the chasm.")
local x = terrain.space.x
local y = terrain.space.y
game.person_fall(_state.hero, x, y)
game.person_damage(_state.hero, 1)
end,
person_terrain_postact = function (person, terrain)
if person == _state.hero then
_state.hero.door = true
else
game.print("The person falls.")
local x = person.space.x
local y = person.space.y
game.person_exit(person)
local f = function ()
game.person_fall(person, x, y)
end
local door = terrain.door
game.postpone(door.name, door.n, f)
end
end,
object_terrain_postact = function (object, terrain)
local x = object.space.x
local y = object.space.y
game.object_exit(object)
local f = function ()
game.object_fall(object, x, y)
end
local door = terrain.door
game.postpone(door.name, door.n, f)
end
}
| gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Cloister_of_Storms/bcnms/trial_by_lightning.lua | 8 | 1535 | -----------------------------------
-- Area: Cloister of Storms
-- BCNM: Trial by Lightning
-----------------------------------
local ID = require("scripts/zones/Cloister_of_Storms/IDs")
require("scripts/globals/battlefield")
require("scripts/globals/keyitems")
require("scripts/globals/quests")
require("scripts/globals/titles")
-----------------------------------
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
local arg8 = (player:hasCompletedQuest(OTHER_AREAS_LOG, dsp.quest.id.otherAreas.TRIAL_BY_LIGHTNING)) and 1 or 0
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), arg8)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 32001 then
player:delKeyItem(dsp.ki.TUNING_FORK_OF_LIGHTNING)
player:addKeyItem(dsp.ki.WHISPER_OF_STORMS)
player:addTitle(dsp.title.HEIR_OF_THE_GREAT_LIGHTNING)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.WHISPER_OF_STORMS)
end
end
| gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Uleguerand_Range/Zone.lua | 6 | 2047 | -----------------------------------
--
-- Zone: Uleguerand_Range (5)
--
-----------------------------------
local ID = require("scripts/zones/Uleguerand_Range/IDs");
require("scripts/globals/conquest");
require("scripts/globals/missions");
require("scripts/globals/weather");
require("scripts/globals/status");
require("scripts/globals/zone");
-----------------------------------
function onInitialize(zone)
UpdateNMSpawnPoint(ID.mob.JORMUNGAND);
GetMobByID(ID.mob.JORMUNGAND):setRespawnTime(math.random(86400, 259200));
-- ffxiclopedia's pages for Black Coney and White Coney say 7 and 5 Earth seconds respectively, in game it is very fast
-- https://ffxiclopedia.fandom.com/wiki/Black_Coney
-- https://ffxiclopedia.fandom.com/wiki/White_Coney
-- BG Wiki has no info. For now, triggers every 3 vana minutes
GetNPCByID(ID.npc.RABBIT_FOOTPRINT):addPeriodicTrigger(0,3,0)
end
function onConquestUpdate(zone, updatetype)
dsp.conq.onConquestUpdate(zone, updatetype)
end;
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(363.025,16,-60,12);
end
if (player:getCurrentMission(COP) == dsp.mission.id.cop.DAWN and player:getCharVar("COP_louverance_story")== 1 ) then
cs=17;
end
return cs;
end;
function onRegionEnter(player,region)
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 17) then
player:setCharVar("COP_louverance_story",2);
end
end;
function onZoneWeatherChange(weather)
local waterfall = GetNPCByID(ID.npc.WATERFALL);
if (weather == dsp.weather.SNOW or weather == dsp.weather.BLIZZARDS) then
if (waterfall:getAnimation() ~= dsp.anim.CLOSE_DOOR) then
waterfall:setAnimation(dsp.anim.CLOSE_DOOR);
end
else
if (waterfall:getAnimation() ~= dsp.anim.OPEN_DOOR) then
waterfall:setAnimation(dsp.anim.OPEN_DOOR);
end
end
end;
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Temenos/mobs/Temenos_Aern.lua | 7 | 2346 | -----------------------------------
-- Area: Temenos
-- NPC: Temenos_Aern
-----------------------------------
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)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
local mobID = mob:getID();
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
switch (mobID): caseof {
[16929054] = function (x)
GetNPCByID(16928768+197):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+197):setStatus(STATUS_NORMAL);
end,
[16929060] = function (x)
GetNPCByID(16928768+199):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+199):setStatus(STATUS_NORMAL);
end,
[16929065] = function (x)
GetNPCByID(16928768+200):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+200):setStatus(STATUS_NORMAL);
end,
[16929075] = function (x)
GetNPCByID(16928768+201):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+201):setStatus(STATUS_NORMAL);
end,
[16929083] = function (x)
GetNPCByID(16928768+202):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+202):setStatus(STATUS_NORMAL);
end,
}
local leftAern=0;
local AernList = {16929053,16929054,16929055,16929057,16929058,16929060,16929061,16929062,16929063,
16929064,16929065,16929066,16929069,16929071,16929072,16929073,16929075,16929076,
16929077,16929078,16929079,16929082,16929083,16929084,16929085,16929086,16929087};
for n=1,27,1 do
if ( IsMobDead(AernList[n]) == false) then
leftAern=leftAern+1;
end
end
--print("leftAern" ..leftAern);
if (leftAern == 0) then
GetMobByID(16929088):setSpawn(mobX,mobY,mobZ);
GetMobByID(16929088):setPos(mobX,mobY,mobZ);
SpawnMob(16929088):updateEnmity(killer);
end
end; | gpl-3.0 |
eugeneia/snabbswitch | lib/ljsyscall/syscall/linux/arm/ffi.lua | 25 | 1602 | -- arm specific definitions
return {
ucontext = [[
typedef int greg_t, gregset_t[18];
typedef struct sigcontext {
unsigned long trap_no, error_code, oldmask;
unsigned long arm_r0, arm_r1, arm_r2, arm_r3;
unsigned long arm_r4, arm_r5, arm_r6, arm_r7;
unsigned long arm_r8, arm_r9, arm_r10, arm_fp;
unsigned long arm_ip, arm_sp, arm_lr, arm_pc;
unsigned long arm_cpsr, fault_address;
} mcontext_t;
typedef struct __ucontext {
unsigned long uc_flags;
struct __ucontext *uc_link;
stack_t uc_stack;
mcontext_t uc_mcontext;
sigset_t uc_sigmask;
unsigned long long uc_regspace[64];
} ucontext_t;
]],
stat = [[
struct stat {
unsigned long long st_dev;
unsigned char __pad0[4];
unsigned long __st_ino;
unsigned int st_mode;
unsigned int st_nlink;
unsigned long st_uid;
unsigned long st_gid;
unsigned long long st_rdev;
unsigned char __pad3[4];
long long st_size;
unsigned long st_blksize;
unsigned long long st_blocks;
unsigned long st_atime;
unsigned long st_atime_nsec;
unsigned long st_mtime;
unsigned int st_mtime_nsec;
unsigned long st_ctime;
unsigned long st_ctime_nsec;
unsigned long long st_ino;
};
]],
statfs = [[
typedef uint32_t statfs_word;
struct statfs64 {
statfs_word f_type;
statfs_word f_bsize;
uint64_t f_blocks;
uint64_t f_bfree;
uint64_t f_bavail;
uint64_t f_files;
uint64_t f_ffree;
kernel_fsid_t f_fsid;
statfs_word f_namelen;
statfs_word f_frsize;
statfs_word f_flags;
statfs_word f_spare[4];
} __attribute__((packed,aligned(4)));
]],
}
| apache-2.0 |
DarkstarProject/darkstar | scripts/globals/weaponskills/cloudsplitter.lua | 10 | 1577 | -----------------------------------
-- Cloudsplitter
-- Axe weapon skill
-- Skill level: NA
-- Description: Deals lightning elemental damage. Damage varies with TP. Farsha: Aftermath.
-- Available only when equipped with Farsha (85), Farsha (90) or Alard's Axe +1.
-- Elemental gorgets do not affect damage. Rairin Obi increases damage on Lightning day and/or weather.
-- Element: Lightning
-- Modifiers: STR:40% MND:40%
-- 100%TP 200%TP 300%TP
-- 3.75 5.0 6.0
-----------------------------------
require("scripts/globals/aftermath")
require("scripts/globals/magic")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.ftp100 = 3.75 params.ftp200 = 5.0 params.ftp300 = 6.0
params.str_wsc = 0.4 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0 params.mnd_wsc = 0.4 params.chr_wsc = 0.0
params.ele = dsp.magic.ele.LIGHTNING
params.skill = dsp.skill.AXE
params.includemab = true
if USE_ADOULIN_WEAPON_SKILL_CHANGES then
params.ftp200 = 6.7 params.ftp300 = 8.5
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, action, primary)
-- Apply aftermath
if damage > 0 then
dsp.aftermath.addStatusEffect(player, tp, dsp.slot.MAIN, dsp.aftermath.type.EMPYREAN)
end
return tpHits, extraHits, criticalHit, damage
end | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/RuLude_Gardens/npcs/Magian_Moogle_Blue.lua | 48 | 1855 | -----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: Magian Moogle (Blue Bobble)
-- Type: Magian Trials NPC (Relic Armor)
-- @pos -6.843 2.459 121.9 64
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
package.loaded["scripts/globals/magiantrials"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/RuLude_Gardens/TextIDs");
require("scripts/globals/magiantrials");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1) then
local ItemID = trade:getItem();
local TrialInfo = getRelicTrialInfo(ItemID);
local invalid = 0;
if (TrialInfo.t1 == 0 and TrialInfo.t2 == 0 and TrialInfo.t3 == 0 and TrialInfo.t4 == 0) then
invalid = 1;
end
player:startEvent(10143, TrialInfo.t1, TrialInfo.t2, TrialInfo.t3, TrialInfo.t4, 0, ItemID, 0, invalid);
else
-- placeholder for multi item trades such as "Forgotten Hope" etc.
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(MAGIAN_TRIAL_LOG) == false) then
player:startEvent(10141);
else
player:startEvent(10142); -- parameters unknown
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 |
ungarscool1/HL2RP | hl2rp/gamemode/modules/hitmenu/sh_init.lua | 5 | 3128 | local plyMeta = FindMetaTable("Player")
local hitmanTeams = {}
function plyMeta:isHitman()
return hitmanTeams[self:Team()]
end
function plyMeta:hasHit()
return self:getDarkRPVar("hasHit") or false
end
function plyMeta:getHitTarget()
return self:getDarkRPVar("hitTarget")
end
function plyMeta:getHitPrice()
return self:getDarkRPVar("hitPrice") or GAMEMODE.Config.minHitPrice
end
function DarkRP.addHitmanTeam(job)
if not job or not RPExtraTeams[job] then return end
if DarkRP.DARKRP_LOADING and DarkRP.disabledDefaults["hitmen"][RPExtraTeams[job].command] then return end
hitmanTeams[job] = true
end
DarkRP.getHitmanTeams = fp{fn.Id, hitmanTeams}
function DarkRP.hooks:canRequestHit(hitman, customer, target, price)
if not hitman:isHitman() then return false, DarkRP.getPhrase("player_not_hitman") end
if customer:GetPos():Distance(hitman:GetPos()) > GAMEMODE.Config.minHitDistance then return false, DarkRP.getPhrase("distance_too_big") end
if hitman == target then return false, DarkRP.getPhrase("hitman_no_suicide") end
if hitman == customer then return false, DarkRP.getPhrase("hitman_no_self_order") end
if not customer:canAfford(price) then return false, DarkRP.getPhrase("cant_afford", DarkRP.getPhrase("hit")) end
if price < GAMEMODE.Config.minHitPrice then return false, DarkRP.getPhrase("price_too_low") end
if hitman:hasHit() then return false, DarkRP.getPhrase("hitman_already_has_hit") end
if IsValid(target) and ((target:getDarkRPVar("lastHitTime") or -GAMEMODE.Config.hitTargetCooldown) > CurTime() - GAMEMODE.Config.hitTargetCooldown) then return false, DarkRP.getPhrase("hit_target_recently_killed_by_hit") end
if IsValid(customer) and ((customer.lastHitAccepted or -GAMEMODE.Config.hitCustomerCooldown) > CurTime() - GAMEMODE.Config.hitCustomerCooldown) then return false, DarkRP.getPhrase("customer_recently_bought_hit") end
return true
end
hook.Add("onJobRemoved", "hitmenuUpdate", function(i, job)
hitmanTeams[i] = nil
end)
/*---------------------------------------------------------------------------
DarkRPVars
---------------------------------------------------------------------------*/
DarkRP.registerDarkRPVar("hasHit", net.WriteBit, fn.Compose{tobool, net.ReadBit})
DarkRP.registerDarkRPVar("hitTarget", net.WriteEntity, net.ReadEntity)
DarkRP.registerDarkRPVar("hitPrice", fn.Curry(fn.Flip(net.WriteInt), 2)(32), fn.Partial(net.ReadInt, 32))
DarkRP.registerDarkRPVar("lastHitTime", fn.Curry(fn.Flip(net.WriteInt), 2)(32), fn.Partial(net.ReadInt, 32))
/*---------------------------------------------------------------------------
Chat commands
---------------------------------------------------------------------------*/
DarkRP.declareChatCommand{
command = "hitprice",
description = "Set the price of your hits",
condition = plyMeta.isHitman,
delay = 10
}
DarkRP.declareChatCommand{
command = "requesthit",
description = "Request a hit from the player you're looking at",
delay = 5,
condition = fn.Compose{fn.Not, fn.Null, fn.Curry(fn.Filter, 2)(plyMeta.isHitman), player.GetAll}
}
| agpl-3.0 |
Fenix-XI/Fenix | scripts/globals/weaponskills/refulgent_arrow.lua | 11 | 1425 | -----------------------------------
-- Refulgent Arrow
-- Archery weapon skill
-- Skill level: 290
-- Delivers a twofold attack. Damage varies with TP.
-- Aligned with the Aqua Gorget & Light Gorget.
-- Aligned with the Aqua Belt & Light Belt.
-- Element: None
-- Modifiers: STR: 60% http://www.bg-wiki.com/bg/Refulgent_Arrow
-- 100%TP 200%TP 300%TP
-- 3.00 4.25 7.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.numHits = 2;
params.ftp100 = 3; params.ftp200 = 4.25; params.ftp300 = 5;
params.str_wsc = 0.16; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.25; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 3; params.ftp200 = 4.25; params.ftp300 = 7;
params.str_wsc = 0.6;
end
local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, wsID, params, tp, primary);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
DarkstarProject/darkstar | scripts/globals/items/sleep_bolt.lua | 12 | 1175 | -----------------------------------------
-- ID: 18149
-- Item: Sleep Bolt
-- Additional Effect: Sleep
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/magic")
require("scripts/globals/msg")
-----------------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 95
if (target:getMainLvl() > player:getMainLvl()) then
chance = chance - 5 * (target:getMainLvl() - player:getMainLvl())
chance = utils.clamp(chance, 5, 95)
end
if (math.random(0,99) >= chance) then
return 0,0,0
else
local duration = 25
if (target:getMainLvl() > player:getMainLvl()) then
duration = duration - (target:getMainLvl() - player:getMainLvl())
end
duration = utils.clamp(duration,1,25)
duration = duration * applyResistanceAddEffect(player,target,dsp.magic.ele.LIGHT,0)
if (not target:hasStatusEffect(dsp.effect.SLEEP_I)) then
target:addStatusEffect(dsp.effect.SLEEP_I, 1, 0, duration)
end
return dsp.subEffect.SLEEP, dsp.msg.basic.ADD_EFFECT_STATUS, dsp.effect.SLEEP_I
end
end | gpl-3.0 |
dualface/killpests | src/framework/cocos2dx/OpenglConstants.lua | 78 | 27074 | --Encapsulate opengl constants.
gl = gl or {}
gl.GCCSO_SHADER_BINARY_FJ = 0x9260
gl._3DC_XY_AMD = 0x87fa
gl._3DC_X_AMD = 0x87f9
gl.ACTIVE_ATTRIBUTES = 0x8b89
gl.ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8b8a
gl.ACTIVE_PROGRAM_EXT = 0x8259
gl.ACTIVE_TEXTURE = 0x84e0
gl.ACTIVE_UNIFORMS = 0x8b86
gl.ACTIVE_UNIFORM_MAX_LENGTH = 0x8b87
gl.ALIASED_LINE_WIDTH_RANGE = 0x846e
gl.ALIASED_POINT_SIZE_RANGE = 0x846d
gl.ALL_COMPLETED_NV = 0x84f2
gl.ALL_SHADER_BITS_EXT = 0xffffffff
gl.ALPHA = 0x1906
gl.ALPHA16F_EXT = 0x881c
gl.ALPHA32F_EXT = 0x8816
gl.ALPHA8_EXT = 0x803c
gl.ALPHA8_OES = 0x803c
gl.ALPHA_BITS = 0xd55
gl.ALPHA_TEST_FUNC_QCOM = 0xbc1
gl.ALPHA_TEST_QCOM = 0xbc0
gl.ALPHA_TEST_REF_QCOM = 0xbc2
gl.ALREADY_SIGNALED_APPLE = 0x911a
gl.ALWAYS = 0x207
gl.AMD_compressed_3DC_texture = 0x1
gl.AMD_compressed_ATC_texture = 0x1
gl.AMD_performance_monitor = 0x1
gl.AMD_program_binary_Z400 = 0x1
gl.ANGLE_depth_texture = 0x1
gl.ANGLE_framebuffer_blit = 0x1
gl.ANGLE_framebuffer_multisample = 0x1
gl.ANGLE_instanced_arrays = 0x1
gl.ANGLE_pack_reverse_row_order = 0x1
gl.ANGLE_program_binary = 0x1
gl.ANGLE_texture_compression_dxt3 = 0x1
gl.ANGLE_texture_compression_dxt5 = 0x1
gl.ANGLE_texture_usage = 0x1
gl.ANGLE_translated_shader_source = 0x1
gl.ANY_SAMPLES_PASSED_CONSERVATIVE_EXT = 0x8d6a
gl.ANY_SAMPLES_PASSED_EXT = 0x8c2f
gl.APPLE_copy_texture_levels = 0x1
gl.APPLE_framebuffer_multisample = 0x1
gl.APPLE_rgb_422 = 0x1
gl.APPLE_sync = 0x1
gl.APPLE_texture_format_BGRA8888 = 0x1
gl.APPLE_texture_max_level = 0x1
gl.ARM_mali_program_binary = 0x1
gl.ARM_mali_shader_binary = 0x1
gl.ARM_rgba8 = 0x1
gl.ARRAY_BUFFER = 0x8892
gl.ARRAY_BUFFER_BINDING = 0x8894
gl.ATC_RGBA_EXPLICIT_ALPHA_AMD = 0x8c93
gl.ATC_RGBA_INTERPOLATED_ALPHA_AMD = 0x87ee
gl.ATC_RGB_AMD = 0x8c92
gl.ATTACHED_SHADERS = 0x8b85
gl.BACK = 0x405
gl.BGRA8_EXT = 0x93a1
gl.BGRA_EXT = 0x80e1
gl.BGRA_IMG = 0x80e1
gl.BINNING_CONTROL_HINT_QCOM = 0x8fb0
gl.BLEND = 0xbe2
gl.BLEND_COLOR = 0x8005
gl.BLEND_DST_ALPHA = 0x80ca
gl.BLEND_DST_RGB = 0x80c8
gl.BLEND_EQUATION = 0x8009
gl.BLEND_EQUATION_ALPHA = 0x883d
gl.BLEND_EQUATION_RGB = 0x8009
gl.BLEND_SRC_ALPHA = 0x80cb
gl.BLEND_SRC_RGB = 0x80c9
gl.BLUE_BITS = 0xd54
gl.BOOL = 0x8b56
gl.BOOL_VEC2 = 0x8b57
gl.BOOL_VEC3 = 0x8b58
gl.BOOL_VEC4 = 0x8b59
gl.BUFFER = 0x82e0
gl.BUFFER_ACCESS_OES = 0x88bb
gl.BUFFER_MAPPED_OES = 0x88bc
gl.BUFFER_MAP_POINTER_OES = 0x88bd
gl.BUFFER_OBJECT_EXT = 0x9151
gl.BUFFER_SIZE = 0x8764
gl.BUFFER_USAGE = 0x8765
gl.BYTE = 0x1400
gl.CCW = 0x901
gl.CLAMP_TO_BORDER_NV = 0x812d
gl.CLAMP_TO_EDGE = 0x812f
gl.COLOR_ATTACHMENT0 = 0x8ce0
gl.COLOR_ATTACHMENT0_NV = 0x8ce0
gl.COLOR_ATTACHMENT10_NV = 0x8cea
gl.COLOR_ATTACHMENT11_NV = 0x8ceb
gl.COLOR_ATTACHMENT12_NV = 0x8cec
gl.COLOR_ATTACHMENT13_NV = 0x8ced
gl.COLOR_ATTACHMENT14_NV = 0x8cee
gl.COLOR_ATTACHMENT15_NV = 0x8cef
gl.COLOR_ATTACHMENT1_NV = 0x8ce1
gl.COLOR_ATTACHMENT2_NV = 0x8ce2
gl.COLOR_ATTACHMENT3_NV = 0x8ce3
gl.COLOR_ATTACHMENT4_NV = 0x8ce4
gl.COLOR_ATTACHMENT5_NV = 0x8ce5
gl.COLOR_ATTACHMENT6_NV = 0x8ce6
gl.COLOR_ATTACHMENT7_NV = 0x8ce7
gl.COLOR_ATTACHMENT8_NV = 0x8ce8
gl.COLOR_ATTACHMENT9_NV = 0x8ce9
gl.COLOR_ATTACHMENT_EXT = 0x90f0
gl.COLOR_BUFFER_BIT = 0x4000
gl.COLOR_BUFFER_BIT0_QCOM = 0x1
gl.COLOR_BUFFER_BIT1_QCOM = 0x2
gl.COLOR_BUFFER_BIT2_QCOM = 0x4
gl.COLOR_BUFFER_BIT3_QCOM = 0x8
gl.COLOR_BUFFER_BIT4_QCOM = 0x10
gl.COLOR_BUFFER_BIT5_QCOM = 0x20
gl.COLOR_BUFFER_BIT6_QCOM = 0x40
gl.COLOR_BUFFER_BIT7_QCOM = 0x80
gl.COLOR_CLEAR_VALUE = 0xc22
gl.COLOR_EXT = 0x1800
gl.COLOR_WRITEMASK = 0xc23
gl.COMPARE_REF_TO_TEXTURE_EXT = 0x884e
gl.COMPILE_STATUS = 0x8b81
gl.COMPRESSED_RGBA_ASTC_10x10_KHR = 0x93bb
gl.COMPRESSED_RGBA_ASTC_10x5_KHR = 0x93b8
gl.COMPRESSED_RGBA_ASTC_10x6_KHR = 0x93b9
gl.COMPRESSED_RGBA_ASTC_10x8_KHR = 0x93ba
gl.COMPRESSED_RGBA_ASTC_12x10_KHR = 0x93bc
gl.COMPRESSED_RGBA_ASTC_12x12_KHR = 0x93bd
gl.COMPRESSED_RGBA_ASTC_4x4_KHR = 0x93b0
gl.COMPRESSED_RGBA_ASTC_5x4_KHR = 0x93b1
gl.COMPRESSED_RGBA_ASTC_5x5_KHR = 0x93b2
gl.COMPRESSED_RGBA_ASTC_6x5_KHR = 0x93b3
gl.COMPRESSED_RGBA_ASTC_6x6_KHR = 0x93b4
gl.COMPRESSED_RGBA_ASTC_8x5_KHR = 0x93b5
gl.COMPRESSED_RGBA_ASTC_8x6_KHR = 0x93b6
gl.COMPRESSED_RGBA_ASTC_8x8_KHR = 0x93b7
gl.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8c03
gl.COMPRESSED_RGBA_PVRTC_2BPPV2_IMG = 0x9137
gl.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8c02
gl.COMPRESSED_RGBA_PVRTC_4BPPV2_IMG = 0x9138
gl.COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83f1
gl.COMPRESSED_RGBA_S3TC_DXT3_ANGLE = 0x83f2
gl.COMPRESSED_RGBA_S3TC_DXT5_ANGLE = 0x83f3
gl.COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8c01
gl.COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8c00
gl.COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83f0
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR = 0x93db
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR = 0x93d8
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR = 0x93d9
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR = 0x93da
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR = 0x93dc
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR = 0x93dd
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 0x93d0
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR = 0x93d1
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR = 0x93d2
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR = 0x93d3
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR = 0x93d4
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR = 0x93d5
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR = 0x93d6
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR = 0x93d7
gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV = 0x8c4d
gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV = 0x8c4e
gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV = 0x8c4f
gl.COMPRESSED_SRGB_S3TC_DXT1_NV = 0x8c4c
gl.COMPRESSED_TEXTURE_FORMATS = 0x86a3
gl.CONDITION_SATISFIED_APPLE = 0x911c
gl.CONSTANT_ALPHA = 0x8003
gl.CONSTANT_COLOR = 0x8001
gl.CONTEXT_FLAG_DEBUG_BIT = 0x2
gl.CONTEXT_ROBUST_ACCESS_EXT = 0x90f3
gl.COUNTER_RANGE_AMD = 0x8bc1
gl.COUNTER_TYPE_AMD = 0x8bc0
gl.COVERAGE_ALL_FRAGMENTS_NV = 0x8ed5
gl.COVERAGE_ATTACHMENT_NV = 0x8ed2
gl.COVERAGE_AUTOMATIC_NV = 0x8ed7
gl.COVERAGE_BUFFERS_NV = 0x8ed3
gl.COVERAGE_BUFFER_BIT_NV = 0x8000
gl.COVERAGE_COMPONENT4_NV = 0x8ed1
gl.COVERAGE_COMPONENT_NV = 0x8ed0
gl.COVERAGE_EDGE_FRAGMENTS_NV = 0x8ed6
gl.COVERAGE_SAMPLES_NV = 0x8ed4
gl.CPU_OPTIMIZED_QCOM = 0x8fb1
gl.CULL_FACE = 0xb44
gl.CULL_FACE_MODE = 0xb45
gl.CURRENT_PROGRAM = 0x8b8d
gl.CURRENT_QUERY_EXT = 0x8865
gl.CURRENT_VERTEX_ATTRIB = 0x8626
gl.CW = 0x900
gl.DEBUG_CALLBACK_FUNCTION = 0x8244
gl.DEBUG_CALLBACK_USER_PARAM = 0x8245
gl.DEBUG_GROUP_STACK_DEPTH = 0x826d
gl.DEBUG_LOGGED_MESSAGES = 0x9145
gl.DEBUG_NEXT_LOGGED_MESSAGE_LENGTH = 0x8243
gl.DEBUG_OUTPUT = 0x92e0
gl.DEBUG_OUTPUT_SYNCHRONOUS = 0x8242
gl.DEBUG_SEVERITY_HIGH = 0x9146
gl.DEBUG_SEVERITY_LOW = 0x9148
gl.DEBUG_SEVERITY_MEDIUM = 0x9147
gl.DEBUG_SEVERITY_NOTIFICATION = 0x826b
gl.DEBUG_SOURCE_API = 0x8246
gl.DEBUG_SOURCE_APPLICATION = 0x824a
gl.DEBUG_SOURCE_OTHER = 0x824b
gl.DEBUG_SOURCE_SHADER_COMPILER = 0x8248
gl.DEBUG_SOURCE_THIRD_PARTY = 0x8249
gl.DEBUG_SOURCE_WINDOW_SYSTEM = 0x8247
gl.DEBUG_TYPE_DEPRECATED_BEHAVIOR = 0x824d
gl.DEBUG_TYPE_ERROR = 0x824c
gl.DEBUG_TYPE_MARKER = 0x8268
gl.DEBUG_TYPE_OTHER = 0x8251
gl.DEBUG_TYPE_PERFORMANCE = 0x8250
gl.DEBUG_TYPE_POP_GROUP = 0x826a
gl.DEBUG_TYPE_PORTABILITY = 0x824f
gl.DEBUG_TYPE_PUSH_GROUP = 0x8269
gl.DEBUG_TYPE_UNDEFINED_BEHAVIOR = 0x824e
gl.DECR = 0x1e03
gl.DECR_WRAP = 0x8508
gl.DELETE_STATUS = 0x8b80
gl.DEPTH24_STENCIL8_OES = 0x88f0
gl.DEPTH_ATTACHMENT = 0x8d00
gl.DEPTH_BITS = 0xd56
gl.DEPTH_BUFFER_BIT = 0x100
gl.DEPTH_BUFFER_BIT0_QCOM = 0x100
gl.DEPTH_BUFFER_BIT1_QCOM = 0x200
gl.DEPTH_BUFFER_BIT2_QCOM = 0x400
gl.DEPTH_BUFFER_BIT3_QCOM = 0x800
gl.DEPTH_BUFFER_BIT4_QCOM = 0x1000
gl.DEPTH_BUFFER_BIT5_QCOM = 0x2000
gl.DEPTH_BUFFER_BIT6_QCOM = 0x4000
gl.DEPTH_BUFFER_BIT7_QCOM = 0x8000
gl.DEPTH_CLEAR_VALUE = 0xb73
gl.DEPTH_COMPONENT = 0x1902
gl.DEPTH_COMPONENT16 = 0x81a5
gl.DEPTH_COMPONENT16_NONLINEAR_NV = 0x8e2c
gl.DEPTH_COMPONENT16_OES = 0x81a5
gl.DEPTH_COMPONENT24_OES = 0x81a6
gl.DEPTH_COMPONENT32_OES = 0x81a7
gl.DEPTH_EXT = 0x1801
gl.DEPTH_FUNC = 0xb74
gl.DEPTH_RANGE = 0xb70
gl.DEPTH_STENCIL_OES = 0x84f9
gl.DEPTH_TEST = 0xb71
gl.DEPTH_WRITEMASK = 0xb72
gl.DITHER = 0xbd0
gl.DMP_shader_binary = 0x1
gl.DONT_CARE = 0x1100
gl.DRAW_BUFFER0_NV = 0x8825
gl.DRAW_BUFFER10_NV = 0x882f
gl.DRAW_BUFFER11_NV = 0x8830
gl.DRAW_BUFFER12_NV = 0x8831
gl.DRAW_BUFFER13_NV = 0x8832
gl.DRAW_BUFFER14_NV = 0x8833
gl.DRAW_BUFFER15_NV = 0x8834
gl.DRAW_BUFFER1_NV = 0x8826
gl.DRAW_BUFFER2_NV = 0x8827
gl.DRAW_BUFFER3_NV = 0x8828
gl.DRAW_BUFFER4_NV = 0x8829
gl.DRAW_BUFFER5_NV = 0x882a
gl.DRAW_BUFFER6_NV = 0x882b
gl.DRAW_BUFFER7_NV = 0x882c
gl.DRAW_BUFFER8_NV = 0x882d
gl.DRAW_BUFFER9_NV = 0x882e
gl.DRAW_BUFFER_EXT = 0xc01
gl.DRAW_FRAMEBUFFER_ANGLE = 0x8ca9
gl.DRAW_FRAMEBUFFER_APPLE = 0x8ca9
gl.DRAW_FRAMEBUFFER_BINDING_ANGLE = 0x8ca6
gl.DRAW_FRAMEBUFFER_BINDING_APPLE = 0x8ca6
gl.DRAW_FRAMEBUFFER_BINDING_NV = 0x8ca6
gl.DRAW_FRAMEBUFFER_NV = 0x8ca9
gl.DST_ALPHA = 0x304
gl.DST_COLOR = 0x306
gl.DYNAMIC_DRAW = 0x88e8
gl.ELEMENT_ARRAY_BUFFER = 0x8893
gl.ELEMENT_ARRAY_BUFFER_BINDING = 0x8895
gl.EQUAL = 0x202
gl.ES_VERSION_2_0 = 0x1
gl.ETC1_RGB8_OES = 0x8d64
gl.ETC1_SRGB8_NV = 0x88ee
gl.EXTENSIONS = 0x1f03
gl.EXT_blend_minmax = 0x1
gl.EXT_color_buffer_half_float = 0x1
gl.EXT_debug_label = 0x1
gl.EXT_debug_marker = 0x1
gl.EXT_discard_framebuffer = 0x1
gl.EXT_map_buffer_range = 0x1
gl.EXT_multi_draw_arrays = 0x1
gl.EXT_multisampled_render_to_texture = 0x1
gl.EXT_multiview_draw_buffers = 0x1
gl.EXT_occlusion_query_boolean = 0x1
gl.EXT_read_format_bgra = 0x1
gl.EXT_robustness = 0x1
gl.EXT_sRGB = 0x1
gl.EXT_separate_shader_objects = 0x1
gl.EXT_shader_framebuffer_fetch = 0x1
gl.EXT_shader_texture_lod = 0x1
gl.EXT_shadow_samplers = 0x1
gl.EXT_texture_compression_dxt1 = 0x1
gl.EXT_texture_filter_anisotropic = 0x1
gl.EXT_texture_format_BGRA8888 = 0x1
gl.EXT_texture_rg = 0x1
gl.EXT_texture_storage = 0x1
gl.EXT_texture_type_2_10_10_10_REV = 0x1
gl.EXT_unpack_subimage = 0x1
gl.FALSE = 0x0
gl.FASTEST = 0x1101
gl.FENCE_CONDITION_NV = 0x84f4
gl.FENCE_STATUS_NV = 0x84f3
gl.FIXED = 0x140c
gl.FJ_shader_binary_GCCSO = 0x1
gl.FLOAT = 0x1406
gl.FLOAT_MAT2 = 0x8b5a
gl.FLOAT_MAT3 = 0x8b5b
gl.FLOAT_MAT4 = 0x8b5c
gl.FLOAT_VEC2 = 0x8b50
gl.FLOAT_VEC3 = 0x8b51
gl.FLOAT_VEC4 = 0x8b52
gl.FRAGMENT_SHADER = 0x8b30
gl.FRAGMENT_SHADER_BIT_EXT = 0x2
gl.FRAGMENT_SHADER_DERIVATIVE_HINT_OES = 0x8b8b
gl.FRAGMENT_SHADER_DISCARDS_SAMPLES_EXT = 0x8a52
gl.FRAMEBUFFER = 0x8d40
gl.FRAMEBUFFER_ATTACHMENT_ANGLE = 0x93a3
gl.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT = 0x8210
gl.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT = 0x8211
gl.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8cd1
gl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8cd0
gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_OES = 0x8cd4
gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8cd3
gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8cd2
gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT = 0x8d6c
gl.FRAMEBUFFER_BINDING = 0x8ca6
gl.FRAMEBUFFER_COMPLETE = 0x8cd5
gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8cd6
gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8cd9
gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8cd7
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE = 0x8d56
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_APPLE = 0x8d56
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT = 0x8d56
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_IMG = 0x9134
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_NV = 0x8d56
gl.FRAMEBUFFER_UNDEFINED_OES = 0x8219
gl.FRAMEBUFFER_UNSUPPORTED = 0x8cdd
gl.FRONT = 0x404
gl.FRONT_AND_BACK = 0x408
gl.FRONT_FACE = 0xb46
gl.FUNC_ADD = 0x8006
gl.FUNC_REVERSE_SUBTRACT = 0x800b
gl.FUNC_SUBTRACT = 0x800a
gl.GENERATE_MIPMAP_HINT = 0x8192
gl.GEQUAL = 0x206
gl.GPU_OPTIMIZED_QCOM = 0x8fb2
gl.GREATER = 0x204
gl.GREEN_BITS = 0xd53
gl.GUILTY_CONTEXT_RESET_EXT = 0x8253
gl.HALF_FLOAT_OES = 0x8d61
gl.HIGH_FLOAT = 0x8df2
gl.HIGH_INT = 0x8df5
gl.IMG_multisampled_render_to_texture = 0x1
gl.IMG_program_binary = 0x1
gl.IMG_read_format = 0x1
gl.IMG_shader_binary = 0x1
gl.IMG_texture_compression_pvrtc = 0x1
gl.IMG_texture_compression_pvrtc2 = 0x1
gl.IMPLEMENTATION_COLOR_READ_FORMAT = 0x8b9b
gl.IMPLEMENTATION_COLOR_READ_TYPE = 0x8b9a
gl.INCR = 0x1e02
gl.INCR_WRAP = 0x8507
gl.INFO_LOG_LENGTH = 0x8b84
gl.INNOCENT_CONTEXT_RESET_EXT = 0x8254
gl.INT = 0x1404
gl.INT_10_10_10_2_OES = 0x8df7
gl.INT_VEC2 = 0x8b53
gl.INT_VEC3 = 0x8b54
gl.INT_VEC4 = 0x8b55
gl.INVALID_ENUM = 0x500
gl.INVALID_FRAMEBUFFER_OPERATION = 0x506
gl.INVALID_OPERATION = 0x502
gl.INVALID_VALUE = 0x501
gl.INVERT = 0x150a
gl.KEEP = 0x1e00
gl.KHR_debug = 0x1
gl.KHR_texture_compression_astc_ldr = 0x1
gl.LEQUAL = 0x203
gl.LESS = 0x201
gl.LINEAR = 0x2601
gl.LINEAR_MIPMAP_LINEAR = 0x2703
gl.LINEAR_MIPMAP_NEAREST = 0x2701
gl.LINES = 0x1
gl.LINE_LOOP = 0x2
gl.LINE_STRIP = 0x3
gl.LINE_WIDTH = 0xb21
gl.LINK_STATUS = 0x8b82
gl.LOSE_CONTEXT_ON_RESET_EXT = 0x8252
gl.LOW_FLOAT = 0x8df0
gl.LOW_INT = 0x8df3
gl.LUMINANCE = 0x1909
gl.LUMINANCE16F_EXT = 0x881e
gl.LUMINANCE32F_EXT = 0x8818
gl.LUMINANCE4_ALPHA4_OES = 0x8043
gl.LUMINANCE8_ALPHA8_EXT = 0x8045
gl.LUMINANCE8_ALPHA8_OES = 0x8045
gl.LUMINANCE8_EXT = 0x8040
gl.LUMINANCE8_OES = 0x8040
gl.LUMINANCE_ALPHA = 0x190a
gl.LUMINANCE_ALPHA16F_EXT = 0x881f
gl.LUMINANCE_ALPHA32F_EXT = 0x8819
gl.MALI_PROGRAM_BINARY_ARM = 0x8f61
gl.MALI_SHADER_BINARY_ARM = 0x8f60
gl.MAP_FLUSH_EXPLICIT_BIT_EXT = 0x10
gl.MAP_INVALIDATE_BUFFER_BIT_EXT = 0x8
gl.MAP_INVALIDATE_RANGE_BIT_EXT = 0x4
gl.MAP_READ_BIT_EXT = 0x1
gl.MAP_UNSYNCHRONIZED_BIT_EXT = 0x20
gl.MAP_WRITE_BIT_EXT = 0x2
gl.MAX_3D_TEXTURE_SIZE_OES = 0x8073
gl.MAX_COLOR_ATTACHMENTS_NV = 0x8cdf
gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8b4d
gl.MAX_CUBE_MAP_TEXTURE_SIZE = 0x851c
gl.MAX_DEBUG_GROUP_STACK_DEPTH = 0x826c
gl.MAX_DEBUG_LOGGED_MESSAGES = 0x9144
gl.MAX_DEBUG_MESSAGE_LENGTH = 0x9143
gl.MAX_DRAW_BUFFERS_NV = 0x8824
gl.MAX_EXT = 0x8008
gl.MAX_FRAGMENT_UNIFORM_VECTORS = 0x8dfd
gl.MAX_LABEL_LENGTH = 0x82e8
gl.MAX_MULTIVIEW_BUFFERS_EXT = 0x90f2
gl.MAX_RENDERBUFFER_SIZE = 0x84e8
gl.MAX_SAMPLES_ANGLE = 0x8d57
gl.MAX_SAMPLES_APPLE = 0x8d57
gl.MAX_SAMPLES_EXT = 0x8d57
gl.MAX_SAMPLES_IMG = 0x9135
gl.MAX_SAMPLES_NV = 0x8d57
gl.MAX_SERVER_WAIT_TIMEOUT_APPLE = 0x9111
gl.MAX_TEXTURE_IMAGE_UNITS = 0x8872
gl.MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84ff
gl.MAX_TEXTURE_SIZE = 0xd33
gl.MAX_VARYING_VECTORS = 0x8dfc
gl.MAX_VERTEX_ATTRIBS = 0x8869
gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8b4c
gl.MAX_VERTEX_UNIFORM_VECTORS = 0x8dfb
gl.MAX_VIEWPORT_DIMS = 0xd3a
gl.MEDIUM_FLOAT = 0x8df1
gl.MEDIUM_INT = 0x8df4
gl.MIN_EXT = 0x8007
gl.MIRRORED_REPEAT = 0x8370
gl.MULTISAMPLE_BUFFER_BIT0_QCOM = 0x1000000
gl.MULTISAMPLE_BUFFER_BIT1_QCOM = 0x2000000
gl.MULTISAMPLE_BUFFER_BIT2_QCOM = 0x4000000
gl.MULTISAMPLE_BUFFER_BIT3_QCOM = 0x8000000
gl.MULTISAMPLE_BUFFER_BIT4_QCOM = 0x10000000
gl.MULTISAMPLE_BUFFER_BIT5_QCOM = 0x20000000
gl.MULTISAMPLE_BUFFER_BIT6_QCOM = 0x40000000
gl.MULTISAMPLE_BUFFER_BIT7_QCOM = 0x80000000
gl.MULTIVIEW_EXT = 0x90f1
gl.NEAREST = 0x2600
gl.NEAREST_MIPMAP_LINEAR = 0x2702
gl.NEAREST_MIPMAP_NEAREST = 0x2700
gl.NEVER = 0x200
gl.NICEST = 0x1102
gl.NONE = 0x0
gl.NOTEQUAL = 0x205
gl.NO_ERROR = 0x0
gl.NO_RESET_NOTIFICATION_EXT = 0x8261
gl.NUM_COMPRESSED_TEXTURE_FORMATS = 0x86a2
gl.NUM_PROGRAM_BINARY_FORMATS_OES = 0x87fe
gl.NUM_SHADER_BINARY_FORMATS = 0x8df9
gl.NV_coverage_sample = 0x1
gl.NV_depth_nonlinear = 0x1
gl.NV_draw_buffers = 0x1
gl.NV_draw_instanced = 0x1
gl.NV_fbo_color_attachments = 0x1
gl.NV_fence = 0x1
gl.NV_framebuffer_blit = 0x1
gl.NV_framebuffer_multisample = 0x1
gl.NV_generate_mipmap_sRGB = 0x1
gl.NV_instanced_arrays = 0x1
gl.NV_read_buffer = 0x1
gl.NV_read_buffer_front = 0x1
gl.NV_read_depth = 0x1
gl.NV_read_depth_stencil = 0x1
gl.NV_read_stencil = 0x1
gl.NV_sRGB_formats = 0x1
gl.NV_shadow_samplers_array = 0x1
gl.NV_shadow_samplers_cube = 0x1
gl.NV_texture_border_clamp = 0x1
gl.NV_texture_compression_s3tc_update = 0x1
gl.NV_texture_npot_2D_mipmap = 0x1
gl.OBJECT_TYPE_APPLE = 0x9112
gl.OES_EGL_image = 0x1
gl.OES_EGL_image_external = 0x1
gl.OES_compressed_ETC1_RGB8_texture = 0x1
gl.OES_compressed_paletted_texture = 0x1
gl.OES_depth24 = 0x1
gl.OES_depth32 = 0x1
gl.OES_depth_texture = 0x1
gl.OES_element_index_uint = 0x1
gl.OES_fbo_render_mipmap = 0x1
gl.OES_fragment_precision_high = 0x1
gl.OES_get_program_binary = 0x1
gl.OES_mapbuffer = 0x1
gl.OES_packed_depth_stencil = 0x1
gl.OES_required_internalformat = 0x1
gl.OES_rgb8_rgba8 = 0x1
gl.OES_standard_derivatives = 0x1
gl.OES_stencil1 = 0x1
gl.OES_stencil4 = 0x1
gl.OES_surfaceless_context = 0x1
gl.OES_texture_3D = 0x1
gl.OES_texture_float = 0x1
gl.OES_texture_float_linear = 0x1
gl.OES_texture_half_float = 0x1
gl.OES_texture_half_float_linear = 0x1
gl.OES_texture_npot = 0x1
gl.OES_vertex_array_object = 0x1
gl.OES_vertex_half_float = 0x1
gl.OES_vertex_type_10_10_10_2 = 0x1
gl.ONE = 0x1
gl.ONE_MINUS_CONSTANT_ALPHA = 0x8004
gl.ONE_MINUS_CONSTANT_COLOR = 0x8002
gl.ONE_MINUS_DST_ALPHA = 0x305
gl.ONE_MINUS_DST_COLOR = 0x307
gl.ONE_MINUS_SRC_ALPHA = 0x303
gl.ONE_MINUS_SRC_COLOR = 0x301
gl.OUT_OF_MEMORY = 0x505
gl.PACK_ALIGNMENT = 0xd05
gl.PACK_REVERSE_ROW_ORDER_ANGLE = 0x93a4
gl.PALETTE4_R5_G6_B5_OES = 0x8b92
gl.PALETTE4_RGB5_A1_OES = 0x8b94
gl.PALETTE4_RGB8_OES = 0x8b90
gl.PALETTE4_RGBA4_OES = 0x8b93
gl.PALETTE4_RGBA8_OES = 0x8b91
gl.PALETTE8_R5_G6_B5_OES = 0x8b97
gl.PALETTE8_RGB5_A1_OES = 0x8b99
gl.PALETTE8_RGB8_OES = 0x8b95
gl.PALETTE8_RGBA4_OES = 0x8b98
gl.PALETTE8_RGBA8_OES = 0x8b96
gl.PERCENTAGE_AMD = 0x8bc3
gl.PERFMON_GLOBAL_MODE_QCOM = 0x8fa0
gl.PERFMON_RESULT_AMD = 0x8bc6
gl.PERFMON_RESULT_AVAILABLE_AMD = 0x8bc4
gl.PERFMON_RESULT_SIZE_AMD = 0x8bc5
gl.POINTS = 0x0
gl.POLYGON_OFFSET_FACTOR = 0x8038
gl.POLYGON_OFFSET_FILL = 0x8037
gl.POLYGON_OFFSET_UNITS = 0x2a00
gl.PROGRAM = 0x82e2
gl.PROGRAM_BINARY_ANGLE = 0x93a6
gl.PROGRAM_BINARY_FORMATS_OES = 0x87ff
gl.PROGRAM_BINARY_LENGTH_OES = 0x8741
gl.PROGRAM_OBJECT_EXT = 0x8b40
gl.PROGRAM_PIPELINE_BINDING_EXT = 0x825a
gl.PROGRAM_PIPELINE_OBJECT_EXT = 0x8a4f
gl.PROGRAM_SEPARABLE_EXT = 0x8258
gl.QCOM_alpha_test = 0x1
gl.QCOM_binning_control = 0x1
gl.QCOM_driver_control = 0x1
gl.QCOM_extended_get = 0x1
gl.QCOM_extended_get2 = 0x1
gl.QCOM_perfmon_global_mode = 0x1
gl.QCOM_tiled_rendering = 0x1
gl.QCOM_writeonly_rendering = 0x1
gl.QUERY = 0x82e3
gl.QUERY_OBJECT_EXT = 0x9153
gl.QUERY_RESULT_AVAILABLE_EXT = 0x8867
gl.QUERY_RESULT_EXT = 0x8866
gl.R16F_EXT = 0x822d
gl.R32F_EXT = 0x822e
gl.R8_EXT = 0x8229
gl.READ_BUFFER_EXT = 0xc02
gl.READ_BUFFER_NV = 0xc02
gl.READ_FRAMEBUFFER_ANGLE = 0x8ca8
gl.READ_FRAMEBUFFER_APPLE = 0x8ca8
gl.READ_FRAMEBUFFER_BINDING_ANGLE = 0x8caa
gl.READ_FRAMEBUFFER_BINDING_APPLE = 0x8caa
gl.READ_FRAMEBUFFER_BINDING_NV = 0x8caa
gl.READ_FRAMEBUFFER_NV = 0x8ca8
gl.RED_BITS = 0xd52
gl.RED_EXT = 0x1903
gl.RENDERBUFFER = 0x8d41
gl.RENDERBUFFER_ALPHA_SIZE = 0x8d53
gl.RENDERBUFFER_BINDING = 0x8ca7
gl.RENDERBUFFER_BLUE_SIZE = 0x8d52
gl.RENDERBUFFER_DEPTH_SIZE = 0x8d54
gl.RENDERBUFFER_GREEN_SIZE = 0x8d51
gl.RENDERBUFFER_HEIGHT = 0x8d43
gl.RENDERBUFFER_INTERNAL_FORMAT = 0x8d44
gl.RENDERBUFFER_RED_SIZE = 0x8d50
gl.RENDERBUFFER_SAMPLES_ANGLE = 0x8cab
gl.RENDERBUFFER_SAMPLES_APPLE = 0x8cab
gl.RENDERBUFFER_SAMPLES_EXT = 0x8cab
gl.RENDERBUFFER_SAMPLES_IMG = 0x9133
gl.RENDERBUFFER_SAMPLES_NV = 0x8cab
gl.RENDERBUFFER_STENCIL_SIZE = 0x8d55
gl.RENDERBUFFER_WIDTH = 0x8d42
gl.RENDERER = 0x1f01
gl.RENDER_DIRECT_TO_FRAMEBUFFER_QCOM = 0x8fb3
gl.REPEAT = 0x2901
gl.REPLACE = 0x1e01
gl.REQUIRED_TEXTURE_IMAGE_UNITS_OES = 0x8d68
gl.RESET_NOTIFICATION_STRATEGY_EXT = 0x8256
gl.RG16F_EXT = 0x822f
gl.RG32F_EXT = 0x8230
gl.RG8_EXT = 0x822b
gl.RGB = 0x1907
gl.RGB10_A2_EXT = 0x8059
gl.RGB10_EXT = 0x8052
gl.RGB16F_EXT = 0x881b
gl.RGB32F_EXT = 0x8815
gl.RGB565 = 0x8d62
gl.RGB565_OES = 0x8d62
gl.RGB5_A1 = 0x8057
gl.RGB5_A1_OES = 0x8057
gl.RGB8_OES = 0x8051
gl.RGBA = 0x1908
gl.RGBA16F_EXT = 0x881a
gl.RGBA32F_EXT = 0x8814
gl.RGBA4 = 0x8056
gl.RGBA4_OES = 0x8056
gl.RGBA8_OES = 0x8058
gl.RGB_422_APPLE = 0x8a1f
gl.RG_EXT = 0x8227
gl.SAMPLER = 0x82e6
gl.SAMPLER_2D = 0x8b5e
gl.SAMPLER_2D_ARRAY_SHADOW_NV = 0x8dc4
gl.SAMPLER_2D_SHADOW_EXT = 0x8b62
gl.SAMPLER_3D_OES = 0x8b5f
gl.SAMPLER_CUBE = 0x8b60
gl.SAMPLER_CUBE_SHADOW_NV = 0x8dc5
gl.SAMPLER_EXTERNAL_OES = 0x8d66
gl.SAMPLES = 0x80a9
gl.SAMPLE_ALPHA_TO_COVERAGE = 0x809e
gl.SAMPLE_BUFFERS = 0x80a8
gl.SAMPLE_COVERAGE = 0x80a0
gl.SAMPLE_COVERAGE_INVERT = 0x80ab
gl.SAMPLE_COVERAGE_VALUE = 0x80aa
gl.SCISSOR_BOX = 0xc10
gl.SCISSOR_TEST = 0xc11
gl.SGX_BINARY_IMG = 0x8c0a
gl.SGX_PROGRAM_BINARY_IMG = 0x9130
gl.SHADER = 0x82e1
gl.SHADER_BINARY_DMP = 0x9250
gl.SHADER_BINARY_FORMATS = 0x8df8
gl.SHADER_BINARY_VIV = 0x8fc4
gl.SHADER_COMPILER = 0x8dfa
gl.SHADER_OBJECT_EXT = 0x8b48
gl.SHADER_SOURCE_LENGTH = 0x8b88
gl.SHADER_TYPE = 0x8b4f
gl.SHADING_LANGUAGE_VERSION = 0x8b8c
gl.SHORT = 0x1402
gl.SIGNALED_APPLE = 0x9119
gl.SLUMINANCE8_ALPHA8_NV = 0x8c45
gl.SLUMINANCE8_NV = 0x8c47
gl.SLUMINANCE_ALPHA_NV = 0x8c44
gl.SLUMINANCE_NV = 0x8c46
gl.SRC_ALPHA = 0x302
gl.SRC_ALPHA_SATURATE = 0x308
gl.SRC_COLOR = 0x300
gl.SRGB8_ALPHA8_EXT = 0x8c43
gl.SRGB8_NV = 0x8c41
gl.SRGB_ALPHA_EXT = 0x8c42
gl.SRGB_EXT = 0x8c40
gl.STACK_OVERFLOW = 0x503
gl.STACK_UNDERFLOW = 0x504
gl.STATE_RESTORE = 0x8bdc
gl.STATIC_DRAW = 0x88e4
gl.STENCIL_ATTACHMENT = 0x8d20
gl.STENCIL_BACK_FAIL = 0x8801
gl.STENCIL_BACK_FUNC = 0x8800
gl.STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802
gl.STENCIL_BACK_PASS_DEPTH_PASS = 0x8803
gl.STENCIL_BACK_REF = 0x8ca3
gl.STENCIL_BACK_VALUE_MASK = 0x8ca4
gl.STENCIL_BACK_WRITEMASK = 0x8ca5
gl.STENCIL_BITS = 0xd57
gl.STENCIL_BUFFER_BIT = 0x400
gl.STENCIL_BUFFER_BIT0_QCOM = 0x10000
gl.STENCIL_BUFFER_BIT1_QCOM = 0x20000
gl.STENCIL_BUFFER_BIT2_QCOM = 0x40000
gl.STENCIL_BUFFER_BIT3_QCOM = 0x80000
gl.STENCIL_BUFFER_BIT4_QCOM = 0x100000
gl.STENCIL_BUFFER_BIT5_QCOM = 0x200000
gl.STENCIL_BUFFER_BIT6_QCOM = 0x400000
gl.STENCIL_BUFFER_BIT7_QCOM = 0x800000
gl.STENCIL_CLEAR_VALUE = 0xb91
gl.STENCIL_EXT = 0x1802
gl.STENCIL_FAIL = 0xb94
gl.STENCIL_FUNC = 0xb92
gl.STENCIL_INDEX1_OES = 0x8d46
gl.STENCIL_INDEX4_OES = 0x8d47
gl.STENCIL_INDEX8 = 0x8d48
gl.STENCIL_PASS_DEPTH_FAIL = 0xb95
gl.STENCIL_PASS_DEPTH_PASS = 0xb96
gl.STENCIL_REF = 0xb97
gl.STENCIL_TEST = 0xb90
gl.STENCIL_VALUE_MASK = 0xb93
gl.STENCIL_WRITEMASK = 0xb98
gl.STREAM_DRAW = 0x88e0
gl.SUBPIXEL_BITS = 0xd50
gl.SYNC_CONDITION_APPLE = 0x9113
gl.SYNC_FENCE_APPLE = 0x9116
gl.SYNC_FLAGS_APPLE = 0x9115
gl.SYNC_FLUSH_COMMANDS_BIT_APPLE = 0x1
gl.SYNC_GPU_COMMANDS_COMPLETE_APPLE = 0x9117
gl.SYNC_OBJECT_APPLE = 0x8a53
gl.SYNC_STATUS_APPLE = 0x9114
gl.TEXTURE = 0x1702
gl.TEXTURE0 = 0x84c0
gl.TEXTURE1 = 0x84c1
gl.TEXTURE10 = 0x84ca
gl.TEXTURE11 = 0x84cb
gl.TEXTURE12 = 0x84cc
gl.TEXTURE13 = 0x84cd
gl.TEXTURE14 = 0x84ce
gl.TEXTURE15 = 0x84cf
gl.TEXTURE16 = 0x84d0
gl.TEXTURE17 = 0x84d1
gl.TEXTURE18 = 0x84d2
gl.TEXTURE19 = 0x84d3
gl.TEXTURE2 = 0x84c2
gl.TEXTURE20 = 0x84d4
gl.TEXTURE21 = 0x84d5
gl.TEXTURE22 = 0x84d6
gl.TEXTURE23 = 0x84d7
gl.TEXTURE24 = 0x84d8
gl.TEXTURE25 = 0x84d9
gl.TEXTURE26 = 0x84da
gl.TEXTURE27 = 0x84db
gl.TEXTURE28 = 0x84dc
gl.TEXTURE29 = 0x84dd
gl.TEXTURE3 = 0x84c3
gl.TEXTURE30 = 0x84de
gl.TEXTURE31 = 0x84df
gl.TEXTURE4 = 0x84c4
gl.TEXTURE5 = 0x84c5
gl.TEXTURE6 = 0x84c6
gl.TEXTURE7 = 0x84c7
gl.TEXTURE8 = 0x84c8
gl.TEXTURE9 = 0x84c9
gl.TEXTURE_2D = 0xde1
gl.TEXTURE_3D_OES = 0x806f
gl.TEXTURE_BINDING_2D = 0x8069
gl.TEXTURE_BINDING_3D_OES = 0x806a
gl.TEXTURE_BINDING_CUBE_MAP = 0x8514
gl.TEXTURE_BINDING_EXTERNAL_OES = 0x8d67
gl.TEXTURE_BORDER_COLOR_NV = 0x1004
gl.TEXTURE_COMPARE_FUNC_EXT = 0x884d
gl.TEXTURE_COMPARE_MODE_EXT = 0x884c
gl.TEXTURE_CUBE_MAP = 0x8513
gl.TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516
gl.TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518
gl.TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851a
gl.TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515
gl.TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517
gl.TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519
gl.TEXTURE_DEPTH_QCOM = 0x8bd4
gl.TEXTURE_EXTERNAL_OES = 0x8d65
gl.TEXTURE_FORMAT_QCOM = 0x8bd6
gl.TEXTURE_HEIGHT_QCOM = 0x8bd3
gl.TEXTURE_IMAGE_VALID_QCOM = 0x8bd8
gl.TEXTURE_IMMUTABLE_FORMAT_EXT = 0x912f
gl.TEXTURE_INTERNAL_FORMAT_QCOM = 0x8bd5
gl.TEXTURE_MAG_FILTER = 0x2800
gl.TEXTURE_MAX_ANISOTROPY_EXT = 0x84fe
gl.TEXTURE_MAX_LEVEL_APPLE = 0x813d
gl.TEXTURE_MIN_FILTER = 0x2801
gl.TEXTURE_NUM_LEVELS_QCOM = 0x8bd9
gl.TEXTURE_OBJECT_VALID_QCOM = 0x8bdb
gl.TEXTURE_SAMPLES_IMG = 0x9136
gl.TEXTURE_TARGET_QCOM = 0x8bda
gl.TEXTURE_TYPE_QCOM = 0x8bd7
gl.TEXTURE_USAGE_ANGLE = 0x93a2
gl.TEXTURE_WIDTH_QCOM = 0x8bd2
gl.TEXTURE_WRAP_R_OES = 0x8072
gl.TEXTURE_WRAP_S = 0x2802
gl.TEXTURE_WRAP_T = 0x2803
gl.TIMEOUT_EXPIRED_APPLE = 0x911b
gl.TIMEOUT_IGNORED_APPLE = 0xffffffffffffffff
gl.TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE = 0x93a0
gl.TRIANGLES = 0x4
gl.TRIANGLE_FAN = 0x6
gl.TRIANGLE_STRIP = 0x5
gl.TRUE = 0x1
gl.UNKNOWN_CONTEXT_RESET_EXT = 0x8255
gl.UNPACK_ALIGNMENT = 0xcf5
gl.UNPACK_ROW_LENGTH = 0xcf2
gl.UNPACK_SKIP_PIXELS = 0xcf4
gl.UNPACK_SKIP_ROWS = 0xcf3
gl.UNSIGNALED_APPLE = 0x9118
gl.UNSIGNED_BYTE = 0x1401
gl.UNSIGNED_INT = 0x1405
gl.UNSIGNED_INT64_AMD = 0x8bc2
gl.UNSIGNED_INT_10_10_10_2_OES = 0x8df6
gl.UNSIGNED_INT_24_8_OES = 0x84fa
gl.UNSIGNED_INT_2_10_10_10_REV_EXT = 0x8368
gl.UNSIGNED_NORMALIZED_EXT = 0x8c17
gl.UNSIGNED_SHORT = 0x1403
gl.UNSIGNED_SHORT_1_5_5_5_REV_EXT = 0x8366
gl.UNSIGNED_SHORT_4_4_4_4 = 0x8033
gl.UNSIGNED_SHORT_4_4_4_4_REV_EXT = 0x8365
gl.UNSIGNED_SHORT_4_4_4_4_REV_IMG = 0x8365
gl.UNSIGNED_SHORT_5_5_5_1 = 0x8034
gl.UNSIGNED_SHORT_5_6_5 = 0x8363
gl.UNSIGNED_SHORT_8_8_APPLE = 0x85ba
gl.UNSIGNED_SHORT_8_8_REV_APPLE = 0x85bb
gl.VALIDATE_STATUS = 0x8b83
gl.VENDOR = 0x1f00
gl.VERSION = 0x1f02
gl.VERTEX_ARRAY_BINDING_OES = 0x85b5
gl.VERTEX_ARRAY_OBJECT_EXT = 0x9154
gl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889f
gl.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE = 0x88fe
gl.VERTEX_ATTRIB_ARRAY_DIVISOR_NV = 0x88fe
gl.VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622
gl.VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886a
gl.VERTEX_ATTRIB_ARRAY_POINTER = 0x8645
gl.VERTEX_ATTRIB_ARRAY_SIZE = 0x8623
gl.VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624
gl.VERTEX_ATTRIB_ARRAY_TYPE = 0x8625
gl.VERTEX_SHADER = 0x8b31
gl.VERTEX_SHADER_BIT_EXT = 0x1
gl.VIEWPORT = 0xba2
gl.VIV_shader_binary = 0x1
gl.WAIT_FAILED_APPLE = 0x911d
gl.WRITEONLY_RENDERING_QCOM = 0x8823
gl.WRITE_ONLY_OES = 0x88b9
gl.Z400_BINARY_AMD = 0x8740
gl.ZERO = 0x0
| mit |
Fenix-XI/Fenix | scripts/zones/Yuhtunga_Jungle/npcs/Mahol_IM.lua | 13 | 3317 | -----------------------------------
-- 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 |
Fenix-XI/Fenix | scripts/zones/Temenos/mobs/Air_Elemental.lua | 7 | 1781 | -----------------------------------
-- Area: Temenos E T
-- NPC: Air_Elemental
-----------------------------------
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)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
local mobID = mob:getID();
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
switch (mobID): caseof {
-- 100 a 106 inclut (Temenos -Northern Tower )
[16928858] = function (x)
GetNPCByID(16928768+181):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+181):setStatus(STATUS_NORMAL);
end ,
[16928859] = function (x)
GetNPCByID(16928768+217):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+217):setStatus(STATUS_NORMAL);
end ,
[16928860] = function (x)
GetNPCByID(16928768+348):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+348):setStatus(STATUS_NORMAL);
end ,
[16928861] = function (x)
GetNPCByID(16928768+46):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+46):setStatus(STATUS_NORMAL);
end ,
[16929035] = function (x)
if (IsMobDead(16929036)==false) then
DespawnMob(16929036);
SpawnMob(16929042);
end
end ,
}
end; | gpl-3.0 |
jmachuca77/ardupilot | libraries/AP_Scripting/examples/logging.lua | 14 | 2082 | -- example of logging to a file on the SD card and to data flash
local file_name = "AHRS_DATA.csv"
local file
-- index for the data and table
local roll = 1
local pitch = 2
local yaw = 3
local interesting_data = {}
local function write_to_file()
if not file then
error("Could not open file")
end
-- write data
-- separate with comas and add a carriage return
file:write(tostring(millis()) .. ", " .. table.concat(interesting_data,", ") .. "\n")
-- make sure file is upto date
file:flush()
end
local function write_to_dataflash()
-- care must be taken when selecting a name, must be less than four characters and not clash with an existing log type
-- format characters specify the type of variable to be logged, see AP_Logger/README.md
-- https://github.com/ArduPilot/ardupilot/tree/master/libraries/AP_Logger
-- not all format types are supported by scripting only: i, L, e, f, n, M, B, I, E, and N
-- lua automatically adds a timestamp in micro seconds
logger.write('SCR1','roll(deg),pitch(deg),yaw(deg)','fff',interesting_data[roll],interesting_data[pitch],interesting_data[yaw])
-- it is also possible to give units and multipliers
logger.write('SCR2','roll,pitch,yaw','fff','ddd','---',interesting_data[roll],interesting_data[pitch],interesting_data[yaw])
end
function update()
-- get some interesting data
interesting_data[roll] = math.deg(ahrs:get_roll())
interesting_data[pitch] = math.deg(ahrs:get_pitch())
interesting_data[yaw] = math.deg(ahrs:get_yaw())
-- write to then new file the SD card
write_to_file()
-- write to a new log in the data flash log
write_to_dataflash()
return update, 1000 -- reschedules the loop
end
-- make a file
-- note that this appends to the same the file each time, you will end up with a very big file
-- you may want to make a new file each time using a unique name
file = io.open(file_name, "a")
if not file then
error("Could not make file")
end
-- write the CSV header
file:write('Time Stamp(ms), roll(deg), pitch(deg), yaw(deg)\n')
file:flush()
return update, 10000
| gpl-3.0 |
wilbefast/boat-peeps-game | src/gameobjects/Food.lua | 1 | 1744 | --[[
(C) Copyright 2014 William Dyce
All rights reserved. This program and the accompanying materials
are made available under the terms of the GNU Lesser General Public License
(LGPL) version 2.1 which accompanies this distribution, and is available at
http://www.gnu.org/licenses/lgpl-2.1.html
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
--]]
--[[------------------------------------------------------------
Initialisation
--]]--
local Food = Class
{
FRICTION = 200,
type = GameObject.newType("Food"),
init = function(self, x, y)
GameObject.init(self, x, y, 6)
end,
}
Food:include(GameObject)
--[[------------------------------------------------------------
Destruction
--]]--
function Food:onPurge()
end
--[[------------------------------------------------------------
Game loop
--]]--
function Food:update(dt)
if self.x > LAND_W then
self.dx = self.dx - 128*dt
elseif self.x < 0 then
self.dx = self.dx + 128*dt
end
GameObject.update(self, dt)
end
function Food:draw(x, y)
fudge.addb("pie", x, y, 0, 1, 1, 8, 16)
useful.pushCanvas(SHADOW_CANVAS)
useful.bindBlack()
useful.oval("fill", self.x, self.y, 8, 8*VIEW_OBLIQUE)
useful.bindWhite()
useful.popCanvas()
end
--[[------------------------------------------------------------
Collisions
--]]--
function Food:eventCollision(other, dt)
if other:isType("Food") or other:isType("Building") then
self:shoveAwayFrom(other, 100*dt)
end
end
--[[------------------------------------------------------------
Export
--]]--
return Food | mit |
Fenix-XI/Fenix | scripts/zones/Heavens_Tower/npcs/Rakano-Marukano.lua | 13 | 2303 | -----------------------------------
-- Area: Heavens Tower
-- NPC: Rakano-Marukano
-- Type: Immigration NPC
-- @pos 6.174 -1 32.285 242
-----------------------------------
package.loaded["scripts/zones/Heavens_Tower/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local new_nation = WINDURST;
local old_nation = player:getNation();
local rank = getNationRank(new_nation);
if (old_nation == new_nation) then
player:startEvent(0x2714,0,0,0,old_nation);
elseif (player:getCurrentMission(old_nation) ~= 255 or player:getVar("MissionStatus") ~= 0) then
player:startEvent(0x2713,0,0,0,new_nation);
elseif (old_nation ~= new_nation) then
local has_gil = 0;
local cost = 0;
if (rank == 1) then
cost = 40000;
elseif (rank == 2) then
cost = 12000;
elseif (rank == 3) then
cost = 4000;
end
if (player:getGil() >= cost) then
has_gil = 1
end
player:startEvent(0x2712,0,1,player:getRank(),new_nation,has_gil,cost);
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 == 0x2712 and option == 1) then
local new_nation = WINDURST;
local rank = getNationRank(new_nation);
local cost = 0;
if (rank == 1) then
cost = 40000;
elseif (rank == 2) then
cost = 12000;
elseif (rank == 3) then
cost = 4000;
end
player:setNation(new_nation)
player:setGil(player:getGil() - cost);
player:setRankPoints(0);
end
end; | gpl-3.0 |
elapuestojoe/survive | build_temp/deployments/default/android/release/arm/intermediate_files/assets/quicklua/dbg.lua | 3 | 11353 | --[[/*
* (C) 2012-2013 Marmalade.
*
* 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.
*/--]]
-- dbg
dbg = {}
dbg.DEBUG = config.debug.general
dbg.TYPECHECKING = config.debug.typeChecking
dbg.ASSERTDIALOGS = config.debug.assertDialogs
dbg.MAKEPRECOMPILEDLUA = config.debug.makePrecompiledLua
dbg.USEPRECOMPILEDLUA = config.debug.usePrecompiledLua
dbg.USECONCATENATEDLUA = config.debug.useConcatenatedLua
-- Print
dbg.print = function(...)
if (dbg.DEBUG == true) then
print(...)
end
end
-- Simple logging
dbg.log = function(msg)
dbg.print("QUICKLUA LOG: " .. msg)
end
-- Serialization of tolua++ metatable, e.g. for debugger
function serializeTLMT(mt, o)
local obj = {}
for field, func in pairs(mt[".get"] or {}) do
obj[field] = func(o)
end
return obj
end
-- Assert
-- From http://lua-users.org/wiki/OptimisationCodingTips
dbg.assert = function(condition, ...)
if dbg.DEBUG == true then
if not condition then
if next({...}) then
local s,r = pcall(function (...) return(string.format(...)) end, ...)
if s then
if dbg.ASSERTDIALOGS == true then
error(r .. "\r\n" .. dbg.getProcessedCallstack(), 2)
else
dbg.print("QUICKLUA ERROR: " .. r .. "\r\n" .. dbg.getProcessedCallstack())
end
end
return
elseif dbg.ASSERTDIALOGS == true then -- only condition was specific
error(dbg.getProcessedCallstack(), 2)
else
dbg.print("QUICKLUA ERROR: " .. dbg.getProcessedCallstack())
end
end
end
end
-- Warning
dbg.warning = function(condition, ...)
if dbg.DEBUG == true then
if not condition then
if next({...}) then
local s,r = pcall(function (...) return(string.format(...)) end, ...)
if s then
dbg.print("QUICKLUA WARNING: " .. r)
end
else
-- Only condition was specified
dbg.print("QUICKLUA WARNING: ")
end
end
end
end
-- Get filtered Lua error string
dbg.getProcessedError = function(v)
local a = string.find(v, ".lua:", 1, true)
if a then
v = "(\'" .. string.sub(v, 1, a+3) .. "\'), line " .. string.sub(v, a+5, -1)
end
return v
end
-- Get filtered Lua callstack
dbg.getProcessedCallstack = function()
local cs = debug.traceback()
local tin = {}
for v in string.gmatch(cs, "%C+") do
table.insert(tin, v)
end
if tin[1] then
tin[1] = "Lua callstack:"
end
-- Process each line
local tout = {}
for i,v in ipairs(tin) do
-- Ignore line?
if string.find(v, "dbg.lua:", 1, true) or
string.find(v, "tail call", 1, true) or
string.find(v, "[C]:", 1, true) then
-- Ignore this line
else
-- Modify line?
local a = string.find(v, ".lua:", 1, true)
if a then
v = "(\'" .. string.sub(v, 1, a+3) .. "\'), line " .. string.sub(v, a+5, -1)
end
-- Insert line
table.insert(tout, v)
end
end
if #tout < 2 then
return ""
end
-- Concatenate
cs = table.concat(tout, "\r\n")
return cs
end
-- Print table, with recursion, only in DEBUG mode
local printedTables = {} -- use this to forbid circular table references!
dbg.printTable = function(t, indent)
if (dbg.DEBUG == true) then
if indent == nil then
indent = ""
printedTables = {}
end
dbg.print(indent .. "{")
indent = indent .. " "
for i,v in pairs(t) do
if type(v) == "table" then
dbg.print(indent .. tostring(i) .. ":")
if table.hasValue(printedTables, v) then
dbg.print("Circular reference! Will not print this table.")
else
table.insert(printedTables, v)
indent = dbg.printTable(v, indent)
end
elseif type(v) == "string" then
dbg.print(indent .. tostring(i) .. ": '" .. v .. "'")
else
dbg.print(indent .. tostring(i) .. ": " .. tostring(v))
end
end
indent = string.sub(indent, 1, string.len(indent)-2)
dbg.print(indent .. "}")
end
return indent
end
-- Print value, including table recursion, only in DEBUG mode
dbg.printValue = function(t)
if (dbg.DEBUG == true) then
if type(t) == "table" then
dbg.printTable(t)
else
dbg.print(tostring(t))
end
end
end
-- Asserts if the object is NOT of the specified type
-- Pass in type as string, followed by object itself (e.g. dbg.assertFuncVarType("table", node))
dbg.assertFuncVarType = function(s, u)
if dbg.TYPECHECKING == true then
dbg.assert(type(u)==s, "Input 1 is of type " .. type(u) .. ", expected type " .. s)
end
end
-- Asserts if the table of type strings does not match 1:1 with the list of inputs
-- Alternatively, if the table and input list are different sizes, we assume the table of type
-- strings are all possible matches for the FIRST input only (any other inputs are not checked)
dbg.assertFuncVarTypes = function(types, ...)
if dbg.TYPECHECKING == true then
local ins = {}
local inSize = select('#',...)
for i = 1,inSize do
ins[i] = select(i, ...)
end
if #ins == #types then
-- Size of "types" array is same as ... so assume they map 1:1
for i,v in ipairs(ins) do
dbg.assert(type(v)==types[i], "Input '" .. i .. "' is of type " .. type(v) .. ", expected type " .. types[i])
end
else
-- Check ONLY ins[1], and assume "types" is all valid types for this input
local ts = type(ins[1])
for i,v in ipairs(types) do
if v==ts then return end
end
dbg.assert(false, "Input is of illegal type: " .. ts)
end
end
end
-- Returns true if the userdata passed is the specified type
dbg.isUserDataType = function(u, t)
if dbg.TYPECHECKING == true then
if type(u) == "userdata" and getmetatable(u) == debug.getregistry()[t] then
return true
else
return false
end
end
end
-- Asserts if the object is NOT of the specified named tolua userdata type
-- Pass in type as string, followed by object itself (e.g. dbg.assertFuncVarType("table", node))
dbg.assertFuncUserDataType = function(s, u)
if dbg.TYPECHECKING == true then
if type(u) ~= "userdata" then
dbg.assert(false, "Input is not of userdata type")
else
dbg.assert(dbg.isUserDataType(u, s), "Input is not of userdata type " .. s)
end
end
end
--------------------------------------------------------------------------------
-- table: add functions to Lua's "table"
--------------------------------------------------------------------------------
-- Check if a table has a specified index
table.hasIndex = function(t, index)
for i,v in pairs(t) do
if (i == index) then
return true
end
end
return false
end
-- Check if a table has a specified value
table.hasValue = function(t, value)
for i,v in pairs(t) do
if (v == value) then
return true
end
end
return false
end
-- Set table values from a table of setter values
-- NOTE: WE OFTEN CALL THIS WITH T=USERDATA, I.E. PASSING IN OBJECTS CREATED THROUGH TOLUA.
-- THIS IS FINE PROVIDED WE DON'T TRY TO ITERATE OVER THE OBJECT VALUES USING pairs(). SO WE CAN'T CALL FUNCTIONS LIKE table.hasIndex
table.setValuesFromTable = function(t, s)
if s == nil then return end
for i,v in pairs(s) do
-- dbg.assert(table.hasIndex(t, i), "Trying to set table value at missing index: ", i)
--dbg.print("i = " ..i ..", v = " ..v)
t[i] = v
end
end
-- Print types of arguments
table.printArgs = function(...)
local argt = {...}
print("Num args: " .. table.maxn(argt))
for i=1,table.maxn(argt) do
print("Arg " .. i .. " is type " .. type(argt[i]))
end
end
-- Count number of keys in table
table.numKeys = function(t)
local k = 0
for i,v in pairs(t) do
k = k + 1
end
return k
end
--------------------------------------------------------------------------------
-- Remap "dofile" to our own version
--------------------------------------------------------------------------------
function unrequire(p)
package.loaded[p] = nil
_G[p] = nil
end
--[[
local _require = require
local requiredFiles = {}
require = function(p)
local r = _require(p)
table.insert(requiredFiles, r)
return r
end
purgeRequiredFiles = function()
for i,v in pairs(requiredFiles) do
package.loaded[i] = nil
-- TODO FIND INDEX OF I WITHIN PACKAGE.LOADED, AND DO
-- TABLE.REMOVE
end
requiredFiles = {}
end
--]]
-- THIS MUST BE THE LAST THING IN DBG.LUA
--if config.debug.general == false then -- only override dofile() for release builds. MH: Now needs to always be overriden
if config.debug.mock_tolua == false then
function dofile(file)
if (string.find(file, ".luac") ~= nil) then
quick.MainLuaLoadFileNRun("luac://" .. file)
return
end
if (config.debug.makePrecompiledLua) then
if (quick.MainLuaPrecompileFile(file) == false) then
dbg.assert(false, "Failed to precompile Lua file '" .. file)
end
if (quick.isFileConcatInProgress()) then
-- If file was concatenated then it was not compiled separately so return nil
return nil
else
return dofile(file .. "c")
end
end
if (config.debug.usePrecompiledLua == true) then
quick.MainLuaLoadFileNRun("luac://" .. file .. "c")
else
quick.MainLuaLoadFileNRun(file)
end
end
-- Dummy required when Lua file preprocessing is used
-- function f(filename) end
end
--end
| mit |
sprcpu/F80-V3.0 | chat.lua | 1 | 1856 | function run(msg, matches)
if matches[1]:lower() == "arisharr" or "silent" or "sudo" then
return "@pahrmakill | @silent_poker"
end
if matches[1]:lower() == "slm" and not is_sudo(msg) then
return "سلام گشاد"
end
if matches[1]:lower() == "slm" and is_sudo(msg) then
return "سلامـ بابایـ خوشگلمـ 🌝"
end
if matches[1]:lower() == "bye" and not is_sudo(msg) then
return "خدافس"
end
if matches[1]:lower() == "bye" or "bedrood" or "bdrod" or "bdrood" or "bedrud" and is_sudo(msg) then
return "خدافس باباجونیـ ●…●"
end
if matches[1]:lower() == "silent" or "arisharr" then
return "با بابامـ چی کار داری \n اذیتش کنی میخورمت😊"
end
if matches[1]:lower() == "SilenT_POKER" or "pharmakill" then
return "بابامه●~●"
end
if matches[1]:lower() == "kir" and not is_sudo(msg) then
return "نداری بگیر:|"
end
if matches[1]:lower() == "کیر" and not is_sudo(msg) then
return "نداری بگیر"
end
if matches[1]:lower() == "بای" and is_sudo(msg) then
return "●…● خدافس باباجونیـ"
end
if matches[1]:lower() == "بای" and not is_sudo(msg) then
return "bby"
end
if matches[1]:lower() == "سلام" and is_sudo(msg) then
return "سلامـ باباجونیـ خوشگلمـ"
end
if matches[1]:lower() == "سلام" and not is_sudo(msg) then
return "سلام"
end
if matches[1]:lower() == "+banall" and is_admin1(msg) then
return "0 b fuke raft:|"
end
if matches[1]:lower() == "س" or and not is_sudo(msg) then
return "سلامـ گشاد"
end
if matches[1]:lower() == "😐" then
return "😐"
end
end
return {
patterns = {
"^(bye)$",
"(arisharr)",
"(sudo)",
"^(slm)$",
"^(silent)$",
"@(SilenT_POKER)",
"@(pharmakill)",
"(kir)",
"^(کیر)$",
"(f80)",
"^(بای)$",
"^(سلام)$",
"(+banall)",
"^(س)$",
"^😐$",
},
run = run
} | gpl-2.0 |
synthein/synthein | src/world/structure.lua | 1 | 12644 | local GridTable = require("gridTable")
local StructureMath = require("world/structureMath")
local StructureParser = require("world/structureParser")
local LocationTable = require("locationTable")
local Location = require("world/location")
local Engine = require("world/shipparts/engine")
local Gun = require("world/shipparts/gun")
local Shield = require("world/shipparts/shield")
local Structure = class(require("world/worldObjects"))
function Structure:__create(worldInfo, location, data, appendix)
self.worldInfo = worldInfo
self.physics = worldInfo.physics
self.createObject = worldInfo.create
local shipTable
if appendix then
local player
shipTable, player = StructureParser.shipUnpack(appendix, data)
self.isPlayer = player
else
shipTable = data
end
local corePart
if not shipTable.parts then
self.gridTable = GridTable()
self.gridTable:index(0, 0, shipTable)
shipTable:setLocation({0, 0, 1})
if shipTable.type ~= "generic" then
corePart = shipTable
end
else
self.gridTable = shipTable.parts
corePart = shipTable.corePart
end
local team = 0
if corePart then
if corePart.type == "control" then
self.body:setAngularDamping(1)
self.body:setLinearDamping(.1)
--self.type = "ship"
elseif corePart.type == "anchor" then
self.body:setType("static")
--self.type = "anchor"
end
corePart.worldInfo = worldInfo
self.corePart = corePart
team = corePart:getTeam()
else
self.body:setAngularDamping(.1)
self.body:setLinearDamping(0.01)
--self.type = "generic"
end
local userDataParent = {
__index = function(t, key)
print("Undesirable connection in structure body userdata. Key:", key)
print(debug.traceback())
return self[key]
end
}
local userData = setmetatable({}, userDataParent)
-- TODO Make a feild not a function
function userData.type()
return "structure"
end
userData.team = team
self.body:setUserData(userData)
self.shield = Shield(self.body)
local function callback(part, structure, x , y)
structure:addPart(part, x, y, part.location[3])
end
self.gridTable:loop(callback, self)
end
function Structure:postCreate(references)
if self.corePart and self.corePart.postCreate then
self.corePart:postCreate(references)
end
end
-- TODO: Remove Duplicate between user data
function Structure:type()
return "structure"
end
function Structure:getSaveData(references)
local team = self.body:getUserData().team
local leader
if self.corePart and self.corePart.leader then
leader = references[self.corePart.leader]
end
return {team, leader}, StructureParser.shipPack(self, true)
end
function Structure:getWorldLocation(l)
local body = self.body
local partX, partY, angle = unpack(l)
local x, y = body:getWorldPoints(partX, partY)
angle = (angle - 1) * math.pi/2 + body:getAngle()
local vx, vy = body:getLinearVelocityFromLocalPoint(partX, partY)
local w = body:getAngularVelocity()
return LocationTable(x, y, angle, vx, vy, w)
end
function Structure:findPart(cursorX, cursorY)
local x, y = self.body:getLocalPoint(cursorX, cursorY)
local part = self.gridTable:index(
math.floor(x + .5),
math.floor(y + .5))
return part
end
-------------------------------
-- Adding and Removing Parts --
-------------------------------
-- Add one part to the structure.
-- x, y are the coordinates in the structure.
-- orientation is the orientation of the part according to the structure.
function Structure:addPart(part, x, y, orientation)
part:setLocation({x, y, orientation})
part:addFixtures(self.body)
--self:calculateSize(x, y)
--self:recalculateSize()
if part.isShield then self.shield:addPart(part) end
self.gridTable:index(x, y, part)
end
-- If there are no more parts in the structure,
-- then mark this structure for destruction.
function Structure:removePart(part)
if part == self.corePart then
self.corePart = nil
end
local x, y = unpack(part.location)
self.gridTable:index(x, y, nil, true)
part:removeFixtures(body)
if part.isShield then self.shield:removePart(part) end
-- for i,fixture in ipairs(self.body:getFixtureList()) do
-- if not fixture:isDestroyed() then
-- return
-- end
-- end
local parts = self.gridTable:loop()
if #parts <= 0 then
self.isDestroyed = true
end
end
-----------------------------------------
-- Adding and removing groups of parts --
-----------------------------------------
-- Annex another structure into this one.
-- ** After calling this method, the annexed structure will be destroyed and
-- should be removed from any tables it is referenced in.
-- Parameters:
-- annexee is the structure to annex
-- annexeePart is the block that will connect to this structure
-- orientation is the side of annexee to attach
-- structurePart is the block to connect the structure to
-- side is the side of structurePart to add the annexee to
function Structure:annex(annexee, annexeeBaseVector, structureVector)
local structureSide = structureVector[3]
structureVector = StructureMath.addUnitVector(structureVector, structureSide)
local baseVector = StructureMath.subtractVectors(structureVector, annexeeBaseVector)
local parts = annexee.gridTable:loop()
for i=1,#parts do
local part = parts[i]
local annexeeVector = {part.location[1], part.location[2], part.location[3]}
local netVector = StructureMath.sumVectors(baseVector, annexeeVector)
local x, y = unpack(netVector)
if self.gridTable:index(x, y) then
annexee:disconnectPart(part.location)
else
annexee:removePart(part)
self:addPart(part, netVector[1], netVector[2], netVector[3])
end
end
end
function Structure:testEdge(vector)
local aX, aY, direction = unpack(vector)
local bX, bY = StructureMath.step(vector)
local gridTable = self.gridTable
local connection = false
local aPart = gridTable:index(aX, aY)
if aPart then
local aSide = StructureMath.subDirections(
aPart.location[3], direction)
connection = aPart.connectableSides[aSide]
end
local bPart = gridTable:index(bX, bY)
if bPart then
local bSide = StructureMath.subDirections(
bPart.location[3], direction + 2)
connection = connection and bPart.connectableSides[bSide]
end
return aPart, bPart, connection, {bX, aX}
end
function Structure:testConnection(testPoints)
local keep = {}
for _, location in ipairs(testPoints) do
local x, y = unpack(location)
if self.gridTable:index(x, y) then
if x ~= 0 or y ~= 0 then
table.insert(keep, {x, y})
end
end
end
testPoints = keep
local testedPoints = {}
local points = {}
local clusters = {}
local tested = GridTable()
if self.gridTable:index(0, 0) then
tested:index(0, 0, 2)
end
while #testPoints ~= 0 do
table.insert(points, table.remove(testPoints))
local testedPointX, TestedPointY = unpack(points[1])
tested:index(testedPointX, TestedPointY, 1)
while #points ~= 0 do
local point = table.remove(points)
table.insert(testedPoints, point)
for i = 1,4 do
local newPoint = StructureMath.addUnitVector(point, i)
local part = self.gridTable:index(unpack(point))
local newPart = self.gridTable:index(unpack(newPoint))
if part and newPart then
local partSide = (i - part.location[3]) % 4 + 1
local partConnect = part.connectableSides[partSide]
local newPartSide = (i - newPart.location[3] + 2) % 4 + 1
local newPartConnect = newPart.connectableSides[newPartSide]
if partConnect and newPartConnect then
for j = #testPoints, 1, -1 do
local ax, ay = unpack(newPoint)
local bx, by = unpack(testPoints[j])
if ax == bx and ay == by then
table.remove(testPoints, j)
end
end
local value = tested:index(unpack(newPoint))
if value == 2 then
for _, testedPoint in ipairs(testedPoints) do
local x, y = unpack(testedPoint)
tested:index(x, y, 2)
end
for _, eachPoint in ipairs(points) do
local x, y = unpack(eachPoint)
tested:index(x, y, 2)
end
testedPoints = {}
points = {}
break
elseif value ~= 1 then
local x, y = unpack(newPoint)
tested:index(x, y, 1)
table.insert(points, newPoint)
end
end
end
end
end
if #testedPoints ~= 0 then
table.insert(clusters, testedPoints)
testedPoints = {}
end
end
for _, group in ipairs(clusters) do
for j, location in ipairs(group) do
group[j] = self.gridTable:index(unpack(location))
end
end
return clusters
end
-- Part was disconnected or destroyed remove part and handle outcome.
function Structure:disconnectPart(location, isDestroyed)
local part = self.gridTable:index(location[1], location[2])
if #self.gridTable:loop() == 1 and not isDestroyed then
-- if structure will bedestoryed
if part.isDestroyed then
self:removePart(part)
end
return
end
--self:removePart(part)
local x, y = unpack(part.location)
self.gridTable:index(x, y, nil, true)
local savedPart
if isDestroyed then
self:removePart(part)
else
savedPart = part
end
local points = {}
for i = 1,4 do
table.insert(points, StructureMath.addUnitVector(part.location, i))
end
local clusters = self:testConnection(points)
local structureList
if savedPart then
if not self.corePart then
structureList = clusters
table.insert(structureList, {savedPart})
else
structureList = {{savedPart}}
for _, group in ipairs(clusters) do
for _, eachPart in ipairs(group) do
table.insert(structureList[1], eachPart)
end
end
end
else
structureList = clusters
end
for i = 1, #structureList do
local partList = structureList[i]
local basePart = partList[1]
local baseVector = basePart.location
local basePartFixture = basePart.modules["hull"].fixture
local location = Location.fixturePoint6(
basePartFixture, baseVector[1], baseVector[2])
baseVector = StructureMath.subtractVectors({0,0,3}, baseVector)
local structure = GridTable()
for _, eachPart in ipairs(partList) do
local partVector = {unpack(eachPart.location)}
local netVector = StructureMath.sumVectors(baseVector, partVector)
--if eachPart ~= savedPart then
self:removePart(eachPart)
--end
eachPart:setLocation(netVector)
structure:index(netVector[1], netVector[2], eachPart)
end
self.createObject("structure", location, {parts = structure})
end
end
-------------------------
-- Mangement functions --
-------------------------
-- Restructure input from player or output from ai
-- make the information easy for parts to handle.
function Structure:command(dt)
--TODO This is a wasteful way to do this look for a better way.
local capabilities = {}
for i, part in ipairs(self.gridTable:loop()) do
for key, module in pairs(part.modules) do
if key == "repair" then
capabilities.repair = true
elseif key == "gun" then
capabilities.combat = true
end
end
end
local orders = {}
if self.corePart then
orders = self.corePart:getOrders(self.body, capabilities)
end
local engineOrders = {}
local gunOrders = {}
for _, order in ipairs(orders) do
if order == "forward" then table.insert(engineOrders, order) end
if order == "back" then table.insert(engineOrders, order) end
if order == "strafeLeft" then table.insert(engineOrders, order) end
if order == "strafeRight" then table.insert(engineOrders, order) end
if order == "right" then table.insert(engineOrders, order) end
if order == "left" then table.insert(engineOrders, order) end
if order == "shoot" then table.insert(gunOrders, order) end
end
local gunControls = Gun.process(gunOrders)
local engineControls = Engine.process(engineOrders)
local function create(object, location)
location = StructureMath.sumVectors(location, object[2])
object[2] = self:getWorldLocation(location)
self.createObject(unpack(object))
end
local function getPart(location, pointer)
pointer[3] = 0
local x, y = unpack(StructureMath.sumVectors(location, pointer))
return self.gridTable:index(x, y)
end
local moduleInputs = {
dt = dt,
body = self.body,
getPart = getPart,
controls = {gun = gunControls, engine = engineControls},
teamHostility = self.worldInfo.teamHostility}
for i, part in ipairs(self.gridTable:loop()) do
for key, module in pairs(part.modules) do
local location = part.location
local newObject, disconnect = module:update(moduleInputs, location)
if newObject then
create(newObject, location)
end
if disconnect then
self:disconnectPart(location, true)
end
end
end
return commands
end
-- Handle commands
-- Update each part
function Structure:update(dt)
local partsInfo = self:command(dt)
self.shield:update(dt)
end
return Structure
| gpl-3.0 |
crunchuser/prosody-modules | mod_throttle_presence/mod_throttle_presence.lua | 31 | 1709 | local filters = require "util.filters";
local st = require "util.stanza";
module:depends("csi");
local function presence_filter(stanza, session)
if stanza._flush then
stanza._flush = nil;
return stanza;
end
local buffer = session.presence_buffer;
local from = stanza.attr.from;
if stanza.name ~= "presence" or (stanza.attr.type and stanza.attr.type ~= "unavailable") then
local cached_presence = buffer[stanza.attr.from];
if cached_presence then
module:log("debug", "Important stanza for %s from %s, flushing presence", session.full_jid, from);
stanza._flush = true;
cached_presence._flush = true;
session.send(cached_presence);
buffer[stanza.attr.from] = nil;
end
else
module:log("debug", "Buffering presence stanza from %s to %s", stanza.attr.from, session.full_jid);
buffer[stanza.attr.from] = st.clone(stanza);
return nil; -- Drop this stanza (we've stored it for later)
end
return stanza;
end
local function throttle_session(event)
local session = event.origin;
if session.presence_buffer then return; end
module:log("debug", "Suppressing presence updates to %s", session.full_jid);
session.presence_buffer = {};
filters.add_filter(session, "stanzas/out", presence_filter);
end
local function restore_session(event)
local session = event.origin;
if not session.presence_buffer then return; end
filters.remove_filter(session, "stanzas/out", presence_filter);
module:log("debug", "Flushing buffer for %s", session.full_jid);
for jid, presence in pairs(session.presence_buffer) do
session.send(presence);
end
session.presence_buffer = nil;
end
module:hook("csi-client-inactive", throttle_session);
module:hook("csi-client-active", restore_session);
| mit |
ld-test/csv2tensor | test/test.lua | 3 | 2700 | csv2tensor = require '../csv2tensor'
require 'csvigo'
--helper function
function get_index(s,ls)
for i,v in ipairs(ls) do
if s == v then return i end
end
return nil
end
--- Testing loading a file ---
function test_values(path)
local csv_data = csvigo.load({path=path})
local tensor_data, col_names = csv2tensor.load(path)
local col_i = nil
--go through each column in the csv table
for k,v in pairs(csv_data) do
col_i = get_index(k,col_names)
for i,n in ipairs(v) do
assert(tonumber(n) == tensor_data[i][col_i])
end
end
end
test_values("simple.csv")
print("passed basic test of loading csv")
function test_string_arg_include(path)
local tensor_data, col_names = csv2tensor.load(path,{include={'col_a'}})
--this one just uses a string rather than a list, used to cause error
local tensor_data, col_names = csv2tensor.load(path,{include='col_a'})
local tensor_data, col_names = csv2tensor.load(path,{exclude={'col_a'}})
--this one just uses a string rather than a list, used to cause error
-- local tensor_data, col_names = csv2tensor.load(path,{exclude='col_a'})
end
test_string_arg_include("simple.csv")
print("single arg in exclude/include passed")
function test_single_column_vector(path)
local tensor_data, col_names = csv2tensor.load(path,{include={'col_a'}})
assert(#(col_names) == 1,"failed on colnames")
assert(#(#tensor_data) == 1,"Nx1 returned")
end
test_single_column_vector("simple.csv")
print("single column as vector passed")
function test_include_order(path)
local keep = {'col_a','col_b'}
local _, col_names = csv2tensor.load(path,
{include=keep})
for i,k in ipairs(keep) do
assert(col_names[i] == k,"include order wrong")
end
local keep = {'col_b','col_c','col_a'}
local _, col_names = csv2tensor.load(path,
{include=keep})
for i,k in ipairs(keep) do
assert(col_names[i] == k,"include order wrong")
end
end
test_include_order("simple.csv")
print("passed include order")
function test_general_column_order(path)
local _, col_names = csv2tensor.load(path)
for i = 1,(#col_names-1) do
assert(col_names[i] < col_names[i+1], "columns in incorrect order")
end
end
test_general_column_order("simple.csv")
print("passed general column order")
function test_exclude_column_order(path)
local _, col_names = csv2tensor.load(path,{exclude='col_a'})
for i = 1,(#col_names-1) do
assert(col_names[i] < col_names[i+1], "columns in incorrect order")
end
end
test_exclude_column_order("simple.csv")
print("passed exclude column order")
print("tests passed") | mit |
Fenix-XI/Fenix | scripts/zones/Port_Windurst/npcs/Yujuju.lua | 13 | 2747 | -----------------------------------
-- Area: Port Windurst
-- NPC: Yujuju
-- Involved In Quest: Making Headlines
-- @pos 201.523 -4.785 138.978 240
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
function testflag(set,flag)
return (set % (2*flag) >= flag)
end
local MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES);
local WildcatWindurst = player:getVar("WildcatWindurst");
if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,19) == false) then
player:startEvent(0x026d);
elseif (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("MEMORIES_OF_A_MAIDEN_Status")==9) then
player:startEvent(0x0250);--COP event
elseif (MakingHeadlines == 1) then
local prog = player:getVar("QuestMakingHeadlines_var");
-- Variable to track if player has talked to 4 NPCs and a door
-- 1 = Kyume
-- 2 = Yujuju
-- 4 = Hiwom
-- 8 = Umumu
-- 16 = Mahogany Door
if (testflag(tonumber(prog),2) == false) then
player:startEvent(0x013a); -- Get Scoop
else
player:startEvent(0x013b); -- After receiving scoop
end
else
player:startEvent(0x0154); -- Standard Conversation
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 == 0x013a) then
prog = player:getVar("QuestMakingHeadlines_var");
player:addKeyItem(PORT_WINDURST_SCOOP);
player:messageSpecial(KEYITEM_OBTAINED,PORT_WINDURST_SCOOP);
player:setVar("QuestMakingHeadlines_var",prog+2);
elseif (csid == 0x0250) then
player:setVar("MEMORIES_OF_A_MAIDEN_Status",10);
elseif (csid == 0x026d) then
player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",19,true);
end
end;
| gpl-3.0 |
DarkstarProject/darkstar | scripts/globals/promyvion.lua | 12 | 3892 | require("scripts/zones/Promyvion-Dem/IDs")
require("scripts/zones/Promyvion-Holla/IDs")
require("scripts/zones/Promyvion-Mea/IDs")
require("scripts/zones/Promyvion-Vahzl/IDs")
require("scripts/globals/status")
------------------------------------
dsp = dsp or {}
dsp.promyvion = dsp.promyvion or {}
------------------------------------
-- LOCAL FUNCTIONS
------------------------------------
local function maxFloor(ID)
local m = 0
for _, v in pairs(ID.mob.MEMORY_RECEPTACLES) do
m = math.max(m, v[1])
end
return m
end
local function randomizeFloorExit(ID, floor)
local streams = {}
for _, v in pairs(ID.mob.MEMORY_RECEPTACLES) do
if v[1] == floor then
GetNPCByID(v[3]):setLocalVar("[promy]floorExit", 0)
table.insert(streams, v[3])
end
end
local exitStreamId = streams[math.random(#streams)]
GetNPCByID(exitStreamId):setLocalVar("[promy]floorExit", 1)
end
local function findMother(mob)
local ID = zones[mob:getZoneID()]
local mobId = mob:getID()
local mother = 0
for k, v in pairs(ID.mob.MEMORY_RECEPTACLES) do
if k < mobId and k > mother then
mother = k
end
end
return mother
end
------------------------------------
-- PUBLIC FUNCTIONS
------------------------------------
dsp.promyvion.initZone = function(zone)
local ID = zones[zone:getID()]
-- register teleporter regions
for k, v in pairs(ID.npc.MEMORY_STREAMS) do
zone:registerRegion(k,v[1],v[2],v[3],v[4],v[5],v[6])
end
-- randomize floor exits
for i = 1, maxFloor(ID) do
randomizeFloorExit(ID, i)
end
end
dsp.promyvion.strayOnSpawn = function(mob)
local mother = GetMobByID(findMother(mob))
if mother ~= nil and mother:isSpawned() then
mob:setPos(mother:getXPos(), mother:getYPos() - 5, mother:getZPos())
mother:AnimationSub(1)
end
end
dsp.promyvion.receptacleOnFight = function(mob, target)
if os.time() > mob:getLocalVar("[promy]nextStray") then
local ID = zones[mob:getZoneID()]
local mobId = mob:getID()
local numStrays = ID.mob.MEMORY_RECEPTACLES[mobId][2]
for i = mobId + 1, mobId + numStrays do
local stray = GetMobByID(i)
if not stray:isSpawned() then
mob:setLocalVar("[promy]nextStray", os.time() + 20)
stray:spawn()
stray:updateEnmity(target)
break
end
end
else
mob:AnimationSub(2)
end
end
dsp.promyvion.receptacleOnDeath = function(mob, isKiller)
if isKiller then
local ID = zones[mob:getZoneID()]
local mobId = mob:getID()
local floor = ID.mob.MEMORY_RECEPTACLES[mobId][1]
local streamId = ID.mob.MEMORY_RECEPTACLES[mobId][3]
local stream = GetNPCByID(streamId)
mob:AnimationSub(0)
-- open floor exit portal
if stream:getLocalVar("[promy]floorExit") == 1 then
randomizeFloorExit(ID, floor)
local events = ID.npc.MEMORY_STREAMS[streamId][7]
local event = events[math.random(#events)]
stream:setLocalVar("[promy]destination",event)
stream:openDoor(180)
end
end
end
dsp.promyvion.onRegionEnter = function(player, region)
if player:getAnimation() == 0 then
local ID = zones[player:getZoneID()]
local regionId = region:GetRegionID()
local event = nil
if regionId < 100 then
event = ID.npc.MEMORY_STREAMS[regionId][7][1]
else
local stream = GetNPCByID(regionId)
if stream ~= nil and stream:getAnimation() == dsp.anim.OPEN_DOOR then
event = stream:getLocalVar("[promy]destination")
end
end
if event ~= nil then
player:startEvent(event)
end
end
end | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Qufim_Island/TextIDs.lua | 10 | 1335 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6384; -- Obtained: <item>.
GIL_OBTAINED = 6385; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>.
BEASTMEN_BANNER = 7126; -- There is a beastmen's banner.
FISHING_MESSAGE_OFFSET = 7204; -- You can't fish here.
HOMEPOINT_SET = 12684; -- Home point set!
-- Conquest
CONQUEST = 7368; -- You've earned conquest points!
-- Quest dialog
THESE_WITHERED_FLOWERS = 7319; -- These withered flowers seem unable to bloom.
NOW_THAT_NIGHT_HAS_FALLEN = 7320; -- Now that night has fallen, the flowers bloom with a strange glow.
-- Other Dialog
AN_EMPTY_LIGHT_SWIRLS = 7728; -- An empty light swirls about the cave, eating away at the surroundings...
YOU_CANNOT_ENTER_DYNAMIS = 7838; -- You cannot enter Dynamis
PLAYERS_HAVE_NOT_REACHED_LEVEL = 7840; -- Players who have not reached levelare prohibited from entering Dynamis.
MYSTERIOUS_VOICE = 7826; -- You hear a mysterious, floating voice: Bring forth the
GIGANTIC_FOOTPRINT = 7812; -- There is a gigantic footprint here.
-- conquest Base
CONQUEST_BASE = 7045; -- Tallying conquest results...
| gpl-3.0 |
DarkstarProject/darkstar | scripts/globals/abilities/gallants_roll.lua | 12 | 2895 | -----------------------------------
-- Ability: Gallant's Roll
-- Reduces physical damage taken by party members within area of effect
-- Optimal Job: Paladin
-- Lucky Number: 3
-- Unlucky Number: 7
-- Level: 55
-- Phantom Roll +1 Value: 2.34
--
-- Die Roll |No PLD |With PLD
-- -------- ------- -----------
-- 1 |6% |11%
-- 2 |8% |13%
-- 3 |24% |29%
-- 4 |9% |14%
-- 5 |11% |16%
-- 6 |12% |17%
-- 7 |3% |8%
-- 8 |15% |20%
-- 9 |17% |22%
-- 10 |18% |23%
-- 11 |30% |35%
-- Bust |-5% |-5%
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/ability")
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------
function onAbilityCheck(player,target,ability)
local effectID = dsp.effect.GALLANTS_ROLL
ability:setRange(ability:getRange() + player:getMod(dsp.mod.ROLL_RANGE))
if (player:hasStatusEffect(effectID)) then
return dsp.msg.basic.ROLL_ALREADY_ACTIVE,0
elseif atMaxCorsairBusts(player) then
return dsp.msg.basic.CANNOT_PERFORM,0
else
return 0,0
end
end
function onUseAbility(caster,target,ability,action)
if (caster:getID() == target:getID()) then
corsairSetup(caster, ability, action, dsp.effect.GALLANTS_ROLL, dsp.job.PLD)
end
local total = caster:getLocalVar("corsairRollTotal")
return applyRoll(caster,target,ability,action,total)
end
function applyRoll(caster,target,ability,action,total)
local duration = 300 + caster:getMerit(dsp.merit.WINNING_STREAK) + caster:getMod(dsp.mod.PHANTOM_DURATION)
local effectpowers = {6, 8, 24, 9, 11, 12, 3, 15, 17, 18, 30, 5}
local effectpower = effectpowers[total]
if (caster:getLocalVar("corsairRollBonus") == 1 and total < 12) then
effectpower = effectpower + 5
end
-- Apply Additional Phantom Roll+ Buff
local phantomBase = 2.34 -- Base increment buff
local effectpower = effectpower + (phantomBase * phantombuffMultiple(caster))
-- Check if COR Main or Sub
if (caster:getMainJob() == dsp.job.COR and caster:getMainLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl())
elseif (caster:getSubJob() == dsp.job.COR and caster:getSubLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl())
end
if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(dsp.merit.BUST_DURATION), dsp.effect.GALLANTS_ROLL, effectpower, 0, duration, caster:getID(), total, dsp.mod.DMG) == false) then
ability:setMsg(dsp.msg.basic.ROLL_MAIN_FAIL)
elseif total > 11 then
ability:setMsg(dsp.msg.basic.DOUBLEUP_BUST)
end
return total
end
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Newton_Movalpolos/npcs/HomePoint#1.lua | 27 | 1274 | -----------------------------------
-- Area: Newton Movalpolos
-- NPC: HomePoint#1
-- @pos 444 27 -22 12
-----------------------------------
package.loaded["scripts/zones/Newton_Movalpolos/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Newton_Movalpolos/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 83);
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 == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Port_Windurst/npcs/Kususu.lua | 12 | 1113 | -----------------------------------
-- Area: Port Windurst
-- NPC: Kususu
-- Standard Merchant NPC
-----------------------------------
local ID = require("scripts/zones/Port_Windurst/IDs")
require("scripts/globals/shop")
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local stock =
{
4641, 1165, 1, -- Diaga
4662, 7025, 1, -- Stoneskin
4664, 837, 1, -- Slow
4610, 585, 2, -- Cure II
4636, 140, 2, -- Banish
4646, 1165, 2, -- Banishga
4661, 2097, 2, -- Blink
4609, 61, 3, -- Cure
4615, 1363, 3, -- Curaga
4622, 180, 3, -- Poisona
4623, 324, 3, -- Paralyna
4624, 990, 3, -- Blindna
4631, 82, 3, -- Dia
4651, 219, 3, -- Protect
4656, 1584, 3, -- Shell
4663, 360, 3, -- Aquaveil
}
player:showText(npc, ID.text.KUSUSU_SHOP_DIALOG)
dsp.shop.nation(player, stock, dsp.nation.WINDURST)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Norg/npcs/Verctissa.lua | 7 | 3120 | -----------------------------------
-- Area: Norg
-- NPC: Verctissa
-- Starts Quest: Trial Size Trial By Water
-- @pos -13 1 -20 252
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/quests");
require("scripts/globals/teleports");
require("scripts/zones/Norg/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(1549,1) and player:getQuestStatus(OUTLANDS,TRIAL_SIZE_TRIAL_BY_WATER) == QUEST_ACCEPTED and player:getMainJob() == JOB_SMN) then
player:startEvent(0x00c8,0,1549,2,20);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local TrialSizeWater = player:getQuestStatus(OUTLANDS,TRIAL_SIZE_TRIAL_BY_WATER);
if (player:getMainLvl() >= 20 and player:getMainJob() == JOB_SMN and TrialSizeWater == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 2) then --Requires player to be Summoner at least lvl 20
player:startEvent(0x00c7,0,1549,2,20); --mini tuning fork of water, zone, level
elseif (TrialSizeWater == QUEST_ACCEPTED) then
local WaterFork = player:hasItem(1549);
if (WaterFork) then
player:startEvent(0x006f); --Dialogue given to remind player to be prepared
elseif (WaterFork == false and tonumber(os.date("%j")) ~= player:getVar("TrialSizeWater_date")) then
player:startEvent(0x00cb,0,1549,2,20); --Need another mini tuning fork
end
elseif (TrialSizeWater == QUEST_COMPLETED) then
player:startEvent(0x00ca); --Defeated Avatar
else
player:startEvent(0x0072); --Standard dialogue
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x00c7 and option == 1) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1549); --Mini tuning fork
else
player:setVar("TrialSizeWater_date", 0);
player:addQuest(OUTLANDS,TRIAL_SIZE_TRIAL_BY_WATER);
player:addItem(1549);
player:messageSpecial(ITEM_OBTAINED,1549);
end
elseif (csid == 0x00cb and option == 1) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1549); --Mini tuning fork
else
player:addItem(1549);
player:messageSpecial(ITEM_OBTAINED,1549);
end
elseif (csid == 0x00c8 and option == 1) then
toCloisterOfTides(player);
end
end; | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Wajaom_Woodlands/npcs/_1f1.lua | 13 | 1097 | -----------------------------------
-- Area: Wajaom Woodlands
-- NPC: Engraved Tablet
-- @pos -64 -11 -641 51
-----------------------------------
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(SICKLEMOON_SALT)) then
player:startEvent(0x0202);
else
player:startEvent(0x0204);
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 == 0x0202 and option == 1) then
player:delKeyItem(SICKLEMOON_SALT);
end
end; | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/King_Ranperres_Tomb/npcs/qm1.lua | 13 | 1232 | -----------------------------------
-- Area: King Ranperre's Tomb
-- NPC: ??? (qm1)
-- Notes: Used to teleport down the stairs
-- @pos -81 -1 -97 190
-----------------------------------
package.loaded["scripts/zones/King_Ranperres_Tomb/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/King_Ranperres_Tomb/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x000a);
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);
-- TODO: Missing teleport-animation. Might be a core issue as to why it wont display.
if (csid == 0x000a and option == 100) then
player:setPos(-81.5,7.297,-127.919,71);
end
end; | gpl-3.0 |
ungarscool1/HL2RP | hl2rp/gamemode/modules/doorsystem/cl_doors.lua | 1 | 4887 | local meta = FindMetaTable("Entity")
local black = Color(0, 0, 0, 255)
local white = Color(255, 255, 255, 200)
local red = Color(128, 30, 30, 255)
function meta:drawOwnableInfo()
if LocalPlayer():InVehicle() then return end
-- Look, if you want to change the way door ownership is drawn, don't edit this file, use the hook instead!
local doorDrawing = hook.Call("HUDDrawDoorData", nil, self)
if doorDrawing == true then return end
local blocked = self:getKeysNonOwnable()
local superadmin = LocalPlayer():IsSuperAdmin()
local doorTeams = self:getKeysDoorTeams()
local doorGroup = self:getKeysDoorGroup()
local playerOwned = self:isKeysOwned() or table.GetFirstValue(self:getKeysCoOwners() or {}) ~= nil
local owned = playerOwned or doorGroup or doorTeams
local doorInfo = {}
local title = self:getKeysTitle()
if title then table.insert(doorInfo, title) end
if owned then
table.insert(doorInfo, DarkRP.getPhrase("keys_owned_by"))
end
if playerOwned then
if self:isKeysOwned() then table.insert(doorInfo, self:getDoorOwner():Nick()) end
for k,v in pairs(self:getKeysCoOwners() or {}) do
local ent = Player(k)
if not IsValid(ent) or not ent:IsPlayer() then continue end
table.insert(doorInfo, ent:Nick())
end
local allowedCoOwn = self:getKeysAllowedToOwn()
if allowedCoOwn and not fn.Null(allowedCoOwn) then
table.insert(doorInfo, DarkRP.getPhrase("keys_other_allowed"))
for k,v in pairs(allowedCoOwn) do
local ent = Player(k)
if not IsValid(ent) or not ent:IsPlayer() then continue end
table.insert(doorInfo, ent:Nick())
end
end
elseif doorGroup then
table.insert(doorInfo, doorGroup)
elseif doorTeams then
for k, v in pairs(doorTeams) do
if not v or not RPExtraTeams[k] then continue end
table.insert(doorInfo, RPExtraTeams[k].name)
end
elseif blocked and superadmin then
table.insert(doorInfo, DarkRP.getPhrase("keys_allow_ownership"))
elseif not blocked then
table.insert(doorInfo, DarkRP.getPhrase("keys_unowned"))
if superadmin then
table.insert(doorInfo, DarkRP.getPhrase("keys_disallow_ownership"))
end
end
if self:IsVehicle() then
for k,v in pairs(player.GetAll()) do
if v:GetVehicle() ~= self then continue end
table.insert(doorInfo, DarkRP.getPhrase("driver", v:Nick()))
break
end
end
local x, y = ScrW() / 2, ScrH() / 2
draw.DrawNonParsedText(table.concat(doorInfo, "\n"), "TargetID", x , y + 1 , black, 1)
draw.DrawNonParsedText(table.concat(doorInfo, "\n"), "TargetID", x, y, (blocked or owned) and white or red, 1)
end
/*---------------------------------------------------------------------------
Door data
---------------------------------------------------------------------------*/
DarkRP.doorData = DarkRP.doorData or {}
/*---------------------------------------------------------------------------
Interface functions
---------------------------------------------------------------------------*/
function meta:getDoorData()
local doorData = DarkRP.doorData[self:EntIndex()] or {}
self.DoorData = doorData -- Backwards compatibility
return doorData
end
/*---------------------------------------------------------------------------
Networking
---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------
Retrieve all the data for all doors
---------------------------------------------------------------------------*/
local function retrieveAllDoorData(len)
local data = net.ReadTable()
DarkRP.doorData = data
end
net.Receive("DarkRP_AllDoorData", retrieveAllDoorData)
hook.Add("InitPostEntity", "DoorData", fp{RunConsoleCommand, "_sendAllDoorData"})
/*---------------------------------------------------------------------------
Update changed variables
---------------------------------------------------------------------------*/
local function updateDoorData()
local door = net.ReadUInt(32)
DarkRP.doorData[door] = DarkRP.doorData[door] or {}
local var = net.ReadString()
local valueType = net.ReadUInt(8)
local value = net.ReadType(valueType)
DarkRP.doorData[door][var] = value
end
net.Receive("DarkRP_UpdateDoorData", updateDoorData)
/*---------------------------------------------------------------------------
Remove doordata of removed entity
---------------------------------------------------------------------------*/
local function removeDoorData()
local door = net.ReadUInt(32)
DarkRP.doorData[door] = nil
end
net.Receive("DarkRP_RemoveDoorData", removeDoorData)
| agpl-3.0 |
soheildiscover/soheil | plugins/boobs.lua | 731 | 1601 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "!boobs" then
url = getRandomBoobs()
end
if matches[1] == "!butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"!boobs: Get a boobs NSFW image. 🔞",
"!butts: Get a butts NSFW image. 🔞"
},
patterns = {
"^!boobs$",
"^!butts$"
},
run = run
}
end
| gpl-2.0 |
Fenix-XI/Fenix | scripts/zones/Windurst_Woods/npcs/Retto-Marutto.lua | 27 | 1193 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Retto-Marutto
-- Guild Merchant NPC: Bonecrafting Guild
-- @pos -6.142 -6.55 -132.639 241
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(5142,8,23,3)) then
player:showText(npc,RETTO_MARUTTO_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
hilllinux/lua-resty-http | lib/resty/http.lua | 6 | 21361 | local http_headers = require "resty.http_headers"
local ngx_socket_tcp = ngx.socket.tcp
local ngx_req = ngx.req
local ngx_req_socket = ngx_req.socket
local ngx_req_get_headers = ngx_req.get_headers
local ngx_req_get_method = ngx_req.get_method
local str_gmatch = string.gmatch
local str_lower = string.lower
local str_upper = string.upper
local str_find = string.find
local str_sub = string.sub
local str_gsub = string.gsub
local tbl_concat = table.concat
local tbl_insert = table.insert
local ngx_encode_args = ngx.encode_args
local ngx_re_match = ngx.re.match
local ngx_re_gsub = ngx.re.gsub
local ngx_log = ngx.log
local ngx_DEBUG = ngx.DEBUG
local ngx_ERR = ngx.ERR
local ngx_NOTICE = ngx.NOTICE
local ngx_var = ngx.var
local co_yield = coroutine.yield
local co_create = coroutine.create
local co_status = coroutine.status
local co_resume = coroutine.resume
-- http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
local HOP_BY_HOP_HEADERS = {
["connection"] = true,
["keep-alive"] = true,
["proxy-authenticate"] = true,
["proxy-authorization"] = true,
["te"] = true,
["trailers"] = true,
["transfer-encoding"] = true,
["upgrade"] = true,
["content-length"] = true, -- Not strictly hop-by-hop, but Nginx will deal
-- with this (may send chunked for example).
}
-- Reimplemented coroutine.wrap, returning "nil, err" if the coroutine cannot
-- be resumed. This protects user code from inifite loops when doing things like
-- repeat
-- local chunk, err = res.body_reader()
-- if chunk then -- <-- This could be a string msg in the core wrap function.
-- ...
-- end
-- until not chunk
local co_wrap = function(func)
local co = co_create(func)
if not co then
return nil, "could not create coroutine"
else
return function(...)
if co_status(co) == "suspended" then
return select(2, co_resume(co, ...))
else
return nil, "can't resume a " .. co_status(co) .. " coroutine"
end
end
end
end
local _M = {
_VERSION = '0.06',
}
_M._USER_AGENT = "lua-resty-http/" .. _M._VERSION .. " (Lua) ngx_lua/" .. ngx.config.ngx_lua_version
local mt = { __index = _M }
local HTTP = {
[1.0] = " HTTP/1.0\r\n",
[1.1] = " HTTP/1.1\r\n",
}
local DEFAULT_PARAMS = {
method = "GET",
path = "/",
version = 1.1,
}
function _M.new(self)
local sock, err = ngx_socket_tcp()
if not sock then
return nil, err
end
return setmetatable({ sock = sock, keepalive = true }, mt)
end
function _M.set_timeout(self, timeout)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:settimeout(timeout)
end
function _M.ssl_handshake(self, ...)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:sslhandshake(...)
end
function _M.connect(self, ...)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
self.host = select(1, ...)
self.keepalive = true
return sock:connect(...)
end
function _M.set_keepalive(self, ...)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
if self.keepalive == true then
return sock:setkeepalive(...)
else
-- The server said we must close the connection, so we cannot setkeepalive.
-- If close() succeeds we return 2 instead of 1, to differentiate between
-- a normal setkeepalive() failure and an intentional close().
local res, err = sock:close()
if res then
return 2, "connection must be closed"
else
return res, err
end
end
end
function _M.get_reused_times(self)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:getreusedtimes()
end
function _M.close(self)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:close()
end
local function _should_receive_body(method, code)
if method == "HEAD" then return nil end
if code == 204 or code == 304 then return nil end
if code >= 100 and code < 200 then return nil end
return true
end
function _M.parse_uri(self, uri)
local m, err = ngx_re_match(uri, [[^(http[s]*)://([^:/]+)(?::(\d+))?(.*)]],
"jo")
if not m then
if err then
return nil, "failed to match the uri: " .. err
end
return nil, "bad uri"
else
if not m[3] then
if m[1] == "https" then
m[3] = 443
else
m[3] = 80
end
end
if not m[4] then m[4] = "/" end
return m, nil
end
end
local function _format_request(params)
local version = params.version
local headers = params.headers or {}
local query = params.query or ""
if query then
if type(query) == "table" then
query = "?" .. ngx_encode_args(query)
end
end
-- Initialize request
local req = {
str_upper(params.method),
" ",
params.path,
query,
HTTP[version],
-- Pre-allocate slots for minimum headers and carriage return.
true,
true,
true,
}
local c = 6 -- req table index it's faster to do this inline vs table.insert
-- Append headers
for key, values in pairs(headers) do
if type(values) ~= "table" then
values = {values}
end
key = tostring(key)
for _, value in pairs(values) do
req[c] = key .. ": " .. tostring(value) .. "\r\n"
c = c + 1
end
end
-- Close headers
req[c] = "\r\n"
return tbl_concat(req)
end
local function _receive_status(sock)
local line, err = sock:receive("*l")
if not line then
return nil, nil, err
end
return tonumber(str_sub(line, 10, 12)), tonumber(str_sub(line, 6, 8))
end
local function _receive_headers(sock)
local headers = http_headers.new()
repeat
local line, err = sock:receive("*l")
if not line then
return nil, err
end
for key, val in str_gmatch(line, "([^:%s]+):%s*(.+)") do
if headers[key] then
if type(headers[key]) ~= "table" then
headers[key] = { headers[key] }
end
tbl_insert(headers[key], tostring(val))
else
headers[key] = tostring(val)
end
end
until str_find(line, "^%s*$")
return headers, nil
end
local function _chunked_body_reader(sock, default_chunk_size)
return co_wrap(function(max_chunk_size)
local max_chunk_size = max_chunk_size or default_chunk_size
local remaining = 0
local length
repeat
-- If we still have data on this chunk
if max_chunk_size and remaining > 0 then
if remaining > max_chunk_size then
-- Consume up to max_chunk_size
length = max_chunk_size
remaining = remaining - max_chunk_size
else
-- Consume all remaining
length = remaining
remaining = 0
end
else -- This is a fresh chunk
-- Receive the chunk size
local str, err = sock:receive("*l")
if not str then
co_yield(nil, err)
end
length = tonumber(str, 16)
if not length then
co_yield(nil, "unable to read chunksize")
end
if max_chunk_size and length > max_chunk_size then
-- Consume up to max_chunk_size
remaining = length - max_chunk_size
length = max_chunk_size
end
end
if length > 0 then
local str, err = sock:receive(length)
if not str then
co_yield(nil, err)
end
max_chunk_size = co_yield(str) or default_chunk_size
-- If we're finished with this chunk, read the carriage return.
if remaining == 0 then
sock:receive(2) -- read \r\n
end
else
-- Read the last (zero length) chunk's carriage return
sock:receive(2) -- read \r\n
end
until length == 0
end)
end
local function _body_reader(sock, content_length, default_chunk_size)
return co_wrap(function(max_chunk_size)
local max_chunk_size = max_chunk_size or default_chunk_size
if not content_length and max_chunk_size then
-- We have no length, but wish to stream.
-- HTTP 1.0 with no length will close connection, so read chunks to the end.
repeat
local str, err, partial = sock:receive(max_chunk_size)
if not str and err == "closed" then
max_chunk_size = tonumber(co_yield(partial, err) or default_chunk_size)
end
max_chunk_size = tonumber(co_yield(str) or default_chunk_size)
if max_chunk_size and max_chunk_size < 0 then max_chunk_size = nil end
if not max_chunk_size then
ngx_log(ngx_ERR, "Buffer size not specified, bailing")
break
end
until not str
elseif not content_length then
-- We have no length but don't wish to stream.
-- HTTP 1.0 with no length will close connection, so read to the end.
co_yield(sock:receive("*a"))
elseif not max_chunk_size then
-- We have a length and potentially keep-alive, but want everything.
co_yield(sock:receive(content_length))
else
-- We have a length and potentially a keep-alive, and wish to stream
-- the response.
local received = 0
repeat
local length = max_chunk_size
if received + length > content_length then
length = content_length - received
end
if length > 0 then
local str, err = sock:receive(length)
if not str then
max_chunk_size = tonumber(co_yield(nil, err) or default_chunk_size)
end
received = received + length
max_chunk_size = tonumber(co_yield(str) or default_chunk_size)
if max_chunk_size and max_chunk_size < 0 then max_chunk_size = nil end
if not max_chunk_size then
ngx_log(ngx_ERR, "Buffer size not specified, bailing")
break
end
end
until length == 0
end
end)
end
local function _no_body_reader()
return nil
end
local function _read_body(res)
local reader = res.body_reader
if not reader then
-- Most likely HEAD or 304 etc.
return nil, "no body to be read"
end
local chunks = {}
local c = 1
local chunk, err
repeat
chunk, err = reader()
if err then
return nil, err, tbl_concat(chunks) -- Return any data so far.
end
if chunk then
chunks[c] = chunk
c = c + 1
end
until not chunk
return tbl_concat(chunks)
end
local function _trailer_reader(sock)
return co_wrap(function()
co_yield(_receive_headers(sock))
end)
end
local function _read_trailers(res)
local reader = res.trailer_reader
if not reader then
return nil, "no trailers"
end
local trailers = reader()
setmetatable(res.headers, { __index = trailers })
end
local function _send_body(sock, body)
if type(body) == 'function' then
repeat
local chunk, err, partial = body()
if chunk then
local ok,err = sock:send(chunk)
if not ok then
return nil, err
end
elseif err ~= nil then
return nil, err, partial
end
until chunk == nil
elseif body ~= nil then
local bytes, err = sock:send(body)
if not bytes then
return nil, err
end
end
return true, nil
end
local function _handle_continue(sock, body)
local status, version, err = _receive_status(sock)
if not status then
return nil, err
end
-- Only send body if we receive a 100 Continue
if status == 100 then
local ok, err = sock:receive("*l") -- Read carriage return
if not ok then
return nil, err
end
_send_body(sock, body)
end
return status, version, err
end
function _M.send_request(self, params)
-- Apply defaults
setmetatable(params, { __index = DEFAULT_PARAMS })
local sock = self.sock
local body = params.body
local headers = http_headers.new()
local params_headers = params.headers
if params_headers then
-- We assign one by one so that the metatable can handle case insensitivity
-- for us. You can blame the spec for this inefficiency.
for k,v in pairs(params_headers) do
headers[k] = v
end
end
-- Ensure minimal headers are set
if type(body) == 'string' and not headers["Content-Length"] then
headers["Content-Length"] = #body
end
if not headers["Host"] then
headers["Host"] = self.host
end
if not headers["User-Agent"] then
headers["User-Agent"] = _M._USER_AGENT
end
if params.version == 1.0 and not headers["Connection"] then
headers["Connection"] = "Keep-Alive"
end
params.headers = headers
-- Format and send request
local req = _format_request(params)
ngx_log(ngx_DEBUG, "\n", req)
local bytes, err = sock:send(req)
if not bytes then
return nil, err
end
-- Send the request body, unless we expect: continue, in which case
-- we handle this as part of reading the response.
if headers["Expect"] ~= "100-continue" then
local ok, err, partial = _send_body(sock, body)
if not ok then
return nil, err, partial
end
end
return true
end
function _M.read_response(self, params)
local sock = self.sock
local status, version, err
-- If we expect: continue, we need to handle this, sending the body if allowed.
-- If we don't get 100 back, then status is the actual status.
if params.headers["Expect"] == "100-continue" then
local _status, _version, _err = _handle_continue(sock, params.body)
if not _status then
return nil, _err
elseif _status ~= 100 then
status, version, err = _status, _version, _err
end
end
-- Just read the status as normal.
if not status then
status, version, err = _receive_status(sock)
if not status then
return nil, err
end
end
local res_headers, err = _receive_headers(sock)
if not res_headers then
return nil, err
end
-- Determine if we should keepalive or not.
local ok, connection = pcall(str_lower, res_headers["Connection"])
if ok then
if (version == 1.1 and connection == "close") or
(version == 1.0 and connection ~= "keep-alive") then
self.keepalive = false
end
end
local body_reader = _no_body_reader
local trailer_reader, err = nil, nil
local has_body = false
-- Receive the body_reader
if _should_receive_body(params.method, status) then
local ok, encoding = pcall(str_lower, res_headers["Transfer-Encoding"])
if ok and version == 1.1 and encoding == "chunked" then
body_reader, err = _chunked_body_reader(sock)
has_body = true
else
local ok, length = pcall(tonumber, res_headers["Content-Length"])
if ok then
body_reader, err = _body_reader(sock, length)
has_body = true
end
end
end
if res_headers["Trailer"] then
trailer_reader, err = _trailer_reader(sock)
end
if err then
return nil, err
else
return {
status = status,
headers = res_headers,
has_body = has_body,
body_reader = body_reader,
read_body = _read_body,
trailer_reader = trailer_reader,
read_trailers = _read_trailers,
}
end
end
function _M.request(self, params)
local res, err = self:send_request(params)
if not res then
return res, err
else
return self:read_response(params)
end
end
function _M.request_pipeline(self, requests)
for i, params in ipairs(requests) do
if params.headers and params.headers["Expect"] == "100-continue" then
return nil, "Cannot pipeline request specifying Expect: 100-continue"
end
local res, err = self:send_request(params)
if not res then
return res, err
end
end
local responses = {}
for i, params in ipairs(requests) do
responses[i] = setmetatable({
params = params,
response_read = false,
}, {
-- Read each actual response lazily, at the point the user tries
-- to access any of the fields.
__index = function(t, k)
local res, err
if t.response_read == false then
res, err = _M.read_response(self, t.params)
t.response_read = true
if not res then
ngx_log(ngx_ERR, err)
else
for rk, rv in pairs(res) do
t[rk] = rv
end
end
end
return rawget(t, k)
end,
})
end
return responses
end
function _M.request_uri(self, uri, params)
if not params then params = {} end
local parsed_uri, err = self:parse_uri(uri)
if not parsed_uri then
return nil, err
end
local scheme, host, port, path = unpack(parsed_uri)
if not params.path then params.path = path end
local c, err = self:connect(host, port)
if not c then
return nil, err
end
if scheme == "https" then
local verify = true
if params.ssl_verify == false then
verify = false
end
local ok, err = self:ssl_handshake(nil, host, verify)
if not ok then
return nil, err
end
end
local res, err = self:request(params)
if not res then
return nil, err
end
local body, err = res:read_body()
if not body then
return nil, err
end
res.body = body
local ok, err = self:set_keepalive()
if not ok then
ngx_log(ngx_ERR, err)
end
return res, nil
end
function _M.get_client_body_reader(self, chunksize, sock)
local chunksize = chunksize or 65536
if not sock then
local ok, err
ok, sock, err = pcall(ngx_req_socket)
if not ok then
return nil, sock -- pcall err
end
if not sock then
if err == "no body" then
return nil
else
return nil, err
end
end
end
local headers = ngx_req_get_headers()
local length = headers.content_length
local encoding = headers.transfer_encoding
if length then
return _body_reader(sock, tonumber(length), chunksize)
elseif encoding and str_lower(encoding) == 'chunked' then
-- Not yet supported by ngx_lua but should just work...
return _chunked_body_reader(sock, chunksize)
else
return nil
end
end
function _M.proxy_request(self, chunksize)
return self:request{
method = ngx_req_get_method(),
path = ngx_re_gsub(ngx_var.uri, "\\s", "%20", "jo") .. ngx_var.is_args .. (ngx_var.query_string or ""),
body = self:get_client_body_reader(chunksize),
headers = ngx_req_get_headers(),
}
end
function _M.proxy_response(self, response, chunksize)
if not response then
ngx_log(ngx_ERR, "no response provided")
return
end
ngx.status = response.status
-- Filter out hop-by-hop headeres
for k,v in pairs(response.headers) do
if not HOP_BY_HOP_HEADERS[str_lower(k)] then
ngx.header[k] = v
end
end
local reader = response.body_reader
repeat
local chunk, err = reader(chunksize)
if err then
ngx_log(ngx_ERR, err)
break
end
if chunk then
ngx.print(chunk)
end
until not chunk
end
return _M
| bsd-2-clause |
DarkstarProject/darkstar | scripts/globals/items/winterflower.lua | 11 | 1056 | -----------------------------------------
-- ID: 5907
-- Item: Winterflower
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Agility +3
-- Intelligence +5
-- Charisma -5
-- Resist Virus +20
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,300,5907)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.AGI, 3)
target:addMod(dsp.mod.INT, 5)
target:addMod(dsp.mod.CHR, -5)
target:addMod(dsp.mod.VIRUSRES, 20)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.AGI, 3)
target:delMod(dsp.mod.INT, 5)
target:delMod(dsp.mod.CHR, -5)
target:delMod(dsp.mod.VIRUSRES, 20)
end
| gpl-3.0 |
ungarscool1/HL2RP | hl2rp/gamemode/modules/fadmin/fadmin/playeractions/ignite/cl_init.lua | 4 | 1154 | FAdmin.StartHooks["Ignite"] = function()
FAdmin.Access.AddPrivilege("Ignite", 2)
FAdmin.Commands.AddCommand("Ignite", nil, "<Player>", "[time]")
FAdmin.Commands.AddCommand("unignite", nil, "<Player>")
FAdmin.ScoreBoard.Player:AddActionButton(function(ply) return (ply:FAdmin_GetGlobal("FAdmin_ignited") and "Extinguish") or "Ignite" end,
function(ply) local disabled = (ply:FAdmin_GetGlobal("FAdmin_ignited") and "fadmin/icons/disable") or nil return "fadmin/icons/ignite", disabled end,
Color(255, 130, 0, 255),
function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "Ignite", ply) end,
function(ply, button)
if not ply:FAdmin_GetGlobal("FAdmin_ignited") then
RunConsoleCommand("_FAdmin", "ignite", ply:UserID())
button:SetImage2("fadmin/icons/disable")
button:SetText("Extinguish")
button:GetParent():InvalidateLayout()
else
RunConsoleCommand("_FAdmin", "unignite", ply:UserID())
button:SetImage2("null")
button:SetText("Ignite")
button:GetParent():InvalidateLayout()
end
end)
end
| agpl-3.0 |
dios-game/dios | templates/lua_cocos/resources/src/cocos/framework/extends/UIScrollView.lua | 55 | 2042 |
--[[
Copyright (c) 2011-2014 chukong-inc.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
local ScrollView = ccui.ScrollView
function ScrollView:onEvent(callback)
self:addEventListener(function(sender, eventType)
local event = {}
if eventType == 0 then
event.name = "SCROLL_TO_TOP"
elseif eventType == 1 then
event.name = "SCROLL_TO_BOTTOM"
elseif eventType == 2 then
event.name = "SCROLL_TO_LEFT"
elseif eventType == 3 then
event.name = "SCROLL_TO_RIGHT"
elseif eventType == 4 then
event.name = "SCROLLING"
elseif eventType == 5 then
event.name = "BOUNCE_TOP"
elseif eventType == 6 then
event.name = "BOUNCE_BOTTOM"
elseif eventType == 7 then
event.name = "BOUNCE_LEFT"
elseif eventType == 8 then
event.name = "BOUNCE_RIGHT"
end
event.target = sender
callback(event)
end)
return self
end
ScrollView.onScroll = ScrollView.onEvent
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.