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 |
|---|---|---|---|---|---|
rns/libmarpa-bindings | lua/location.lua | 2 | 1670 | --[[
location object prototype for the Kollos project
according to
https://github.com/rns/kollos-luif-doc/blob/master/etc/internals.md
--]]
--[[
-- the blob name. Required. Archetypally a file name, but not all locations will be in files.
Blob name must be suitable for appearing in messages.
start() and end() -- start and end positions. Length of the text will be end - start.
range() -- start and end positions as a two-element array.
text() -- the text from start to end. LUIF source follows Lua restrictions, which means no Unicode.
line_column(pos) -- given a position, of the sort returned by start() and end(), returns the position in a more convenient representation. What is "more convenient" depends on the class of the blob, but typically this will be line and column.
sublocation() -- the current location within the blob in form suitable for an error message.
location() -- the current location, including the blob name.
--]]
-- namespace
local location_class = {}
-- methods to go to prototype
function location_class.location (location_object)
return location_object.blob .. ': ' .. location_object.line
end
-- prototype with default values and methods
location_class.prototype = {
_type = "location", blob = "", text = "", line = "",
location = location_class.location,
}
-- constructor
function location_class.new (location_object)
setmetatable(location_object, location_class.mt)
return location_object
end
-- metatable
location_class.mt = {}
-- the __index metamethod points to prototype
location_class.mt.__tostring = location_class.location
location_class.mt.__index = location_class.prototype
return location_class
| gpl-3.0 |
BillardDRP/nathaniel-rp-addons | addons/billard_ents/lua/entities/billard_wrap/init.lua | 1 | 1389 | AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
function ENT:Initialize()
self:SetModel("models/props/cs_office/Paper_towels.mdl")
self:SetMaterial("models/debug/debugwhite")
self:SetColor(Color(120, 255, 0, 255))
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
local phys = self:GetPhysicsObject()
if phys:IsValid() then
phys:Wake()
end
self:SetUseType(3)
self:SetCanBeUsed(true)
end
function ENT:Touch(toucher)
if IsValid(toucher) and !toucher:IsPlayer() and !toucher:IsWorld() and self:GetCanBeUsed() then
self:SetCanBeUsed(false)
local gift = ents.Create("billard_gift")
if !IsValid(gift) then return end
gift:SetOutputModel(toucher:GetModel())
gift:SetOutputClass(toucher:GetClass())
gift:SetOutputPitch(toucher:GetAngles().pitch)
gift:SetOutputYaw(toucher:GetAngles().yaw)
gift:SetOutputRoll(toucher:GetAngles().roll)
if toucher:GetColor() then
gift:SetOutputRed(toucher:GetColor().r)
gift:SetOutputGreen(toucher:GetColor().g)
gift:SetOutputBlue(toucher:GetColor().b)
end
if toucher:GetMaterial() then
gift:SetOutputMaterial(toucher:GetMaterial())
end
gift:SetPos(self:GetPos() + Vector(0, 0, 40))
gift:Spawn()
toucher:Remove()
self:EmitSound("ui/item_gift_wrap_use.wav")
self:Remove()
end
end
| gpl-3.0 |
guiquanz/Dato-Core | src/unity/python/graphlab/lua/pl/lapp.lua | 20 | 13955 | --- Simple command-line parsing using human-readable specification.
-- Supports GNU-style parameters.
--
-- lapp = require 'pl.lapp'
-- local args = lapp [[
-- Does some calculations
-- -o,--offset (default 0.0) Offset to add to scaled number
-- -s,--scale (number) Scaling factor
-- <number>; (number ) Number to be scaled
-- ]]
--
-- print(args.offset + args.scale * args.number)
--
-- Lines begining with '-' are flags; there may be a short and a long name;
-- lines begining wih '<var>' are arguments. Anything in parens after
-- the flag/argument is either a default, a type name or a range constraint.
--
-- See @{08-additional.md.Command_line_Programs_with_Lapp|the Guide}
--
-- Dependencies: `pl.sip`
-- @module pl.lapp
local status,sip = pcall(require,'pl.sip')
if not status then
sip = require 'sip'
end
local match = sip.match_at_start
local append,tinsert = table.insert,table.insert
sip.custom_pattern('X','(%a[%w_%-]*)')
local function lines(s) return s:gmatch('([^\n]*)\n') end
local function lstrip(str) return str:gsub('^%s+','') end
local function strip(str) return lstrip(str):gsub('%s+$','') end
local function at(s,k) return s:sub(k,k) end
local function isdigit(s) return s:find('^%d+$') == 1 end
local lapp = {}
local open_files,parms,aliases,parmlist,usage,windows,script
lapp.callback = false -- keep Strict happy
local filetypes = {
stdin = {io.stdin,'file-in'}, stdout = {io.stdout,'file-out'},
stderr = {io.stderr,'file-out'}
}
--- controls whether to dump usage on error.
-- Defaults to true
lapp.show_usage_error = true
--- quit this script immediately.
-- @string msg optional message
-- @bool no_usage suppress 'usage' display
function lapp.quit(msg,no_usage)
if no_usage == 'throw' then
error(msg)
end
if msg then
io.stderr:write(msg..'\n\n')
end
if not no_usage then
io.stderr:write(usage)
end
os.exit(1)
end
--- print an error to stderr and quit.
-- @string msg a message
-- @bool no_usage suppress 'usage' display
function lapp.error(msg,no_usage)
if not lapp.show_usage_error then
no_usage = true
elseif lapp.show_usage_error == 'throw' then
no_usage = 'throw'
end
lapp.quit(script..': '..msg,no_usage)
end
--- open a file.
-- This will quit on error, and keep a list of file objects for later cleanup.
-- @string file filename
-- @string[opt] opt same as second parameter of `io.open`
function lapp.open (file,opt)
local val,err = io.open(file,opt)
if not val then lapp.error(err,true) end
append(open_files,val)
return val
end
--- quit if the condition is false.
-- @bool condn a condition
-- @string msg message text
function lapp.assert(condn,msg)
if not condn then
lapp.error(msg)
end
end
local function range_check(x,min,max,parm)
lapp.assert(min <= x and max >= x,parm..' out of range')
end
local function xtonumber(s)
local val = tonumber(s)
if not val then lapp.error("unable to convert to number: "..s) end
return val
end
local types = {}
local builtin_types = {string=true,number=true,['file-in']='file',['file-out']='file',boolean=true}
local function convert_parameter(ps,val)
if ps.converter then
val = ps.converter(val)
end
if ps.type == 'number' then
val = xtonumber(val)
elseif builtin_types[ps.type] == 'file' then
val = lapp.open(val,(ps.type == 'file-in' and 'r') or 'w' )
elseif ps.type == 'boolean' then
return val
end
if ps.constraint then
ps.constraint(val)
end
return val
end
--- add a new type to Lapp. These appear in parens after the value like
-- a range constraint, e.g. '<ival> (integer) Process PID'
-- @string name name of type
-- @param converter either a function to convert values, or a Lua type name.
-- @func[opt] constraint optional function to verify values, should use lapp.error
-- if failed.
function lapp.add_type (name,converter,constraint)
types[name] = {converter=converter,constraint=constraint}
end
local function force_short(short)
lapp.assert(#short==1,short..": short parameters should be one character")
end
-- deducing type of variable from default value;
local function process_default (sval,vtype)
local val
if not vtype or vtype == 'number' then
val = tonumber(sval)
end
if val then -- we have a number!
return val,'number'
elseif filetypes[sval] then
local ft = filetypes[sval]
return ft[1],ft[2]
else
if sval == 'true' and not vtype then
return true, 'boolean'
end
if sval:match '^["\']' then sval = sval:sub(2,-2) end
return sval,vtype or 'string'
end
end
--- process a Lapp options string.
-- Usually called as `lapp()`.
-- @string str the options text
-- @tparam {string} args a table of arguments (default is `_G.arg`)
-- @return a table with parameter-value pairs
function lapp.process_options_string(str,args)
local results = {}
local opts = {at_start=true}
local varargs
local arg = args or _G.arg
open_files = {}
parms = {}
aliases = {}
parmlist = {}
local function check_varargs(s)
local res,cnt = s:gsub('^%.%.%.%s*','')
return res, (cnt > 0)
end
local function set_result(ps,parm,val)
parm = type(parm) == "string" and parm:gsub("%W", "_") or parm -- so foo-bar becomes foo_bar in Lua
if not ps.varargs then
results[parm] = val
else
if not results[parm] then
results[parm] = { val }
else
append(results[parm],val)
end
end
end
usage = str
for line in lines(str) do
local res = {}
local optspec,optparm,i1,i2,defval,vtype,constraint,rest
line = lstrip(line)
local function check(str)
return match(str,line,res)
end
-- flags: either '-<short>', '-<short>,--<long>' or '--<long>'
if check '-$v{short}, --$o{long} $' or check '-$v{short} $' or check '--$o{long} $' then
if res.long then
optparm = res.long:gsub('[^%w%-]','_') -- I'm not sure the $o pattern will let anything else through?
if res.short then aliases[res.short] = optparm end
else
optparm = res.short
end
if res.short and not lapp.slack then force_short(res.short) end
res.rest, varargs = check_varargs(res.rest)
elseif check '$<{name} $' then -- is it <parameter_name>?
-- so <input file...> becomes input_file ...
optparm,rest = res.name:match '([^%.]+)(.*)'
optparm = optparm:gsub('%A','_')
varargs = rest == '...'
append(parmlist,optparm)
end
-- this is not a pure doc line and specifies the flag/parameter type
if res.rest then
line = res.rest
res = {}
local optional
-- do we have ([optional] [<type>] [default <val>])?
if match('$({def} $',line,res) or match('$({def}',line,res) then
local typespec = strip(res.def)
local ftype, rest = typespec:match('^(%S+)(.*)$')
rest = strip(rest)
if ftype == 'optional' then
ftype, rest = rest:match('^(%S+)(.*)$')
rest = strip(rest)
optional = true
end
local default
if ftype == 'default' then
default = true
if rest == '' then lapp.error("value must follow default") end
else -- a type specification
if match('$f{min}..$f{max}',ftype,res) then
-- a numerical range like 1..10
local min,max = res.min,res.max
vtype = 'number'
constraint = function(x)
range_check(x,min,max,optparm)
end
elseif not ftype:match '|' then -- plain type
vtype = ftype
else
-- 'enum' type is a string which must belong to
-- one of several distinct values
local enums = ftype
local enump = '|' .. enums .. '|'
vtype = 'string'
constraint = function(s)
lapp.assert(enump:match('|'..s..'|'),
"value '"..s.."' not in "..enums
)
end
end
end
res.rest = rest
typespec = res.rest
-- optional 'default value' clause. Type is inferred as
-- 'string' or 'number' if there's no explicit type
if default or match('default $r{rest}',typespec,res) then
defval,vtype = process_default(res.rest,vtype)
end
else -- must be a plain flag, no extra parameter required
defval = false
vtype = 'boolean'
end
local ps = {
type = vtype,
defval = defval,
required = defval == nil and not optional,
comment = res.rest or optparm,
constraint = constraint,
varargs = varargs
}
varargs = nil
if types[vtype] then
local converter = types[vtype].converter
if type(converter) == 'string' then
ps.type = converter
else
ps.converter = converter
end
ps.constraint = types[vtype].constraint
elseif not builtin_types[vtype] then
lapp.error(vtype.." is unknown type")
end
parms[optparm] = ps
end
end
-- cool, we have our parms, let's parse the command line args
local iparm = 1
local iextra = 1
local i = 1
local parm,ps,val
local function check_parm (parm)
local eqi = parm:find '='
if eqi then
tinsert(arg,i+1,parm:sub(eqi+1))
parm = parm:sub(1,eqi-1)
end
return parm,eqi
end
local function is_flag (parm)
return parms[aliases[parm] or parm]
end
while i <= #arg do
local theArg = arg[i]
local res = {}
-- look for a flag, -<short flags> or --<long flag>
if match('--$S{long}',theArg,res) or match('-$S{short}',theArg,res) then
if res.long then -- long option
parm = check_parm(res.long)
elseif #res.short == 1 or is_flag(res.short) then
parm = res.short
else
local parmstr,eq = check_parm(res.short)
if not eq then
parm = at(parmstr,1)
local flag = is_flag(parm)
if flag and flag.type ~= 'boolean' then
--if isdigit(at(parmstr,2)) then
-- a short option followed by a digit is an exception (for AW;))
-- push ahead into the arg array
tinsert(arg,i+1,parmstr:sub(2))
else
-- push multiple flags into the arg array!
for k = 2,#parmstr do
tinsert(arg,i+k-1,'-'..at(parmstr,k))
end
end
else
parm = parmstr
end
end
if aliases[parm] then parm = aliases[parm] end
if not parms[parm] and (parm == 'h' or parm == 'help') then
lapp.quit()
end
else -- a parameter
parm = parmlist[iparm]
if not parm then
-- extra unnamed parameters are indexed starting at 1
parm = iextra
ps = { type = 'string' }
parms[parm] = ps
iextra = iextra + 1
else
ps = parms[parm]
end
if not ps.varargs then
iparm = iparm + 1
end
val = theArg
end
ps = parms[parm]
if not ps then lapp.error("unrecognized parameter: "..parm) end
if ps.type ~= 'boolean' then -- we need a value! This should follow
if not val then
i = i + 1
val = arg[i]
end
lapp.assert(val,parm.." was expecting a value")
else -- toggle boolean flags (usually false -> true)
val = not ps.defval
end
ps.used = true
val = convert_parameter(ps,val)
set_result(ps,parm,val)
if builtin_types[ps.type] == 'file' then
set_result(ps,parm..'_name',theArg)
end
if lapp.callback then
lapp.callback(parm,theArg,res)
end
i = i + 1
val = nil
end
-- check unused parms, set defaults and check if any required parameters were missed
for parm,ps in pairs(parms) do
if not ps.used then
if ps.required then lapp.error("missing required parameter: "..parm) end
set_result(ps,parm,ps.defval)
end
end
return results
end
if arg then
script = arg[0]
script = script or rawget(_G,"LAPP_SCRIPT") or "unknown"
-- strip dir and extension to get current script name
script = script:gsub('.+[\\/]',''):gsub('%.%a+$','')
else
script = "inter"
end
setmetatable(lapp, {
__call = function(tbl,str,args) return lapp.process_options_string(str,args) end,
})
return lapp
| agpl-3.0 |
gedads/Neodynamis | scripts/zones/Southern_San_dOria_[S]/npcs/Wyatt.lua | 3 | 2081 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Wyatt
-- @zone 80
-- !pos 124 0 84
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
require("scripts/globals/titles");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 4 and trade:hasItemQty(2506,4)) then
player:startEvent(0x0004);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local seeingSpots = player:getQuestStatus(CRYSTAL_WAR,SEEING_SPOTS);
if (seeingSpots == QUEST_AVAILABLE) then
player:startEvent(0x0002);
elseif (seeingSpots == QUEST_ACCEPTED) then
player:startEvent(0x0003);
else
player:showText(npc, WYATT_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 == 0x0002) then
player:addQuest(CRYSTAL_WAR,SEEING_SPOTS);
elseif (csid == 0x0004) then
player:tradeComplete();
if (player:getQuestStatus(CRYSTAL_WAR,SEEING_SPOTS) == QUEST_ACCEPTED) then
player:addTitle(LADY_KILLER);
player:addGil(GIL_RATE*3000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000);
player:completeQuest(CRYSTAL_WAR,SEEING_SPOTS);
else
player:addTitle(LADY_KILLER);
player:addGil(GIL_RATE*3000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000);
end
end
end;
| gpl-3.0 |
starlightknight/darkstar | scripts/globals/mobskills/hydro_canon.lua | 11 | 1388 | ---------------------------------------------------
-- Hydro_Canon
-- Description:
-- Type: Magical
-- additional effect : 40hp/tick Poison
---------------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
-- skillList 54 = Omega
-- skillList 727 = Proto-Omega
-- skillList 728 = Ultima
-- skillList 729 = Proto-Ultima
local skillList = mob:getMobMod(dsp.mobMod.SKILL_LIST)
local mobhp = mob:getHPP()
local phase = mob:getLocalVar("battlePhase")
if ((skillList == 729 and phase >= 1 and phase <= 2) or (skillList == 728 and mobhp < 70 and mobhp >= 40)) then
return 0
end
return 1
end
function onMobWeaponSkill(target, mob, skill)
local typeEffect = dsp.effect.POISON
local power = 40
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, power, 3, 60)
local dmgmod = 2
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,dsp.magic.ele.WATER,dmgmod,TP_MAB_BONUS,1)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.WATER,MOBPARAM_IGNORE_SHADOWS)
target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.WATER)
return dmg
end | gpl-3.0 |
tommy3/Urho3D | Source/ThirdParty/toluapp/src/bin/lua/custom.lua | 25 | 1388 |
function extract_code(fn,s)
local code = ""
if fn then
code = '\n$#include "'..fn..'"\n'
end
s= "\n" .. s .. "\n" -- add blank lines as sentinels
local _,e,c,t = strfind(s, "\n([^\n]-)SCRIPT_([%w_]*)[^\n]*\n")
while e do
t = strlower(t)
if t == "bind_begin" then
_,e,c = strfind(s,"(.-)\n[^\n]*SCRIPT_BIND_END[^\n]*\n",e)
if not e then
tolua_error("Unbalanced 'SCRIPT_BIND_BEGIN' directive in header file")
end
end
if t == "bind_class" or t == "bind_block" then
local b
_,e,c,b = string.find(s, "([^{]-)(%b{})", e)
c = c..'{\n'..extract_code(nil, b)..'\n};\n'
end
code = code .. c .. "\n"
_,e,c,t = strfind(s, "\n([^\n]-)SCRIPT_([%w_]*)[^\n]*\n",e)
end
return code
end
function preprocess_hook(p)
end
function preparse_hook(p)
end
function include_file_hook(p, filename)
do return end
--print("FILENAME is "..filename)
p.code = string.gsub(p.code, "\n%s*SigC::Signal", "\n\ttolua_readonly SigC::Signal")
p.code = string.gsub(p.code, "#ifdef __cplusplus\nextern \"C\" {\n#endif", "")
p.code = string.gsub(p.code, "#ifdef __cplusplus\n};?\n#endif", "")
p.code = string.gsub(p.code, "DECLSPEC", "")
p.code = string.gsub(p.code, "SDLCALL", "")
p.code = string.gsub(p.code, "DLLINTERFACE", "")
p.code = string.gsub(p.code, "#define[^\n]*_[hH]_?%s*\n", "\n")
--print("code is "..p.code)
end
| mit |
hades2013/openwrt-mtk | package/ralink/ui/luci-mtk/src/applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo.lua | 141 | 1038 | --[[
smap_devinfo - SIP Device Information
(c) 2009 Daniel Dickinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.model.uci")
require("luci.controller.luci_diag.smap_common")
require("luci.controller.luci_diag.devinfo_common")
local debug = false
m = SimpleForm("luci-smap-to-devinfo", translate("SIP Device Information"), translate("Scan for supported SIP devices on specified networks."))
m.reset = false
m.submit = false
local outnets = luci.controller.luci_diag.smap_common.get_params()
luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.smap_common.command_function)
luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, true, "smap", false, debug)
luci.controller.luci_diag.smap_common.action_links(m, false)
return m
| gpl-2.0 |
gedads/Neodynamis | scripts/zones/Apollyon/mobs/Fir_Bholg.lua | 17 | 1394 | -----------------------------------
-- Area: Apollyon SW
-- NPC: Fir Bholg
-----------------------------------
package.loaded["scripts/zones/Apollyon/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Apollyon/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
local mobID = mob:getID();
-- print(mobID);
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
if (mobID ==16932869) then -- time
GetNPCByID(16932864+14):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+14):setStatus(STATUS_NORMAL);
elseif (mobID ==16932871) then -- recover
GetNPCByID(16932864+16):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+16):setStatus(STATUS_NORMAL);
elseif (mobID ==16932874) then -- item
GetNPCByID(16932864+15):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+15):setStatus(STATUS_NORMAL);
end
end; | gpl-3.0 |
gedads/Neodynamis | scripts/globals/items/bowl_of_yayla_corbasi_+1.lua | 12 | 1481 | -----------------------------------------
-- ID: 5580
-- Item: bowl_of_yayla_corbasi_+1
-- Food Effect: 4Hrs, All Races
-----------------------------------------
-- HP 25
-- Dexterity -1
-- Vitality 3
-- HP Recovered While Healing 5
-- MP Recovered While Healing 2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5580);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 25);
target:addMod(MOD_DEX, -1);
target:addMod(MOD_VIT, 3);
target:addMod(MOD_HPHEAL, 5);
target:addMod(MOD_MPHEAL, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 25);
target:delMod(MOD_DEX, -1);
target:delMod(MOD_VIT, 3);
target:delMod(MOD_HPHEAL, 5);
target:delMod(MOD_MPHEAL, 2);
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Lower_Jeuno/npcs/_l03.lua | 3 | 2851 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Streetlamp
-- Involved in Quests: Community Service
-- !pos -87 0 -124 245
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/NPCIDs");
require("scripts/zones/Lower_Jeuno/TextIDs");
-- lamp id vary from 17780881 to 17780892
-- lamp cs vary from 0x0078 to 0x0083 (120 to 131)
local lampNum = 3;
local lampId = lampIdOffset + lampNum;
local cs = lampCsOffset + lampNum;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hour = VanadielHour();
local playerOnQuest = GetServerVariable("[JEUNO]CommService");
-- player is on the quest
if playerOnQuest == player:getID() then
if hour >= 20 and hour < 21 then
player:startEvent(cs,4); -- It is too early to light it. You must wait until nine o'clock.
elseif hour >= 21 or hour < 1 then
if npc:getAnimation() == ANIMATION_OPEN_DOOR then
player:startEvent(cs,2); -- The lamp is already lit.
else
player:startEvent(cs,1,lampNum); -- Light the lamp? Yes/No
end
else
player:startEvent(cs,3); -- You have failed to light the lamps in time.
end
-- player is not on the quest
else
if npc:getAnimation() == ANIMATION_OPEN_DOOR then
player:startEvent(cs,5); -- The lamp is lit.
else
player:startEvent(cs,6); -- You examine the lamp. It seems that it must be lit manually.
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if csid == cs and option == 1 then
-- lamp is now lit
GetNPCByID(lampId):setAnimation(ANIMATION_OPEN_DOOR);
-- tell player how many remain
local lampsRemaining = 12;
for i=0,11 do
local lamp = GetNPCByID(lampIdOffset + i);
if lamp:getAnimation() == ANIMATION_OPEN_DOOR then
lampsRemaining = lampsRemaining - 1;
end
end
if lampsRemaining == 0 then
player:messageSpecial(LAMP_MSG_OFFSET);
else
player:messageSpecial(LAMP_MSG_OFFSET+1,lampsRemaining);
end
end
end;
| gpl-3.0 |
pedro-andrade-inpe/terrame | test/packages/twoerrors/tests/Tube2.lua | 3 | 1618 | -------------------------------------------------------------------------------------------
-- TerraME - a software platform for multiple scale spatially-explicit dynamic modeling.
-- Copyright (C) 2001-2014 INPE and TerraLAB/UFOP.
--
-- This code is part of the TerraME framework.
-- This framework 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.1 of the License, or (at your option) any later version.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library.
--
-- The authors reassure the license terms regarding the warranties.
-- They specifically disclaim any warranties, including, but not limited to,
-- the implied warranties of merchantability and fitness for a particular purpose.
-- The framework provided hereunder is on an "as is" basis, and the authors have no
-- obligation to provide maintenance, support, updates, enhancements, or modifications.
-- In no event shall INPE and TerraLAB / UFOP be held liable to any party for direct,
-- indirect, special, incidental, or consequential damages arising out of the use
-- of this library and its documentation.
--
-- Authors: Tiago Garcia de Senna Carneiro (tiago@dpi.inpe.br)
-- Pedro R. Andrade (pedro.andrade@inpe.br)
-------------------------------------------------------------------------------------------
return{
Tube2 = function(unitTest)
local t = Tube{}
unitTest:assert(true)
end,
w2 = function(unitTest)
unitTest:assert(true)
end
}
| lgpl-3.0 |
gedads/Neodynamis | scripts/zones/Caedarva_Mire/npcs/_273.lua | 2 | 5138 | -----------------------------------
-- Area: Caedarva Mire
-- Door: Runic Seal
-- !pos -353 -3 -20 79
-----------------------------------
package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/globals/besieged");
require("scripts/zones/Caedarva_Mire/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(PERIQIA_ASSAULT_AREA_ENTRY_PERMIT)) then
player:setVar("ShadesOfVengeance",1);
player:startEvent(0x008F,79,-6,0,99,3,0);
elseif (player:hasKeyItem(PERIQIA_ASSAULT_ORDERS)) then
local assaultid = player:getCurrentAssault();
local recommendedLevel = getRecommendedAssaultLevel(assaultid);
local armband = 0;
if (player:hasKeyItem(ASSAULT_ARMBAND)) then
armband = 1;
end
player:startEvent(0x008F, assaultid, -4, 0, recommendedLevel, 3, armband);
else
player:messageSpecial(NOTHING_HAPPENS);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option,target)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local assaultid = player:getCurrentAssault();
local cap = bit.band(option, 0x03);
if (cap == 0) then
cap = 99;
elseif (cap == 1) then
cap = 70;
elseif (cap == 2) then
cap = 60;
else
cap = 50;
end
player:setVar("AssaultCap", cap);
local party = player:getParty();
if(player:getVar("ShadesOfVengeance") == 1) then
if (party ~= nil) then
for i,v in ipairs(party) do
if (not (v:hasKeyItem(PERIQIA_ASSAULT_AREA_ENTRY_PERMIT))) then
player:messageText(target,MEMBER_NO_REQS, false);
player:instanceEntry(target,1);
elseif (v:getZoneID() == player:getZoneID() and v:checkDistance(player) > 50) then
player:messageText(target,MEMBER_TOO_FAR, false);
player:instanceEntry(target,1);
return;
end
end
end
player:createInstance(79,56);
else
if (party ~= nil) then
for i,v in ipairs(party) do
if (not (v:hasKeyItem(PERIQIA_ASSAULT_ORDERS) and v:getCurrentAssault() == assaultid)) then
player:messageText(target,MEMBER_NO_REQS, false);
player:instanceEntry(target,1);
return;
elseif (v:getZoneID() == player:getZoneID() and v:checkDistance(player) > 50) then
player:messageText(target,MEMBER_TOO_FAR, false);
player:instanceEntry(target,1);
return;
end
end
end
player:createInstance(player:getCurrentAssault(), 56);
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,target)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x85 or (csid == 0x8F and option == 4)) then
player:setPos(0,0,0,0,56);
end
end;
-----------------------------------
-- onInstanceLoaded
-----------------------------------
function onInstanceCreated(player,target,instance)
if (instance and player:getVar("ShadesOfVengeance") == 1) then
player:setInstance(instance);
player:instanceEntry(target,4);
player:setVar("ShadesOfVengeance", 0);
player:delKeyItem(PERIQIA_ASSAULT_AREA_ENTRY_PERMIT);
local party = player:getParty();
if (party ~= nil) then
for i,v in ipairs(party) do
if (v:getID() ~= player:getID() and v:getZoneID() == player:getZoneID()) then
v:setInstance(instance);
v:startEvent(0x85);
v:delKeyItem(PERIQIA_ASSAULT_AREA_ENTRY_PERMIT);
end
end
end
elseif (instance) then
instance:setLevelCap(player:getVar("AssaultCap"));
player:setVar("AssaultCap", 0);
player:setInstance(instance);
player:instanceEntry(target,4);
player:delKeyItem(PERIQIA_ASSAULT_ORDERS);
player:delKeyItem(ASSAULT_ARMBAND);
local party = player:getParty();
if (party ~= nil) then
for i,v in ipairs(party) do
if (v:getID() ~= player:getID() and v:getZoneID() == player:getZoneID()) then
v:setInstance(instance);
v:startEvent(0x85, 3);
v:delKeyItem(PERIQIA_ASSAULT_ORDERS);
end
end
end
else
player:messageText(target,CANNOT_ENTER, false);
player:instanceEntry(target,3);
end
end;
| gpl-3.0 |
starlightknight/darkstar | scripts/globals/abilities/pets/flame_breath.lua | 11 | 1410 | ---------------------------------------------------
-- Flame Breath
---------------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
require("scripts/globals/ability")
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0
end
function onUseAbility(pet, target, skill, action)
local master = pet:getMaster()
---------- Deep Breathing ----------
-- 0 for none
-- 1 for first merit
-- 0.25 for each merit after the first
-- TODO: 0.1 per merit for augmented AF2 (10663 *w/ augment*)
local deep = 1
if (pet:hasStatusEffect(dsp.effect.MAGIC_ATK_BOOST) == true) then
deep = deep + 1 + (master:getMerit(dsp.merit.DEEP_BREATHING)-1)*0.25
pet:delStatusEffect(dsp.effect.MAGIC_ATK_BOOST)
end
local gear = master:getMod(dsp.mod.WYVERN_BREATH)/256 -- Master gear that enhances breath
local dmgmod = MobBreathMove(pet, target, 0.185, pet:getMainLvl()*15, dsp.magic.ele.FIRE) -- Works out to (hp/6) + 15, as desired
dmgmod = (dmgmod * (1+gear))*deep
pet:setTP(0)
local dmg = AbilityFinalAdjustments(dmgmod,pet,skill,target,dsp.attackType.BREATH,dsp.damageType.FIRE,MOBPARAM_IGNORE_SHADOWS)
target:takeDamage(dmg, pet, dsp.attackType.BREATH, dsp.damageType.FIRE)
return dmg
end
| gpl-3.0 |
gedads/Neodynamis | scripts/globals/settings.lua | 9 | 12127 | -----------------------------------------------
------------- GLOBAL SETTINGS -------------
-----------------------------------------------
-- This is to allow server operators to further customize their servers. As more features are added to pXI, the list will surely expand.
-- Anything scripted can be customized with proper script editing.
-- PLEASE REQUIRE THIS SCRIPT IN ANY SCRIPTS YOU DO: ADD THIS LINE TO THE TOP!!!!
-- require("scripts/globals/settings");
-- With this script added to yours, you can pull variables from it!!
-- Always include status.lua, which defines mods
-- require("scripts/globals/status");
-- Common functions
require("scripts/globals/common");
-- Enable Expansion (1= yes 0= no)
ENABLE_COP = 0;
ENABLE_TOAU = 0;
ENABLE_WOTG = 0;
ENABLE_ACP = 0;
ENABLE_AMK = 0;
ENABLE_ASA = 0;
ENABLE_ABYSSEA = 0;
ENABLE_SOA = 0;
ENABLE_ROV = 0;
ENABLE_VOIDWATCH = 0; -- Not an expansion, but has its own storyline.
-- FIELDS OF VALOR/Grounds of Valor settings
ENABLE_FIELD_MANUALS = 1; -- Enables Fields of Valor
ENABLE_GROUNDS_TOMES = 1; -- Enables Grounds of Valor
REGIME_WAIT = 1; -- Make people wait till 00:00 game time as in retail. If it's 0, there is no wait time.
LOW_LEVEL_REGIME = 0; -- Allow people to kill regime targets even if they give no exp, allowing people to farm regime targets at 75 in low level areas.
-- Setting to lock content more accurately to the content you have defined above
-- This generally results in a more accurate presentation of your selected expansions
-- as well as a less confusing player experience for things that are disabled (things that are disabled are not loaded)
-- This feature correlates to the content_tag column in the SQL files
RESTRICT_CONTENT = 0;
-- CHARACTER CONFIG
INITIAL_LEVEL_CAP = 50; -- The initial level cap for new players. There seems to be a hardcap of 255.
MAX_LEVEL = 75; -- Level max of the server, lowers the attainable cap by disabling Limit Break quests.
NORMAL_MOB_MAX_LEVEL_RANGE_MIN = 81; -- Lower Bound of Max Level Range for Normal Mobs (0 = Uncapped)
NORMAL_MOB_MAX_LEVEL_RANGE_MAX = 84; -- Upper Bound of Max Level Range for Normal Mobs (0 = Uncapped)
START_GIL = 10; -- Amount of gil given to newly created characters.
START_INVENTORY = 30; -- Starting inventory and satchel size. Ignores values < 30. Do not set above 80!
OPENING_CUTSCENE_ENABLE = 0; -- Set to 1 to enable opening cutscenes, 0 to disable.
SUBJOB_QUEST_LEVEL = 18; -- Minimum level to accept either subjob quest. Set to 0 to start the game with subjobs unlocked.
ADVANCED_JOB_LEVEL = 30; -- Minimum level to accept advanced job quests. Set to 0 to start the game with advanced jobs.
ALL_MAPS = 0; -- Set to 1 to give starting characters all the maps.
UNLOCK_OUTPOST_WARPS = 0; -- Set to 1 to give starting characters all outpost warps. 2 to add Tu'Lia and Tavnazia.
SHOP_PRICE = 1.000; -- Multiplies prices in NPC shops.
GIL_RATE = 1.000; -- Multiplies gil earned from quests. Won't always display in game.
BAYLD_RATE = 1.000; -- Multiples bayld earned from quests.
EXP_RATE = 1.000; -- Multiplies exp earned from fov and quests.
TABS_RATE = 1.000; -- Multiplies tabs earned from fov.
CURE_POWER = 1.000; -- Multiplies amount healed from Healing Magic, including the relevant Blue Magic.
ELEMENTAL_POWER = 1.000; -- Multiplies damage dealt by Elemental and non-drain Dark Magic.
DIVINE_POWER = 1.000; -- Multiplies damage dealt by Divine Magic.
NINJUTSU_POWER = 1.000; -- Multiplies damage dealt by Ninjutsu Magic.
BLUE_POWER = 1.000; -- Multiplies damage dealt by Blue Magic.
DARK_POWER = 1.000; -- Multiplies amount drained by Dark Magic.
ITEM_POWER = 1.000; -- Multiplies the effect of items such as Potions and Ethers.
WEAPON_SKILL_POWER = 1.000; -- Multiplies damage dealt by Weapon Skills.
WEAPON_SKILL_POINTS = 1.000; -- Multiplies points earned during weapon unlocking.
USE_ADOULIN_WEAPON_SKILL_CHANGES = false; -- true/false. Change to toggle new Adoulin weapon skill damage calculations
HARVESTING_BREAK_CHANCE = 0.33; -- % chance for the sickle to break during harvesting. Set between 0 and 1.
EXCAVATION_BREAK_CHANCE = 0.33; -- % chance for the pickaxe to break during excavation. Set between 0 and 1.
LOGGING_BREAK_CHANCE = 0.33; -- % chance for the hatchet to break during logging. Set between 0 and 1.
MINING_BREAK_CHANCE = 0.33; -- % chance for the pickaxe to break during mining. Set between 0 and 1.
HARVESTING_RATE = 0.50; -- % chance to recieve an item from haresting. Set between 0 and 1.
EXCAVATION_RATE = 0.50; -- % chance to recieve an item from excavation. Set between 0 and 1.
LOGGING_RATE = 0.50; -- % chance to recieve an item from logging. Set between 0 and 1.
MINING_RATE = 50; -- % chance to recieve an item from mining. Set between 0 and 100.
HEALING_TP_CHANGE = -100; -- Change in TP for each healing tick. Default is -100
-- SE implemented coffer/chest illusion time in order to prevent coffer farming. No-one in the same area can open a chest or coffer for loot (gil, gems & items)
-- till a random time between MIN_ILLSION_TIME and MAX_ILLUSION_TIME. During this time players can loot keyitem and item related to quests (AF, maps... etc.)
COFFER_MAX_ILLUSION_TIME = 3600; -- 1 hour
COFFER_MIN_ILLUSION_TIME = 1800; -- 30 minutes
CHEST_MAX_ILLUSION_TIME = 3600; -- 1 hour
CHEST_MIN_ILLUSION_TIME = 1800; -- 30 minutes
-- Sets spawn type for: Behemoth, Fafnir, Adamantoise, King Behemoth, Nidhog, Aspidochelone.
-- Use 0 for timed spawns, 1 for force pop only, 2 for both
LandKingSystem_NQ = 0;
LandKingSystem_HQ = 0;
-- DYNAMIS SETTINGS
BETWEEN_2DYNA_WAIT_TIME = 1; -- wait time between 2 Dynamis (in real day) min: 1 day
DYNA_MIDNIGHT_RESET = true; -- if true, makes the wait time count by number of server midnights instead of full 24 hour intervals
DYNA_LEVEL_MIN = 65; -- level min for entering in Dynamis
TIMELESS_HOURGLASS_COST = 500000; -- cost of the timeless hourglass for Dynamis.
CURRENCY_EXCHANGE_RATE = 100; -- X Tier 1 ancient currency -> 1 Tier 2, and so on. Certain values may conflict with shop items. Not designed to exceed 198.
RELIC_2ND_UPGRADE_WAIT_TIME = 604800; -- wait time for 2nd relic upgrade (stage 2 -> stage 3) in seconds. 604800s = 1 RL week.
RELIC_3RD_UPGRADE_WAIT_TIME = 295200; -- wait time for 3rd relic upgrade (stage 3 -> stage 4) in seconds. 295200s = 82 hours.
FREE_COP_DYNAMIS = 1 ; -- Authorize player to entering inside COP Dynamis without completing COP mission ( 1 = enable 0= disable)
-- QUEST/MISSION SPECIFIC SETTINGS
WSNM_LEVEL = 70; -- Min Level to get WSNM Quests
WSNM_SKILL_LEVEL = 240;
AF1_QUEST_LEVEL = 40; -- Minimum level to start AF1 quest
AF2_QUEST_LEVEL = 50; -- Minimum level to start AF2 quest
AF3_QUEST_LEVEL = 50; -- Minimum level to start AF3 quest
AF1_FAME = 20; -- base fame for completing an AF1 quest
AF2_FAME = 40; -- base fame for completing an AF2 quest
AF3_FAME = 60; -- base fame for completing an AF3 quest
DEBUG_MODE = 0; -- Set to 1 to activate auto-warping to the next location (only supported by certain missions / quests).
QM_RESET_TIME = 300; -- Default time (in seconds) you have from killing ???-pop mission NMs to click again and get key item, until ??? resets.
OldSchoolG1 = false; -- Set to true to require farming Exoray Mold, Bombd Coal, and Ancient Papyrus drops instead of allowing key item method.
OldSchoolG2 = false; -- Set true to require the NMs for "Atop the Highest Mountains" be dead to get KI like before SE changed it.
FrigiciteDuration = 30; -- When OldSChoolG2 is enabled, this is the time (in seconds) you have from killing Boreal NMs to click the "???" target.
-- JOB ABILITY/TRAIT SPECIFIC SETTINGS
CIRCLE_KILLER_EFFECT = 20; -- Intimidation percentage granted by circle effects. (made up number)
KILLER_EFFECT = 10; -- Intimidation percentage from killer job traits.
-- SPELL SPECIFIC SETTINGS
DIA_OVERWRITE = 1; --Set to 1 to allow Bio to overwrite same tier Dia. Default is 1.
BIO_OVERWRITE = 0; --Set to 1 to allow Dia to overwrite same tier Bio. Default is 0.
BARELEMENT_OVERWRITE = 1; --Set to 1 to allow Barelement spells to overwrite each other (prevent stacking). Default is 1.
BARSTATUS_OVERWRITE = 1; --Set to 1 to allow Barstatus spells to overwrite each other (prevent stacking). Default is 1.
STONESKIN_CAP = 350; -- soft cap for hp absorbed by stoneskin
BLINK_SHADOWS = 2; -- number of shadows supplied by Blink spell
ENSPELL_DURATION = 180; -- duration of RDM en-spells
SPIKE_EFFECT_DURATION = 180; -- the duration of RDM, BLM spikes effects (not Reprisal)
ELEMENTAL_DEBUFF_DURATION = 120; -- base duration of elemental debuffs
AQUAVEIL_COUNTER = 1; -- Base amount of hits Aquaveil absorbs to prevent spell interrupts. Retail is 1.
ABSORB_SPELL_AMOUNT = 8; -- how much of a stat gets absorbed by DRK absorb spells - expected to be a multiple of 8.
ABSORB_SPELL_TICK = 9; -- duration of 1 absorb spell tick
SNEAK_INVIS_DURATION_MULTIPLIER = 1; -- multiplies duration of sneak,invis,deodorize to reduce player torture. 1 = retail behavior.
USE_OLD_CURE_FORMULA = false; -- true/false. if true, uses older cure formula (3*MND + VIT + 3*(healing skill/5)) // cure 6 will use the newer formula
-- CELEBRATIONS
EXPLORER_MOOGLE = 1; -- Enables Explorer Moogle teleports
EXPLORER_MOOGLE_LEVELCAP = 10;
JINX_MODE_2005 = 0; -- Set to 1 to give starting characters swimsuits from 2005. Ex: Hume Top
JINX_MODE_2008 = 0; -- Set to 1 to give starting characters swimsuits from 2008. Ex: Custom Top
JINX_MODE_2012 = 0; -- Set to 1 to give starting characters swimsuits from 2012. Ex: Marine Top
SUMMERFEST_2004 = 0; -- Set to 1 to give starting characters Far East dress from 2004. Ex: Onoko Yukata
SUNBREEZE_2009 = 0; -- Set to 1 to give starting characters Far East dress from 2009. Ex: Otokogusa Yukata
SUNBREEZE_2011 = 0; -- Set to 1 to give starting characters Far East dress from 2011. Ex: Hikogami Yukata
CHRISTMAS = 0; -- Set to 1 to give starting characters Christmas dress.
HALLOWEEN = 0; -- Set to 1 to give starting characters Halloween items (Does not start event).
HALLOWEEN_2005 = 0; -- Set to 1 to Enable the 2005 version of Harvest Festival, will start on Oct. 20 and end Nov. 1.
HALLOWEEN_YEAR_ROUND = 0; -- Set to 1 to have Harvest Festival initialize outside of normal times.
-- MISC
HOMEPOINT_HEAL = 0; --Set to 1 if you want Home Points to heal you like in single-player Final Fantasy games.
RIVERNE_PORTERS = 120; -- Time in seconds that Unstable Displacements in Cape Riverne stay open after trading a scale.
LANTERNS_STAY_LIT = 1200; -- time in seconds that lanterns in the Den of Rancor stay lit.
ENABLE_COP_ZONE_CAP=1; -- enable or disable lvl cap
TIMEZONE_OFFSET = 9.0; -- Offset from UTC used to determine when "JP Midnight" is for the server. Default is JST (+9.0).
ALLOW_MULTIPLE_EXP_RINGS = 0; -- Set to 1 to remove ownership restrictions on the Chariot/Empress/Emperor Band trio.
BYPASS_EXP_RING_ONE_PER_WEEK = 0; -- -- Set to 1 to bypass the limit of one ring per Conquest Tally Week.
NUMBER_OF_DM_EARRINGS = 1; -- Number of earrings players can simultaneously own from Divine Might before scripts start blocking them (Default: 1)
HOMEPOINT_TELEPORT = 0; -- Enables the homepoint teleport system
DIG_ABUNDANCE_BONUS = 0; -- Increase chance of digging up an item (450 = item digup chance +45)
DIG_FATIGUE = 1; -- Set to 0 to disable Dig Fatigue
ENM_COOLDOWN = 120; -- Number of hours before a player can obtain same KI for ENMs (default: 5 days)
FORCE_SPAWN_QM_RESET_TIME = 300; -- Number of seconds the ??? remains hidden for after the despawning of the mob it force spawns.
-- LIMBUS
BETWEEN_2COSMOCLEANSE_WAIT_TIME = 3; -- day between 2 limbus keyitem (default 3 days)
DIMENSIONAL_PORTAL_UNLOCK = false; -- Set true to bypass requirements for using dimensional portals to reach sea for Limbus
-- ABYSSEA
VISITANT_BONUS = 1.00; -- Default: 1.00 - (retail) - Multiplies the base time value of each Traverser Stone. | gpl-3.0 |
pedro-andrade-inpe/terrame | packages/gis/data/emas.lua | 1 | 2738 | -------------------------------------------------------------------------------------------
-- TerraME - a software platform for multiple scale spatially-explicit dynamic modeling.
-- Copyright (C) 2001-2017 INPE and TerraLAB/UFOP -- www.terrame.org
-- This code is part of the TerraME framework.
-- This framework 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.1 of the License, or (at your option) any later version.
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library.
-- The authors reassure the license terms regarding the warranties.
-- They specifically disclaim any warranties, including, but not limited to,
-- the implied warranties of merchantability and fitness for a particular purpose.
-- The framework provided hereunder is on an "as is" basis, and the authors have no
-- obligation to provide maintenance, support, updates, enhancements, or modifications.
-- In no event shall INPE and TerraLAB / UFOP be held liable to any party for direct,
-- indirect, special, incidental, or consequential damages arising out of the use
-- of this software and its documentation.
--
-------------------------------------------------------------------------------------------
-- @example Creates a database that can be used by the example fire-spread of base package.
import("gis")
project = Project{
file = "emas.tview",
clean = true,
author = "Almeida, R.",
title = "Emas database",
firebreak = filePath("emas-firebreak.shp", "gis"),
river = filePath("emas-river.shp", "gis"),
limit = filePath("emas-limit.shp", "gis")
}
Layer{
project = project,
name = "cover",
file = filePath("emas-accumulation.tif", "gis"),
epsg = 29192
}
cl = Layer{
project = project,
file = "emas.shp",
clean = true,
input = "limit",
name = "cells",
resolution = 500
}
cl:fill{
operation = "presence",
attribute = "firebreak",
layer = "firebreak"
}
cl:fill{
operation = "presence",
attribute = "river",
layer = "river"
}
cl:fill{
operation = "maximum",
attribute = "maxcover",
layer = "cover"
}
cl:fill{
operation = "minimum",
attribute = "mincover",
layer = "cover"
}
cs = CellularSpace{
project = project,
layer = "cells"
}
Map{
target = cs,
select = "firebreak",
value = {0, 1},
color = {"darkGreen", "black"},
label = {"forest", "firebreak"}
}
Map{
target = cs,
select = "river",
value = {0, 1},
color = {"darkGreen", "darkBlue"},
label = {"forest", "river"}
}
Map{
target = cs,
select = "mincover",
slices = 5,
color = "YlGn"
}
Map{
target = cs,
select = "maxcover",
slices = 5,
color = "YlGn"
}
| lgpl-3.0 |
starlightknight/darkstar | scripts/zones/Garlaige_Citadel/npcs/qm19.lua | 11 | 1753 | -----------------------------------
-- Area: Garlaige Citadel
-- NPC: qm19 (??? - Bomb Coal Fragments)
-- Involved in Quest: In Defiant Challenge
-- !pos -50.175 6.264 251.669 200
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
local ID = require("scripts/zones/Garlaige_Citadel/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (OldSchoolG1 == false) then
if (player:hasItem(1090) == false and player:hasKeyItem(dsp.ki.BOMB_COAL_FRAGMENT2) == false
and player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then
player:addKeyItem(dsp.ki.BOMB_COAL_FRAGMENT2);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.BOMB_COAL_FRAGMENT2);
end
if (player:hasKeyItem(dsp.ki.BOMB_COAL_FRAGMENT1) and player:hasKeyItem(dsp.ki.BOMB_COAL_FRAGMENT2) and player:hasKeyItem(dsp.ki.BOMB_COAL_FRAGMENT3)) then
if (player:getFreeSlotsCount() >= 1) then
player:addItem(1090, 1);
player:messageSpecial(ID.text.ITEM_OBTAINED, 1090);
else
player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED, 1090);
end
end
if (player:hasItem(1090)) then
player:delKeyItem(dsp.ki.BOMB_COAL_FRAGMENT1);
player:delKeyItem(dsp.ki.BOMB_COAL_FRAGMENT2);
player:delKeyItem(dsp.ki.BOMB_COAL_FRAGMENT3);
end
end
end;
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
function onEventFinish(player,csid,option)
end; | gpl-3.0 |
gedads/Neodynamis | scripts/globals/weaponskills.lua | 2 | 42744 | -- Contains all common weaponskill calculations including but not limited to:
-- fSTR
-- Alpha
-- Ratio -> cRatio
-- min/max cRatio
-- applications of fTP
-- applications of critical hits ('Critical hit rate varies with TP.')
-- applications of accuracy mods ('Accuracy varies with TP.')
-- applications of damage mods ('Damage varies with TP.')
-- performance of the actual WS (rand numbers, etc)
require("scripts/globals/magicburst");
require("scripts/globals/status");
require("scripts/globals/utils");
require("scripts/globals/magic");
require("scripts/globals/msg");
REACTION_NONE = 0x00
REACTION_MISS = 0x01
REACTION_PARRY = 0x03
REACTION_BLOCK = 0x04
REACTION_HIT = 0x08
REACTION_EVADE = 0x09
REACTION_GUARD = 0x14
SPECEFFECT_NONE = 0x00
SPECEFFECT_BLOOD = 0x02
SPECEFFECT_HIT = 0x10
SPECEFFECT_RAISE = 0x11
SPECEFFECT_RECOIL = 0x20
SPECEFFECT_CRITICAL_HIT = 0x22
-- params contains: ftp100, ftp200, ftp300, str_wsc, dex_wsc, vit_wsc, int_wsc, mnd_wsc, canCrit, crit100, crit200, crit300, acc100, acc200, acc300, ignoresDef, ignore100, ignore200, ignore300, atkmulti, kick
function doPhysicalWeaponskill(attacker, target, wsID, tp, primary, action, taChar, params)
local criticalHit = false;
local bonusTP = 0;
if (params.bonusTP ~= nil) then
bonusTP = params.bonusTP;
end
local multiHitfTP = false;
if (params.multiHitfTP ~= nil) then
multiHitfTP = params.multiHitfTP;
end
local bonusfTP, bonusacc = handleWSGorgetBelt(attacker);
bonusacc = bonusacc + attacker:getMod(MOD_WSACC);
-- get fstr
local fstr = fSTR(attacker:getStat(MOD_STR),target:getStat(MOD_VIT),attacker:getWeaponDmgRank());
-- apply WSC
local weaponDamage = attacker:getWeaponDmg();
local weaponType = attacker:getWeaponSkillType(0);
if (weaponType == SKILL_H2H or weaponType == SKILL_NON) then
local h2hSkill = ((attacker:getSkillLevel(1) * 0.11) + 3);
if (params.kick and attacker:hasStatusEffect(EFFECT_FOOTWORK)) then
weaponDamage = attacker:getMod(MOD_KICK_DMG) + 18; -- footwork formerly added 18 base dmg to all kicks, its effect on weaponskills was unchanged by update
else
weaponDamage = utils.clamp(attacker:getWeaponDmg()-3, 0);
end
weaponDamage = weaponDamage + h2hSkill;
end
local base = weaponDamage + fstr +
(attacker:getStat(MOD_STR) * params.str_wsc + attacker:getStat(MOD_DEX) * params.dex_wsc +
attacker:getStat(MOD_VIT) * params.vit_wsc + attacker:getStat(MOD_AGI) * params.agi_wsc +
attacker:getStat(MOD_INT) * params.int_wsc + attacker:getStat(MOD_MND) * params.mnd_wsc +
attacker:getStat(MOD_CHR) * params.chr_wsc) * getAlpha(attacker:getMainLvl());
-- Applying fTP multiplier
local ftp = fTP(tp,params.ftp100,params.ftp200,params.ftp300) + bonusfTP;
local ignoredDef = 0;
if (params.ignoresDef == not nil and params.ignoresDef == true) then
ignoredDef = calculatedIgnoredDef(tp, target:getStat(MOD_DEF), params.ignored100, params.ignored200, params.ignored300);
end
-- get cratio min and max
local cratio, ccritratio = cMeleeRatio(attacker, target, params, ignoredDef);
local ccmin = 0;
local ccmax = 0;
local hasMightyStrikes = attacker:hasStatusEffect(EFFECT_MIGHTY_STRIKES);
local isSneakValid = attacker:hasStatusEffect(EFFECT_SNEAK_ATTACK);
if (isSneakValid and not (attacker:isBehind(target) or attacker:hasStatusEffect(EFFECT_HIDE))) then
isSneakValid = false;
end
attacker:delStatusEffectsByFlag(EFFECTFLAG_DETECTABLE);
attacker:delStatusEffect(EFFECT_SNEAK_ATTACK);
local isTrickValid = taChar ~= nil
local isAssassinValid = isTrickValid;
if (isAssassinValid and not attacker:hasTrait(68)) then
isAssassinValid = false;
end
local critrate = 0;
local nativecrit = 0;
if (params.canCrit) then -- work out critical hit ratios, by +1ing
critrate = fTP(tp,params.crit100,params.crit200,params.crit300);
-- add on native crit hit rate (guesstimated, it actually follows an exponential curve)
local flourisheffect = attacker:getStatusEffect(EFFECT_BUILDING_FLOURISH);
if flourisheffect ~= nil and flourisheffect:getPower() > 1 then
critrate = critrate + (10 + flourisheffect:getSubPower()/2)/100;
end
nativecrit = (attacker:getStat(MOD_DEX) - target:getStat(MOD_AGI))*0.005; -- assumes +0.5% crit rate per 1 dDEX
if (nativecrit > 0.2) then -- caps only apply to base rate, not merits and mods
nativecrit = 0.2;
elseif (nativecrit < 0.05) then
nativecrit = 0.05;
end
nativecrit = nativecrit + (attacker:getMod(MOD_CRITHITRATE)/100) + attacker:getMerit(MERIT_CRIT_HIT_RATE)/100 - target:getMerit(MERIT_ENEMY_CRIT_RATE)/100;
if (attacker:hasStatusEffect(EFFECT_INNIN) and attacker:isBehind(target, 23)) then -- Innin acc boost attacker is behind target
nativecrit = nativecrit + attacker:getStatusEffect(EFFECT_INNIN):getPower();
end
critrate = critrate + nativecrit;
end
-- Applying pDIF
local pdif = generatePdif (cratio[1], cratio[2], true);
local missChance = math.random();
local finaldmg = 0;
local hitrate = getHitRate(attacker,target,true,bonusacc);
if (params.acc100~=0) then
-- ACCURACY VARIES WITH TP, APPLIED TO ALL HITS.
-- print("Accuracy varies with TP.");
hr = accVariesWithTP(getHitRate(attacker,target,false,bonusacc),attacker:getACC(),tp,params.acc100,params.acc200,params.acc300);
hitrate = hr;
end
local dmg = base * ftp;
local tpHitsLanded = 0;
local shadowsAbsorbed = 0;
if ((missChance <= hitrate or isSneakValid or isAssassinValid or math.random() < attacker:getMod(MOD_ZANSHIN)/100) and
not target:hasStatusEffect(EFFECT_PERFECT_DODGE) and not target:hasStatusEffect(EFFECT_ALL_MISS) ) then
if not shadowAbsorb(target) then
if (params.canCrit or isSneakValid or isAssassinValid) then
local critchance = math.random();
if (critchance <= critrate or hasMightyStrikes or isSneakValid or isAssassinValid) then -- crit hit!
local cpdif = generatePdif (ccritratio[1], ccritratio[2], true);
finaldmg = dmg * cpdif;
if (isSneakValid and attacker:getMainJob() == JOBS.THF) then -- have to add on DEX bonus if on THF main
finaldmg = finaldmg + (attacker:getStat(MOD_DEX) * ftp * cpdif) * ((100+(attacker:getMod(MOD_AUGMENTS_SA)))/100);
end
if (isTrickValid and attacker:getMainJob() == JOBS.THF) then
finaldmg = finaldmg + (attacker:getStat(MOD_AGI) * (1 + attacker:getMod(MOD_TRICK_ATK_AGI)/100) * ftp * cpdif) * ((100+(attacker:getMod(MOD_AUGMENTS_TA)))/100);
end
else
finaldmg = dmg * pdif;
if (isTrickValid and attacker:getMainJob() == JOBS.THF) then
finaldmg = finaldmg + (attacker:getStat(MOD_AGI) * (1 + attacker:getMod(MOD_TRICK_ATK_AGI)/100) * ftp * pdif) * ((100+(attacker:getMod(MOD_AUGMENTS_TA)))/100);
end
end
else
finaldmg = dmg * pdif;
if (isTrickValid and attacker:getMainJob() == JOBS.THF) then
finaldmg = finaldmg + (attacker:getStat(MOD_AGI) * (1 + attacker:getMod(MOD_TRICK_ATK_AGI)/100) * ftp * pdif) * ((100+(attacker:getMod(MOD_AUGMENTS_TA)))/100);
end
end
tpHitsLanded = 1;
else
shadowsAbsorbed = shadowsAbsorbed + 1
end
end
if not multiHitfTP then dmg = base end
if ((attacker:getOffhandDmg() ~= 0) and (attacker:getOffhandDmg() > 0 or weaponType==SKILL_H2H)) then
local chance = math.random();
if ((chance<=hitrate or math.random() < attacker:getMod(MOD_ZANSHIN)/100 or isSneakValid)
and not target:hasStatusEffect(EFFECT_PERFECT_DODGE) and not target:hasStatusEffect(EFFECT_ALL_MISS) ) then -- it hit
if not shadowAbsorb(target) then
pdif = generatePdif (cratio[1], cratio[2], true);
if (params.canCrit) then
critchance = math.random();
if (critchance <= nativecrit or hasMightyStrikes) then -- crit hit!
criticalHit = true;
cpdif = generatePdif (ccritratio[1], ccritratio[2], true);
finaldmg = finaldmg + dmg * cpdif;
else
finaldmg = finaldmg + dmg * pdif;
end
else
finaldmg = finaldmg + dmg * pdif;
end
tpHitsLanded = tpHitsLanded + 1;
else
shadowsAbsorbed = shadowsAbsorbed + 1
end
end
end
-- Store first hit bonus for use after other calcs are done..
local firstHitBonus = ((finaldmg * attacker:getMod(MOD_ALL_WSDMG_FIRST_HIT))/100);
local numHits = getMultiAttacks(attacker, params.numHits);
local extraHitsLanded = 0;
if (numHits > 1) then
local hitsdone = 1;
while (hitsdone < numHits) do
local chance = math.random();
local targetHP = target:getHP();
if ((chance<=hitrate or math.random() < attacker:getMod(MOD_ZANSHIN)/100) and
not target:hasStatusEffect(EFFECT_PERFECT_DODGE) and not target:hasStatusEffect(EFFECT_ALL_MISS) ) then -- it hit
if not shadowAbsorb(target) then
pdif = generatePdif (cratio[1], cratio[2], true);
if (params.canCrit) then
critchance = math.random();
if (critchance <= nativecrit or hasMightyStrikes) then -- crit hit!
criticalHit = true;
cpdif = generatePdif (ccritratio[1], ccritratio[2], true);
finaldmg = finaldmg + dmg * cpdif;
else
finaldmg = finaldmg + dmg * pdif;
end
else
finaldmg = finaldmg + dmg * pdif;
end
extraHitsLanded = extraHitsLanded + 1;
else
shadowsAbsorbed = shadowsAbsorbed + 1
end
end
hitsdone = hitsdone + 1;
if (finaldmg > targetHP) then
break;
end
end
end
finaldmg = finaldmg + souleaterBonus(attacker, (tpHitsLanded+extraHitsLanded));
-- print("Landed " .. hitslanded .. "/" .. numHits .. " hits with hitrate " .. hitrate .. "!");
-- DMG Bonus for any WS
local bonusdmg = attacker:getMod(MOD_ALL_WSDMG_ALL_HITS);
-- Ws Specific DMG Bonus
if (attacker:getMod(MOD_WEAPONSKILL_DAMAGE_BASE + wsID) > 0) then
bonusdmg = bonusdmg + attacker:getMod(MOD_WEAPONSKILL_DAMAGE_BASE + wsID);
end
-- Add in bonusdmg
finaldmg = finaldmg * ((100 + bonusdmg)/100);
finaldmg = finaldmg + firstHitBonus;
-- Check for reductions from PDT
finaldmg = target:physicalDmgTaken(finaldmg);
-- Check for reductions from phys resistances
if (weaponType == SKILL_H2H) then
finaldmg = finaldmg * target:getMod(MOD_HTHRES) / 1000;
elseif (weaponType == SKILL_DAG or weaponType == SKILL_POL) then
finaldmg = finaldmg * target:getMod(MOD_PIERCERES) / 1000;
elseif (weaponType == SKILL_CLB or weaponType == SKILL_STF) then
finaldmg = finaldmg * target:getMod(MOD_IMPACTRES) / 1000;
else
finaldmg = finaldmg * target:getMod(MOD_SLASHRES) / 1000;
end
attacker:delStatusEffectSilent(EFFECT_BUILDING_FLOURISH);
finaldmg = finaldmg * WEAPON_SKILL_POWER
finaldmg = takeWeaponskillDamage(target, attacker, params, primary, finaldmg, SLOT_MAIN, tpHitsLanded, extraHitsLanded, shadowsAbsorbed, bonusTP, action, taChar)
return finaldmg, criticalHit, tpHitsLanded, extraHitsLanded;
end;
-- params: ftp100, ftp200, ftp300, wsc_str, wsc_dex, wsc_vit, wsc_agi, wsc_int, wsc_mnd, wsc_chr,
-- ele (ELE_FIRE), skill (SKILL_STF), includemab = true
function doMagicWeaponskill(attacker, target, wsID, tp, primary, action, params)
local bonusTP = 0;
if (params.bonusTP ~= nil) then
bonusTP = params.bonusTP;
end
local bonusfTP, bonusacc = handleWSGorgetBelt(attacker);
bonusacc = bonusacc + attacker:getMod(MOD_WSACC);
local fint = utils.clamp(8 + (attacker:getStat(MOD_INT) - target:getStat(MOD_INT)), -32, 32);
local dmg = 0
local shadowsAbsorbed = 0
if not shadowAbsorb(target) then
dmg = attacker:getMainLvl() + 2 + (attacker:getStat(MOD_STR) * params.str_wsc + attacker:getStat(MOD_DEX) * params.dex_wsc +
attacker:getStat(MOD_VIT) * params.vit_wsc + attacker:getStat(MOD_AGI) * params.agi_wsc +
attacker:getStat(MOD_INT) * params.int_wsc + attacker:getStat(MOD_MND) * params.mnd_wsc +
attacker:getStat(MOD_CHR) * params.chr_wsc) + fint;
-- Applying fTP multiplier
local ftp = fTP(tp,params.ftp100,params.ftp200,params.ftp300) + bonusfTP;
dmg = dmg * ftp;
dmg = addBonusesAbility(attacker, params.ele, target, dmg, params);
dmg = dmg * applyResistanceAbility(attacker,target,params.ele,params.skill, bonusacc);
dmg = target:magicDmgTaken(dmg);
dmg = adjustForTarget(target,dmg,params.ele);
-- Add first hit bonus..No such thing as multihit magic ws is there?
local firstHitBonus = ((dmg * attacker:getMod(MOD_ALL_WSDMG_FIRST_HIT))/100);
-- DMG Bonus for any WS
local bonusdmg = attacker:getMod(MOD_ALL_WSDMG_ALL_HITS);
-- Ws Specific DMG Bonus
if (attacker:getMod(MOD_WEAPONSKILL_DAMAGE_BASE + wsID) > 0) then
bonusdmg = bonusdmg + attacker:getMod(MOD_WEAPONSKILL_DAMAGE_BASE + wsID);
end
-- Add in bonusdmg
dmg = dmg * ((100 + bonusdmg)/100);
dmg = dmg + firstHitBonus;
dmg = dmg * WEAPON_SKILL_POWER
else
shadowsAbsorbed = shadowsAbsorbed + 1
end
dmg = takeWeaponskillDamage(target, attacker, params, primary, dmg, SLOT_MAIN, 1, 0, shadowsAbsorbed, bonusTP, action, nil)
return dmg, false, 1, 0;
end
function souleaterBonus(attacker, numhits)
if attacker:hasStatusEffect(EFFECT_SOULEATER) then
local damage = 0;
local percent = 0.1;
if attacker:getMainJob() ~= JOBS.DRK then
percent = percent / 2;
end
percent = percent + math.min(0.02, 0.01 * attacker:getMod(MOD_SOULEATER_EFFECT));
local hitscounted = 0;
while (hitscounted < numhits) do
local health = attacker:getHP();
if health > 10 then
damage = damage + health*percent;
end
hitscounted = hitscounted + 1;
end
attacker:delHP(numhits*0.10*attacker:getHP());
return damage;
else
return 0;
end
end;
function accVariesWithTP(hitrate,acc,tp,a1,a2,a3)
-- sadly acc varies with tp ALL apply an acc PENALTY, the acc at various %s are given as a1 a2 a3
accpct = fTP(tp,a1,a2,a3);
acclost = acc - (acc*accpct);
hrate = hitrate - (0.005*acclost);
-- cap it
if (hrate>0.95) then
hrate = 0.95;
end
if (hrate<0.2) then
hrate = 0.2;
end
return hrate;
end;
function getHitRate(attacker,target,capHitRate,bonus)
local flourisheffect = attacker:getStatusEffect(EFFECT_BUILDING_FLOURISH);
if flourisheffect ~= nil and flourisheffect:getPower() > 1 then
attacker:addMod(MOD_ACC, 20 + flourisheffect:getSubPower())
end
local acc = attacker:getACC();
local eva = target:getEVA();
if flourisheffect ~= nil and flourisheffect:getPower() > 1 then
attacker:delMod(MOD_ACC, 20 + flourisheffect:getSubPower())
end
if (bonus == nil) then
bonus = 0;
end
if (attacker:hasStatusEffect(EFFECT_INNIN) and attacker:isBehind(target, 23)) then -- Innin acc boost if attacker is behind target
bonus = bonus + attacker:getStatusEffect(EFFECT_INNIN):getPower();
end
if (target:hasStatusEffect(EFFECT_YONIN) and attacker:isFacing(target, 23)) then -- Yonin evasion boost if attacker is facing target
bonus = bonus - target:getStatusEffect(EFFECT_YONIN):getPower();
end
if (attacker:hasTrait(76) and attacker:isBehind(target, 23)) then --TRAIT_AMBUSH
bonus = bonus + attacker:getMerit(MERIT_AMBUSH);
end
acc = acc + bonus;
if (attacker:getMainLvl() > target:getMainLvl()) then -- acc bonus!
acc = acc + ((attacker:getMainLvl()-target:getMainLvl())*4);
elseif (attacker:getMainLvl() < target:getMainLvl()) then -- acc penalty :(
acc = acc - ((target:getMainLvl()-attacker:getMainLvl())*4);
end
local hitdiff = 0;
local hitrate = 75;
if (acc>eva) then
hitdiff = (acc-eva)/2;
end
if (eva>acc) then
hitdiff = ((-1)*(eva-acc))/2;
end
hitrate = hitrate+hitdiff;
hitrate = hitrate/100;
-- Applying hitrate caps
if (capHitRate) then -- this isn't capped for when acc varies with tp, as more penalties are due
if (hitrate>0.95) then
hitrate = 0.95;
end
if (hitrate<0.2) then
hitrate = 0.2;
end
end
return hitrate;
end;
function getRangedHitRate(attacker,target,capHitRate,bonus)
local acc = attacker:getRACC();
local eva = target:getEVA();
if (bonus == nil) then
bonus = 0;
end
if (target:hasStatusEffect(EFFECT_YONIN) and target:isFacing(attacker, 23)) then -- Yonin evasion boost if defender is facing attacker
bonus = bonus - target:getStatusEffect(EFFECT_YONIN):getPower();
end
if (attacker:hasTrait(76) and attacker:isBehind(target, 23)) then --TRAIT_AMBUSH
bonus = bonus + attacker:getMerit(MERIT_AMBUSH);
end
acc = acc + bonus;
if (attacker:getMainLvl() > target:getMainLvl()) then -- acc bonus!
acc = acc + ((attacker:getMainLvl()-target:getMainLvl())*4);
elseif (attacker:getMainLvl() < target:getMainLvl()) then -- acc penalty :(
acc = acc - ((target:getMainLvl()-attacker:getMainLvl())*4);
end
local hitdiff = 0;
local hitrate = 75;
if (acc>eva) then
hitdiff = (acc-eva)/2;
end
if (eva>acc) then
hitdiff = ((-1)*(eva-acc))/2;
end
hitrate = hitrate+hitdiff;
hitrate = hitrate/100;
-- Applying hitrate caps
if (capHitRate) then -- this isn't capped for when acc varies with tp, as more penalties are due
if (hitrate>0.95) then
hitrate = 0.95;
end
if (hitrate<0.2) then
hitrate = 0.2;
end
end
return hitrate;
end;
function fTP(tp,ftp1,ftp2,ftp3)
if (tp < 1000) then
tp = 1000;
end
if (tp >= 1000 and tp < 2000) then
return ftp1 + ( ((ftp2-ftp1)/1000) * (tp-1000));
elseif (tp >= 2000 and tp <= 3000) then
-- generate a straight line between ftp2 and ftp3 and find point @ tp
return ftp2 + ( ((ftp3-ftp2)/1000) * (tp-2000));
else
print("fTP error: TP value is not between 1000-3000!");
end
return 1; -- no ftp mod
end;
function calculatedIgnoredDef(tp, def, ignore1, ignore2, ignore3)
if (tp>=1000 and tp <2000) then
return (ignore1 + ( ((ignore2-ignore1)/1000) * (tp-1000)))*def;
elseif (tp>=2000 and tp<=3000) then
return (ignore2 + ( ((ignore3-ignore2)/1000) * (tp-2000)))*def;
end
return 1; -- no def ignore mod
end
-- Given the raw ratio value (atk/def) and levels, returns the cRatio (min then max)
function cMeleeRatio(attacker, defender, params, ignoredDef)
local flourisheffect = attacker:getStatusEffect(EFFECT_BUILDING_FLOURISH);
if flourisheffect ~= nil and flourisheffect:getPower() > 1 then
attacker:addMod(MOD_ATTP, 25 + flourisheffect:getSubPower()/2)
end
local cratio = (attacker:getStat(MOD_ATT) * params.atkmulti) / (defender:getStat(MOD_DEF) - ignoredDef);
cratio = utils.clamp(cratio, 0, 2.25);
if flourisheffect ~= nil and flourisheffect:getPower() > 1 then
attacker:delMod(MOD_ATTP, 25 + flourisheffect:getSubPower()/2)
end
local levelcor = 0;
if (attacker:getMainLvl() < defender:getMainLvl()) then
levelcor = 0.05 * (defender:getMainLvl() - attacker:getMainLvl());
end
cratio = cratio - levelcor;
if (cratio < 0) then
cratio = 0;
end
local pdifmin = 0;
local pdifmax = 0;
-- max
if (cratio < 0.5) then
pdifmax = cratio + 0.5;
elseif (cratio < 0.7) then
pdifmax = 1;
elseif (cratio < 1.2) then
pdifmax = cratio + 0.3;
elseif (cratio < 1.5) then
pdifmax = (cratio * 0.25) + cratio;
elseif (cratio < 2.625) then
pdifmax = cratio + 0.375;
else
pdifmax = 3;
end
-- min
if (cratio < 0.38) then
pdifmin = 0;
elseif (cratio < 1.25) then
pdifmin = cratio * (1176/1024) - (448/1024);
elseif (cratio < 1.51) then
pdifmin = 1;
elseif (cratio < 2.44) then
pdifmin = cratio * (1176/1024) - (775/1024);
else
pdifmin = cratio - 0.375;
end
local pdif = {};
pdif[1] = pdifmin;
pdif[2] = pdifmax;
local pdifcrit = {};
cratio = cratio + 1;
cratio = utils.clamp(cratio, 0, 3);
-- printf("ratio: %f min: %f max %f\n", cratio, pdifmin, pdifmax);
if (cratio < 0.5) then
pdifmax = cratio + 0.5;
elseif (cratio < 0.7) then
pdifmax = 1;
elseif (cratio < 1.2) then
pdifmax = cratio + 0.3;
elseif (cratio < 1.5) then
pdifmax = (cratio * 0.25) + cratio;
elseif (cratio < 2.625) then
pdifmax = cratio + 0.375;
else
pdifmax = 3;
end
-- min
if (cratio < 0.38) then
pdifmin = 0;
elseif (cratio < 1.25) then
pdifmin = cratio * (1176/1024) - (448/1024);
elseif (cratio < 1.51) then
pdifmin = 1;
elseif (cratio < 2.44) then
pdifmin = cratio * (1176/1024) - (775/1024);
else
pdifmin = cratio - 0.375;
end
local critbonus = attacker:getMod(MOD_CRIT_DMG_INCREASE)
critbonus = utils.clamp(critbonus, 0, 100);
pdifcrit[1] = pdifmin * ((100 + critbonus)/100);
pdifcrit[2] = pdifmax * ((100 + critbonus)/100);
return pdif, pdifcrit;
end;
function cRangedRatio(attacker, defender, params, ignoredDef)
local cratio = attacker:getRATT() / (defender:getStat(MOD_DEF) - ignoredDef);
local levelcor = 0;
if (attacker:getMainLvl() < defender:getMainLvl()) then
levelcor = 0.025 * (defender:getMainLvl() - attacker:getMainLvl());
end
cratio = cratio - levelcor;
cratio = cratio * params.atkmulti;
if (cratio > 3 - levelcor) then
cratio = 3 - levelcor;
end
if (cratio < 0) then
cratio = 0;
end
-- max
local pdifmax = 0;
if (cratio < 0.9) then
pdifmax = cratio * (10/9);
elseif (cratio < 1.1) then
pdifmax = 1;
else
pdifmax = cratio;
end
-- min
local pdifmin = 0;
if (cratio < 0.9) then
pdifmin = cratio;
elseif (cratio < 1.1) then
pdifmin = 1;
else
pdifmin = (cratio * (20/19))-(3/19);
end
pdif = {};
pdif[1] = pdifmin;
pdif[2] = pdifmax;
-- printf("ratio: %f min: %f max %f\n", cratio, pdifmin, pdifmax);
pdifcrit = {};
pdifmin = pdifmin * 1.25;
pdifmax = pdifmax * 1.25;
pdifcrit[1] = pdifmin;
pdifcrit[2] = pdifmax;
return pdif, pdifcrit;
end
-- Given the attacker's str and the mob's vit, fSTR is calculated
function fSTR(atk_str,def_vit,base_dmg)
local dSTR = atk_str - def_vit;
if (dSTR >= 12) then
fSTR2 = ((dSTR+4)/2);
elseif (dSTR >= 6) then
fSTR2 = ((dSTR+6)/2);
elseif (dSTR >= 1) then
fSTR2 = ((dSTR+7)/2);
elseif (dSTR >= -2) then
fSTR2 = ((dSTR+8)/2);
elseif (dSTR >= -7) then
fSTR2 = ((dSTR+9)/2);
elseif (dSTR >= -15) then
fSTR2 = ((dSTR+10)/2);
elseif (dSTR >= -21) then
fSTR2 = ((dSTR+12)/2);
else
fSTR2 = ((dSTR+13)/2);
end
-- Apply fSTR caps.
if (fSTR2<((base_dmg/9)*(-1))) then
fSTR2 = (base_dmg/9)*(-1);
elseif (fSTR2>((base_dmg/9)+8)) then
fSTR2 = (base_dmg/9)+8;
end
return fSTR2;
end;
-- obtains alpha, used for working out WSC
function getAlpha(level)
alpha = 1.00;
if (level <= 5) then
alpha = 1.00;
elseif (level <= 11) then
alpha = 0.99;
elseif (level <= 17) then
alpha = 0.98;
elseif (level <= 23) then
alpha = 0.97;
elseif (level <= 29) then
alpha = 0.96;
elseif (level <= 35) then
alpha = 0.95;
elseif (level <= 41) then
alpha = 0.94;
elseif (level <= 47) then
alpha = 0.93;
elseif (level <= 53) then
alpha = 0.92;
elseif (level <= 59) then
alpha = 0.91;
elseif (level <= 61) then
alpha = 0.90;
elseif (level <= 63) then
alpha = 0.89;
elseif (level <= 65) then
alpha = 0.88;
elseif (level <= 67) then
alpha = 0.87;
elseif (level <= 69) then
alpha = 0.86;
elseif (level <= 71) then
alpha = 0.85;
elseif (level <= 73) then
alpha = 0.84;
elseif (level <= 75) then
alpha = 0.83;
elseif (level < 99) then
alpha = 0.85;
else
alpha = 1; -- Retail has no alpha anymore!
end
return alpha;
end;
-- params contains: ftp100, ftp200, ftp300, str_wsc, dex_wsc, vit_wsc, int_wsc, mnd_wsc, canCrit, crit100, crit200, crit300, acc100, acc200, acc300, ignoresDef, ignore100, ignore200, ignore300, atkmulti
function doRangedWeaponskill(attacker, target, wsID, params, tp, primary, action)
local bonusTP = 0;
if (params.bonusTP ~= nil) then
bonusTP = params.bonusTP;
end
local multiHitfTP = false;
if (params.multiHitfTP ~= nil) then
multiHitfTP = params.multiHitfTP;
end
local bonusfTP, bonusacc = handleWSGorgetBelt(attacker);
bonusacc = bonusacc + attacker:getMod(MOD_WSACC);
-- get fstr
local fstr = fSTR(attacker:getStat(MOD_STR),target:getStat(MOD_VIT),attacker:getRangedDmgForRank());
-- apply WSC
local base = attacker:getRangedDmg() + fstr +
(attacker:getStat(MOD_STR) * params.str_wsc + attacker:getStat(MOD_DEX) * params.dex_wsc +
attacker:getStat(MOD_VIT) * params.vit_wsc + attacker:getStat(MOD_AGI) * params.agi_wsc +
attacker:getStat(MOD_INT) * params.int_wsc + attacker:getStat(MOD_MND) * params.mnd_wsc +
attacker:getStat(MOD_CHR) * params.chr_wsc) * getAlpha(attacker:getMainLvl());
-- Applying fTP multiplier
local ftp = fTP(tp,params.ftp100,params.ftp200,params.ftp300) + bonusfTP;
local crit = false
local ignoredDef = 0;
if (params.ignoresDef == not nil and params.ignoresDef == true) then
ignoredDef = calculatedIgnoredDef(tp, target:getStat(MOD_DEF), params.ignored100, params.ignored200, params.ignored300);
end
-- get cratio min and max
local cratio, ccritratio = cRangedRatio( attacker, target, params, ignoredDef);
local ccmin = 0;
local ccmax = 0;
local hasMightyStrikes = attacker:hasStatusEffect(EFFECT_MIGHTY_STRIKES);
local critrate = 0;
if (params.canCrit) then -- work out critical hit ratios, by +1ing
critrate = fTP(tp,params.crit100,params.crit200,params.crit300);
-- add on native crit hit rate (guesstimated, it actually follows an exponential curve)
local nativecrit = (attacker:getStat(MOD_DEX) - target:getStat(MOD_AGI))*0.005; -- assumes +0.5% crit rate per 1 dDEX
if (nativecrit > 0.2) then -- caps only apply to base rate, not merits and mods
nativecrit = 0.2;
elseif (nativecrit < 0.05) then
nativecrit = 0.05;
end
nativecrit = nativecrit + (attacker:getMod(MOD_CRITHITRATE)/100) + attacker:getMerit(MERIT_CRIT_HIT_RATE)/100 - target:getMerit(MERIT_ENEMY_CRIT_RATE)/100;
if (attacker:hasStatusEffect(EFFECT_INNIN) and attacker:isBehind(target, 23)) then -- Innin crit boost if attacker is behind target
nativecrit = nativecrit + attacker:getStatusEffect(EFFECT_INNIN):getPower();
end
critrate = critrate + nativecrit;
end
local dmg = base * ftp;
-- Applying pDIF
local pdif = generatePdif (cratio[1],cratio[2], false);
-- First hit has 95% acc always. Second hit + affected by hit rate.
local missChance = math.random();
local finaldmg = 0;
local hitrate = getRangedHitRate(attacker,target,true,bonusacc);
if (params.acc100~=0) then
-- ACCURACY VARIES WITH TP, APPLIED TO ALL HITS.
-- print("Accuracy varies with TP.");
hr = accVariesWithTP(getRangedHitRate(attacker,target,false,bonusacc),attacker:getRACC(),tp,params.acc100,params.acc200,params.acc300);
hitrate = hr;
end
local tpHitsLanded = 0;
local shadowsAbsorbed = 0
if (missChance <= hitrate) then
if not shadowAbsorb(target) then
if (params.canCrit) then
local critchance = math.random();
if (critchance <= critrate or hasMightyStrikes) then -- crit hit!
crit = true
local cpdif = generatePdif (ccritratio[1], ccritratio[2], false);
finaldmg = dmg * cpdif;
else
finaldmg = dmg * pdif;
end
else
finaldmg = dmg * pdif;
end
tpHitsLanded = 1;
else
shadowsAbsorbed = shadowsAbsorbed + 1
end
end
-- Store first hit bonus for use after other calcs are done..
local firstHitBonus = ((finaldmg * attacker:getMod(MOD_ALL_WSDMG_FIRST_HIT))/100);
local numHits = params.numHits;
if not multiHitfTP then dmg = base end
local extraHitsLanded = 0;
if (numHits>1) then
if (params.acc100==0) then
-- work out acc since we actually need it now
hitrate = getRangedHitRate(attacker,target,true,bonusacc);
end
hitsdone = 1;
while (hitsdone < numHits) do
chance = math.random();
if (chance<=hitrate) then -- it hit
if not shadowAbsorb(target) then
pdif = generatePdif (cratio[1],cratio[2], false);
if (canCrit) then
critchance = math.random();
if (critchance <= critrate or hasMightyStrikes) then -- crit hit!
cpdif = generatePdif (ccritratio[1], ccritratio[2], false);
finaldmg = finaldmg + dmg * cpdif;
else
finaldmg = finaldmg + dmg * pdif;
end
else
finaldmg = finaldmg + dmg * pdif; -- NOTE: not using 'dmg' since fTP is 1.0 for subsequent hits!!
end
extraHitsLanded = extraHitsLanded + 1;
else
shadowsAbsorbed = shadowsAbsorbed + 1
end
end
hitsdone = hitsdone + 1;
end
end
-- print("Landed " .. hitslanded .. "/" .. numHits .. " hits with hitrate " .. hitrate .. "!");
-- DMG Bonus for any WS
local bonusdmg = attacker:getMod(MOD_ALL_WSDMG_ALL_HITS);
-- Ws Specific DMG Bonus
if (attacker:getMod(MOD_WEAPONSKILL_DAMAGE_BASE + wsID) > 0) then
bonusdmg = bonusdmg + attacker:getMod(MOD_WEAPONSKILL_DAMAGE_BASE + wsID);
end
-- Add in bonusdmg
finaldmg = finaldmg * ((100 + bonusdmg)/100);
finaldmg = finaldmg + firstHitBonus;
-- Check for reductions
finaldmg = target:rangedDmgTaken(finaldmg);
finaldmg = finaldmg * target:getMod(MOD_PIERCERES) / 1000;
finaldmg = finaldmg * WEAPON_SKILL_POWER
finaldmg = takeWeaponskillDamage(target, attacker, params, primary, finaldmg, SLOT_RANGED, tpHitsLanded, extraHitsLanded, shadowsAbsorbed, bonusTP, action, nil)
return finaldmg, crit, tpHitsLanded, extraHitsLanded, shadowsAbsorbed;
end;
function getMultiAttacks(attacker, numHits)
local bonusHits = 0;
local multiChances = 1;
local doubleRate = (attacker:getMod(MOD_DOUBLE_ATTACK) + attacker:getMerit(MERIT_DOUBLE_ATTACK_RATE))/100;
local tripleRate = (attacker:getMod(MOD_TRIPLE_ATTACK) + attacker:getMerit(MERIT_TRIPLE_ATTACK_RATE))/100;
local quadRate = attacker:getMod(MOD_QUAD_ATTACK)/100;
-- QA/TA/DA can only proc on the first hit of each weapon or each fist
if (attacker:getOffhandDmg() > 0 or attacker:getWeaponSkillType(SLOT_MAIN) == SKILL_H2H) then
multiChances = 2;
end
for i = 1, multiChances, 1 do
local chance = math.random()
if (chance < quadRate) then
bonusHits = bonusHits + 3;
elseif (chance < tripleRate + quadRate) then
bonusHits = bonusHits + 2;
elseif(chance < doubleRate + tripleRate + quadRate) then
bonusHits = bonusHits + 1;
end
if (i == 1) then
attacker:delStatusEffect(EFFECT_ASSASSIN_S_CHARGE);
attacker:delStatusEffect(EFFECT_WARRIOR_S_CHARGE);
-- recalculate DA/TA/QA rate
doubleRate = (attacker:getMod(MOD_DOUBLE_ATTACK) + attacker:getMerit(MERIT_DOUBLE_ATTACK_RATE))/100;
tripleRate = (attacker:getMod(MOD_TRIPLE_ATTACK) + attacker:getMerit(MERIT_TRIPLE_ATTACK_RATE))/100;
quadRate = attacker:getMod(MOD_QUAD_ATTACK)/100;
end
end
if ((numHits + bonusHits ) > 8) then
return 8;
end
return numHits + bonusHits;
end;
function generatePdif (cratiomin, cratiomax, melee)
local pdif = math.random(cratiomin*1000, cratiomax*1000) / 1000;
if (melee) then
pdif = pdif * (math.random(100,105)/100);
end
return pdif;
end
function getStepAnimation(skill)
if skill <= 1 then
return 15;
elseif skill <= 3 then
return 14;
elseif skill == 4 then
return 19;
elseif skill == 5 then
return 16;
elseif skill <= 7 then
return 18;
elseif skill == 8 then
return 20;
elseif skill == 9 then
return 21;
elseif skill == 10 then
return 22;
elseif skill == 11 then
return 17;
elseif skill == 12 then
return 23;
else
return 0;
end
end
function getFlourishAnimation(skill)
if skill <= 1 then
return 25;
elseif skill <= 3 then
return 24;
elseif skill == 4 then
return 29;
elseif skill == 5 then
return 26;
elseif skill <= 7 then
return 28;
elseif skill == 8 then
return 30;
elseif skill == 9 then
return 31;
elseif skill == 10 then
return 32;
elseif skill == 11 then
return 27;
elseif skill == 12 then
return 33;
else
return 0;
end
end
function takeWeaponskillDamage(defender, attacker, params, primary, finaldmg, slot, tpHitsLanded, extraHitsLanded, shadowsAbsorbed, bonusTP, action, taChar)
if tpHitsLanded + extraHitsLanded > 0 then
if finaldmg >= 0 then
if primary then
action:messageID(defender:getID(), msgBasic.DAMAGE)
else
action:messageID(defender:getID(), msgBasic.DAMAGE_SECONDARY)
end
if finaldmg > 0 then
action:reaction(defender:getID(), REACTION_HIT)
action:speceffect(defender:getID(), SPECEFFECT_RECOIL)
end
else
if primary then
action:messageID(defender:getID(), msgBasic.SELF_HEAL)
else
action:messageID(defender:getID(), msgBasic.SELF_HEAL_SECONDARY)
end
end
action:param(defender:getID(), finaldmg)
elseif shadowsAbsorbed > 0 then
action:messageID(defender:getID(), msgBasic.SHADOW_ABSORB)
action:param(defender:getID(), shadowsAbsorbed)
else
if primary then
action:messageID(defender:getID(), msgBasic.SKILL_MISS)
else
action:messageID(defender:getID(), msgBasic.EVADES)
end
action:reaction(defender:getID(), REACTION_EVADE)
end
local targetTPMult = params.targetTPMult or 1
finaldmg = defender:takeWeaponskillDamage(attacker, finaldmg, slot, primary, tpHitsLanded, (extraHitsLanded * 10) + bonusTP, targetTPMult)
local enmityEntity = taChar or attacker;
if (params.overrideCE and params.overrideVE) then
defender:addEnmity(enmityEntity, params.overrideCE, params.overrideVE)
else
local enmityMult = params.enmityMult or 1
defender:updateEnmityFromDamage(enmityEntity, finaldmg * enmityMult)
end
return finaldmg;
end
-- Params should have the following members:
-- params.power.lv1: Base value for AM power @ level 1
-- params.power.lv2: Base value for AM power @ level 2
-- params.power.lv3: Base value for AM power @ level 3
-- params.power.lv1_inc: How much to increment at each power level
-- params.power.lv2_inc: How much to increment at each power level
-- params.subpower.lv1: Subpower for level 1
-- params.subpower.lv2: Subpower for level 2
-- params.subpower.lv3: Subpower for level 3
-- params.duration.lv1: Duration for AM level 1
-- params.duration.lv2: Duration for AM level 2
-- params.duration.lv3: Duration for AM level 3
function applyAftermathEffect(player, tp, params)
if (params == nil) then
params = initAftermathParams()
end
local apply_power = 0
if (tp == 3000 and shouldApplyAftermath(player, EFFECT_AFTERMATH_LV3)) then
player:delStatusEffect(EFFECT_AFTERMATH_LV1);
player:delStatusEffect(EFFECT_AFTERMATH_LV2);
player:addStatusEffect(EFFECT_AFTERMATH_LV3, params.power.lv3, 0,
params.duration.lv3, 0, params.subpower.lv3);
elseif (tp >= 2000 and shouldApplyAftermath(player, EFFECT_AFTERMATH_LV2)) then
player:delStatusEffect(EFFECT_AFTERMATH_LV1);
apply_power = math.floor(params.power.lv2 + ((tp - 2000) / (100 / params.power.lv2_inc)))
player:addStatusEffect(EFFECT_AFTERMATH_LV2, apply_power, 0,
params.duration.lv2, 0, params.subpower.lv2);
elseif (tp >= 1000 and shouldApplyAftermath(player, EFFECT_AFTERMATH_LV1)) then
apply_power = math.floor(params.power.lv1 + ((tp - 1000) / (100 / params.power.lv1_inc)))
player:addStatusEffect(EFFECT_AFTERMATH_LV1, apply_power, 0,
params.duration.lv1, 0, params.subpower.lv1);
end
end;
function initAftermathParams()
local params = {}
params.power = {}
params.subpower = {}
params.duration = {}
params.power.lv1 = 10
params.power.lv2 = 20
params.power.lv3 = 40
params.power.lv1_inc = 1
params.power.lv2_inc = 4
params.subpower.lv1 = 1
params.subpower.lv2 = 1
params.subpower.lv3 = 1
params.duration.lv1 = 60
params.duration.lv2 = 90
params.duration.lv3 = 120
return params
end;
function shouldApplyAftermath(player, effect)
local result = true;
if (effect == EFFECT_AFTERMATH_LV1 and (player:hasStatusEffect(EFFECT_AFTERMATH_LV2) or player:hasStatusEffect(EFFECT_AFTERMATH_LV3))) then
result = false;
elseif (effect == EFFECT_AFTERMATH_LV2 and player:hasStatusEffect(EFFECT_AFTERMATH_LV3)) then
result = false;
end;
return result;
end;
function handleWSGorgetBelt(attacker)
local ftpBonus = 0;
local accBonus = 0;
if (attacker:getObjType() == TYPE_PC) then
-- TODO: Get these out of itemid checks when possible.
local elementalGorget = { 15495, 15498, 15500, 15497, 15496, 15499, 15501, 15502 };
local elementalBelt = { 11755, 11758, 11760, 11757, 11756, 11759, 11761, 11762 };
local neck = attacker:getEquipID(SLOT_NECK);
local belt = attacker:getEquipID(SLOT_WAIST);
local SCProp1, SCProp2, SCProp3 = attacker:getWSSkillchainProp();
for i,v in ipairs(elementalGorget) do
if (neck == v) then
if (doesElementMatchWeaponskill(i, SCProp1) or doesElementMatchWeaponskill(i, SCProp2) or doesElementMatchWeaponskill(i, SCProp3)) then
accBonus = accBonus + 10;
ftpBonus = ftpBonus + 0.1;
end
break;
end
end
if (neck == 27510) then -- Fotia Gorget
accBonus = accBonus + 10;
ftpBonus = ftpBonus + 0.1;
end
for i,v in ipairs(elementalBelt) do
if (belt == v) then
if (doesElementMatchWeaponskill(i, SCProp1) or doesElementMatchWeaponskill(i, SCProp2) or doesElementMatchWeaponskill(i, SCProp3)) then
accBonus = accBonus + 10;
ftpBonus = ftpBonus + 0.1;
end
break;
end
end
if (belt == 28420) then -- Fotia Belt
accBonus = accBonus + 10;
ftpBonus = ftpBonus + 0.1;
end
end
return ftpBonus, accBonus;
end;
function shadowAbsorb(target)
local targShadows = target:getMod(MOD_UTSUSEMI)
local shadowType = MOD_UTSUSEMI
if targShadows == 0 then
if math.random() < 0.8 then
targShadows = target:getMod(MOD_BLINK)
shadowType = MOD_BLINK
end
end
if targShadows > 0 then
if shadowType == MOD_UTSUSEMI then
local effect = target:getStatusEffect(EFFECT_COPY_IMAGE)
if effect then
if targShadows - 1 == 1 then
effect:setIcon(EFFECT_COPY_IMAGE)
elseif targShadows - 1 == 2 then
effect:setIcon(EFFECT_COPY_IMAGE_2)
elseif targShadows - 1 == 3 then
effect:setIcon(EFFECT_COPY_IMAGE_3)
end
end
end
target:setMod(shadowType, targShadows - 1)
if targShadows - 1 == 0 then
target:delStatusEffect(EFFECT_COPY_IMAGE)
target:delStatusEffect(EFFECT_COPY_BLINK)
end
return true
end
return false
end
| gpl-3.0 |
mrdiegoa/ramcloud | ft/wireshark_rpc.lua | 20 | 5693 | -- (c) 2010 Stanford University
-- Wireshark is under the GPL, so I think this script has to be as well.
print("hello world!")
require "luabit/bit"
----------------
-- from http://ricilake.blogspot.com/2007/10/iterating-bits-in-lua.html:
function getbit(p)
return 2 ^ (p - 1) -- 1-based indexing
end
-- Typical call: if hasbit(x, getbit(3)) then ...
function hasbit(x, p)
return x % (p + p) >= p
end
----------------
do
local p_ack_proto = Proto("rcack", "RAMCloud ACK")
local p_sess_proto = Proto("rcsess", "RAMCloud Session Open")
local maxpt = 0
do -- RAMCloud session open response dissector
local f_maxChannelId = ProtoField.uint16("rcsess.maxChannelId", "Max Avail. Channel Id", base.DEC)
p_sess_proto.fields = { f_maxChannelId }
function p_sess_proto.dissector(buf, pkt, root)
local t = root:add(p_sess_proto, buf(0))
t:add_le(f_maxChannelId, buf(0, 1))
end
end
do -- RAMCloud ACK response dissector
local p_frag_proto = Proto("rcackgaps", "Fragments")
local f_ack = ProtoField.uint16("rcack.ack", "ACK", base.DEC)
p_frag_proto.fields = { f_ack }
local f_firstMissingFrag = ProtoField.uint16("rcack.firstMissingFrag", "First Missing Fragment", base.DEC)
p_ack_proto.fields = { f_firstMissingFrag }
function p_ack_proto.dissector(buf, pkt, root)
local t = root:add(p_ack_proto, buf(0))
t:add_le(f_firstMissingFrag, buf(0, 2))
local u = t:add(p_frag_proto, buf(2))
local bitNumber = 0
while bitNumber < 32 do
local byte = buf(2 + bitNumber / 8, 1):le_uint()
if bit.band(byte, bit.blshift(1, bitNumber % 8)) ~= 0 then
u:add_le(f_ack, bitNumber + buf(0, 2):le_uint() + 1)
end
bitNumber = bitNumber + 1
end
-- Dissector.get("data"):call(buf(2):tvb(), pkt, t)
end
end
do -- RAMCloud transport header dissector
local p_proto = Proto("rc", "RAMCloud")
local f_sessionToken = ProtoField.uint64("rc.sessionToken", "Session Token", base.HEX)
local f_rpcId = ProtoField.uint32("rc.rpcId", "RPC ID", base.HEX)
local f_clientSessionHint = ProtoField.uint32("rc.clientSessionHint", "Client Session Hint", base.DEC)
local f_serverSessionHint = ProtoField.uint32("rc.serverSessionHint", "Server Session Hint", base.DEC)
local f_fragNumber = ProtoField.uint16("rc.fragNumber", "Fragment Number", base.DEC)
local f_totalFrags = ProtoField.uint16("rc.totalFrags", "Total Fragments", base.DEC)
local f_channelId = ProtoField.uint8("rc.channelId", "Channel ID", base.DEC)
local t_payloadTypes = { [0x0] = "DATA",
[0x1] = "ACK",
[0x2] = "SESSION_OPEN",
[0x3] = "RESERVED 1",
[0x4] = "BAD_SESSION",
[0x5] = "RETRY_WITH_NEW_RPCID",
[0x6] = "RESERVED 2",
[0x7] = "RESERVED 3"}
local f_payloadType = ProtoField.uint8("rc.payloadType", "Payload Type", base.DEC,
t_payloadTypes, 0xF0)
local f_direction = ProtoField.uint8("rc.direction", "Direction", nil,
{ [0] = "client to server", [1] = "server to client" }, 0x01)
local f_requestAck = ProtoField.uint8("rc.requestAck", "Request ACK", nil, nil, 0x02)
local f_pleaseDrop = ProtoField.uint8("rc.pleaseDrop", "Please Drop", nil, nil, 0x04)
p_proto.fields = { f_sessionToken, f_rpcId, f_clientSessionHint, f_serverSessionHint,
f_fragNumber, f_totalFrags,
f_channelId, f_payloadType, f_direction, f_requestAck, f_pleaseDrop }
function p_proto.dissector(buf, pkt, root)
local header_len = 26
local t = root:add(p_proto, buf(0, header_len))
t:add_le(f_sessionToken, buf(0, 8))
t:add_le(f_rpcId, buf(8, 4))
t:add_le(f_clientSessionHint, buf(12, 4))
t:add_le(f_serverSessionHint, buf(16, 4))
t:add_le(f_fragNumber, buf(20, 2))
t:add_le(f_totalFrags, buf(22, 2))
t:add_le(f_channelId, buf(24, 1))
t:add_le(f_payloadType, buf(25, 1))
t:add_le(f_direction, buf(25, 1))
t:add_le(f_requestAck, buf(25, 1))
t:add_le(f_pleaseDrop, buf(25, 1))
local i_payloadType = bit.blogic_rshift(buf(25, 1):le_uint(), 4)
if i_payloadType > maxpt then
maxpt = i_payloadType
print(i_payloadType)
end
local i_direction = bit.band(buf(25, 1):le_uint(), 0x01)
local i_requestAck = bit.band(buf(25, 1):le_uint(), 0x02)
local s_fragDisplay = "";
local s_directionDisplay = "";
local s_requestAckDisplay = "";
if i_payloadType == 0x0 then
s_fragDisplay = "[" .. buf(20,2):le_uint() .. "/" .. buf(22,2):le_uint() - 1 .. "] "
if i_requestAck ~= 0 then
s_requestAckDisplay = " requesting ACK"
end
end
if i_payloadType ~= 0x1 then
if i_direction == 0 then
s_directionDisplay = "request"
else
s_directionDisplay = "response"
end
else
if i_direction == 0 then
s_directionDisplay = "to server"
else
s_directionDisplay = "to client"
end
end
local s_info = buf(0, 1):le_uint() .. "." .. buf(24, 1):le_uint() .. "." .. buf(8, 1):le_uint() .. ": "
s_info = s_info .. s_fragDisplay .. t_payloadTypes[i_payloadType] .. " "
s_info = s_info .. s_directionDisplay .. s_requestAckDisplay
pkt.columns.info = s_info
pkt.columns.protocol = "RAMCloud"
if i_payloadType == 0x1 then
p_ack_proto.dissector:call(buf(header_len):tvb(), pkt, root)
elseif i_payloadType == 0x2 and i_direction == 1 then
p_sess_proto.dissector:call(buf(header_len):tvb(), pkt, root)
else
Dissector.get("data"):call(buf(header_len):tvb(), pkt, root)
end
end
local udp_encap_table = DissectorTable.get("udp.port")
udp_encap_table:add(12242, p_proto)
local eth_dissector_table = DissectorTable.get("ethertype")
if eth_dissector_table ~= nil then
eth_dissector_table:add(0x8001, p_proto)
end
end
end
| isc |
Maxsteam/4568584657657 | plugins/minecraft.lua | 624 | 2605 | local usage = {
"!mine [ip]: Searches Minecraft server on specified ip and sends info. Default port: 25565",
"!mine [ip] [port]: Searches Minecraft server on specified ip and port and sends info.",
}
local ltn12 = require "ltn12"
local function mineSearch(ip, port, receiver) --25565
local responseText = ""
local api = "https://api.syfaro.net/server/status"
local parameters = "?ip="..(URL.escape(ip) or "").."&port="..(URL.escape(port) or "").."&players=true&favicon=true"
local http = require("socket.http")
local respbody = {}
local body, code, headers, status = http.request{
url = api..parameters,
method = "GET",
redirect = true,
sink = ltn12.sink.table(respbody)
}
local body = table.concat(respbody)
if (status == nil) then return "ERROR: status = nil" end
if code ~=200 then return "ERROR: "..code..". Status: "..status end
local jsonData = json:decode(body)
responseText = responseText..ip..":"..port.." ->\n"
if (jsonData.motd ~= nil) then
local tempMotd = ""
tempMotd = jsonData.motd:gsub('%Β§.', '')
if (jsonData.motd ~= nil) then responseText = responseText.." Motd: "..tempMotd.."\n" end
end
if (jsonData.online ~= nil) then
responseText = responseText.." Online: "..tostring(jsonData.online).."\n"
end
if (jsonData.players ~= nil) then
if (jsonData.players.max ~= nil) then
responseText = responseText.." Max Players: "..jsonData.players.max.."\n"
end
if (jsonData.players.now ~= nil) then
responseText = responseText.." Players online: "..jsonData.players.now.."\n"
end
if (jsonData.players.sample ~= nil and jsonData.players.sample ~= false) then
responseText = responseText.." Players: "..table.concat(jsonData.players.sample, ", ").."\n"
end
end
if (jsonData.favicon ~= nil and false) then
--send_photo(receiver, jsonData.favicon) --(decode base64 and send)
end
return responseText
end
local function parseText(chat, text)
if (text == nil or text == "!mine") then
return usage
end
ip, port = string.match(text, "^!mine (.-) (.*)$")
if (ip ~= nil and port ~= nil) then
return mineSearch(ip, port, chat)
end
local ip = string.match(text, "^!mine (.*)$")
if (ip ~= nil) then
return mineSearch(ip, "25565", chat)
end
return "ERROR: no input ip?"
end
local function run(msg, matches)
local chat_id = tostring(msg.to.id)
local result = parseText(chat_id, msg.text)
return result
end
return {
description = "Searches Minecraft server and sends info",
usage = usage,
patterns = {
"^!mine (.*)$"
},
run = run
} | gpl-2.0 |
boliu/synchronicity | share/lua/playlist/canalplus.lua | 113 | 3501 | --[[
$Id: $
Copyright (c) 2007 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return vlc.access == "http" and string.match( vlc.path, "www.canalplus.fr" )
end
-- Parse function.
function parse()
p = {}
--vlc.msg.dbg( vlc.path )
if string.match( vlc.path, "www.canalplus.fr/.*%?pid=.*" )
then -- This is the HTML page's URL
local _,_,pid = string.find( vlc.path, "pid(%d-)%-" )
local id, name, description, arturl
while true do
-- Try to find the video's title
local line = vlc.readline()
if not line then break end
-- vlc.msg.dbg( line )
if string.match( line, "aVideos" ) then
if string.match( line, "CONTENT_ID.*=" ) then
_,_,id = string.find( line, "\"(.-)\"" )
elseif string.match( line, "CONTENT_VNC_TITRE" ) then
_,_,arturl = string.find( line, "src=\"(.-)\"" )
_,_,name = string.find( line, "title=\"(.-)\"" )
elseif string.match( line, "CONTENT_VNC_DESCRIPTION" ) then
_,_,description = string.find( line, "\"(.-)\"" )
end
if id and string.match( line, "new Array" ) then
add_item( p, id, name, description, arturl )
id = nil
name = nil
arturl = nil
description = nil
end
end
end
if id then
add_item( p, id, name, description, arturl )
end
return p
elseif string.match( vlc.path, "embed%-video%-player" ) then
while true do
local line = vlc.readline()
if not line then break end
--vlc.msg.dbg( line )
if string.match( line, "<hi" ) then
local _,_,path = string.find( line, "%[(http.-)%]" )
return { { path = path } }
end
end
end
end
function get_url_param( url, name )
local _,_,ret = string.find( url, "[&?]"..name.."=([^&]*)" )
return ret
end
function add_item( p, id, name, description, arturl )
--[[vlc.msg.dbg( "id: " .. tostring(id) )
vlc.msg.dbg( "name: " .. tostring(name) )
vlc.msg.dbg( "arturl: " .. tostring(arturl) )
vlc.msg.dbg( "description: " .. tostring(description) )
--]]
--local path = "http://www.canalplus.fr/flash/xml/configuration/configuration-embed-video-player.php?xmlParam="..id.."-"..get_url_param(vlc.path,"pid")
local path = "http://www.canalplus.fr/flash/xml/module/embed-video-player/embed-video-player.php?video_id="..id.."&pid="..get_url_param(vlc.path,"pid")
table.insert( p, { path = path; name = name; description = description; arturl = arturl } )
end
| gpl-2.0 |
gedads/Neodynamis | scripts/zones/Abyssea-Uleguerand/npcs/qm8.lua | 3 | 1353 | -----------------------------------
-- Zone: Abyssea-Uleguerand
-- NPC: qm8 (???)
-- Spawns Anemic Aloysius
-- !pos ? ? ? 253
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
--[[
if (trade:hasItemQty(3255,1) and trade:getItemCount() == 1) then -- Player has all the required items.
if (GetMobAction(17813938) == ACTION_NONE) then -- Mob not already spawned from this
SpawnMob(17813938):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:tradeComplete();
end
end
]]
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(1010, 3255); -- Inform player what items they need.
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 |
starlightknight/darkstar | scripts/globals/items/roast_pipira.lua | 11 | 1285 | -----------------------------------------
-- ID: 4538
-- Item: roast_pipira
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Dexterity 3
-- Mind -3
-- Attack % 14
-- Attack Cap 75
-- Ranged ATT % 14
-- Ranged ATT Cap 75
-----------------------------------------
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,4538)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.DEX, 3)
target:addMod(dsp.mod.MND, -3)
target:addMod(dsp.mod.FOOD_ATTP, 14)
target:addMod(dsp.mod.FOOD_ATT_CAP, 75)
target:addMod(dsp.mod.FOOD_RATTP, 14)
target:addMod(dsp.mod.FOOD_RATT_CAP, 75)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.DEX, 3)
target:delMod(dsp.mod.MND, -3)
target:delMod(dsp.mod.FOOD_ATTP, 14)
target:delMod(dsp.mod.FOOD_ATT_CAP, 75)
target:delMod(dsp.mod.FOOD_RATTP, 14)
target:delMod(dsp.mod.FOOD_RATT_CAP, 75)
end
| gpl-3.0 |
LuaDist2/lua-fann | test/module.lua | 2 | 1669 | -- This Lua script demonstrates how to use the LuaFann module
-- through the require("fann") statement.
-- It is based on the xor_train.c and xor_test.c example
-- programs distributed with FANN
require("fann")
-- Create a neural network, with 2 inputs, two hidden layer neurons,
-- and one output neuron
ann = fann.create_standard(3, 2, 2, 1)
-- Load training data from "xor.data"
train = fann.read_train_from_file("xor.data")
-- Set some parameters
ann:set_activation_steepness_hidden(1)
ann:set_activation_steepness_output(1)
ann:set_activation_function_hidden(fann.FANN_SIGMOID_SYMMETRIC)
ann:set_activation_function_output(fann.FANN_SIGMOID_SYMMETRIC)
ann:set_train_stop_function(fann.FANN_STOPFUNC_BIT)
ann:set_bit_fail_limit(0.01)
-- Initialise the weights based on the training data
ann:init_weights(train)
-- Train the network on the training data
ann:train_on_data(train, 500000, 1000, 0.001)
-- Test the network against the training data
mse = ann:test_data(train)
print("MSE: " .. mse)
-- Save the network to a file
ann:save("myxor.net")
-- For testing, recreate neural net from the file
ann = fann.create_from_file("myxor.net")
ann:print_connections()
ann:print_parameters()
-- Run the network through some samples to demonstrate its functionality
xor = ann:run(1, 1)
print("Result: " .. xor)
xor = ann:run(1, -1)
print("Result: " .. xor)
xor = ann:run(-1, -1)
print("Result: " .. xor)
xor = ann:run(-1, 1)
print("Result: " .. xor)
-- Now load some non-exact test data and test the NN
test = fann.read_train_from_file("xortest.data")
print("Test data read: " .. test:__tostring())
mse = ann:test_data(test)
print("MSE on test data: " .. mse)
| lgpl-2.1 |
starlightknight/darkstar | scripts/zones/King_Ranperres_Tomb/mobs/Cemetery_Cherry.lua | 10 | 1368 | -----------------------------------
-- Area: King Ranperres Tomb
-- NM: Cemetery Cherry
-- !pos 33.000 0.500 -287.000 190
-----------------------------------
local ID = require("scripts/zones/King_Ranperres_Tomb/IDs")
require("scripts/globals/titles")
-----------------------------------
function spawnSaplings()
for i = ID.mob.CHERRY_SAPLING_OFFSET, ID.mob.CHERRY_SAPLING_OFFSET + 12 do
local mob = GetMobByID(i)
if mob ~= nil and mob:getName() == 'Cherry_Sapling' and not mob:isSpawned() then
SpawnMob(i)
end
end
end
function onMobInitialize(mob)
mob:setMobMod(dsp.mobMod.IDLE_DESPAWN, 180)
mob:setMobMod(dsp.mobMod.DRAW_IN, 1)
local saplingsRespawn = math.random(1800, 3600) -- 30 to 60 minutes
mob:timer(saplingsRespawn * 1000, function(mob) spawnSaplings() end)
end
function onMobSpawn(mob)
mob:setLocalVar("wasKilled", 0)
end
function onMobDeath(mob, player, isKiller)
mob:setLocalVar("wasKilled", 1)
player:addTitle(dsp.title.MON_CHERRY)
end
function onMobDespawn(mob)
local saplingsRespawn = 0
if mob:getLocalVar("wasKilled") == 1 then
saplingsRespawn = math.random(216000, 259200) -- 60 to 72 hours
else
saplingsRespawn = math.random(1800, 3600) -- 30 to 60 minutes
end
mob:timer(saplingsRespawn * 1000, function(mob) spawnSaplings() end)
end
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/Nashmau/npcs/Kyokyoroon.lua | 9 | 1194 | -----------------------------------
-- Area: Nashmau
-- NPC: Kyokyoroon
-- Standard Info NPC
-- !pos 18.020 -6.000 10.467 53
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(AHT_URHGAN,dsp.quest.id.ahtUrhgan.RAT_RACE) == QUEST_ACCEPTED and player:getCharVar("ratraceCS") == 5) then
if (trade:hasItemQty(5595,1) and trade:getItemCount() == 1) then
player:startEvent(311);
end
end
end;
function onTrigger(player,npc)
local ratRaceProg = player:getCharVar("ratraceCS");
if (ratRaceProg == 5) then
player:startEvent(263);
elseif (ratRaceProg == 6) then
player:startEvent(316);
elseif (player:getQuestStatus(AHT_URHGAN,dsp.quest.id.ahtUrhgan.RAT_RACE) == QUEST_COMPLETED) then
player:startEvent(317);
else
player:startEvent(263);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 311) then
player:tradeComplete();
player:setCharVar("ratraceCS",6);
end
end;
| gpl-3.0 |
laino/luakit | tests/test_clib_soup.lua | 6 | 2670 | require "lunit"
module("test_clib_soup", lunit.testcase, package.seeall)
function test_module()
assert_table(soup)
end
function test_properties()
-- accept_language accept_language_auto
soup.accept_language_auto = true
assert_equal(true, soup.accept_language_auto)
assert_string(soup.accept_language)
soup.accept_language = "en-au, en"
assert_equal("en-au, en", soup.accept_language)
assert_equal(false, soup.accept_language_auto)
soup.idle_timeout = 60
assert_equal(60, soup.idle_timeout)
soup.max_conns = 10
assert_equal(10, soup.max_conns)
soup.max_conns_per_host = 10
assert_equal(10, soup.max_conns_per_host)
soup.proxy_uri = "http://localhost/"
assert_equal("http://localhost/", soup.proxy_uri)
soup.proxy_uri = nil
-- System dependant
--soup.ssl_ca_file = "/etc/certs/ca-certificates.crt"
--assert_equal("/etc/certs/ca-certificates.crt", soup.ssl_ca_file)
soup.ssl_strict = true
assert_equal(true, soup.ssl_strict)
soup.timeout = 10
assert_equal(10, soup.timeout)
end
function test_add_cookies()
assert_error(function () soup.add_cookies("error") end)
assert_error(function () soup.add_cookies({"error"}) end)
assert_error(function () soup.add_cookies({{}}) end)
assert_pass(function ()
soup.add_cookies({
{ domain = "google.com", path = "/", name = "test",
value = "test", expires = 10, http_only = true, secure = true }
})
end)
assert_pass(function ()
soup.add_cookies({
{ domain = "google.com", path = "/", name = nil,
value = "test", expires = 10, http_only = true, secure = true }
})
soup.add_cookies({
{ domain = "google.com", path = "/", name = "",
value = nil, expires = 10, http_only = true, secure = true }
})
soup.add_cookies({
{ domain = "google.com", path = "/", name = "",
value = "", expires = 10, http_only = true, secure = true }
})
soup.add_cookies({
{ domain = "google.com", path = "/", name = "test",
value = "test", expires = 10, http_only = 1, secure = 1 }
})
end)
assert_error(function ()
soup.add_cookies({
{ domain = 10, path = "/", name = "test",
value = "test", expires = 10, http_only = true, secure = true }
})
end)
assert_error(function ()
soup.add_cookies({
{ domain = "google.com", path = 10, name = "test",
value = "test", expires = 10, http_only = true, secure = true }
})
end)
end
| gpl-3.0 |
pedro-andrade-inpe/terrame | packages/base/tests/internal/basic/utils.lua | 3 | 2604 | -------------------------------------------------------------------------------------------
-- TerraME - a software platform for multiple scale spatially-explicit dynamic modeling.
-- Copyright (C) 2001-2017 INPE and TerraLAB/UFOP -- www.terrame.org
-- This code is part of the TerraME framework.
-- This framework 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.1 of the License, or (at your option) any later version.
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library.
-- The authors reassure the license terms regarding the warranties.
-- They specifically disclaim any warranties, including, but not limited to,
-- the implied warranties of merchantability and fitness for a particular purpose.
-- The framework provided hereunder is on an "as is" basis, and the authors have no
-- obligation to provide maintenance, support, updates, enhancements, or modifications.
-- In no event shall INPE and TerraLAB / UFOP be held liable to any party for direct,
-- indirect, special, incidental, or consequential damages arising out of the use
-- of this software and its documentation.
--
-------------------------------------------------------------------------------------------
return{
cleanErrorMessage = function(unitTest)
local str = "...o/github/terrame/bin/packages/base/lua/CellularSpace.lua:871: "
local err = "attempt to call field '?' (a string value)"
unitTest:assertEquals(_Gtme.cleanErrorMessage(str..err), err)
end,
stringToLabel = function(unitTest)
unitTest:assertEquals(_Gtme.stringToLabel("MyFirstString"), "My First String")
unitTest:assertEquals(_Gtme.stringToLabel("myFirstString"), "My First String")
unitTest:assertEquals(_Gtme.stringToLabel(255), "255")
unitTest:assertEquals(_Gtme.stringToLabel("value255Abc"), "Value 255 Abc")
unitTest:assertEquals(_Gtme.stringToLabel("UFMG"), "UFMG")
unitTest:assertEquals(_Gtme.stringToLabel("valueABC233"), "Value ABC 233")
unitTest:assertEquals(_Gtme.stringToLabel("my_first_string"), "My First String")
unitTest:assertEquals(_Gtme.stringToLabel("my_first_string_"), "My First String")
unitTest:assertEquals(_Gtme.stringToLabel("myFirstString_"), "My First String")
unitTest:assertEquals(_Gtme.stringToLabel("myFirstStr", "myParent"), "My First Str (in My Parent)")
unitTest:assertEquals(_Gtme.stringToLabel("scenario1rain"), "Scenario 1 Rain")
end
}
| lgpl-3.0 |
groupforspeed/telespeed | plugins/location.lua | 93 | 1704 | -- Implement a command !loc [area] which uses
-- the static map API to get a location image
-- Not sure if this is the proper way
-- Intent: get_latlong is in time.lua, we need it here
-- loadfile "time.lua"
-- Globals
-- If you have a google api key for the geocoding/timezone api
do
local api_key = nil
local base_api = "https://maps.googleapis.com/maps/api"
function get_staticmap(area)
local api = base_api .. "/staticmap?"
-- Get a sense of scale
local lat,lng,acc,types = get_latlong(area)
local scale = types[1]
if scale=="locality" then zoom=8
elseif scale=="country" then zoom=4
else zoom = 13 end
local parameters =
"size=600x300" ..
"&zoom=" .. zoom ..
"¢er=" .. URL.escape(area) ..
"&markers=color:red"..URL.escape("|"..area)
if api_key ~=nil and api_key ~= "" then
parameters = parameters .. "&key="..api_key
end
return lat, lng, api..parameters
end
function run(msg, matches)
local receiver = get_receiver(msg)
local lat,lng,url = get_staticmap(matches[1])
-- Send the actual location, is a google maps link
send_location(receiver, lat, lng, ok_cb, false)
-- Send a picture of the map, which takes scale into account
send_photo_from_url(receiver, url)
-- Return a link to the google maps stuff is now not needed anymore
return nil
end
return {
description = "Gets information about a location, maplink and overview",
usage = "!loc (location): Gets information about a location, maplink and overview",
patterns = {"^!loc (.*)$"},
run = run
}
end
--Copyright and edit; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--Ϊ©ΩΎΫ Ψ¨Ψ―ΩΩ Ψ°Ϊ©Ψ± Ω
ΩΨ¨ΨΉ ΨΨ±Ψ§Ω
Ψ§Ψ³Ψͺ
| gpl-2.0 |
BeamNG/luawebserver | webserver.lua | 1 | 3601 | -- warning: this project was not completed, however the basefile serving over ltn12 should work
local M = {}
local bindhost = 'localhost'
local bindport = 23512
local tcp_socket = nil
local socket = require("socket.socket")
local url = require("socket.url")
local ltn12 = require("socket.ltn12")
ltn12.BLOCKSIZE = 4096
local clients_read = {}
local clients_write = {}
local sinks = {}
local function init(_bindhost, _bindport)
bindhost = _bindhost
bindport = _bindport
tcp_socket = socket.tcp()
res, err = tcp_socket:bind(bindhost, bindport)
if res == nil then
print("unable to create webserver: " .. err)
end
tcp_socket:settimeout(0, 't')
tcp_socket:listen()
print("WebServer running on port "..bindport)
end
local function receiveRequest(c)
-- receive first line only
local line, err = c:receive()
if err then
-- 'timeout'
print("client.receive error: " .. tostring(err))
return
end
-- process URI's in that
for uri in string.gmatch(line, "GET /([^ ]*) HTTP/[0-9].[0-9]") do
local headers = {}
while true do
local line, err = c:receive()
if err then
-- 'timeout'
print("client.receive error: " .. tostring(err))
return nil
end
if line == '' then
break
end
local args = split(line, ':', 1)
if #args == 2 then
local key = string.lower(trim(args[1]))
local value = trim(args[2])
headers[key] = value
end
end
local uri_parsed = url.parse(uri)
return {uri = uri_parsed, headers = headers}
end
return nil
end
local function update()
-- accept new connections
while true do
local new_client = tcp_socket:accept()
if new_client then
--new_client:settimeout(0.1, 't')
table.insert(clients_read, new_client)
table.insert(clients_write, new_client)
else
break
end
end
local read, write, _ = socket.select(clients_read, clients_write, 0) -- _ = 'timeout' or nil, does not matter for our non-blocking usecase
for _, c in ipairs(read) do
if write[c] == nil then
goto continue
end
c:settimeout(0.1, 't')
local request = receiveRequest(c)
if request == nil then
goto continue
end
if request['uri'] == nil or request['uri']['path'] == nil then
print('unable to open file for reading: '.. request['uri']['path'])
goto continue
end
local fileHandle, err = io.open(request['uri']['path'], "rb")
if fileHandle == nil or err then
print('unable to open file for reading: '.. request['uri']['path'])
goto continue
end
local fileSource = ltn12.source.file(fileHandle)
local sink = socket.sink('close-when-done', c)
table.insert(sinks, {c, fileSource, sink})
::continue::
end
-- now pump the data
local newList = {}
for i, sinkData in ipairs(sinks) do
if write[sinkData[1]] then
local res, err = ltn12.pump.step(sinkData[2], sinkData[3])
print(tostring(res))
print(tostring(err))
if res then
table.insert(newList, sinkData)
end
end
end
sinks = newList
end
-- public interface
M.init = init
M.update = update
return M | isc |
starlightknight/darkstar | scripts/zones/Grauberg_[S]/IDs.lua | 9 | 1897 | -----------------------------------
-- Area: Grauberg_[S]
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.GRAUBERG_S] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
NOTHING_OUT_OF_ORDINARY = 6402, -- There is nothing out of the ordinary here.
FISHING_MESSAGE_OFFSET = 7049, -- You can't fish here.
HARVESTING_IS_POSSIBLE_HERE = 7687, -- Harvesting is possible here if you have <item>.
COMMON_SENSE_SURVIVAL = 9292, -- It appears that you have arrived at a new survival guide provided by the Servicemen's Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world.
},
mob =
{
KOTAN_KOR_KAMUY_PH =
{
[17141958] = 17141962,
[17141959] = 17141962,
[17141960] = 17141962,
[17141963] = 17141962,
[17141964] = 17141962,
[17141965] = 17141962,
[17141966] = 17141962,
[17141967] = 17141962,
},
SCITALIS_PH =
{
[17141977] = 17141979,
[17141978] = 17141979,
[17141981] = 17141979,
},
MIGRATORY_HIPPOGRYPH = 17142108,
},
npc =
{
HARVESTING =
{
17142545,
17142546,
17142547,
17142548,
17142549,
17142550,
},
INDESCRIPT_MARKINGS = 17142586,
},
}
return zones[dsp.zone.GRAUBERG_S] | gpl-3.0 |
gedads/Neodynamis | scripts/globals/items/hellsteak_+1.lua | 12 | 1923 | -----------------------------------------
-- ID: 5610
-- Item: hellsteak_+1
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Health 22
-- Strength 7
-- Intelligence -3
-- Health Regen While Healing 2
-- hMP +1
-- Attack % 20 (cap 150)
-- Ranged ATT % 20 (cap 150)
-- Dragon Killer 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5610);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 22);
target:addMod(MOD_STR, 7);
target:addMod(MOD_INT, -3);
target:addMod(MOD_HPHEAL, 2);
target:addMod(MOD_MPHEAL, 1);
target:addMod(MOD_FOOD_ATTP, 20);
target:addMod(MOD_FOOD_ATT_CAP, 150);
target:addMod(MOD_FOOD_RATTP, 20);
target:addMod(MOD_FOOD_RATT_CAP, 150);
target:addMod(MOD_DRAGON_KILLER, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 22);
target:delMod(MOD_STR, 7);
target:delMod(MOD_INT, -3);
target:delMod(MOD_HPHEAL, 2);
target:delMod(MOD_MPHEAL, 1);
target:delMod(MOD_FOOD_ATTP, 20);
target:delMod(MOD_FOOD_ATT_CAP, 150);
target:delMod(MOD_FOOD_RATTP, 20);
target:delMod(MOD_FOOD_RATT_CAP, 150);
target:delMod(MOD_DRAGON_KILLER, 5);
end;
| gpl-3.0 |
APItools/autoswagger.lua | spec/host_spec.lua | 1 | 17948 | local Host = require('autoswagger.host')
local EOL = require('autoswagger.lib.straux').EOL
local function create_host()
local h = Host:new('google.com', nil, nil, nil, 'guid')
h:learn("GET","/users/foo/activate.xml")
h:learn("GET","/applications/foo/activate.xml")
h:learn("GET","/applications/foo2/activate.xml")
h:learn("GET","/applications/foo3/activate.xml")
h:learn("GET","/users/foo4/activate.xml")
h:learn("GET","/users/foo5/activate.xml")
h:learn("GET","/applications/foo4/activate.xml")
h:learn("GET","/applications/foo5/activate.xml")
h:learn("GET","/services/foo5/activate.xml")
h:learn("GET","/fulanitos/foo5/activate.xml")
h:learn("GET","/fulanitos/foo6/activate.xml")
h:learn("GET","/fulanitos/foo7/activate.xml")
h:learn("GET","/fulanitos/foo8/activate.xml")
h:learn("GET","/services/foo6/activate.xml")
h:learn("GET","/services/foo7/activate.xml")
h:learn("GET","/services/foo8/activate.xml")
return h
end
describe('Host', function()
describe(':match', function()
it('returns a list of the paths that match a given path. The list can be empty', function()
local h = create_host()
local all_paths = h:get_paths()
assert.same(all_paths, h:match("/*/*/activate.xml"))
assert.same(all_paths, h:match("/*/*/*.xml"))
assert.same({"/fulanitos/*/activate.xml"}, h:match("/fulanitos/whatever/activate.xml"))
assert.same({"/*/foo/activate.xml"}, h:match("/whatever/foo/activate.xml"))
assert.same({"/*/foo5/activate.xml"}, h:match("/whatever/foo5/activate.xml"))
assert.same({}, h:match("/"))
assert.same({}, h:match("/*/*/activate.xml.whatever"))
assert.same({}, h:match("/whatever/foo_not_there/activate.xml"))
end)
end)
describe(':learn', function()
it('builds the expected paths', function()
local h = create_host()
local v = h:get_paths()
assert.same(v, {
"/*/foo/activate.xml",
"/*/foo5/activate.xml",
"/applications/*/activate.xml",
"/fulanitos/*/activate.xml",
"/services/*/activate.xml",
"/users/*/activate.xml"
})
end)
it('adds new paths only when they are really new', function()
local h = Host:new('google.com', nil, nil, nil, 'host_guid')
h:learn("GET","/users/foo/activate.xml")
assert.same( {"/users/foo/activate.xml"}, h:get_paths())
h:learn("GET","/applications/foo/activate.xml")
assert.same( {"/*/foo/activate.xml"}, h:get_paths())
h:learn("GET","/applications/foo2/activate.xml")
h:learn("GET","/applications/foo3/activate.xml")
h:learn("GET","/users/foo4/activate.xml")
h:learn("GET","/users/foo5/activate.xml")
h:learn("GET","/users/foo6/activate.xml")
h:learn("GET","/users/foo7/activate.xml")
assert.same(h:get_paths(), {
"/*/foo/activate.xml",
"/applications/*/activate.xml",
"/users/*/activate.xml"
})
h:learn("GET","/users/foo/activate.xml")
assert.same( h:get_paths(), {
"/applications/*/activate.xml",
"/users/*/activate.xml"
})
h:learn("GET","/applications/foo4/activate.xml")
h:learn("GET","/applications/foo5/activate.xml")
h:learn("GET","/services/bar5/activate.xml")
h:learn("GET","/fulanitos/bar5/activate.xml")
h:learn("GET","/fulanitos/bar6/activate.xml")
h:learn("GET","/fulanitos/bar7/activate.xml")
h:learn("GET","/fulanitos/bar8/activate.xml")
h:learn("GET","/services/foo6/activate.xml")
h:learn("GET","/services/foo7/activate.xml")
h:learn("GET","/services/foo8/activate.xml")
h:learn("GET","/applications/foo4/activate.xml")
h:learn("GET","/applications/foo5/activate.xml")
h:learn("GET","/services/bar5/activate.xml")
h:learn("GET","/fulanitos/bar5/activate.xml")
h:learn("GET","/fulanitos/bar6/activate.xml")
h:learn("GET","/fulanitos/bar7/activate.xml")
h:learn("GET","/fulanitos/bar8/activate.xml")
h:learn("GET","/services/bar6/activate.xml")
h:learn("GET","/services/bar7/activate.xml")
h:learn("GET","/services/bar8/activate.xml")
assert.same( h:get_paths(), {
"/applications/*/activate.xml",
"/fulanitos/*/activate.xml",
"/services/*/activate.xml",
"/users/*/activate.xml"
})
assert.same( {"/services/*/activate.xml"}, h:match("/services/foo8/activate.xml"))
assert.same( {"/services/*/activate.xml"}, h:match("/services/foo18/activate.xml"))
assert.same( {}, h:match("/services/foo8/activate.json"))
assert.same( {}, h:match("/ser/foo8/activate.xml"))
end)
it('can handle edge cases', function()
local h = Host:new('google.com', nil, nil, nil, 'guid')
h:learn("GET","/services/foo6/activate.xml")
h:learn("GET","/services/foo7/activate.xml")
h:learn("GET","/services/foo8/activate.xml")
assert.same( {"/services/*/activate.xml"}, h:get_paths())
h:learn("GET","/services/foo6/deactivate.xml")
h:learn("GET","/services/foo7/deactivate.xml")
h:learn("GET","/services/foo8/deactivate.xml")
assert.same( h:get_paths(), {
"/services/*/activate.xml",
"/services/*/deactivate.xml"
})
h:learn("GET","/services/foo/60.xml")
h:learn("GET","/services/foo/61.xml")
h:learn("GET","/services/foo/62.xml")
assert.same( h:get_paths(), {
"/services/*/activate.xml",
"/services/*/deactivate.xml",
"/services/foo/*.xml"
})
end)
it('understands threshold', function()
local h = Host:new('google.com', nil, nil, nil, 'guid') -- default threshold = 1
h:learn("GET","/services/foo6/activate.xml")
h:learn("GET","/services/foo6/deactivate.xml")
h:learn("GET","/services/foo7/activate.xml")
h:learn("GET","/services/foo7/deactivate.xml")
h:learn("GET","/services/foo8/activate.xml")
h:learn("GET","/services/foo8/deactivate.xml")
assert.same( h:get_paths(), {
"/services/foo6/*.xml",
"/services/foo7/*.xml",
"/services/foo8/*.xml"
})
-- never merge
h = Host:new('google.com', nil, 0.0, nil, 'guid')
h:learn("GET","/services/foo6/activate.xml")
h:learn("GET","/services/foo6/deactivate.xml")
h:learn("GET","/services/foo7/activate.xml")
h:learn("GET","/services/foo7/deactivate.xml")
h:learn("GET","/services/foo8/activate.xml")
h:learn("GET","/services/foo8/deactivate.xml")
assert.same( h:get_paths(), {
"/services/foo6/activate.xml",
"/services/foo6/deactivate.xml",
"/services/foo7/activate.xml",
"/services/foo7/deactivate.xml",
"/services/foo8/activate.xml",
"/services/foo8/deactivate.xml"
})
h = Host:new('google.com', nil, 0.2, nil, 'guid')
-- fake the score so that the words that are not var are seen more often
-- the threshold 0.2 means that only merge if word is 5 (=1/0.2) times less frequent
-- than the most common word
h.score = {
services = 20, activate = 10, deactivate = 10,
foo6 = 1, foo7 = 1, foo8 = 1
}
h:learn("GET","/services/foo6/activate.xml")
h:learn("GET","/services/foo6/deactivate.xml")
h:learn("GET","/services/foo7/activate.xml")
h:learn("GET","/services/foo7/deactivate.xml")
h:learn("GET","/services/foo8/activate.xml")
h:learn("GET","/services/foo8/deactivate.xml")
assert.same( h:get_paths(), {
"/services/*/activate.xml",
"/services/*/deactivate.xml"
})
end)
end)
it('understands unmergeable tokens', function()
-- without unmergeable tokens
local h = Host:new('google.com', nil, nil, nil, 'guid')
h:learn("GET","/services/foo6/activate.xml")
h:learn("GET","/services/foo6/deactivate.xml")
assert.same( h:get_paths(), { "/services/foo6/*.xml" })
h:learn("GET","/services/foo7/activate.xml")
h:learn("GET","/services/foo7/deactivate.xml")
h:learn("GET","/services/foo8/activate.xml")
h:learn("GET","/services/foo8/deactivate.xml")
assert.same( h:get_paths(), {
"/services/foo6/*.xml",
"/services/foo7/*.xml",
"/services/foo8/*.xml"
})
-- with unmergeable tokens
h = Host:new('google.com', nil, 1.0, {"activate", "deactivate"}, 'guid')
h:learn("GET","/services/foo6/activate.xml")
h:learn("GET","/services/foo6/deactivate.xml")
assert.same( h:get_paths(), {
"/services/foo6/activate.xml",
"/services/foo6/deactivate.xml"
})
h:learn("GET","/services/foo7/activate.xml")
h:learn("GET","/services/foo7/deactivate.xml")
h:learn("GET","/services/foo8/activate.xml")
h:learn("GET","/services/foo8/deactivate.xml")
assert.same( h:get_paths(), {
"/services/*/activate.xml",
"/services/*/deactivate.xml"
})
end)
it('understands basepath', function()
local h = Host:new('google.com', nil, nil, nil, 'guid')
assert.equal(h.base_path, 'google.com')
local h = Host:new('google.com', 'http://google.com', nil, nil, 'guid')
assert.equal(h.base_path, 'http://google.com')
end)
it('unifies paths', function()
local h = Host:new('google.com', nil, nil, nil, 'guid')
h:learn("GET","/services/foo6/activate.xml")
h:learn("GET","/services/foo6/deactivate.xml")
assert.same( {"/services/foo6/*.xml"}, h:get_paths())
h:learn("GET","/services/foo6/activate.xml")
h:learn("GET","/services/foo6/deactivate.xml")
h:learn("GET","/services/foo7/activate.xml")
h:learn("GET","/services/foo7/deactivate.xml")
h:learn("GET","/services/foo8/activate.xml")
h:learn("GET","/services/foo8/deactivate.xml")
h:learn("GET","/services/foo9/activate.xml")
h:learn("GET","/services/foo9/deactivate.xml")
assert.same( {
"/services/foo6/*.xml",
"/services/foo7/*.xml",
"/services/foo8/*.xml",
"/services/foo9/*.xml"
}, h:get_paths())
h:learn("GET","/services/foo1/activate.xml")
h:learn("GET","/services/foo2/activate.xml")
assert.same( {
"/services/*/activate.xml",
"/services/foo6/*.xml",
"/services/foo7/*.xml",
"/services/foo8/*.xml",
"/services/foo9/*.xml"
}, h:get_paths())
for i=1,5 do
h:learn("GET","/services/" .. tostring(i) .. "/deactivate.xml")
h:learn("GET","/services/" .. tostring(i) .. "/activate.xml")
end
assert.same( {
"/services/*/activate.xml",
"/services/*/deactivate.xml",
"/services/foo6/*.xml",
"/services/foo7/*.xml",
"/services/foo8/*.xml",
"/services/foo9/*.xml"
}, h:get_paths())
h:learn("GET","/services/foo6/activate.xml")
h:learn("GET","/services/foo7/activate.xml")
h:learn("GET","/services/foo8/deactivate.xml")
h:learn("GET","/services/foo9/deactivate.xml")
assert.same( {
"/services/*/activate.xml",
"/services/*/deactivate.xml",
}, h:get_paths())
end)
it('compresses paths (again)', function()
local h = Host:new('google.com', nil, nil, nil, 'guid')
h:learn("GET","/admin/api/features.xml")
h:learn("GET","/admin/api/applications.xml")
h:learn("GET","/admin/api/users.xml")
assert.same( { "/admin/api/*.xml" }, h:get_paths())
h:learn("GET","/admin/xxx/features.xml")
h:learn("GET","/admin/xxx/applications.xml")
h:learn("GET","/admin/xxx/users.xml")
assert.same( {
"/admin/api/*.xml",
"/admin/xxx/*.xml"
}, h:get_paths())
end)
it('compresses in even more cases', function()
local h = Host:new('google.com', nil, nil, nil, 'guid')
h:learn("GET","/admin/api/features.xml")
h:learn("GET","/admin/api/applications.xml")
h:learn("GET","/admin/api/users.xml")
assert.same( { "/admin/api/*.xml" }, h:get_paths())
h:learn("GET","/admin/xxx/features.xml")
h:learn("GET","/admin/xxx/applications.xml")
h:learn("GET","/admin/xxx/users.xml")
assert.same( {
"/admin/api/*.xml",
"/admin/xxx/*.xml"
}, h:get_paths())
h = Host:new('google.com', nil, nil, nil, 'guid')
h:learn("GET","/admin/api/features.xml")
h:learn("GET","/admin/xxx/features.xml")
assert.same( { "/admin/*/features.xml" }, h:get_paths())
h:learn("GET","/admin/api/applications.xml")
h:learn("GET","/admin/xxx/applications.xml")
h:learn("GET","/admin/api/users.xml")
h:learn("GET","/admin/xxx/users.xml")
assert.same( {
"/admin/*/applications.xml",
"/admin/*/features.xml",
"/admin/*/users.xml"
}, h:get_paths())
end)
describe(':forget', function()
it('forgets the given path rules', function()
local h = create_host()
assert.truthy(h:forget("/*/foo5/activate.xml"))
assert.same(h:get_paths(), {
"/*/foo/activate.xml",
"/applications/*/activate.xml",
"/fulanitos/*/activate.xml",
"/services/*/activate.xml",
"/users/*/activate.xml"
})
assert.truthy(h:forget("/services/*/activate.xml"))
assert.same(h:get_paths(), {
"/*/foo/activate.xml",
"/applications/*/activate.xml",
"/fulanitos/*/activate.xml",
"/users/*/activate.xml"
})
-- forget only works for exact paths, not for matches
assert.equals(false, h:forget("/*/*/activate.xml"))
end)
it('handles a regression test that happened in the past', function()
local h = Host:new('google.com', nil, nil, nil, 'guid')
h.root = {
services = {
["*"]= {
activate = { [".xml"] = {[EOL]={}}},
deactivate = { [".xml"] = {[EOL]={}}},
suspend = { [".xml"] = {[EOL]={}}},
},
foo6 = { ["*"] = {[".xml"] = {[EOL]={}}}},
foo7 = { ["*"] = {[".xml"] = {[EOL]={}}}},
foo8 = { ["*"] = {[".xml"] = {[EOL]={}}}},
foo9 = { ["*"] = {[".xml"] = {[EOL]={}}}}
}
}
assert.same(h:get_paths(), {
"/services/*/activate.xml",
"/services/*/deactivate.xml",
"/services/*/suspend.xml",
"/services/foo6/*.xml",
"/services/foo7/*.xml",
"/services/foo8/*.xml",
"/services/foo9/*.xml"
})
h:forget("/services/*/activate.xml")
assert.same(h:get_paths(), {
"/services/*/deactivate.xml",
"/services/*/suspend.xml",
"/services/foo6/*.xml",
"/services/foo7/*.xml",
"/services/foo8/*.xml",
"/services/foo9/*.xml"
})
end)
describe('to_swagger', function()
it('returns a table with the swagger spec corresponding to the host', function()
local h = Host:new('localhost', 'http://google.com', nil, nil, 'guid')
for i=1,10 do
h:learn('GET', '/users/' .. tostring(i) .. '/app/' .. tostring(i) .. '.xml', nil, nil, nil, tostring(i))
end
local s = h:to_swagger()
-- I'm dividing this in two because busted (stupidly) hides part of the output when there are
-- mismatches on the asserts
local expected_operation = {
method = 'GET',
httpMethod = 'GET',
nickname = 'get_app_of_users',
summary = 'Get app of users',
notes = 'Automatically generated Operation spec',
guid = 'c75b5c3d46a01e4a3677da7968147dd6',
parameters = {
{ paramType = 'path',
name = 'app_id',
description = "Possible values are: '8', '9', '10'",
['type'] = 'string',
required = true
},
{ paramType = 'path',
name = 'user_id',
description = "Possible values are: '8', '9', '10'",
['type'] = 'string',
['type'] = 'string',
required = true
}
}
}
assert.same(s.apis[1].operations[1], expected_operation)
s.apis[1].operations = nil
assert.same(s, {
hostname = "localhost",
basePath = "http://google.com",
apiVersion = "1.0",
swaggerVersion = "1.2",
models = {},
guid = "guid",
apis = {
{ path = "/users/{user_id}/app/{app_id}.xml",
description = "Automatically generated API spec",
guid = "81869c4caaedb459732c089621e27f63"
}
}
})
end)
end)
end)
describe('new_from_table', function()
it('rebuilds a brain using a table', function()
local tbl = {
hostname = "localhost",
basePath = "foo.com",
guid = "lalala",
root = {
users = {
["*"] = {
app = {
["*"] = {
[".xml"] = {
___EOL___ = {}
}
}
}
}
}
},
apis = {
{ path = "/users/*/app/*.xml",
guid = "lilili",
operations = {
{ method = 'GET',
guid = 'lololo',
parameters = {
{ paramType = 'path',
name = 'app_id',
values = {1,2,3}
},
{ paramType = 'path',
name = 'user_id',
values = {1,2,3}
}
}
}
}
}
}
}
local h = Host:new_from_table(tbl)
assert.equal(h.hostname, 'localhost')
assert.equal(h.base_path, 'foo.com')
assert.equal(h.guid, 'lalala')
assert.same(h:get_paths(), {"/users/*/app/*.xml"})
assert.same(h.root, tbl.root)
end)
end)
end)
| mit |
starlightknight/darkstar | scripts/globals/spells/absorb-chr.lua | 12 | 1564 | --------------------------------------
-- Spell: Absorb-CHR
-- Steals an enemy's Charism.
--------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/magic")
require("scripts/globals/msg")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
if (target:hasStatusEffect(dsp.effect.CHR_DOWN) or caster:hasStatusEffect(dsp.effect.CHR_BOOST)) then
spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) -- no effect
else
local dINT = caster:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT)
local params = {}
params.diff = nil
params.attribute = dsp.mod.INT
params.skillType = 37
params.bonus = 0
params.effect = nil
local resist = applyResistance(caster, target, spell, params)
if (resist <= 0.125) then
spell:setMsg(dsp.msg.basic.MAGIC_RESIST)
else
spell:setMsg(dsp.msg.basic.MAGIC_ABSORB_CHR)
caster:addStatusEffect(dsp.effect.CHR_BOOST,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(dsp.mod.AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK) -- caster gains CHR
target:addStatusEffect(dsp.effect.CHR_DOWN,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(dsp.mod.AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK) -- target loses CHR
end
end
return dsp.effect.CHR_DOWN
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Oldton_Movalpolos/Zone.lua | 13 | 2534 | -----------------------------------
--
-- Zone: Oldton_Movalpolos (11)
--
-----------------------------------
package.loaded["scripts/zones/Oldton_Movalpolos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/conquest");
require("scripts/zones/Oldton_Movalpolos/TextIDs");
require("scripts/globals/missions");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
UpdateTreasureSpawnPoint(16822531);
SetRegionalConquestOverseers(zone:getRegionID())
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local currentday = tonumber(os.date("%j"));
local LouverancePath=player:getVar("COP_Louverance_s_Path");
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(70.956,5.99,139.843,134);
end
if (player:getCurrentMission(COP) == THREE_PATHS and (LouverancePath == 3 or LouverancePath == 4)) then
cs=0x0001;
elseif (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")==3 and player:getVar("Promathia_kill_day")~=currentday and player:getVar("COP_jabbos_story")== 0 ) then
cs=0x0039;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid==0x0001) then
player:setVar("COP_Louverance_s_Path",5);
elseif (csid == 0x0039) then
player:setVar("COP_jabbos_story",1);
end
end;
| gpl-3.0 |
pichina/skynet | lualib/snax/hotfix.lua | 39 | 2268 | local si = require "snax.interface"
local io = io
local hotfix = {}
local function envid(f)
local i = 1
while true do
local name, value = debug.getupvalue(f, i)
if name == nil then
return
end
if name == "_ENV" then
return debug.upvalueid(f, i)
end
i = i + 1
end
end
local function collect_uv(f , uv, env)
local i = 1
while true do
local name, value = debug.getupvalue(f, i)
if name == nil then
break
end
local id = debug.upvalueid(f, i)
if uv[name] then
assert(uv[name].id == id, string.format("ambiguity local value %s", name))
else
uv[name] = { func = f, index = i, id = id }
if type(value) == "function" then
if envid(value) == env then
collect_uv(value, uv, env)
end
end
end
i = i + 1
end
end
local function collect_all_uv(funcs)
local global = {}
for _, v in pairs(funcs) do
if v[4] then
collect_uv(v[4], global, envid(v[4]))
end
end
if not global["_ENV"] then
global["_ENV"] = {func = collect_uv, index = 1}
end
return global
end
local function loader(source)
return function (filename, ...)
return load(source, "=patch", ...)
end
end
local function find_func(funcs, group , name)
for _, desc in pairs(funcs) do
local _, g, n = table.unpack(desc)
if group == g and name == n then
return desc
end
end
end
local dummy_env = {}
local function patch_func(funcs, global, group, name, f)
local desc = assert(find_func(funcs, group, name) , string.format("Patch mismatch %s.%s", group, name))
local i = 1
while true do
local name, value = debug.getupvalue(f, i)
if name == nil then
break
elseif value == nil or value == dummy_env then
local old_uv = global[name]
if old_uv then
debug.upvaluejoin(f, i, old_uv.func, old_uv.index)
end
end
i = i + 1
end
desc[4] = f
end
local function inject(funcs, source, ...)
local patch = si("patch", dummy_env, loader(source))
local global = collect_all_uv(funcs)
for _, v in pairs(patch) do
local _, group, name, f = table.unpack(v)
if f then
patch_func(funcs, global, group, name, f)
end
end
local hf = find_func(patch, "system", "hotfix")
if hf and hf[4] then
return hf[4](...)
end
end
return function (funcs, source, ...)
return pcall(inject, funcs, source, ...)
end
| mit |
starlightknight/darkstar | scripts/globals/mobskills/chemical_bomb.lua | 12 | 1125 | ---------------------------------------------
-- Chemical_Bomb
--
-- Description: slow + elegy
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
---------------------------------------------
function onMobSkillCheck(target, mob, skill)
-- skillList 54 = Omega
-- skillList 727 = Proto-Omega
-- skillList 728 = Ultima
-- skillList 729 = Proto-Ultima
local skillList = mob:getMobMod(dsp.mobMod.SKILL_LIST)
local mobhp = mob:getHPP()
local phase = mob:getLocalVar("battlePhase")
if (skillList == 729 and phase < 3) or (skillList == 728 and mobhp >= 70 or mobhp < 40) then
return 0
end
return 1
end
function onMobWeaponSkill(target, mob, skill)
local typeEffectOne = dsp.effect.ELEGY
local typeEffectTwo = dsp.effect.SLOW
skill:setMsg(MobStatusEffectMove(mob, target, typeEffectOne, 5000, 0, 120))
skill:setMsg(MobStatusEffectMove(mob, target, typeEffectTwo, 5000, 0, 120))
-- This likely doesn't behave like retail.
return typeEffectTwo
end
| gpl-3.0 |
yaukeywang/2DPlatformer-SLua | Assets/StreamingAssets/Lua/Logic/LgBackgroundParallax.lua | 3 | 3371 | --
-- Back ground parallax class.
--
-- @filename LgBackgroundParallax.lua
-- @copyright Copyright (c) 2015 Yaukey/yaukeywang/WangYaoqi (yaukeywang@gmail.com) all rights reserved.
-- @license The MIT License (MIT)
-- @author Yaukey
-- @date 2015-09-02
--
local DLog = YwDebug.Log
local DLogWarn = YwDebug.LogWarning
local DLogError = YwDebug.LogError
local Vector3 = Vector3
local Time = Time
-- Register new class LgBackgroundParallax.
local strClassName = "LgBackgroundParallax"
local LgBackgroundParallax = YwDeclare(strClassName, YwClass(strClassName, YwMonoBehaviour))
-- Member variables.
-- The background transforms.
LgBackgroundParallax.m_aBackgrounds = false
-- The parallax scale.
LgBackgroundParallax.m_fParallaxScale = 0.5
-- The parallax reduction factor.
LgBackgroundParallax.m_fParallaxReductionFactor = 0.4
-- The smoothing.
LgBackgroundParallax.m_fSmoothing = 8.0
-- The current camera transform.
LgBackgroundParallax.m_cCam = false
-- The previous camera pos.
LgBackgroundParallax.m_vPreviousCamPos = false
-- Constructor.
function LgBackgroundParallax:ctor()
--print("LgBackgroundParallax:ctor")
self.m_aBackgrounds = {}
self.m_vPreviousCamPos = Vector3.zero
end
-- Destructor.
function LgBackgroundParallax:dtor()
--print("LgBackgroundParallax:dtor")
self.m_aBackgrounds = nil
end
-- Awake method.
function LgBackgroundParallax:Awake()
--print("LgBackgroundParallax:Awake")
-- Check variable.
if (not self.this) or (not self.transform) or (not self.gameObject) then
DLogError("Init error in LgBackgroundParallax!")
return
end
-- Get camera.
self.m_cCam = Camera.main.transform
-- Init background transform
for i = 1, #self.m_aParameters do
self.m_aBackgrounds[i] = self.m_aParameters[i].transform
end
end
-- Start method.
function LgBackgroundParallax:Start()
--print("LgBackgroundParallax:Start")
-- The 'previous frame' had the current frame's camera position.
self.m_vPreviousCamPos = self.m_cCam.position
end
-- Update method.
function LgBackgroundParallax:Update()
--print("LgBackgroundParallax:Update")
-- The parallax is the opposite of the camera movement since the previous frame multiplied by the scale.
local fParallax = (self.m_vPreviousCamPos.x - self.m_cCam.position.x) * self.m_fParallaxScale
-- For each successive background...
local aBackgrounds = self.m_aBackgrounds
for i = 1, #aBackgrounds do
-- ... set a target x position which is their current position plus the parallax multiplied by the reduction.
local fBackgroundTargetPosX = aBackgrounds[i].position.x + fParallax * (i * self.m_fParallaxReductionFactor + 1.0)
-- Create a target position which is the background's current position but with it's target x position.
local vBackgroundTargetPos = Vector3(fBackgroundTargetPosX, aBackgrounds[i].position.y, aBackgrounds[i].position.z)
-- Lerp the background's position between itself and it's target position.
aBackgrounds[i].position = Vector3.Lerp(aBackgrounds[i].position, vBackgroundTargetPos, self.m_fSmoothing * Time.deltaTime)
end
-- Set the previousCamPos to the camera's position at the end of this frame.
self.m_vPreviousCamPos = self.m_cCam.position
end
-- Return this class.
return LgBackgroundParallax
| mit |
gedads/Neodynamis | scripts/zones/Mount_Zhayolm/npcs/qm5.lua | 3 | 1335 | -----------------------------------
-- Area: Mount Zhayolm
-- NPC: ??? (Spawn Sarameya(ZNM T4))
-- !pos 322 -14 -581 61
-----------------------------------
package.loaded["scripts/zones/Mount_Zhayolm/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mount_Zhayolm/TextIDs");
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local mobID = 17027485;
if (trade:hasItemQty(2583,1) and trade:getItemCount() == 1) then -- Trade Buffalo Corpse
if (GetMobAction(mobID) == ACTION_NONE) then
player:tradeComplete();
SpawnMob(mobID):updateClaim(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_HAPPENS);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
starlightknight/darkstar | scripts/globals/items/dish_of_spaghetti_pescatora.lua | 11 | 1378 | -----------------------------------------
-- ID: 5191
-- Item: dish_of_spaghetti_pescatora
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Health % 15
-- Health Cap 150
-- Vitality 3
-- Mind -1
-- Defense % 22
-- Defense Cap 65
-- Store TP 6
-----------------------------------------
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,5191)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.FOOD_HPP, 15)
target:addMod(dsp.mod.FOOD_HP_CAP, 150)
target:addMod(dsp.mod.VIT, 3)
target:addMod(dsp.mod.MND, -1)
target:addMod(dsp.mod.FOOD_DEFP, 22)
target:addMod(dsp.mod.FOOD_DEF_CAP, 65)
target:addMod(dsp.mod.STORETP, 6)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.FOOD_HPP, 15)
target:delMod(dsp.mod.FOOD_HP_CAP, 150)
target:delMod(dsp.mod.VIT, 3)
target:delMod(dsp.mod.MND, -1)
target:delMod(dsp.mod.FOOD_DEFP, 22)
target:delMod(dsp.mod.FOOD_DEF_CAP, 65)
target:delMod(dsp.mod.STORETP, 6)
end
| gpl-3.0 |
sebastianlis/OOP-Samples-for-Corona-SDK | classes/samples/GettingStarted/TimeAnimation.lua | 1 | 4451 | require "classes.constants.screen"
TimeAnimation={}
function TimeAnimation:new()
local this = display.newGroup()
local public = this
local private = {}
local background = display.newImageRect("img/backgroundTimeAnimation.png", 360, 570)
local labelInfo = display.newText("Drag or fling ball to bounce", 0, 0, native.systemFontBold, 20)
local ball = display.newCircle(0, 0, 40)
local lastTime = 0
local prevTime = 0
local friction = 0.8
local g = .09
function private.TimeAnimation()
background.x = screen.centerX
background.y = screen.centerY
labelInfo.x = screen.centerX
labelInfo.y = 60
labelInfo.anchorX = 0.5
labelInfo.anchorY = 0.5
labelInfo:setFillColor(255/255, 255/255, 255/255)
ball:setFillColor(255/255, 255/255, 255/255, 166/255)
ball.x = screen.centerX
ball.y = ball.height
ball.vx = 0
ball.vy = 0
ball.xPrev = 0
ball.yPrev = 0
this:insert(background)
this:insert(labelInfo)
this:insert(ball)
ball:addEventListener("touch", private.onDragBall)
Runtime:addEventListener("enterFrame", private.setTimeFromRunApp)
Runtime:addEventListener("enterFrame", private.updateBallPosition)
end
function private.setTimeFromRunApp(event)
lastTime = event.time
Runtime:removeEventListener("enterFrame", private.setTimeFromRunApp)
end
function private.updateBallPosition(event)
local timePassed = event.time - lastTime
lastTime = lastTime + timePassed
ball.vy = ball.vy + g
ball.x = ball.x + ball.vx*timePassed
ball.y = ball.y + ball.vy*timePassed
if ball.x+ball.width/2 >= screen.right then
ball.x = screen.right - ball.width/2
ball.vx = ball.vx*friction
ball.vx = -ball.vx
elseif ball.x - ball.width/2 <= screen.left then
ball.x = screen.left + ball.width/2
ball.vx = ball.vx*friction
ball.vx = -ball.vx
end
if ball.y >= screen.bottom - ball.height/2 then
ball.y = screen.bottom - ball.height/2
ball.vy = ball.vy*friction
ball.vx = ball.vx*friction
ball.vy = -ball.vy
elseif ball.y <= screen.top + ball.height/2 then
ball.y = screen.top + ball.height/2
ball.vy = ball.vy*friction
ball.vy = -ball.vy
end
end
function private.onDragBall(event)
if event.phase == "began" then
display.getCurrentStage():setFocus(event.target)
event.target.isFocus = true
event.target.x0 = event.x - event.target.x
event.target.y0 = event.y - event.target.y
Runtime:removeEventListener("enterFrame", private.updateBallPosition)
Runtime:addEventListener("enterFrame", private.updateBallParameters)
elseif event.target.isFocus then
if event.phase == "moved" then
event.target.x = event.x - event.target.x0
event.target.y = event.y - event.target.y0
elseif event.phase == "ended" or event.phase == "cancelled" then
lastTime = event.time
Runtime:removeEventListener("enterFrame", private.updateBallParameters)
Runtime:addEventListener("enterFrame", private.updateBallPosition)
display.getCurrentStage():setFocus(nil)
event.target.isFocus = false
end
end
return true
end
function private.updateBallParameters(event)
local timePassed = event.time - prevTime
prevTime = prevTime + timePassed
ball.vx = (ball.x - ball.xPrev)/timePassed
ball.vy = (ball.y - ball.yPrev)/timePassed
ball.xPrev = ball.x
ball.yPrev = ball.y
end
function public:destroy()
ball:removeEventListener("touch", private.onDragBall)
Runtime:removeEventListener("enterFrame", private.updateBallPosition)
Runtime:removeEventListener("enterFrame", private.updateBallParameters)
background:removeSelf()
background = nil
labelInfo:removeSelf()
labelInfo = nil
ball:removeSelf()
ball = nil
this:removeSelf()
this = nil
end
private.TimeAnimation()
return this
end
return TimeAnimation
| mit |
gedads/Neodynamis | scripts/commands/completequest.lua | 7 | 1554 | ---------------------------------------------------------------------------------------------------
-- func: completequest <logID> <questID> <player>
-- desc: Completes the given quest for the GM or target player.
---------------------------------------------------------------------------------------------------
require("scripts/globals/quests")
cmdprops =
{
permission = 1,
parameters = "sss"
};
function error(player, msg)
player:PrintToPlayer(msg);
player:PrintToPlayer("!completequest <logID> <questID> {player}");
end;
function onTrigger(player, logId, questId, target)
-- validate logId
local questLog = GetQuestLogInfo(logId);
if (questLog == nil) then
error(player, "Invalid logID.");
return;
end
local logName = questLog.full_name;
logId = questLog.quest_log;
-- validate questId
if (questId ~= nil) then
questId = tonumber(questId) or _G[string.upper(questId)];
end
if (questId == nil or questId < 0) then
error(player, "Invalid questID.");
return;
end
-- validate target
local targ;
if (target == nil) then
targ = player;
else
targ = GetPlayerByName(target);
if (targ == nil) then
error(player, string.format("Player named '%s' not found!", target));
return;
end
end
-- complete quest
targ:completeQuest( logId, questId );
player:PrintToPlayer( string.format( "Completed %s Quest with ID %u for %s", logName, questId, targ:getName() ) );
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Garlaige_Citadel/mobs/Fallen_Major.lua | 3 | 1055 | -- Area: Garlaige Citadel
-- MOB: Fallen Major
-- Note: Place holder Hovering Hotpot
-----------------------------------
require("scripts/zones/Garlaige_Citadel/MobIDs");
require("scripts/globals/groundsofvalor");
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
checkRegime(player,mob,703,2);
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
local mobID = mob:getID();
if (Hovering_Hotpot_PH[mobID] ~= nil) then
local ToD = GetServerVariable("[POP]Hovering_Hotpot");
if (ToD <= os.time(t) and GetMobAction(Hovering_Hotpot) == 0) then
if (math.random(1,4) == 4) then
UpdateNMSpawnPoint(Hovering_Hotpot);
GetMobByID(Hovering_Hotpot):setRespawnTime(GetMobRespawnTime(mobID));
SetServerVariable("[PH]Hovering_Hotpot", mobID);
DisallowRespawn(mobID, true);
end
end
end
end;
| gpl-3.0 |
ykwd/thrift | lib/lua/TBinaryProtocol.lua | 90 | 6141 | --
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
require 'TProtocol'
require 'libluabpack'
require 'libluabitwise'
TBinaryProtocol = __TObject.new(TProtocolBase, {
__type = 'TBinaryProtocol',
VERSION_MASK = -65536, -- 0xffff0000
VERSION_1 = -2147418112, -- 0x80010000
TYPE_MASK = 0x000000ff,
strictRead = false,
strictWrite = true
})
function TBinaryProtocol:writeMessageBegin(name, ttype, seqid)
if self.strictWrite then
self:writeI32(libluabitwise.bor(TBinaryProtocol.VERSION_1, ttype))
self:writeString(name)
self:writeI32(seqid)
else
self:writeString(name)
self:writeByte(ttype)
self:writeI32(seqid)
end
end
function TBinaryProtocol:writeMessageEnd()
end
function TBinaryProtocol:writeStructBegin(name)
end
function TBinaryProtocol:writeStructEnd()
end
function TBinaryProtocol:writeFieldBegin(name, ttype, id)
self:writeByte(ttype)
self:writeI16(id)
end
function TBinaryProtocol:writeFieldEnd()
end
function TBinaryProtocol:writeFieldStop()
self:writeByte(TType.STOP);
end
function TBinaryProtocol:writeMapBegin(ktype, vtype, size)
self:writeByte(ktype)
self:writeByte(vtype)
self:writeI32(size)
end
function TBinaryProtocol:writeMapEnd()
end
function TBinaryProtocol:writeListBegin(etype, size)
self:writeByte(etype)
self:writeI32(size)
end
function TBinaryProtocol:writeListEnd()
end
function TBinaryProtocol:writeSetBegin(etype, size)
self:writeByte(etype)
self:writeI32(size)
end
function TBinaryProtocol:writeSetEnd()
end
function TBinaryProtocol:writeBool(bool)
if bool then
self:writeByte(1)
else
self:writeByte(0)
end
end
function TBinaryProtocol:writeByte(byte)
local buff = libluabpack.bpack('c', byte)
self.trans:write(buff)
end
function TBinaryProtocol:writeI16(i16)
local buff = libluabpack.bpack('s', i16)
self.trans:write(buff)
end
function TBinaryProtocol:writeI32(i32)
local buff = libluabpack.bpack('i', i32)
self.trans:write(buff)
end
function TBinaryProtocol:writeI64(i64)
local buff = libluabpack.bpack('l', i64)
self.trans:write(buff)
end
function TBinaryProtocol:writeDouble(dub)
local buff = libluabpack.bpack('d', dub)
self.trans:write(buff)
end
function TBinaryProtocol:writeString(str)
-- Should be utf-8
self:writeI32(string.len(str))
self.trans:write(str)
end
function TBinaryProtocol:readMessageBegin()
local sz, ttype, name, seqid = self:readI32()
if sz < 0 then
local version = libluabitwise.band(sz, TBinaryProtocol.VERSION_MASK)
if version ~= TBinaryProtocol.VERSION_1 then
terror(TProtocolException:new{
message = 'Bad version in readMessageBegin: ' .. sz
})
end
ttype = libluabitwise.band(sz, TBinaryProtocol.TYPE_MASK)
name = self:readString()
seqid = self:readI32()
else
if self.strictRead then
terror(TProtocolException:new{message = 'No protocol version header'})
end
name = self.trans:readAll(sz)
ttype = self:readByte()
seqid = self:readI32()
end
return name, ttype, seqid
end
function TBinaryProtocol:readMessageEnd()
end
function TBinaryProtocol:readStructBegin()
return nil
end
function TBinaryProtocol:readStructEnd()
end
function TBinaryProtocol:readFieldBegin()
local ttype = self:readByte()
if ttype == TType.STOP then
return nil, ttype, 0
end
local id = self:readI16()
return nil, ttype, id
end
function TBinaryProtocol:readFieldEnd()
end
function TBinaryProtocol:readMapBegin()
local ktype = self:readByte()
local vtype = self:readByte()
local size = self:readI32()
return ktype, vtype, size
end
function TBinaryProtocol:readMapEnd()
end
function TBinaryProtocol:readListBegin()
local etype = self:readByte()
local size = self:readI32()
return etype, size
end
function TBinaryProtocol:readListEnd()
end
function TBinaryProtocol:readSetBegin()
local etype = self:readByte()
local size = self:readI32()
return etype, size
end
function TBinaryProtocol:readSetEnd()
end
function TBinaryProtocol:readBool()
local byte = self:readByte()
if byte == 0 then
return false
end
return true
end
function TBinaryProtocol:readByte()
local buff = self.trans:readAll(1)
local val = libluabpack.bunpack('c', buff)
return val
end
function TBinaryProtocol:readI16()
local buff = self.trans:readAll(2)
local val = libluabpack.bunpack('s', buff)
return val
end
function TBinaryProtocol:readI32()
local buff = self.trans:readAll(4)
local val = libluabpack.bunpack('i', buff)
return val
end
function TBinaryProtocol:readI64()
local buff = self.trans:readAll(8)
local val = libluabpack.bunpack('l', buff)
return val
end
function TBinaryProtocol:readDouble()
local buff = self.trans:readAll(8)
local val = libluabpack.bunpack('d', buff)
return val
end
function TBinaryProtocol:readString()
local len = self:readI32()
local str = self.trans:readAll(len)
return str
end
TBinaryProtocolFactory = TProtocolFactory:new{
__type = 'TBinaryProtocolFactory',
strictRead = false
}
function TBinaryProtocolFactory:getProtocol(trans)
-- TODO Enforce that this must be a transport class (ie not a bool)
if not trans then
terror(TProtocolException:new{
message = 'Must supply a transport to ' .. ttype(self)
})
end
return TBinaryProtocol:new{
trans = trans,
strictRead = self.strictRead,
strictWrite = true
}
end
| apache-2.0 |
yaukeywang/2DPlatformer-SLua | Assets/StreamingAssets/Lua/sproto/testrpc.lua | 5 | 2610 | local sproto = require "sproto"
local print_r = require "print_r"
local server_proto = sproto.parse [[
.package {
type 0 : integer
session 1 : integer
}
foobar 1 {
request {
what 0 : string
}
response {
ok 0 : boolean
}
}
foo 2 {
response {
ok 0 : boolean
}
}
bar 3 {}
blackhole 4 {
}
]]
local client_proto = sproto.parse [[
.package {
type 0 : integer
session 1 : integer
}
]]
assert(server_proto:exist_type "package")
assert(server_proto:exist_proto "foobar")
print("=== default table")
print_r(server_proto:default("package"))
print_r(server_proto:default("foobar", "REQUEST"))
assert(server_proto:default("foo", "REQUEST")==nil)
assert(server_proto:request_encode("foo")=="")
server_proto:response_encode("foo", { ok = true })
assert(server_proto:request_decode("blackhole")==nil)
assert(server_proto:response_decode("blackhole")==nil)
print("=== test 1")
-- The type package must has two field : type and session
local server = server_proto:host "package"
local client = client_proto:host "package"
local client_request = client:attach(server_proto)
print("client request foobar")
local req = client_request("foobar", { what = "foo" }, 1)
print("request foobar size =", #req)
local type, name, request, response = server:dispatch(req)
assert(type == "REQUEST" and name == "foobar")
print_r(request)
print("server response")
local resp = response { ok = true }
print("response package size =", #resp)
print("client dispatch")
local type, session, response = client:dispatch(resp)
assert(type == "RESPONSE" and session == 1)
print_r(response)
local req = client_request("foo", nil, 2)
print("request foo size =", #req)
local type, name, request, response = server:dispatch(req)
assert(type == "REQUEST" and name == "foo" and request == nil)
local resp = response { ok = false }
print("response package size =", #resp)
print("client dispatch")
local type, session, response = client:dispatch(resp)
assert(type == "RESPONSE" and session == 2)
print_r(response)
local req = client_request("bar") -- bar has no response
print("request bar size =", #req)
local type, name, request, response = server:dispatch(req)
assert(type == "REQUEST" and name == "bar" and request == nil and response == nil)
local req = client_request "blackhole"
print("request blackhole size = ", #req)
print("=== test 2")
local v, tag = server_proto:request_encode("foobar", { what = "hello"})
print("tag =", tag)
print_r(server_proto:request_decode("foobar", v))
local v, tag = server_proto:response_encode("foobar", { ok = true })
print("tag =", tag)
print_r(server_proto:response_decode("foobar", v))
| mit |
starlightknight/darkstar | scripts/globals/mobskills/crosswind.lua | 11 | 1102 | ---------------------------------------------
-- Crosswind
--
-- Description: Deals Wind damage to enemies within a fan-shaped area. Additional effect: Knockback
-- Type: Breath
-- Utsusemi/Blink absorb: Ignores shadows
-- Range: Unknown cone
-- Notes:
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if(mob:getFamily() == 91) then
local mobSkin = mob:getModelId()
if (mobSkin == 1746) then
return 0
else
return 1
end
end
return 0
end
function onMobWeaponSkill(target, mob, skill)
local dmgmod = 1
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,dsp.magic.ele.WIND,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.WIND,MOBPARAM_IGNORE_SHADOWS)
target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.WIND)
return dmg
end
| gpl-3.0 |
gedads/Neodynamis | scripts/globals/items/stick_of_cotton_candy.lua | 12 | 1231 | -----------------------------------------
-- ID: 5709
-- Item: Cotton Candy
-- Food Effect: 5 Min, All Races
-----------------------------------------
-- MP % 10 Cap 200
-- MP Healing 3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD)) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5709);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_MPP, 10);
target:addMod(MOD_FOOD_MP_CAP, 200);
target:addMod(MOD_MPHEAL, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_MPP, 10);
target:delMod(MOD_FOOD_MP_CAP, 200);
target:delMod(MOD_MPHEAL, 3);
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Upper_Jeuno/npcs/Brutus.lua | 3 | 8199 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Brutus
-- Starts Quest: Chocobo's Wounds, Save My Son, Path of the Beastmaster, Wings of gold, Scattered into Shadow, Chocobo on the Loose!
-- !pos -55 8 95 244
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Upper_Jeuno/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local chocoboOnTheLoose = player:getQuestStatus(JEUNO,CHOCOBO_ON_THE_LOOSE);
local chocoboOnTheLooseStatus = player:getVar("ChocoboOnTheLoose");
local ChocobosWounds = player:getQuestStatus(JEUNO,CHOCOBO_S_WOUNDS);
local saveMySon = player:getQuestStatus(JEUNO,SAVE_MY_SON);
local wingsOfGold = player:getQuestStatus(JEUNO,WINGS_OF_GOLD);
local scatIntoShadow = player:getQuestStatus(JEUNO,SCATTERED_INTO_SHADOW);
local mLvl = player:getMainLvl();
local mJob = player:getMainJob();
if (chocoboOnTheLoose == QUEST_AVAILABLE) then
player:startEvent(0x276D);
elseif (chocoboOnTheLoose == QUEST_ACCEPTED and chocoboOnTheLooseStatus == 0) then
player:startEvent(0x276E);
elseif (chocoboOnTheLoose == QUEST_ACCEPTED and chocoboOnTheLooseStatus == 2) then
player:startEvent(0x276F);
elseif (chocoboOnTheLoose == QUEST_ACCEPTED and chocoboOnTheLooseStatus == 3) then
player:startEvent(0x2773);
elseif (chocoboOnTheLoose == QUEST_ACCEPTED and (chocoboOnTheLooseStatus == 5 or chocoboOnTheLooseStatus == 6)) then
player:startEvent(0x2774);
elseif (chocoboOnTheLoose == QUEST_ACCEPTED and chocoboOnTheLooseStatus == 7 and player:needToZone() == false and (player:getVar("ChocoboOnTheLooseDay") < VanadielDayOfTheYear() or player:getVar("ChocoboOnTheLooseYear") < VanadielYear())) then
player:startEvent(0x277D);
elseif (player:getMainLvl() >= 20 and ChocobosWounds ~= QUEST_COMPLETED) then
local chocoFeed = player:getVar("ChocobosWounds_Event");
if (ChocobosWounds == QUEST_AVAILABLE) then
player:startEvent(0x0047);
elseif (chocoFeed == 1) then
player:startEvent(0x0041);
elseif (chocoFeed == 2) then
player:startEvent(0x0042);
else
player:startEvent(0x0066);
end
elseif (ChocobosWounds == QUEST_COMPLETED and saveMySon == QUEST_AVAILABLE) then
player:startEvent(0x0016);
elseif (saveMySon == QUEST_COMPLETED and player:getQuestStatus(JEUNO,PATH_OF_THE_BEASTMASTER) == QUEST_AVAILABLE) then
player:startEvent(0x0046);
elseif (mLvl >= AF1_QUEST_LEVEL and mJob == 9 and wingsOfGold == QUEST_AVAILABLE) then
if (player:getVar("wingsOfGold_shortCS") == 1) then
player:startEvent(0x0089); -- Start Quest "Wings of gold" (Short dialog)
else
player:setVar("wingsOfGold_shortCS",1);
player:startEvent(0x008b); -- Start Quest "Wings of gold" (Long dialog)
end
elseif (wingsOfGold == QUEST_ACCEPTED) then
if (player:hasKeyItem(GUIDING_BELL) == false) then
player:startEvent(0x0088);
else
player:startEvent(0x008a); -- Finish Quest "Wings of gold"
end
elseif (wingsOfGold == QUEST_COMPLETED and mLvl < AF2_QUEST_LEVEL and mJob == 9) then
player:startEvent(0x0086); -- Standard dialog after "Wings of gold"
elseif (scatIntoShadow == QUEST_AVAILABLE and mLvl >= AF2_QUEST_LEVEL and mJob == 9) then
if (player:getVar("scatIntoShadow_shortCS") == 1) then
player:startEvent(0x008f);
else
player:setVar("scatIntoShadow_shortCS",1);
player:startEvent(0x008d);
end
elseif (scatIntoShadow == QUEST_ACCEPTED) then
local scatIntoShadowCS = player:getVar("scatIntoShadowCS");
if (player:hasKeyItem(AQUAFLORA1) or player:hasKeyItem(AQUAFLORA2) or player:hasKeyItem(AQUAFLORA3)) then
player:startEvent(0x008e);
elseif (scatIntoShadowCS == 0) then
player:startEvent(0x0090);
elseif (scatIntoShadowCS == 1) then
player:startEvent(0x0095);
elseif (scatIntoShadowCS == 2) then
player:startEvent(0x0087);
end
elseif (scatIntoShadow == QUEST_COMPLETED) then
player:startEvent(0x0097);
elseif (player:getQuestStatus(JEUNO,PATH_OF_THE_BEASTMASTER) == QUEST_COMPLETED) then
player:startEvent(0x0014);
else
player:startEvent(0x0042, player:getMainLvl());
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 == 0x276D) then
player:addQuest(JEUNO,CHOCOBO_ON_THE_LOOSE);
elseif (csid == 0x276E) then
player:setVar("ChocoboOnTheLoose", 1);
elseif (csid == 0x276F) then
player:setVar("ChocoboOnTheLoose", 3);
elseif (csid == 0x2773) then
player:setVar("ChocoboOnTheLoose", 4);
elseif (csid == 0x2774) then
player:setVar("ChocoboOnTheLoose", 7);
player:setVar("ChocoboOnTheLooseDay", VanadielDayOfTheYear());
player:setVar("ChocoboOnTheLooseYear", VanadielYear());
player:needToZone(true);
elseif (csid == 0x277D) then
player:setVar("ChocoboOnTheLoose", 0);
player:setVar("ChocoboOnTheLooseDay", 0);
player:setVar("ChocoboOnTheLooseYear", 0);
player:addFame(JEUNO, 30);
player:addItem(2317);
player:messageSpecial(ITEM_OBTAINED,2317); -- Chocobo Egg (a bit warm)
player:completeQuest(JEUNO,CHOCOBO_ON_THE_LOOSE);
elseif (csid == 0x0047 and option == 1) then
player:addQuest(JEUNO,CHOCOBO_S_WOUNDS);
player:setVar("ChocobosWounds_Event",1);
elseif (csid == 0x0046) then
player:addQuest(JEUNO,PATH_OF_THE_BEASTMASTER);
player:addTitle(ANIMAL_TRAINER);
player:unlockJob(9); -- Beastmaster
player:messageSpecial(YOU_CAN_NOW_BECOME_A_BEASTMASTER);
player:addFame(JEUNO, 30);
player:completeQuest(JEUNO,PATH_OF_THE_BEASTMASTER);
elseif ((csid == 0x008b or csid == 0x0089) and option == 1) then
player:addQuest(JEUNO,WINGS_OF_GOLD);
player:setVar("wingsOfGold_shortCS",0);
elseif (csid == 0x008a) then
if (player:getFreeSlotsCount() < 1) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16680);
else
player:delKeyItem(GUIDING_BELL);
player:addItem(16680);
player:messageSpecial(ITEM_OBTAINED,16680); -- Barbaroi Axe
player:addFame(JEUNO,AF1_FAME);
player:completeQuest(JEUNO,WINGS_OF_GOLD);
end
elseif ((csid == 0x008f or csid == 0x008d) and option == 1) then
player:addQuest(JEUNO,SCATTERED_INTO_SHADOW);
player:setVar("scatIntoShadow_shortCS",0);
player:addKeyItem(AQUAFLORA1);
player:addKeyItem(AQUAFLORA2);
player:addKeyItem(AQUAFLORA3);
player:messageSpecial(KEYITEM_OBTAINED,AQUAFLORA1);
elseif (csid == 0x0090) then
player:setVar("scatIntoShadowCS",1);
elseif (csid == 0x0087) then
if (player:getFreeSlotsCount() < 1) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14097);
else
player:setVar("scatIntoShadowCS",0);
player:addItem(14097);
player:messageSpecial(ITEM_OBTAINED,14097); -- Beast Gaiters
player:addFame(JEUNO,AF2_FAME);
player:completeQuest(JEUNO,SCATTERED_INTO_SHADOW);
end
end
end;
| gpl-3.0 |
etienne-gauvin/invaders | gui/main-menu-gui.lua | 1 | 1433 | local GUI = require 'gui'
local Button = require "uiobjects/button"
local gamestate = require "libs/hump/gamestate"
local MainMenuGUI = GUI:subclass('MainMenuGUI')
-- CrΓ©ation de l'interface
function MainMenuGUI:initialize(x, y, width, height)
GUI.initialize(self, x, y, width, height)
-- Liste des boutons
local b = {}
self.buttons = b
-- Boutons
b.continue = Button('Continuer', self, 0, 0)
b.continue.width = 300
b.continue.fixedWidth = true
b.continue.enabled = syst.save
b.continue.hidden = not syst.save
b.continue.onclick = function()
self:disable(function()
syst.currentState = game
gamestate.switch(game)
end)
end
b.newgame = Button('Nouvelle partie', self, 0, b.continue.pos.y + b.continue.height + 20)
b.newgame.width = 300
b.newgame.fixedWidth = true
b.newgame.onclick = function()
self:disable(function()
syst.currentState = game
gamestate.switch(game)
end)
end
b.params = Button('Paramètres', self, 0, b.newgame.pos.y + b.newgame.height + 20)
b.params.width = 300
b.params.fixedWidth = true
b.params.onclick = function()
print(menu)
menu:goToParams()
end
b.quit = Button('Quitter', self, 0, b.params.pos.y + b.params.height + 20)
b.quit.width = 300
b.quit.fixedWidth = true
b.quit.onclick = function() love.event.quit() end
for ib in pairs(b) do
self:add(b[ib])
end
end
return MainMenuGUI
| mit |
gedads/Neodynamis | scripts/globals/items/flame_claymore.lua | 7 | 1037 | -----------------------------------------
-- ID: 16588
-- Item: Flame Claymore
-- Additional Effect: Fire Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/msg");
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 5;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(3,10);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_FIRE, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_FIRE,0);
dmg = adjustForTarget(target,dmg,ELE_FIRE);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_FIRE,dmg);
local message = msgBasic.ADD_EFFECT_DMG;
if (dmg < 0) then
message = msgBasic.ADD_EFFECT_HEAL;
end
return SUBEFFECT_FIRE_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
DEVSTAEM/TAEMNEW | plugins/me.lua | 2 | 2580 |
do
local function run(msg,matches)
if is_sudo(msg) then
local sudo = "ΨΉΨ²ΩΨ² Ω
ΩΩΨΉΩ ΩΩ
ΨΉΩΩΩ
Ψ§ΨͺΩ ΩΩΨ§ πβ€π"..msg.from.first_name.."\n"
.."πΨ§ΩΨ―ΩΩ :("..msg.from.id..")\n"
.."ππ₯Ψ§ΩΨ―Ω Ψ§ΩΩΨ±ΩΨ¨ :("..msg.to.id..")\n"
.."πΩ
ΨΉΨ±ΩΩ :(@"..(msg.from.username or "ΩΨ§ ΩΩΨ¬Ψ―")..")\n"
.."βΨ±ΩΩ
Ω :("..(msg.from.phone or " ΩΨ§ ΩΩΨ¬Ψ―")..")\n"
.."π€Ω
ΩΩΨΉΩ: Ψ§ΩΨͺΩ Ω
Ψ·ΩΨ± Ω
Ψ§ΩΨͺΩ πβ€π "
return reply_msg(msg.id, sudo, ok_cb, true)
end
if is_owner(msg) then
local owner = "ΨΉΨ²ΩΨ²Ω Ω
ΩΩΨΉΩ ΩΩ
ΨΉΩΩΩ
Ψ§ΨͺΩ ΩΩΨ§ ππ"..msg.from.first_name.."\n"
.."πΨ§ΩΨ―ΩΩ :("..msg.from.id..")\n"
.."ππ₯Ψ§ΩΨ―Ω Ψ§ΩΩΨ±ΩΨ¨ :("..msg.to.id..")\n"
.."πΩ
ΨΉΨ±ΩΩ :(@"..(msg.from.username or "ΩΨ§ ΩΩΨ¬Ψ―")..")\n"
.."βΨ±ΩΩ
Ω :("..(msg.from.phone or " ΩΨ§ ΩΩΨ¬Ψ― ")..")\n"
.."π€Ω
ΩΩΨΉΩ :Ψ§ΩΨͺΩ Ω
Ψ―ΩΨ± Ψ§ΩΩ
Ψ¬Ω
ΩΨΉΩ Ψ§ΩΩ
ΨΨͺΨ±Ω
πΊπ₯ Β»"
return reply_msg(msg.id, owner, ok_cb, true)
end
if is_admin1(msg) then
local admin1 = "ΨΉΨ²ΩΨ²Ω Ω
ΩΩΨΉΩ ΩΩ
ΨΉΩΩΩ
Ψ§ΨͺΩ ΩΩΨ§ππ"
.."πΨ§ΩΨ―ΩΩ :("..msg.from.id..")\n"
.."ππ₯Ψ§ΩΨ―Ω Ψ§ΩΩΨ±ΩΨ¨ :("..msg.to.id..")\n"
.."πΩ
ΨΉΨ±ΩΩ :(@"..(msg.from.username or "ΩΨ§ ΩΩΨ¬Ψ―")..")\n"
.."βΨ±ΩΩ
Ω :("..(msg.from.phone or " ΩΨ§ΩΩΨ¬Ψ― ")..")\n"
.."π€Ω
ΩΩΨΉΩ :Ψ§ΩΨͺΩ Ψ§Ψ―Ψ±Ψ§Ω πβ€Β» "
return reply_msg(msg.id, admin1, ok_cb, true)
end
if is_momod(msg) then
local admin = "ΨΉΨ²ΩΨ²Ω Ω
ΩΩΨΉΩ ΩΩ
ΨΉΩΩΩ
Ψ§ΨͺΩ ΩΩΨ§ ππ "..msg.from.first_name.."\n"
.."πΨ§ΩΨ―ΩΩ :("..msg.from.id..")\n"
.."ππ₯Ψ§ΩΨ―Ω Ψ§ΩΩΨ±ΩΨ¨ :("..msg.to.id..")\n"
.."πΩ
ΨΉΨ±ΩΩ :(@"..(msg.from.username or "ΩΨ§ ΩΩΨ¬Ψ―")..")\n"
.."βΨ±ΩΩ
Ω :("..(msg.from.phone or " ΩΨ§ ΩΩΨ¬Ψ― ")..")\n"
.."π€Ω
ΩΩΨΉΩ :Ψ§ΩΨͺΩ Ψ§Ψ―Ω
Ω Ψ§ΩΩ
ΨΨͺΨ±Ω
π©"
return reply_msg(msg.id, admin, ok_cb, true)
end
if not is_momod(msg) then
local member = "ΨΉΨ²ΩΨ²Ω Ω
ΩΩΨΉΩ ΩΩ
ΨΉΩΩΩ
Ψ§ΨͺΩ ΩΩΨ§ ππ "..msg.from.first_name.."\n"
.."πΨ§ΩΨ―ΩΩ :("..msg.from.id..")\n"
.."ππ₯Ψ§ΩΨ―Ω Ψ§ΩΩΨ±ΩΨ¨ :("..msg.to.id..")\n"
.."πΩ
ΨΉΨ±ΩΩ :(@"..(msg.from.username or "ΩΨ§ ΩΩΨ¬Ψ―")..")\n"
.."βΨ±ΩΩ
Ω :("..(msg.from.phone or "ΩΨ§ΩΩΨ¬Ψ― " )..")\n"
.."π€Ω
ΩΩΨΉΩ :Ψ§ΩΨͺΩ Ψ―Ψ§ΩΨ ΩΨ΅Ψ―Ω ΨΉΨΆΩ πΉπΒ» "
return reply_msg(msg.id, member, ok_cb, true)
end
end
return {
patterns = {
"^(Ω
ΩΩΨΉΩ)$",
},
run = run,
}
end
| gpl-2.0 |
gedads/Neodynamis | scripts/zones/Southern_San_dOria_[S]/npcs/Sabiliont.lua | 3 | 1706 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Sabiliont
-- @zone 80
-- !pos 9 2 -87
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("GiftsOfGriffonProg") == 2) then
local mask = player:getVar("GiftsOfGriffonPlumes");
if (trade:hasItemQty(2528,1) and trade:getItemCount() == 1 and not player:getMaskBit(mask,4)) then
player:startEvent(0x01B) -- Gifts of Griffon Trade
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, 6999); -- (Couldn't find default dialogue) What are you doing here? This is no place for civillians
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 == 0x01B) then -- Gifts Of Griffon Trade
player:tradeComplete();
local mask = player:getVar("GiftsOfGriffonPlumes");
player:setMaskBit(mask,"GiftsOfGriffonPlumes",4,true);
end
end; | gpl-3.0 |
gedads/Neodynamis | scripts/zones/Rabao/npcs/Pakhi_Churhebi.lua | 3 | 1034 | ----------------------------------
-- Area: Rabao
-- NPC: Pakhi Churhebi
-- Type: Item Deliverer
-- @zone 247
-- !pos 158.428 7.999 78.009
--
-----------------------------------
package.loaded["scripts/zones/Rabao/TextIDs"] = nil;
require("scripts/zones/Rabao/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, PAKHI_DELIVERY_DIALOG);
player:openSendBox();
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
BillardDRP/nathaniel-rp-addons | addons/bperks/lua/autorun/sv_perks.lua | 1 | 1128 | --[[
List of Perks:
diehard - Explode on death
groundpound - Deal splash damage when hitting the group
feather - Take no fall damage
arson - Ignite targets
]]--
BPerks = {}
BPerks.PerkList = {
["diehard"] = true,
["groundpound"] = true,
["feather"] = true,
["arson"] = true,
}
local PlyMeta = FindMetaTable("Player")
function PlyMeta:HasBPerk(perk)
return self:GetPData("bperk_"..perk, 0) > 0
end
function PlyMeta:GiveBPerk(perk)
self:SetPData("bperk_"..perk, 1)
end
function PlyMeta:TakeBPerk(perk)
self:SetPData("bperk_"..perk, 0)
end
function PlyMeta:TakeAllBPerks()
for k, v in pairs(BPerks.PerkList) do
if v then
self:SetPData("bperk_"..tostring(k), 0)
end
end
end
hook.Add("PlayerDeath", "BPerks_DieHard", function(victim, inflictor, attacker)
if !IsValid(victim) or !IsValid(attacker) or !IsPlayer(attacker) then return end
if victim:HasBPerk("diehard") then
end
end)
hook.Add("PlayerShouldTakeDamage", "BPerks_Arson", function(ply, attacker)
if !IsValid(ply) or !IsValid(attacker) or !IsPlayer(attacker) then return end
if attacker:HasBPerk("arson") then
ply:Ignite(3, 16)
end
end)
| gpl-3.0 |
Amorph/premake-stable | tests/actions/vstudio/test_vs2010_flags.lua | 7 | 11973 |
T.vs2010_flags = { }
local vs10_flags = T.vs2010_flags
local sln, prj
function vs10_flags.setup()
_ACTION = "vs2010"
sln = solution "MySolution"
configurations { "Debug" }
platforms {}
prj = project "MyProject"
language "C++"
kind "ConsoleApp"
uuid "AE61726D-187C-E440-BD07-2556188A6565"
includedirs{"foo/bar"}
end
function vs10_flags.teardown()
sln = nil
prj = nil
end
local function get_buffer()
io.capture()
premake.bake.buildconfigs()
sln.vstudio_configs = premake.vstudio.buildconfigs(sln)
prj = premake.solution.getproject(sln, 1)
premake.vs2010_vcxproj(prj)
local buffer = io.endcapture()
return buffer
end
function vs10_flags.sseSet()
flags {"EnableSSE"}
local buffer = get_buffer()
test.string_contains(buffer,'<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>')
end
function vs10_flags.sse2Set()
flags {"EnableSSE2"}
local buffer = get_buffer()
test.string_contains(buffer,'<EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>')
end
function vs10_flags.extraWarningNotSet_warningLevelIsThree()
local buffer = get_buffer()
test.string_contains(buffer,'<WarningLevel>Level3</WarningLevel>')
end
function vs10_flags.extraWarning_warningLevelIsFour()
flags {"ExtraWarnings"}
local buffer = get_buffer()
test.string_contains(buffer,'<WarningLevel>Level4</WarningLevel>')
end
function vs10_flags.extraWarning_treatWarningsAsError_setToTrue()
flags {"FatalWarnings"}
local buffer = get_buffer()
test.string_contains(buffer,'<TreatWarningAsError>true</TreatWarningAsError>')
end
function vs10_flags.floatFast_floatingPointModel_setToFast()
flags {"FloatFast"}
local buffer = get_buffer()
test.string_contains(buffer,'<FloatingPointModel>Fast</FloatingPointModel>')
end
function vs10_flags.floatStrict_floatingPointModel_setToStrict()
flags {"FloatStrict"}
local buffer = get_buffer()
test.string_contains(buffer,'<FloatingPointModel>Strict</FloatingPointModel>')
end
function vs10_flags.nativeWideChar_TreatWChar_tAsBuiltInType_setToTrue()
flags {"NativeWChar"}
local buffer = get_buffer()
test.string_contains(buffer,'<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>')
end
function vs10_flags.nativeWideChar_TreatWChar_tAsBuiltInType_setToFalse()
flags {"NoNativeWChar"}
local buffer = get_buffer()
test.string_contains(buffer,'<TreatWChar_tAsBuiltInType>false</TreatWChar_tAsBuiltInType>')
end
function vs10_flags.noExceptions_exceptionHandling_setToFalse()
flags {"NoExceptions"}
local buffer = get_buffer()
test.string_contains(buffer,'<ExceptionHandling>false</ExceptionHandling>')
end
function vs10_flags.structuredExceptions_exceptionHandling_setToAsync()
flags {"SEH"}
local buffer = get_buffer()
test.string_contains(buffer,'<ExceptionHandling>Async</ExceptionHandling>')
end
function vs10_flags.noFramePointer_omitFramePointers_setToTrue()
flags {"NoFramePointer"}
local buffer = get_buffer()
test.string_contains(buffer,'<OmitFramePointers>true</OmitFramePointers>')
end
function vs10_flags.noRTTI_runtimeTypeInfo_setToFalse()
flags {"NoRTTI"}
local buffer = get_buffer()
test.string_contains(buffer,'<RuntimeTypeInfo>false</RuntimeTypeInfo>')
end
function vs10_flags.optimizeSize_optimization_setToMinSpace()
flags {"OptimizeSize"}
local buffer = get_buffer()
test.string_contains(buffer,'<Optimization>MinSpace</Optimization>')
end
function vs10_flags.optimizeSpeed_optimization_setToMaxSpeed()
flags {"OptimizeSpeed"}
local buffer = get_buffer()
test.string_contains(buffer,'<Optimization>MaxSpeed</Optimization>')
end
function vs10_flags.optimizeSpeed_optimization_setToMaxSpeed()
flags {"Optimize"}
local buffer = get_buffer()
test.string_contains(buffer,'<Optimization>Full</Optimization>')
end
local debug_string = "Symbols"
local release_string = "Optimize"
function vs10_flags.debugHasNoStaticRuntime_runtimeLibrary_setToMultiThreadedDebugDLL()
flags {debug_string}
local buffer = get_buffer()
test.string_contains(buffer,'<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>')
end
function vs10_flags.debugAndStaticRuntime_runtimeLibrary_setToMultiThreadedDebug()
flags {debug_string,"StaticRuntime"}
local buffer = get_buffer()
test.string_contains(buffer,'<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>')
end
function vs10_flags.releaseHasNoStaticRuntime_runtimeLibrary_setToMultiThreadedDLL()
flags {release_string}
local buffer = get_buffer()
test.string_contains(buffer,'<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>')
end
function vs10_flags.releaseAndStaticRuntime_runtimeLibrary_setToMultiThreaded()
flags {release_string,"StaticRuntime"}
local buffer = get_buffer()
test.string_contains(buffer,'<RuntimeLibrary>MultiThreaded</RuntimeLibrary>')
end
function vs10_flags.noCharacterSetDefine_characterSet_setToMultiByte()
local buffer = get_buffer()
test.string_contains(buffer,'<CharacterSet>MultiByte</CharacterSet>')
end
function vs10_flags.unicode_characterSet_setToUnicode()
flags {"Unicode"}
local buffer = get_buffer()
test.string_contains(buffer,'<CharacterSet>Unicode</CharacterSet>')
end
function vs10_flags.debugAndNoMinimalRebuildAndSymbols_minimalRebuild_setToFalse()
flags {debug_string,"NoMinimalRebuild"}
local buffer = get_buffer()
test.string_contains(buffer,'<MinimalRebuild>false</MinimalRebuild>')
end
function vs10_flags.debugYetNotMinimalRebuild_minimalRebuild_setToTrue()
flags {debug_string}
local buffer = get_buffer()
test.string_contains(buffer,'<MinimalRebuild>true</MinimalRebuild>')
end
function vs10_flags.release_minimalRebuild_setToFalse()
flags {release_string}
local buffer = get_buffer()
test.string_contains(buffer,'<MinimalRebuild>false</MinimalRebuild>')
end
function vs10_flags.mfc_useOfMfc_setToStatic()
flags{"MFC"}
local buffer = get_buffer()
test.string_contains(buffer,'<UseOfMfc>Dynamic</UseOfMfc>')
end
--there is not an option for /Z7 OldStyle
--/ZI is not compatible with /clr or x64_64
--minimal Rebuild requires /Zi in x86_64
function vs10_flags.symbols_32BitBuild_DebugInformationFormat_setToEditAndContinue()
flags{"Symbols"}
platforms{'x32'}
local buffer = get_buffer()
test.string_contains(buffer,'<DebugInformationFormat>EditAndContinue</DebugInformationFormat>')
end
function vs10_flags.symbols_64BitBuild_DebugInformationFormat_setToProgramDatabase()
flags{"Symbols"}
platforms{"x64"}
local buffer = get_buffer()
test.string_contains(buffer,'<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>')
end
function vs10_flags.symbolsAndNoEditAndContinue_DebugInformationFormat_setToProgramDatabase()
flags{"Symbols","NoEditAndContinue"}
local buffer = get_buffer()
test.string_contains(buffer,'<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>')
end
function vs10_flags.symbolsAndRelease_DebugInformationFormat_setToProgramDatabase()
flags{"Symbols",release_string}
local buffer = get_buffer()
test.string_contains(buffer,'<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>')
end
function vs10_flags.symbolsManaged_DebugInformationFormat_setToProgramDatabase()
flags{"Symbols","Managed"}
local buffer = get_buffer()
test.string_contains(buffer,'<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>')
end
function vs10_flags.noSymbols_DebugInformationFormat_blockIsEmpty()
local buffer = get_buffer()
test.string_contains(buffer,'<DebugInformationFormat></DebugInformationFormat>')
end
function vs10_flags.noSymbols_bufferDoesNotContainprogramDataBaseFile()
local buffer = get_buffer()
test.string_does_not_contain(buffer,'<Link>.*<ProgramDataBaseFileName>.*</Link>')
end
function vs10_flags.symbols_bufferContainsprogramDataBaseFile()
flags{"Symbols"}
local buffer = get_buffer()
test.string_contains(buffer,'<ClCompile>.*<ProgramDataBaseFileName>%$%(OutDir%)MyProject%.pdb</ProgramDataBaseFileName>.*</ClCompile>')
end
function vs10_flags.WithOutManaged_bufferContainsKeywordWin32Proj()
local buffer = get_buffer()
test.string_contains(buffer,'<PropertyGroup Label="Globals">.*<Keyword>Win32Proj</Keyword>.*</PropertyGroup>')
end
function vs10_flags.WithOutManaged_bufferDoesNotContainKeywordManagedCProj()
local buffer = get_buffer()
test.string_does_not_contain(buffer,'<PropertyGroup Label="Globals">.*<Keyword>ManagedCProj</Keyword>.*</PropertyGroup>')
end
T.vs2010_managedFlag = { }
local vs10_managedFlag = T.vs2010_managedFlag
local function vs10_managedFlag_setOnProject()
local sln = solution "Sol"
configurations { "Debug" }
language "C++"
kind "ConsoleApp"
local prj = project "Prj"
flags {"Managed"}
return sln,prj
end
local function get_managed_buffer(sln,prj)
io.capture()
premake.bake.buildconfigs()
sln.vstudio_configs = premake.vstudio.buildconfigs(sln)
prj = premake.solution.getproject(sln, 1)
premake.vs2010_vcxproj(prj)
local buffer = io.endcapture()
return buffer
end
function vs10_managedFlag.setup()
end
function vs10_managedFlag.managedSetOnProject_CLRSupport_setToTrue()
local sln, prj = vs10_managedFlag_setOnProject()
local buffer = get_managed_buffer(sln,prj)
test.string_contains(buffer,
'<PropertyGroup Condition=".*" Label="Configuration">'
..'.*<CLRSupport>true</CLRSupport>'
..'.*</PropertyGroup>')
end
function vs10_managedFlag.globals_bufferContainsKeywordManagedCProj()
local sln, prj = vs10_managedFlag_setOnProject()
local buffer = get_managed_buffer(sln,prj)
test.string_contains(buffer,'<PropertyGroup Label="Globals">.*<Keyword>ManagedCProj</Keyword>.*</PropertyGroup>')
end
function vs10_managedFlag.globals_bufferDoesNotContainKeywordWin32Proj()
local sln, prj = vs10_managedFlag_setOnProject()
local buffer = get_managed_buffer(sln,prj)
test.string_does_not_contain(buffer,'<PropertyGroup Label="Globals">.*<Keyword>Win32Proj</Keyword>.*</PropertyGroup>')
end
function vs10_managedFlag.globals_FrameworkVersion_setToV4()
local sln, prj = vs10_managedFlag_setOnProject()
local buffer = get_managed_buffer(sln,prj)
test.string_contains(buffer,'<PropertyGroup Label="Globals">.*<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>.*</PropertyGroup>')
end
function vs10_managedFlag.withFloatFast_FloatingPointModelNotFoundInBuffer()
local sln, prj = vs10_managedFlag_setOnProject()
flags {"FloatStrict"}
local buffer = get_managed_buffer(sln,prj)
test.string_does_not_contain(buffer,'<FloatingPointModel>.*</FloatingPointModel>')
end
function vs10_managedFlag.debugWithStaticRuntime_flagIgnoredAndRuntimeSetToMDd()
local sln, prj = vs10_managedFlag_setOnProject()
flags {"Symbols","StaticRuntime"}
local buffer = get_managed_buffer(sln,prj)
test.string_contains(buffer,'<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>')
end
function vs10_managedFlag.notDebugWithStaticRuntime_flagIgnoredAndRuntimeSetToMD()
local sln, prj = vs10_managedFlag_setOnProject()
flags {"StaticRuntime"}
local buffer = get_managed_buffer(sln,prj)
test.string_contains(buffer,'<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>')
end
function vs10_managedFlag.noOptimisationFlag_basicRuntimeChecksNotFoundInBuffer()
local sln, prj = vs10_managedFlag_setOnProject()
local buffer = get_managed_buffer(sln,prj)
test.string_does_not_contain(buffer,'<BasicRuntimeChecks>.*</BasicRuntimeChecks>')
end
function vs10_managedFlag.applictionWithOutWinMain_EntryPointSymbolNotFoundInBuffer()
local sln, prj = vs10_managedFlag_setOnProject()
local buffer = get_managed_buffer(sln,prj)
test.string_does_not_contain(buffer,'<EntryPointSymbol>.*</EntryPointSymbol>')
end
| bsd-3-clause |
nathanaeljones/weaver-nodelua | lua/lib.lua | 1 | 7559 |
display={out=""}
this = {}
shared = {}
function roundtrip(type,name)
return state_update(coroutine.yield(outdata(type,name)))
end
function state_update(indata)
-- Display value is only passed in on occasion - if it's missing, we just use the copy we have.
if indata.display ~= nil then _G.display = indata.display end
_G.user = indata.user
_G.branch = indata.branch
if user[loaded_filename] == nil then user[loaded_filename] = {} end
if branch[loaded_filename] == nil then branch[loaded_filename] = {} end
_G.this = _G.user[loaded_filename]
_G.shared = _G.branch[loaded_filename]
-- Run all filters passed to us.
local filters = indata.childfilters
if filters ~= nil then
local _,filter
for _,filter in ipairs(indata.childfilters) do
filter(indata)
end
end
return indata
end
function outdata(type, funcname)
local d = {display=_G.display,user=_G.user,branch=_G.branch, msg = {type=type, funcname=funcname}}
-- Remove convenience tables unless they have data in them.
if table.isempty(user[loaded_filename]) then user[loaded_filename] = nil end
if table.isempty(branch[loaded_filename]) then branch[loaded_filename] = nil end
_G.this = nil
_G.shared = nil
_G.user = nil -- We don't want these included in the continuation. They'll be outdated when it restarts, and will be passed back to us anyway.
_G.branch = nil
return d;
end
function define_var( name,defaultValue)
local tab = get_parent_of_var(name, true)
name = ns.member(name)
if (tab[name] == nil) then
tab[name] = defaultValue;
end
end
function get_parent_of_var(name, create_missing_levels)
local tab = _G
while name:find("%.") ~= nil do
local _,_,part = name:find("^([^%.]*)%.")
name = name:gsub("^([^%.]*)%.","")
if (tab[part] == nil) then
if create_missing_levels then
tab[part] = {}
else
return nil
end
end
tab = tab[part]
end
return tab
end
function short_hash(text)
return sha2.sha256hex(text):sub(0,8)
end
function get_var( name,defaultValue)
local tab = get_parent_of_var(name, false)
if (tab == nil) then return defaultValue end
local val = tab[name]
if (val == nil) then return defaultValue end
return val
end
function set_var( name,value)
local tab = get_parent_of_var(name, true)
tab[name] = value;
return value
end
function inc(name, offset, defaultValue)
if offset == nil then offset = 1 end
if defaultValue == nil then defaultValue = 0 end
return set_var(name, get_var(name,defaultValue) + offset)
end
function printlocals()
print(table.show(locals(3),"locals"))
end
function locals(level)
if (level == nil) then level = 2 end
local variables = {}
local idx = 1
while true do
local ln, lv = debug.getlocal(level, idx)
if ln ~= nil then
variables[ln] = lv
else
break
end
idx = 1 + idx
end
return variables
end
function lookup_external_var(name)
return roundtrip("getvar",name).getvar
end
function p (message)
display.out = display.out .. '\n\n' .. message:gsub("^[ \t]+",""):gsub("\n[ \t]+","\n")
end
function add_option(text, id, shortcut)
if (display.menu == nil) then
display.menu = {}
end
display.menu[#display.menu + 1] = {text = text, shortcut= shortcut, id=id}
end
function choose(options)
-- Build a dict keyed on both caption hashes and shortcut keys
local by_id_or_s = {}
for key,value in pairs(options) do
-- Allow shortcuts (non-pairs)
if (type(key) == 'number') then
key = _G[value .. "_"] --Try to lookup the place_ variable, first locally
-- Then in a remote file, if a . is in the name
if (key == nil and value:find("%.") ~= nil) then
key = lookup_external_var(value .. "_")
end
-- Fallback to autonaming
if (key == nil) then key = "Go to " .. ns.member(value) end
end
_,_,shortcut = key:find("%((%l)%)")
if shortcut ~= nil then by_id_or_s[shortcut] = value end
local id = short_hash(key)
by_id_or_s[id] = value
add_option(key, id, shortcut)
end
-- Allow either the shortcut key or the hash to be used
local answer
repeat
local indata = roundtrip('prompt')
answer = indata.response
until answer ~= nil
print ("You pressed " .. answer)
local dest = by_id_or_s[answer]
if dest == nil then
-- TODO, throw error and restart loop
end
if type(dest) == 'string' then
roundtrip('goto',dest)
else
dest()
end
end
function message(text, button_text)
if button_text == nill then button_text = "Continue" end
display.out = text
display.menu = {{text=button_text, shortcut='c', id='continue'}}
roundtrip('prompt')
end
function clear()
display.out = ""
display.menu = {}
end
-- Returns a value between 0 and 1
function random_number()
math.randomseed( tonumber(tostring(os.time()):reverse():sub(1,6)) )
return math.random()
end
function random_chance_of(zerotoone)
return random_number() < zerotoone
end
-- Randomly executes one of the specified actions (if functions). If a string is specified, it is assumed to be text.
-- Weights can be provided for any item, simply add a number before it. In {action1, action2, 4, action5}, action5 will have a 4 times large probabibility of being selected.
function do_random(actions)
-- Calculate the weights for each action, the sum of all weights
-- And build a new array of weight/action pairs
local weight = 1
local weight_sum = 0
local new_table = {}
local v
for _, v in ipairs(actions) do
if type(v) == 'number' then
weight = v
else
table.insert(new_table, {weight=weight, action = v})
weight_sum = weight_sum + weight
weight = 1
end
end
local random_value = random_number() * weight_sum
-- Go through the actions looking for the action corresponding to the random value
local previous_weight = 0
for _, v in ipairs(new_table) do
if (random_value >= previous_weight and random_value <= previous_weight + v.weight) then
local act = v.action
if type(act) == 'string' then
p(act)
else if type(act) == 'function' then
act()
else
--TODO: throw an error?
end
end
end
end
-- TODO: Throw an error
end
function table.isempty(tab)
return next(tab) == nil
end
-- Ends the currently executing module, and starts the newly specified one
function switchto(name)
display.menu = {}
display.out = ""
roundtrip('goto',name)
end
function goto(name)
switchto(name)
end
if ns == nil then ns = {} end
-- Gets the parent of a namespace. "world.town.center" -> "world.town"
function ns.parent(name)
return name:gsub("%.[^%.]+$","",1)
end
-- Gets the last segment of a namespace. "world.town.center" -> "center"
function ns.member(name)
local _,_,membername = name:find("%.([^%.]+)$")
return membername and membername or name
end
function ns.hasdot(name)
return name:match("^[^%.]+$") == nil
end
function ns.resolve(name, base)
if ns.hasdot(name) then
return name
else
return base .. "." .. name
end
end
-- Define time spans
time = {
one_year = os.time{year=1971, month=1, day=1, hour=0} - os.time{year=1970, month=1, day=1, hour=0},
one_month = os.time{year=1970, month=5, day=1, hour=0} - os.time{year=1970, month=4, day=1, hour=0},
one_day = os.time{year=1970, month=5, day=2, hour=0} - os.time{year=1970, month=5, day=1, hour=0},
one_hour = os.time{year=1970, month=5, day=1, hour=1} - os.time{year=1970, month=5, day=1, hour=0},
one_minute = os.time{year=1970, month=5, day=1, hour=1, min = 1, sec = 0} - os.time{year=1970, month=5, day=1, hour=0, min = 0, sec = 0},
one_second = os.time{year=1970, month=5, day=1, hour=1, min = 0, sec = 1} - os.time{year=1970, month=5, day=1, hour=0, min = 0, sec = 0}
}
| apache-2.0 |
gedads/Neodynamis | scripts/globals/items/pot_of_honey.lua | 12 | 1127 | -----------------------------------------
-- ID: 4370
-- Item: pot_of_honey
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Magic Regen While Healing 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4370);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MPHEAL, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MPHEAL, 1);
end;
| gpl-3.0 |
starlightknight/darkstar | scripts/globals/items/roast_carp.lua | 11 | 1069 | -----------------------------------------
-- ID: 4537
-- Item: roast_carp
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Dexterity 1
-- Mind -1
-- Ranged ATT % 14 (cap 40)
-----------------------------------------
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,4537)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.DEX, 1)
target:addMod(dsp.mod.MND, -1)
target:addMod(dsp.mod.FOOD_RATTP, 14)
target:addMod(dsp.mod.FOOD_RATT_CAP, 40)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.DEX, 1)
target:delMod(dsp.mod.MND, -1)
target:delMod(dsp.mod.FOOD_RATTP, 14)
target:delMod(dsp.mod.FOOD_RATT_CAP, 40)
end
| gpl-3.0 |
gedads/Neodynamis | scripts/globals/effects/int_boost.lua | 34 | 1027 | -----------------------------------
--
-- EFFECT_INT_BOOST
--
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_INT,effect:getPower());
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
-- the effect loses intelligence of 1 every 3 ticks depending on the source of the boost
local boostINT_effect_size = effect:getPower();
if (boostINT_effect_size > 0) then
effect:setPower(boostINT_effect_size - 1)
target:delMod(MOD_INT,1);
end
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
local boostINT_effect_size = effect:getPower();
if (boostINT_effect_size > 0) then
target:delMod(MOD_INT,boostINT_effect_size);
end
end;
| gpl-3.0 |
starlightknight/darkstar | scripts/globals/items/dish_of_spaghetti_carbonara.lua | 11 | 1545 | -----------------------------------------
-- ID: 5190
-- Item: dish_of_spaghetti_carbonara
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Health % 14
-- Health Cap 175
-- Magic 10
-- Strength 4
-- Vitality 2
-- Intelligence -3
-- Attack % 17
-- Attack Cap 65
-- Store TP 6
-----------------------------------------
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,5190)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.FOOD_HPP, 14)
target:addMod(dsp.mod.FOOD_HP_CAP, 175)
target:addMod(dsp.mod.MP, 10)
target:addMod(dsp.mod.STR, 4)
target:addMod(dsp.mod.VIT, 2)
target:addMod(dsp.mod.INT, -3)
target:addMod(dsp.mod.FOOD_ATTP, 17)
target:addMod(dsp.mod.FOOD_ATT_CAP, 65)
target:addMod(dsp.mod.STORETP, 6)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.FOOD_HPP, 14)
target:delMod(dsp.mod.FOOD_HP_CAP, 175)
target:delMod(dsp.mod.MP, 10)
target:delMod(dsp.mod.STR, 4)
target:delMod(dsp.mod.VIT, 2)
target:delMod(dsp.mod.INT, -3)
target:delMod(dsp.mod.FOOD_ATTP, 17)
target:delMod(dsp.mod.FOOD_ATT_CAP, 65)
target:delMod(dsp.mod.STORETP, 6)
end
| gpl-3.0 |
gedads/Neodynamis | scripts/globals/abilities/pets/attachments/heat_seeker.lua | 4 | 2220 | -----------------------------------
-- Attachment: Heat Seeker
-----------------------------------
require("scripts/globals/status")
-----------------------------------
-- onUseAbility
-----------------------------------
function onEquip(pet)
pet:addListener("ENGAGE", "AUTO_HEAT_SEEKER_ENGAGE", function(pet, target)
pet:setLocalVar("heatseekertick", VanadielTime())
end)
pet:addListener("AUTOMATON_AI_TICK", "AUTO_HEAT_SEEKER_TICK", function(pet, target)
if pet:getLocalVar("heatseekertick") > 0 then
local master = pet:getMaster()
local maneuvers = master:countEffect(EFFECT_THUNDER_MANEUVER)
local lasttick = pet:getLocalVar("heatseekertick")
local tick = VanadielTime()
local dt = tick - lasttick
local prevamount = pet:getLocalVar("heatseeker")
local amount = 0
if maneuvers > 0 then
amount = maneuvers * dt
if (amount + prevamount) > 30 then
amount = 30 - prevamount
end
if amount ~= 0 then
pet:addMod(MOD_ACC, amount)
end
else
amount = -1 * dt
if (amount + prevamount) < 0 then
amount = -prevamount
end
if amount ~= 0 then
pet:delMod(MOD_ACC, -amount)
end
end
if amount ~= 0 then
pet:setLocalVar("heatseeker", prevamount + amount)
end
pet:setLocalVar("heatseekertick", tick)
end
end)
pet:addListener("DISENGAGE", "AUTO_HEAT_SEEKER_DISENGAGE", function(pet)
if pet:getLocalVar("heatseeker") > 0 then
pet:delMod(MOD_ACC, pet:getLocalVar("heatseeker"))
pet:setLocalVar("heatseeker", 0)
end
pet:setLocalVar("heatseekertick", 0)
end)
end
function onUnequip(pet)
pet:removeListener("AUTO_HEAT_SEEKER_ENGAGE")
pet:removeListener("AUTO_HEAT_SEEKER_TICK")
pet:removeListener("AUTO_HEAT_SEEKER_DISENGAGE")
end
function onManeuverGain(pet,maneuvers)
end
function onManeuverLose(pet,maneuvers)
end
| gpl-3.0 |
starlightknight/darkstar | scripts/globals/abilities/pets/attachments/mana_channeler_ii.lua | 11 | 1251 | -----------------------------------
-- Attachment: Mana Channeler II
-----------------------------------
require("scripts/globals/status")
-----------------------------------
function onEquip(pet)
pet:addMod(dsp.mod.MATT, 20) -- Values unknown, best guess based on other attachment methods
pet:addMod(dsp.mod.AUTO_MAGIC_DELAY, -3)
end
function onUnequip(pet)
pet:delMod(dsp.mod.MATT, 20)
pet:delMod(dsp.mod.AUTO_MAGIC_DELAY, -3)
end
function onManeuverGain(pet, maneuvers)
if maneuvers == 1 then
pet:addMod(dsp.mod.MATT, 10)
pet:addMod(dsp.mod.AUTO_MAGIC_DELAY, -3)
elseif maneuvers == 2 then
pet:addMod(dsp.mod.MATT, 10)
pet:addMod(dsp.mod.AUTO_MAGIC_DELAY, -3)
elseif maneuvers == 3 then
pet:addMod(dsp.mod.MATT, 10)
pet:addMod(dsp.mod.AUTO_MAGIC_DELAY, -3)
end
end
function onManeuverLose(pet, maneuvers)
if maneuvers == 1 then
pet:delMod(dsp.mod.MATT, 10)
pet:delMod(dsp.mod.AUTO_MAGIC_DELAY, -3)
elseif maneuvers == 2 then
pet:delMod(dsp.mod.MATT, 10)
pet:delMod(dsp.mod.AUTO_MAGIC_DELAY, -3)
elseif maneuvers == 3 then
pet:delMod(dsp.mod.MATT, 10)
pet:delMod(dsp.mod.AUTO_MAGIC_DELAY, -3)
end
end | gpl-3.0 |
starlightknight/darkstar | scripts/zones/Sealions_Den/npcs/Airship_Door.lua | 8 | 1246 | -----------------------------------
-- Area: Sealion's Den
-- NPC: Airship_Door
-----------------------------------
local ID = require("scripts/zones/Sealions_Den/IDs")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local offset = npc:getID() - ID.npc.AIRSHIP_DOOR_OFFSET
player:startEvent(32003, offset + 1)
end
function onEventUpdate(player, csid, option)
local inst = player:getCharVar("bcnm_instanceid")
-- spawn omega for given instance
if csid == 1 and option == 0 then
local omegaId = ID.mob.ONE_TO_BE_FEARED_OFFSET + (7 * (inst - 1)) + 5
if omegaId and not GetMobByID(omegaId):isSpawned() then
SpawnMob(omegaId)
end
-- spawn ultima for given instance
elseif csid == 2 and option == 0 then
local ultimaId = ID.mob.ONE_TO_BE_FEARED_OFFSET + (7 * (inst - 1)) + 6
if ultimaId and not GetMobByID(ultimaId):isSpawned() then
SpawnMob(ultimaId)
end
end
end
function onEventFinish(player, csid, option)
if csid == 32003 and option >= 100 and option <= 102 then
local inst = option - 99
player:startEvent(player:getLocalVar("[OTBF]cs"), inst)
end
end
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/Aydeewa_Subterrane/Zone.lua | 9 | 2145 | -----------------------------------
--
-- Zone: Aydeewa_Subterrane (68)
--
-----------------------------------
local ID = require("scripts/zones/Aydeewa_Subterrane/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
require("scripts/globals/npc_util")
require("scripts/globals/quests")
require("scripts/globals/status")
require("scripts/globals/titles")
-----------------------------------
function onInitialize(zone)
zone:registerRegion(1,378,-3,338,382,3,342)
end
function onZoneIn(player,prevZone)
local cs = -1
if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then
player:setPos(356.503,-0.364,-179.607,122)
end
if player:getCurrentMission(TOAU) == dsp.mission.id.toau.TEAHOUSE_TUMULT and player:getCharVar("AhtUrganStatus") == 0 then
cs = 10
end
return cs
end
function onRegionEnter(player,region)
if region:GetRegionID() == 1 then
local StoneID = player:getCharVar("EmptyVesselStone")
if player:getQuestStatus(AHT_URHGAN,dsp.quest.id.ahtUrhgan.AN_EMPTY_VESSEL) == QUEST_ACCEPTED and player:getCharVar("AnEmptyVesselProgress") == 4 and player:hasItem(StoneID) then
player:startEvent(3,StoneID)
end
end
end
function onRegionLeave(player,region)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if
csid == 3 and
option == 13 and
npcUtil.completeQuest(player, AHT_URHGAN, dsp.quest.id.ahtUrhgan.AN_EMPTY_VESSEL, {title=dsp.title.BEARER_OF_THE_MARK_OF_ZAHAK, ki=dsp.ki.MARK_OF_ZAHAK, var={"AnEmptyVesselProgress", "EmptyVesselStone"}})
then -- Accept and unlock
player:unlockJob(dsp.job.BLU)
player:setPos(148,-2,0,130,50)
elseif csid == 3 and option ~= 13 then -- Make a mistake and get reset
player:setCharVar("AnEmptyVesselProgress", 0)
player:setCharVar("EmptyVesselStone", 0)
player:delQuest(AHT_URHGAN,dsp.quest.id.ahtUrhgan.AN_EMPTY_VESSEL)
player:setPos(148,-2,0,130,50)
elseif csid == 10 then
player:setCharVar("AhtUrganStatus", 1)
end
end | gpl-3.0 |
ironjade/DevStack | LanCom/DesignPattern/LUA/String.lua | 1 | 3449 | #!/usr/local/bin/lua
--[[
Copyright (c) 2004 by Bruno R. Preiss, P.Eng.
$Author: brpreiss $
$Date: 2004/12/05 14:47:20 $
$RCSfile: String.lua,v $
$Revision: 1.12 $
$Id: String.lua,v 1.12 2004/12/05 14:47:20 brpreiss Exp $
--]]
require "Class"
require "Integer"
-- Wrapper class for strings.
String = Class.new("String", Object)
-- Constructs an string with the given value.
-- @param value A string value.
function String.methods:initialize(value)
String.super(self)
assert(type(value) == "string", "DomainError")
self.value = value
end
-- The value of this string.
String:attr_reader("value")
-- Compares this string with the given string.
function String.methods:compare(obj)
if self.value < obj.value then
return -1
elseif self.value > obj.value then
return 1
else
return 0
end
end
-- Returns a string representation of the given string.
function String.methods:toString()
return self.value
end
-- Returns the concatenation of this string and the given string.
function String.methods:concat(obj)
return String.new(self.value .. obj.value)
end
--{
-- Provides a hash method for the String class.
-- Used in the hash method.
String.SHIFT = Integer.new(6)
-- Used in the hash method.
String.MASK =
Integer.new(0):NOT():lshift(Integer.BITS - String.SHIFT)
-- Returns a hash value for the given String.
function String.methods:hash()
local result = Integer.new(0)
for i = 1, string.len(self.value) do
local c = Integer.new(string.byte(self.value, i))
result = ( result:AND(String.MASK):XOR(
result:lshift(String.SHIFT) ) ):XOR(c)
end
return tonumber(result)
end
--}>a
-- String hash test program.
function String.testHash()
print "String hash test program."
printf("ett=0%o", hash("ett"))
printf("tva=0%o", hash("tva"))
printf("tre=0%o", hash("tre"))
printf("fyra=0%o", hash("fyra"))
printf("fem=0%o", hash("fem"))
printf("sex=0%o", hash("sex"))
printf("sju=0%o", hash("sju"))
printf("atta=0%o", hash("atta"))
printf("nio=0%o", hash("nio"))
printf("tio=0%o", hash("tio"))
printf("elva=0%o", hash("elva"))
printf("tolv=0%o", hash("tolv"))
printf("abcdefghijklmnopqrstuvwxy=0%o",
hash("abcdefghijklmnopqrstuvwxyz"))
printf("ece.uwaterloo.ca=0%o", hash("ece.uwaterloo.ca"))
printf("cs.uwaterloo.ca=0%o", hash("cs.uwaterloo.ca"))
printf("un=0%o", hash("un"))
printf("deux=0%o", hash("deux"))
printf("trois=0%o", hash("trois"))
printf("quatre=0%o", hash("quatre"))
printf("cinq=0%o", hash("cinq"))
printf("six=0%o", hash("six"))
printf("sept=0%o", hash("sept"))
printf("huit=0%o", hash("huit"))
printf("neuf=0%o", hash("neuf"))
printf("dix=0%o", hash("dix"))
printf("onze=0%o", hash("onze"))
printf("douze=0%o", hash("douze"))
end
-- String test program.
-- @param arg Command-line arguments.
function String.main(arg)
print "String test program."
local s1 = box("one")
local s2 = box("one")
local s3 = box("two")
print("s1 = ", s1)
print("s2 = ", s2)
print("s3 = ", s3)
print("s1 < s2", s1 < s2)
print("s1 == s2", s1 == s2)
print("s1:is(s2)", s1:is(s2))
print("s1 > s2", s1 > s2)
print("s1 .. s2", s1 .. s2)
print(unbox(s1))
print(unbox(s2))
print(unbox(s3))
String.testHash()
print(String)
end
if _REQUIREDNAME == nil then
os.exit( String.main(arg) )
end
| apache-2.0 |
starlightknight/darkstar | scripts/zones/Norg/npcs/Ryoma.lua | 9 | 4100 | -----------------------------------
-- Area: Norg
-- NPC: Ryoma
-- Start and Finish Quest: 20 in Pirate Years, I'll Take the Big Box, True Will, Bugi Soden
-- Involved in Quest: Ayame and Kaede
-- !pos -23 0 -9 252
-----------------------------------
local ID = require("scripts/zones/Norg/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/settings")
require("scripts/globals/wsquest")
require("scripts/globals/quests")
require("scripts/globals/status")
require("scripts/globals/shop")
-----------------------------------
local wsQuest = dsp.wsquest.blade_ku
function onTrade(player,npc,trade)
local wsQuestEvent = dsp.wsquest.getTradeEvent(wsQuest,player,trade)
if (wsQuestEvent ~= nil) then
player:startEvent(wsQuestEvent)
end
end
function onTrigger(player,npc)
local wsQuestEvent = dsp.wsquest.getTriggerEvent(wsQuest,player)
local twentyInPirateYears = player:getQuestStatus(OUTLANDS,dsp.quest.id.outlands.TWENTY_IN_PIRATE_YEARS)
local illTakeTheBigBox = player:getQuestStatus(OUTLANDS,dsp.quest.id.outlands.I_LL_TAKE_THE_BIG_BOX)
local trueWill = player:getQuestStatus(OUTLANDS,dsp.quest.id.outlands.TRUE_WILL)
local mLvl = player:getMainLvl()
local mJob = player:getMainJob()
if (wsQuestEvent ~= nil) then
player:startEvent(wsQuestEvent)
elseif (player:getQuestStatus(BASTOK,dsp.quest.id.bastok.AYAME_AND_KAEDE) == QUEST_ACCEPTED) then
if (player:getCharVar("AyameAndKaede_Event") == 3) then
player:startEvent(95) -- During Quest "Ayame and Kaede"
else
player:startEvent(94)
end
elseif (twentyInPirateYears == QUEST_AVAILABLE and mJob == dsp.job.NIN and mLvl >= 40) then
player:startEvent(133) -- Start Quest "20 in Pirate Years"
elseif (twentyInPirateYears == QUEST_ACCEPTED and player:hasKeyItem(dsp.ki.TRICK_BOX)) then
player:startEvent(134) -- Finish Quest "20 in Pirate Years"
elseif (twentyInPirateYears == QUEST_COMPLETED and illTakeTheBigBox == QUEST_AVAILABLE and mJob == dsp.job.NIN and mLvl >= 50 and player:needToZone() == false) then
player:startEvent(135) -- Start Quest "I'll Take the Big Box"
elseif (illTakeTheBigBox == QUEST_COMPLETED and trueWill == QUEST_AVAILABLE) then
player:startEvent(136) -- Start Quest "True Will"
elseif (player:hasKeyItem(dsp.ki.OLD_TRICK_BOX) and player:getCharVar("trueWillCS") == 0) then
player:startEvent(137)
elseif (player:getCharVar("trueWillCS") == 1) then
player:startEvent(138)
else
player:startEvent(94)
end
end
function onEventFinish(player,csid,option)
if (csid == 95) then
player:addKeyItem(dsp.ki.SEALED_DAGGER)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.SEALED_DAGGER)
player:delKeyItem(dsp.ki.STRANGELY_SHAPED_CORAL)
player:setCharVar("AyameAndKaede_Event", 4)
elseif (csid == 133) then
player:addQuest(OUTLANDS,dsp.quest.id.outlands.TWENTY_IN_PIRATE_YEARS)
player:setCharVar("twentyInPirateYearsCS",1)
elseif (csid == 134) then
if (player:getFreeSlotsCount() <= 1) then
player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,17771)
else
player:delKeyItem(dsp.ki.TRICK_BOX)
player:addItem(17771)
player:addItem(17772)
player:messageSpecial(ID.text.ITEM_OBTAINED, 17771) -- Anju
player:messageSpecial(ID.text.ITEM_OBTAINED, 17772) -- Zushio
player:needToZone()
player:setCharVar("twentyInPirateYearsCS",0)
player:addFame(NORG,30)
player:completeQuest(OUTLANDS,dsp.quest.id.outlands.TWENTY_IN_PIRATE_YEARS)
end
elseif (csid == 135) then
player:addQuest(OUTLANDS,dsp.quest.id.outlands.I_LL_TAKE_THE_BIG_BOX)
elseif (csid == 136) then
player:addQuest(OUTLANDS,dsp.quest.id.outlands.TRUE_WILL)
elseif (csid == 137) then
player:setCharVar("trueWillCS",1)
else
dsp.wsquest.handleEventFinish(wsQuest,player,csid,option,ID.text.BLADE_KU_LEARNED)
end
end | gpl-3.0 |
starlightknight/darkstar | scripts/zones/Tavnazian_Safehold/Zone.lua | 9 | 2660 | -----------------------------------
--
-- Zone: Tavnazian_Safehold (26)
--
-----------------------------------
local ID = require("scripts/zones/Tavnazian_Safehold/IDs");
require("scripts/globals/conquest");
require("scripts/globals/settings");
require("scripts/globals/missions");
-----------------------------------
function onInitialize(zone)
zone:registerRegion(1, -5, -24, 18, 5, -20, 27);
zone:registerRegion(2, 104, -42, -88, 113, -38, -77);
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(27.971,-14.068,43.735,66);
end
if (player:getCurrentMission(COP) == dsp.mission.id.cop.AN_INVITATION_WEST) then
if (player:getCharVar("PromathiaStatus") == 1) then
cs = 101;
end
elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.SHELTERING_DOUBT and player:getCharVar("PromathiaStatus") == 0) then
cs = 107;
elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.CHAINS_AND_BONDS and player:getCharVar("PromathiaStatus") == 1) then
cs = 114;
end
return cs;
end;
function onRegionEnter(player,region)
switch (region:GetRegionID()): caseof
{
[1] = function (x)
if (player:getCurrentMission(COP) == dsp.mission.id.cop.AN_ETERNAL_MELODY and player:getCharVar("PromathiaStatus") == 2) then
player:startEvent(105);
end
end,
[2] = function (x)
if (player:getCurrentMission(COP) == dsp.mission.id.cop.SLANDEROUS_UTTERINGS and player:getCharVar("PromathiaStatus") == 0) then
player:startEvent(112);
end
end,
}
end;
function onRegionLeave(player,region)
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 101) then
player:completeMission(COP,dsp.mission.id.cop.AN_INVITATION_WEST);
player:addMission(COP,dsp.mission.id.cop.THE_LOST_CITY);
player:setCharVar("PromathiaStatus",0);
elseif (csid == 105) then
player:setCharVar("PromathiaStatus",0);
player:completeMission(COP,dsp.mission.id.cop.AN_ETERNAL_MELODY);
player:addMission(COP,dsp.mission.id.cop.ANCIENT_VOWS);
elseif (csid == 107) then
player:setCharVar("PromathiaStatus",1);
elseif (csid == 112) then
player:setCharVar("PromathiaStatus",1);
elseif (csid == 114) then
player:setCharVar("PromathiaStatus",2);
end
end; | gpl-3.0 |
gedads/Neodynamis | scripts/zones/Port_Windurst/npcs/Posso_Ruhbini.lua | 17 | 1550 | -----------------------------------
-- Area: Port Windurst
-- NPC: Posso Ruhbini
-- Regional Marchant NPC
-- Only sells when Windurst controlls Norvallen
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(NORVALLEN);
if (RegionOwner ~= NATION_WINDURST) then
player:showText(npc,POSSORUHBINI_CLOSED_DIALOG);
else
player:showText(npc,POSSORUHBINI_OPEN_DIALOG);
stock = {
0x02B0, 18, --Arrowwood Log
0x02BA, 87, --Ash Log
0x026A, 25, --Blue Peas
0x026D, 25 --Crying Mustard
}
showShop(player,WINDURST,stock);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/RuLude_Gardens/npcs/Radeivepart.lua | 9 | 2635 | -----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: Radeivepart
-- Starts and Finishes Quest: Northward
-- Involved in Quests: Save the Clock Tower
-- !pos 5 9 -39 243
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/shop");
require("scripts/globals/quests");
local ID = require("scripts/zones/RuLude_Gardens/IDs");
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(555,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then
local a = player:getCharVar("saveTheClockTowerNPCz1"); -- NPC Zone1
if (a == 0 or (a ~= 1 and a ~= 3 and a ~= 5 and a ~= 9 and a ~= 17 and a ~= 7 and a ~= 25 and a ~= 11 and
a ~= 13 and a ~= 19 and a ~= 21 and a ~= 15 and a ~= 23 and a ~= 27 and a ~= 29 and a ~= 31)) then
player:startEvent(160,10 - player:getCharVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest
end
elseif (player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.NORTHWARD) == QUEST_ACCEPTED) then
if (trade:hasItemQty(16522,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then
player:startEvent(61); -- Finish quest "Northward"
end
end
end;
function onTrigger(player,npc)
local northward = player:getQuestStatus(JEUNO, dsp.quest.id.jeuno.NORTHWARD);
if (player:getFameLevel(JEUNO) >= 4 and northward == QUEST_AVAILABLE) then
player:startEvent(159, 1, 0, 0, 0, 0, 0, 8);
elseif (northward == QUEST_ACCEPTED) then
player:startEvent(159, 2, 0, 0, 0, 0, 0, 8);
elseif (northward == QUEST_COMPLETED) then
player:startEvent(159, 3, 0, 0, 0, 0, 0, 8);
else
-- Standard dialogue
player:startEvent(159);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 160) then
player:addCharVar("saveTheClockTowerVar", 1);
player:addCharVar("saveTheClockTowerNPCz1", 1);
elseif (csid == 159 and option == 1) then
player:addQuest(JEUNO, dsp.quest.id.jeuno.NORTHWARD);
elseif (csid == 61) then
player:completeQuest(JEUNO, dsp.quest.id.jeuno.NORTHWARD);
player:addTitle(dsp.title.ENVOY_TO_THE_NORTH);
if (player:hasKeyItem(dsp.ki.MAP_OF_CASTLE_ZVAHL) == false) then
player:addKeyItem(dsp.ki.MAP_OF_CASTLE_ZVAHL);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.MAP_OF_CASTLE_ZVAHL);
end
player:addFame(JEUNO, 30);
player:tradeComplete();
end
end;
| gpl-3.0 |
soulgame/slua | jit/jit/dis_arm64.lua | 59 | 30904 | ----------------------------------------------------------------------------
-- LuaJIT ARM64 disassembler module.
--
-- Copyright (C) 2005-2017 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
--
-- Contributed by Djordje Kovacevic and Stefan Pejic from RT-RK.com.
-- Sponsored by Cisco Systems, Inc.
----------------------------------------------------------------------------
-- This is a helper module used by the LuaJIT machine code dumper module.
--
-- It disassembles most user-mode AArch64 instructions.
-- NYI: Advanced SIMD and VFP instructions.
------------------------------------------------------------------------------
local type = type
local sub, byte, format = string.sub, string.byte, string.format
local match, gmatch, gsub = string.match, string.gmatch, string.gsub
local concat = table.concat
local bit = require("bit")
local band, bor, bxor, tohex = bit.band, bit.bor, bit.bxor, bit.tohex
local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift
local ror = bit.ror
------------------------------------------------------------------------------
-- Opcode maps
------------------------------------------------------------------------------
local map_adr = { -- PC-relative addressing.
shift = 31, mask = 1,
[0] = "adrDBx", "adrpDBx"
}
local map_addsubi = { -- Add/subtract immediate.
shift = 29, mask = 3,
[0] = "add|movDNIg", "adds|cmnD0NIg", "subDNIg", "subs|cmpD0NIg",
}
local map_logi = { -- Logical immediate.
shift = 31, mask = 1,
[0] = {
shift = 22, mask = 1,
[0] = {
shift = 29, mask = 3,
[0] = "andDNig", "orr|movDN0ig", "eorDNig", "ands|tstD0Nig"
},
false -- unallocated
},
{
shift = 29, mask = 3,
[0] = "andDNig", "orr|movDN0ig", "eorDNig", "ands|tstD0Nig"
}
}
local map_movwi = { -- Move wide immediate.
shift = 31, mask = 1,
[0] = {
shift = 22, mask = 1,
[0] = {
shift = 29, mask = 3,
[0] = "movnDWRg", false, "movz|movDYRg", "movkDWRg"
}, false -- unallocated
},
{
shift = 29, mask = 3,
[0] = "movnDWRg", false, "movz|movDYRg", "movkDWRg"
},
}
local map_bitf = { -- Bitfield.
shift = 31, mask = 1,
[0] = {
shift = 22, mask = 1,
[0] = {
shift = 29, mask = 3,
[0] = "sbfm|sbfiz|sbfx|asr|sxtw|sxth|sxtbDN12w",
"bfm|bfi|bfxilDN13w",
"ubfm|ubfiz|ubfx|lsr|lsl|uxth|uxtbDN12w"
}
},
{
shift = 22, mask = 1,
{
shift = 29, mask = 3,
[0] = "sbfm|sbfiz|sbfx|asr|sxtw|sxth|sxtbDN12x",
"bfm|bfi|bfxilDN13x",
"ubfm|ubfiz|ubfx|lsr|lsl|uxth|uxtbDN12x"
}
}
}
local map_datai = { -- Data processing - immediate.
shift = 23, mask = 7,
[0] = map_adr, map_adr, map_addsubi, false,
map_logi, map_movwi, map_bitf,
{
shift = 15, mask = 0x1c0c1,
[0] = "extr|rorDNM4w", [0x10080] = "extr|rorDNM4x",
[0x10081] = "extr|rorDNM4x"
}
}
local map_logsr = { -- Logical, shifted register.
shift = 31, mask = 1,
[0] = {
shift = 15, mask = 1,
[0] = {
shift = 29, mask = 3,
[0] = {
shift = 21, mask = 7,
[0] = "andDNMSg", "bicDNMSg", "andDNMSg", "bicDNMSg",
"andDNMSg", "bicDNMSg", "andDNMg", "bicDNMg"
},
{
shift = 21, mask = 7,
[0] ="orr|movDN0MSg", "orn|mvnDN0MSg", "orr|movDN0MSg", "orn|mvnDN0MSg",
"orr|movDN0MSg", "orn|mvnDN0MSg", "orr|movDN0Mg", "orn|mvnDN0Mg"
},
{
shift = 21, mask = 7,
[0] = "eorDNMSg", "eonDNMSg", "eorDNMSg", "eonDNMSg",
"eorDNMSg", "eonDNMSg", "eorDNMg", "eonDNMg"
},
{
shift = 21, mask = 7,
[0] = "ands|tstD0NMSg", "bicsDNMSg", "ands|tstD0NMSg", "bicsDNMSg",
"ands|tstD0NMSg", "bicsDNMSg", "ands|tstD0NMg", "bicsDNMg"
}
},
false -- unallocated
},
{
shift = 29, mask = 3,
[0] = {
shift = 21, mask = 7,
[0] = "andDNMSg", "bicDNMSg", "andDNMSg", "bicDNMSg",
"andDNMSg", "bicDNMSg", "andDNMg", "bicDNMg"
},
{
shift = 21, mask = 7,
[0] = "orr|movDN0MSg", "orn|mvnDN0MSg", "orr|movDN0MSg", "orn|mvnDN0MSg",
"orr|movDN0MSg", "orn|mvnDN0MSg", "orr|movDN0Mg", "orn|mvnDN0Mg"
},
{
shift = 21, mask = 7,
[0] = "eorDNMSg", "eonDNMSg", "eorDNMSg", "eonDNMSg",
"eorDNMSg", "eonDNMSg", "eorDNMg", "eonDNMg"
},
{
shift = 21, mask = 7,
[0] = "ands|tstD0NMSg", "bicsDNMSg", "ands|tstD0NMSg", "bicsDNMSg",
"ands|tstD0NMSg", "bicsDNMSg", "ands|tstD0NMg", "bicsDNMg"
}
}
}
local map_assh = {
shift = 31, mask = 1,
[0] = {
shift = 15, mask = 1,
[0] = {
shift = 29, mask = 3,
[0] = {
shift = 22, mask = 3,
[0] = "addDNMSg", "addDNMSg", "addDNMSg", "addDNMg"
},
{
shift = 22, mask = 3,
[0] = "adds|cmnD0NMSg", "adds|cmnD0NMSg",
"adds|cmnD0NMSg", "adds|cmnD0NMg"
},
{
shift = 22, mask = 3,
[0] = "sub|negDN0MSg", "sub|negDN0MSg", "sub|negDN0MSg", "sub|negDN0Mg"
},
{
shift = 22, mask = 3,
[0] = "subs|cmp|negsD0N0MzSg", "subs|cmp|negsD0N0MzSg",
"subs|cmp|negsD0N0MzSg", "subs|cmp|negsD0N0Mzg"
},
},
false -- unallocated
},
{
shift = 29, mask = 3,
[0] = {
shift = 22, mask = 3,
[0] = "addDNMSg", "addDNMSg", "addDNMSg", "addDNMg"
},
{
shift = 22, mask = 3,
[0] = "adds|cmnD0NMSg", "adds|cmnD0NMSg", "adds|cmnD0NMSg",
"adds|cmnD0NMg"
},
{
shift = 22, mask = 3,
[0] = "sub|negDN0MSg", "sub|negDN0MSg", "sub|negDN0MSg", "sub|negDN0Mg"
},
{
shift = 22, mask = 3,
[0] = "subs|cmp|negsD0N0MzSg", "subs|cmp|negsD0N0MzSg",
"subs|cmp|negsD0N0MzSg", "subs|cmp|negsD0N0Mzg"
}
}
}
local map_addsubsh = { -- Add/subtract, shifted register.
shift = 22, mask = 3,
[0] = map_assh, map_assh, map_assh
}
local map_addsubex = { -- Add/subtract, extended register.
shift = 22, mask = 3,
[0] = {
shift = 29, mask = 3,
[0] = "addDNMXg", "adds|cmnD0NMXg", "subDNMXg", "subs|cmpD0NMzXg",
}
}
local map_addsubc = { -- Add/subtract, with carry.
shift = 10, mask = 63,
[0] = {
shift = 29, mask = 3,
[0] = "adcDNMg", "adcsDNMg", "sbc|ngcDN0Mg", "sbcs|ngcsDN0Mg",
}
}
local map_ccomp = {
shift = 4, mask = 1,
[0] = {
shift = 10, mask = 3,
[0] = { -- Conditional compare register.
shift = 29, mask = 3,
"ccmnNMVCg", false, "ccmpNMVCg",
},
[2] = { -- Conditional compare immediate.
shift = 29, mask = 3,
"ccmnN5VCg", false, "ccmpN5VCg",
}
}
}
local map_csel = { -- Conditional select.
shift = 11, mask = 1,
[0] = {
shift = 10, mask = 1,
[0] = {
shift = 29, mask = 3,
[0] = "cselDNMzCg", false, "csinv|cinv|csetmDNMcg", false,
},
{
shift = 29, mask = 3,
[0] = "csinc|cinc|csetDNMcg", false, "csneg|cnegDNMcg", false,
}
}
}
local map_data1s = { -- Data processing, 1 source.
shift = 29, mask = 1,
[0] = {
shift = 31, mask = 1,
[0] = {
shift = 10, mask = 0x7ff,
[0] = "rbitDNg", "rev16DNg", "revDNw", false, "clzDNg", "clsDNg"
},
{
shift = 10, mask = 0x7ff,
[0] = "rbitDNg", "rev16DNg", "rev32DNx", "revDNx", "clzDNg", "clsDNg"
}
}
}
local map_data2s = { -- Data processing, 2 sources.
shift = 29, mask = 1,
[0] = {
shift = 10, mask = 63,
false, "udivDNMg", "sdivDNMg", false, false, false, false, "lslDNMg",
"lsrDNMg", "asrDNMg", "rorDNMg"
}
}
local map_data3s = { -- Data processing, 3 sources.
shift = 29, mask = 7,
[0] = {
shift = 21, mask = 7,
[0] = {
shift = 15, mask = 1,
[0] = "madd|mulDNMA0g", "msub|mnegDNMA0g"
}
}, false, false, false,
{
shift = 15, mask = 1,
[0] = {
shift = 21, mask = 7,
[0] = "madd|mulDNMA0g", "smaddl|smullDxNMwA0x", "smulhDNMx", false,
false, "umaddl|umullDxNMwA0x", "umulhDNMx"
},
{
shift = 21, mask = 7,
[0] = "msub|mnegDNMA0g", "smsubl|smneglDxNMwA0x", false, false,
false, "umsubl|umneglDxNMwA0x"
}
}
}
local map_datar = { -- Data processing, register.
shift = 28, mask = 1,
[0] = {
shift = 24, mask = 1,
[0] = map_logsr,
{
shift = 21, mask = 1,
[0] = map_addsubsh, map_addsubex
}
},
{
shift = 21, mask = 15,
[0] = map_addsubc, false, map_ccomp, false, map_csel, false,
{
shift = 30, mask = 1,
[0] = map_data2s, map_data1s
},
false, map_data3s, map_data3s, map_data3s, map_data3s, map_data3s,
map_data3s, map_data3s, map_data3s
}
}
local map_lrl = { -- Load register, literal.
shift = 26, mask = 1,
[0] = {
shift = 30, mask = 3,
[0] = "ldrDwB", "ldrDxB", "ldrswDxB"
},
{
shift = 30, mask = 3,
[0] = "ldrDsB", "ldrDdB"
}
}
local map_lsriind = { -- Load/store register, immediate pre/post-indexed.
shift = 30, mask = 3,
[0] = {
shift = 26, mask = 1,
[0] = {
shift = 22, mask = 3,
[0] = "strbDwzL", "ldrbDwzL", "ldrsbDxzL", "ldrsbDwzL"
}
},
{
shift = 26, mask = 1,
[0] = {
shift = 22, mask = 3,
[0] = "strhDwzL", "ldrhDwzL", "ldrshDxzL", "ldrshDwzL"
}
},
{
shift = 26, mask = 1,
[0] = {
shift = 22, mask = 3,
[0] = "strDwzL", "ldrDwzL", "ldrswDxzL"
},
{
shift = 22, mask = 3,
[0] = "strDszL", "ldrDszL"
}
},
{
shift = 26, mask = 1,
[0] = {
shift = 22, mask = 3,
[0] = "strDxzL", "ldrDxzL"
},
{
shift = 22, mask = 3,
[0] = "strDdzL", "ldrDdzL"
}
}
}
local map_lsriro = {
shift = 21, mask = 1,
[0] = { -- Load/store register immediate.
shift = 10, mask = 3,
[0] = { -- Unscaled immediate.
shift = 26, mask = 1,
[0] = {
shift = 30, mask = 3,
[0] = {
shift = 22, mask = 3,
[0] = "sturbDwK", "ldurbDwK"
},
{
shift = 22, mask = 3,
[0] = "sturhDwK", "ldurhDwK"
},
{
shift = 22, mask = 3,
[0] = "sturDwK", "ldurDwK"
},
{
shift = 22, mask = 3,
[0] = "sturDxK", "ldurDxK"
}
}
}, map_lsriind, false, map_lsriind
},
{ -- Load/store register, register offset.
shift = 10, mask = 3,
[2] = {
shift = 26, mask = 1,
[0] = {
shift = 30, mask = 3,
[0] = {
shift = 22, mask = 3,
[0] = "strbDwO", "ldrbDwO", "ldrsbDxO", "ldrsbDwO"
},
{
shift = 22, mask = 3,
[0] = "strhDwO", "ldrhDwO", "ldrshDxO", "ldrshDwO"
},
{
shift = 22, mask = 3,
[0] = "strDwO", "ldrDwO", "ldrswDxO"
},
{
shift = 22, mask = 3,
[0] = "strDxO", "ldrDxO"
}
},
{
shift = 30, mask = 3,
[2] = {
shift = 22, mask = 3,
[0] = "strDsO", "ldrDsO"
},
[3] = {
shift = 22, mask = 3,
[0] = "strDdO", "ldrDdO"
}
}
}
}
}
local map_lsp = { -- Load/store register pair, offset.
shift = 22, mask = 1,
[0] = {
shift = 30, mask = 3,
[0] = {
shift = 26, mask = 1,
[0] = "stpDzAzwP", "stpDzAzsP",
},
{
shift = 26, mask = 1,
"stpDzAzdP"
},
{
shift = 26, mask = 1,
[0] = "stpDzAzxP"
}
},
{
shift = 30, mask = 3,
[0] = {
shift = 26, mask = 1,
[0] = "ldpDzAzwP", "ldpDzAzsP",
},
{
shift = 26, mask = 1,
[0] = "ldpswDAxP", "ldpDzAzdP"
},
{
shift = 26, mask = 1,
[0] = "ldpDzAzxP"
}
}
}
local map_ls = { -- Loads and stores.
shift = 24, mask = 0x31,
[0x10] = map_lrl, [0x30] = map_lsriro,
[0x20] = {
shift = 23, mask = 3,
map_lsp, map_lsp, map_lsp
},
[0x21] = {
shift = 23, mask = 3,
map_lsp, map_lsp, map_lsp
},
[0x31] = {
shift = 26, mask = 1,
[0] = {
shift = 30, mask = 3,
[0] = {
shift = 22, mask = 3,
[0] = "strbDwzU", "ldrbDwzU"
},
{
shift = 22, mask = 3,
[0] = "strhDwzU", "ldrhDwzU"
},
{
shift = 22, mask = 3,
[0] = "strDwzU", "ldrDwzU"
},
{
shift = 22, mask = 3,
[0] = "strDxzU", "ldrDxzU"
}
},
{
shift = 30, mask = 3,
[2] = {
shift = 22, mask = 3,
[0] = "strDszU", "ldrDszU"
},
[3] = {
shift = 22, mask = 3,
[0] = "strDdzU", "ldrDdzU"
}
}
},
}
local map_datafp = { -- Data processing, SIMD and FP.
shift = 28, mask = 7,
{ -- 001
shift = 24, mask = 1,
[0] = {
shift = 21, mask = 1,
{
shift = 10, mask = 3,
[0] = {
shift = 12, mask = 1,
[0] = {
shift = 13, mask = 1,
[0] = {
shift = 14, mask = 1,
[0] = {
shift = 15, mask = 1,
[0] = { -- FP/int conversion.
shift = 31, mask = 1,
[0] = {
shift = 16, mask = 0xff,
[0x20] = "fcvtnsDwNs", [0x21] = "fcvtnuDwNs",
[0x22] = "scvtfDsNw", [0x23] = "ucvtfDsNw",
[0x24] = "fcvtasDwNs", [0x25] = "fcvtauDwNs",
[0x26] = "fmovDwNs", [0x27] = "fmovDsNw",
[0x28] = "fcvtpsDwNs", [0x29] = "fcvtpuDwNs",
[0x30] = "fcvtmsDwNs", [0x31] = "fcvtmuDwNs",
[0x38] = "fcvtzsDwNs", [0x39] = "fcvtzuDwNs",
[0x60] = "fcvtnsDwNd", [0x61] = "fcvtnuDwNd",
[0x62] = "scvtfDdNw", [0x63] = "ucvtfDdNw",
[0x64] = "fcvtasDwNd", [0x65] = "fcvtauDwNd",
[0x68] = "fcvtpsDwNd", [0x69] = "fcvtpuDwNd",
[0x70] = "fcvtmsDwNd", [0x71] = "fcvtmuDwNd",
[0x78] = "fcvtzsDwNd", [0x79] = "fcvtzuDwNd"
},
{
shift = 16, mask = 0xff,
[0x20] = "fcvtnsDxNs", [0x21] = "fcvtnuDxNs",
[0x22] = "scvtfDsNx", [0x23] = "ucvtfDsNx",
[0x24] = "fcvtasDxNs", [0x25] = "fcvtauDxNs",
[0x28] = "fcvtpsDxNs", [0x29] = "fcvtpuDxNs",
[0x30] = "fcvtmsDxNs", [0x31] = "fcvtmuDxNs",
[0x38] = "fcvtzsDxNs", [0x39] = "fcvtzuDxNs",
[0x60] = "fcvtnsDxNd", [0x61] = "fcvtnuDxNd",
[0x62] = "scvtfDdNx", [0x63] = "ucvtfDdNx",
[0x64] = "fcvtasDxNd", [0x65] = "fcvtauDxNd",
[0x66] = "fmovDxNd", [0x67] = "fmovDdNx",
[0x68] = "fcvtpsDxNd", [0x69] = "fcvtpuDxNd",
[0x70] = "fcvtmsDxNd", [0x71] = "fcvtmuDxNd",
[0x78] = "fcvtzsDxNd", [0x79] = "fcvtzuDxNd"
}
}
},
{ -- FP data-processing, 1 source.
shift = 31, mask = 1,
[0] = {
shift = 22, mask = 3,
[0] = {
shift = 15, mask = 63,
[0] = "fmovDNf", "fabsDNf", "fnegDNf",
"fsqrtDNf", false, "fcvtDdNs", false, false,
"frintnDNf", "frintpDNf", "frintmDNf", "frintzDNf",
"frintaDNf", false, "frintxDNf", "frintiDNf",
},
{
shift = 15, mask = 63,
[0] = "fmovDNf", "fabsDNf", "fnegDNf",
"fsqrtDNf", "fcvtDsNd", false, false, false,
"frintnDNf", "frintpDNf", "frintmDNf", "frintzDNf",
"frintaDNf", false, "frintxDNf", "frintiDNf",
}
}
}
},
{ -- FP compare.
shift = 31, mask = 1,
[0] = {
shift = 14, mask = 3,
[0] = {
shift = 23, mask = 1,
[0] = {
shift = 0, mask = 31,
[0] = "fcmpNMf", [8] = "fcmpNZf",
[16] = "fcmpeNMf", [24] = "fcmpeNZf",
}
}
}
}
},
{ -- FP immediate.
shift = 31, mask = 1,
[0] = {
shift = 5, mask = 31,
[0] = {
shift = 23, mask = 1,
[0] = "fmovDFf"
}
}
}
},
{ -- FP conditional compare.
shift = 31, mask = 1,
[0] = {
shift = 23, mask = 1,
[0] = {
shift = 4, mask = 1,
[0] = "fccmpNMVCf", "fccmpeNMVCf"
}
}
},
{ -- FP data-processing, 2 sources.
shift = 31, mask = 1,
[0] = {
shift = 23, mask = 1,
[0] = {
shift = 12, mask = 15,
[0] = "fmulDNMf", "fdivDNMf", "faddDNMf", "fsubDNMf",
"fmaxDNMf", "fminDNMf", "fmaxnmDNMf", "fminnmDNMf",
"fnmulDNMf"
}
}
},
{ -- FP conditional select.
shift = 31, mask = 1,
[0] = {
shift = 23, mask = 1,
[0] = "fcselDNMCf"
}
}
}
},
{ -- FP data-processing, 3 sources.
shift = 31, mask = 1,
[0] = {
shift = 15, mask = 1,
[0] = {
shift = 21, mask = 5,
[0] = "fmaddDNMAf", "fnmaddDNMAf"
},
{
shift = 21, mask = 5,
[0] = "fmsubDNMAf", "fnmsubDNMAf"
}
}
}
}
}
local map_br = { -- Branches, exception generating and system instructions.
shift = 29, mask = 7,
[0] = "bB",
{ -- Compare & branch, immediate.
shift = 24, mask = 3,
[0] = "cbzDBg", "cbnzDBg", "tbzDTBw", "tbnzDTBw"
},
{ -- Conditional branch, immediate.
shift = 24, mask = 3,
[0] = {
shift = 4, mask = 1,
[0] = {
shift = 0, mask = 15,
[0] = "beqB", "bneB", "bhsB", "bloB", "bmiB", "bplB", "bvsB", "bvcB",
"bhiB", "blsB", "bgeB", "bltB", "bgtB", "bleB", "balB"
}
}
}, false, "blB",
{ -- Compare & branch, immediate.
shift = 24, mask = 3,
[0] = "cbzDBg", "cbnzDBg", "tbzDTBx", "tbnzDTBx"
},
{
shift = 24, mask = 3,
[0] = { -- Exception generation.
shift = 0, mask = 0xe0001f,
[0x200000] = "brkW"
},
{ -- System instructions.
shift = 0, mask = 0x3fffff,
[0x03201f] = "nop"
},
{ -- Unconditional branch, register.
shift = 0, mask = 0xfffc1f,
[0x1f0000] = "brNx", [0x3f0000] = "blrNx",
[0x5f0000] = "retNx"
},
}
}
local map_init = {
shift = 25, mask = 15,
[0] = false, false, false, false, map_ls, map_datar, map_ls, map_datafp,
map_datai, map_datai, map_br, map_br, map_ls, map_datar, map_ls, map_datafp
}
------------------------------------------------------------------------------
local map_regs = { x = {}, w = {}, d = {}, s = {} }
for i=0,30 do
map_regs.x[i] = "x"..i
map_regs.w[i] = "w"..i
map_regs.d[i] = "d"..i
map_regs.s[i] = "s"..i
end
map_regs.x[31] = "sp"
map_regs.w[31] = "wsp"
map_regs.d[31] = "d31"
map_regs.s[31] = "s31"
local map_cond = {
[0] = "eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc",
"hi", "ls", "ge", "lt", "gt", "le", "al",
}
local map_shift = { [0] = "lsl", "lsr", "asr", }
local map_extend = {
[0] = "uxtb", "uxth", "uxtw", "uxtx", "sxtb", "sxth", "sxtw", "sxtx",
}
------------------------------------------------------------------------------
-- Output a nicely formatted line with an opcode and operands.
local function putop(ctx, text, operands)
local pos = ctx.pos
local extra = ""
if ctx.rel then
local sym = ctx.symtab[ctx.rel]
if sym then
extra = "\t->"..sym
end
end
if ctx.hexdump > 0 then
ctx.out(format("%08x %s %-5s %s%s\n",
ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra))
else
ctx.out(format("%08x %-5s %s%s\n",
ctx.addr+pos, text, concat(operands, ", "), extra))
end
ctx.pos = pos + 4
end
-- Fallback for unknown opcodes.
local function unknown(ctx)
return putop(ctx, ".long", { "0x"..tohex(ctx.op) })
end
local function match_reg(p, pat, regnum)
return map_regs[match(pat, p.."%w-([xwds])")][regnum]
end
local function fmt_hex32(x)
if x < 0 then
return tohex(x)
else
return format("%x", x)
end
end
local imm13_rep = { 0x55555555, 0x11111111, 0x01010101, 0x00010001, 0x00000001 }
local function decode_imm13(op)
local imms = band(rshift(op, 10), 63)
local immr = band(rshift(op, 16), 63)
if band(op, 0x00400000) == 0 then
local len = 5
if imms >= 56 then
if imms >= 60 then len = 1 else len = 2 end
elseif imms >= 48 then len = 3 elseif imms >= 32 then len = 4 end
local l = lshift(1, len)-1
local s = band(imms, l)
local r = band(immr, l)
local imm = ror(rshift(-1, 31-s), r)
if len ~= 5 then imm = band(imm, lshift(1, l)-1) + rshift(imm, 31-l) end
imm = imm * imm13_rep[len]
local ix = fmt_hex32(imm)
if rshift(op, 31) ~= 0 then
return ix..tohex(imm)
else
return ix
end
else
local lo, hi = -1, 0
if imms < 32 then lo = rshift(-1, 31-imms) else hi = rshift(-1, 63-imms) end
if immr ~= 0 then
lo, hi = ror(lo, immr), ror(hi, immr)
local x = immr == 32 and 0 or band(bxor(lo, hi), lshift(-1, 32-immr))
lo, hi = bxor(lo, x), bxor(hi, x)
if immr >= 32 then lo, hi = hi, lo end
end
if hi ~= 0 then
return fmt_hex32(hi)..tohex(lo)
else
return fmt_hex32(lo)
end
end
end
local function parse_immpc(op, name)
if name == "b" or name == "bl" then
return arshift(lshift(op, 6), 4)
elseif name == "adr" or name == "adrp" then
local immlo = band(rshift(op, 29), 3)
local immhi = lshift(arshift(lshift(op, 8), 13), 2)
return bor(immhi, immlo)
elseif name == "tbz" or name == "tbnz" then
return lshift(arshift(lshift(op, 13), 18), 2)
else
return lshift(arshift(lshift(op, 8), 13), 2)
end
end
local function parse_fpimm8(op)
local sign = band(op, 0x100000) == 0 and 1 or -1
local exp = bxor(rshift(arshift(lshift(op, 12), 5), 24), 0x80) - 131
local frac = 16+band(rshift(op, 13), 15)
return sign * frac * 2^exp
end
local function prefer_bfx(sf, uns, imms, immr)
if imms < immr or imms == 31 or imms == 63 then
return false
end
if immr == 0 then
if sf == 0 and (imms == 7 or imms == 15) then
return false
end
if sf ~= 0 and uns == 0 and (imms == 7 or imms == 15 or imms == 31) then
return false
end
end
return true
end
-- Disassemble a single instruction.
local function disass_ins(ctx)
local pos = ctx.pos
local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4)
local op = bor(lshift(b3, 24), lshift(b2, 16), lshift(b1, 8), b0)
local operands = {}
local suffix = ""
local last, name, pat
local map_reg
ctx.op = op
ctx.rel = nil
last = nil
local opat
opat = map_init[band(rshift(op, 25), 15)]
while type(opat) ~= "string" do
if not opat then return unknown(ctx) end
opat = opat[band(rshift(op, opat.shift), opat.mask)] or opat._
end
name, pat = match(opat, "^([a-z0-9]*)(.*)")
local altname, pat2 = match(pat, "|([a-z0-9_.|]*)(.*)")
if altname then pat = pat2 end
if sub(pat, 1, 1) == "." then
local s2, p2 = match(pat, "^([a-z0-9.]*)(.*)")
suffix = suffix..s2
pat = p2
end
local rt = match(pat, "[gf]")
if rt then
if rt == "g" then
map_reg = band(op, 0x80000000) ~= 0 and map_regs.x or map_regs.w
else
map_reg = band(op, 0x400000) ~= 0 and map_regs.d or map_regs.s
end
end
local second0, immr
for p in gmatch(pat, ".") do
local x = nil
if p == "D" then
local regnum = band(op, 31)
x = rt and map_reg[regnum] or match_reg(p, pat, regnum)
elseif p == "N" then
local regnum = band(rshift(op, 5), 31)
x = rt and map_reg[regnum] or match_reg(p, pat, regnum)
elseif p == "M" then
local regnum = band(rshift(op, 16), 31)
x = rt and map_reg[regnum] or match_reg(p, pat, regnum)
elseif p == "A" then
local regnum = band(rshift(op, 10), 31)
x = rt and map_reg[regnum] or match_reg(p, pat, regnum)
elseif p == "B" then
local addr = ctx.addr + pos + parse_immpc(op, name)
ctx.rel = addr
x = "0x"..tohex(addr)
elseif p == "T" then
x = bor(band(rshift(op, 26), 32), band(rshift(op, 19), 31))
elseif p == "V" then
x = band(op, 15)
elseif p == "C" then
x = map_cond[band(rshift(op, 12), 15)]
elseif p == "c" then
local rn = band(rshift(op, 5), 31)
local rm = band(rshift(op, 16), 31)
local cond = band(rshift(op, 12), 15)
local invc = bxor(cond, 1)
x = map_cond[cond]
if altname and cond ~= 14 and cond ~= 15 then
local a1, a2 = match(altname, "([^|]*)|(.*)")
if rn == rm then
local n = #operands
operands[n] = nil
x = map_cond[invc]
if rn ~= 31 then
if a1 then name = a1 else name = altname end
else
operands[n-1] = nil
name = a2
end
end
end
elseif p == "W" then
x = band(rshift(op, 5), 0xffff)
elseif p == "Y" then
x = band(rshift(op, 5), 0xffff)
local hw = band(rshift(op, 21), 3)
if altname and (hw == 0 or x ~= 0) then
name = altname
end
elseif p == "L" then
local rn = map_regs.x[band(rshift(op, 5), 31)]
local imm9 = arshift(lshift(op, 11), 23)
if band(op, 0x800) ~= 0 then
x = "["..rn..", #"..imm9.."]!"
else
x = "["..rn.."], #"..imm9
end
elseif p == "U" then
local rn = map_regs.x[band(rshift(op, 5), 31)]
local sz = band(rshift(op, 30), 3)
local imm12 = lshift(arshift(lshift(op, 10), 20), sz)
if imm12 ~= 0 then
x = "["..rn..", #"..imm12.."]"
else
x = "["..rn.."]"
end
elseif p == "K" then
local rn = map_regs.x[band(rshift(op, 5), 31)]
local imm9 = arshift(lshift(op, 11), 23)
if imm9 ~= 0 then
x = "["..rn..", #"..imm9.."]"
else
x = "["..rn.."]"
end
elseif p == "O" then
local rn, rm = map_regs.x[band(rshift(op, 5), 31)]
local m = band(rshift(op, 13), 1)
if m == 0 then
rm = map_regs.w[band(rshift(op, 16), 31)]
else
rm = map_regs.x[band(rshift(op, 16), 31)]
end
x = "["..rn..", "..rm
local opt = band(rshift(op, 13), 7)
local s = band(rshift(op, 12), 1)
local sz = band(rshift(op, 30), 3)
-- extension to be applied
if opt == 3 then
if s == 0 then x = x.."]"
else x = x..", lsl #"..sz.."]" end
elseif opt == 2 or opt == 6 or opt == 7 then
if s == 0 then x = x..", "..map_extend[opt].."]"
else x = x..", "..map_extend[opt].." #"..sz.."]" end
else
x = x.."]"
end
elseif p == "P" then
local opcv, sh = rshift(op, 26), 2
if opcv >= 0x2a then sh = 4 elseif opcv >= 0x1b then sh = 3 end
local imm7 = lshift(arshift(lshift(op, 10), 25), sh)
local rn = map_regs.x[band(rshift(op, 5), 31)]
local ind = band(rshift(op, 23), 3)
if ind == 1 then
x = "["..rn.."], #"..imm7
elseif ind == 2 then
if imm7 == 0 then
x = "["..rn.."]"
else
x = "["..rn..", #"..imm7.."]"
end
elseif ind == 3 then
x = "["..rn..", #"..imm7.."]!"
end
elseif p == "I" then
local shf = band(rshift(op, 22), 3)
local imm12 = band(rshift(op, 10), 0x0fff)
local rn, rd = band(rshift(op, 5), 31), band(op, 31)
if altname == "mov" and shf == 0 and imm12 == 0 and (rn == 31 or rd == 31) then
name = altname
x = nil
elseif shf == 0 then
x = imm12
elseif shf == 1 then
x = imm12..", lsl #12"
end
elseif p == "i" then
x = "#0x"..decode_imm13(op)
elseif p == "1" then
immr = band(rshift(op, 16), 63)
x = immr
elseif p == "2" then
x = band(rshift(op, 10), 63)
if altname then
local a1, a2, a3, a4, a5, a6 =
match(altname, "([^|]*)|([^|]*)|([^|]*)|([^|]*)|([^|]*)|(.*)")
local sf = band(rshift(op, 26), 32)
local uns = band(rshift(op, 30), 1)
if prefer_bfx(sf, uns, x, immr) then
name = a2
x = x - immr + 1
elseif immr == 0 and x == 7 then
local n = #operands
operands[n] = nil
if sf ~= 0 then
operands[n-1] = gsub(operands[n-1], "x", "w")
end
last = operands[n-1]
name = a6
x = nil
elseif immr == 0 and x == 15 then
local n = #operands
operands[n] = nil
if sf ~= 0 then
operands[n-1] = gsub(operands[n-1], "x", "w")
end
last = operands[n-1]
name = a5
x = nil
elseif x == 31 or x == 63 then
if x == 31 and immr == 0 and name == "sbfm" then
name = a4
local n = #operands
operands[n] = nil
if sf ~= 0 then
operands[n-1] = gsub(operands[n-1], "x", "w")
end
last = operands[n-1]
else
name = a3
end
x = nil
elseif band(x, 31) ~= 31 and immr == x+1 and name == "ubfm" then
name = a4
last = "#"..(sf+32 - immr)
operands[#operands] = last
x = nil
elseif x < immr then
name = a1
last = "#"..(sf+32 - immr)
operands[#operands] = last
x = x + 1
end
end
elseif p == "3" then
x = band(rshift(op, 10), 63)
if altname then
local a1, a2 = match(altname, "([^|]*)|(.*)")
if x < immr then
name = a1
local sf = band(rshift(op, 26), 32)
last = "#"..(sf+32 - immr)
operands[#operands] = last
x = x + 1
elseif x >= immr then
name = a2
x = x - immr + 1
end
end
elseif p == "4" then
x = band(rshift(op, 10), 63)
local rn = band(rshift(op, 5), 31)
local rm = band(rshift(op, 16), 31)
if altname and rn == rm then
local n = #operands
operands[n] = nil
last = operands[n-1]
name = altname
end
elseif p == "5" then
x = band(rshift(op, 16), 31)
elseif p == "S" then
x = band(rshift(op, 10), 63)
if x == 0 then x = nil
else x = map_shift[band(rshift(op, 22), 3)].." #"..x end
elseif p == "X" then
local opt = band(rshift(op, 13), 7)
-- Width specifier <R>.
if opt ~= 3 and opt ~= 7 then
last = map_regs.w[band(rshift(op, 16), 31)]
operands[#operands] = last
end
x = band(rshift(op, 10), 7)
-- Extension.
if opt == 2 + band(rshift(op, 31), 1) and
band(rshift(op, second0 and 5 or 0), 31) == 31 then
if x == 0 then x = nil
else x = "lsl #"..x end
else
if x == 0 then x = map_extend[band(rshift(op, 13), 7)]
else x = map_extend[band(rshift(op, 13), 7)].." #"..x end
end
elseif p == "R" then
x = band(rshift(op,21), 3)
if x == 0 then x = nil
else x = "lsl #"..x*16 end
elseif p == "z" then
local n = #operands
if operands[n] == "sp" then operands[n] = "xzr"
elseif operands[n] == "wsp" then operands[n] = "wzr"
end
elseif p == "Z" then
x = 0
elseif p == "F" then
x = parse_fpimm8(op)
elseif p == "g" or p == "f" or p == "x" or p == "w" or
p == "d" or p == "s" then
-- These are handled in D/N/M/A.
elseif p == "0" then
if last == "sp" or last == "wsp" then
local n = #operands
operands[n] = nil
last = operands[n-1]
if altname then
local a1, a2 = match(altname, "([^|]*)|(.*)")
if not a1 then
name = altname
elseif second0 then
name, altname = a2, a1
else
name, altname = a1, a2
end
end
end
second0 = true
else
assert(false)
end
if x then
last = x
if type(x) == "number" then x = "#"..x end
operands[#operands+1] = x
end
end
return putop(ctx, name..suffix, operands)
end
------------------------------------------------------------------------------
-- Disassemble a block of code.
local function disass_block(ctx, ofs, len)
if not ofs then ofs = 0 end
local stop = len and ofs+len or #ctx.code
ctx.pos = ofs
ctx.rel = nil
while ctx.pos < stop do disass_ins(ctx) end
end
-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len).
local function create(code, addr, out)
local ctx = {}
ctx.code = code
ctx.addr = addr or 0
ctx.out = out or io.write
ctx.symtab = {}
ctx.disass = disass_block
ctx.hexdump = 8
return ctx
end
-- Simple API: disassemble code (a string) at address and output via out.
local function disass(code, addr, out)
create(code, addr, out):disass()
end
-- Return register name for RID.
local function regname(r)
if r < 32 then return map_regs.x[r] end
return map_regs.d[r-32]
end
-- Public module functions.
return {
create = create,
disass = disass,
regname = regname
}
| mit |
starlightknight/darkstar | scripts/globals/spells/hojo_ni.lua | 12 | 1459 | -----------------------------------------
-- Spell: Hojo:Ni
-- Description: Inflicts Slow on target.
-- Edited from slow.lua
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/magic")
require("scripts/globals/msg")
-----------------------------------------
function onMagicCastingCheck(caster, target, spell)
return 0
end
function onSpellCast(caster, target, spell)
local dINT = caster:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT)
--Power for Hojo is a flat 19.5% reduction
local power = 2000
--Duration and Resistance calculation
local duration = 300
local params = {}
params.attribute = dsp.mod.INT
params.skillType = dsp.skill.NINJUTSU
params.bonus = 0
duration = duration * applyResistance(caster, target, spell, params)
--Calculates the resist chance from Resist Blind trait
if math.random(0,100) >= target:getMod(dsp.mod.SLOWRES) then
-- Spell succeeds if a 1 or 1/2 resist check is achieved
if duration >= 150 then
if target:addStatusEffect(dsp.effect.SLOW, power, 0, duration) then
spell:setMsg(dsp.msg.basic.MAGIC_ENFEEB_IS)
else
spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT)
end
else
spell:setMsg(dsp.msg.basic.MAGIC_RESIST)
end
else
spell:setMsg(dsp.msg.basic.MAGIC_RESIST_2)
end
return dsp.effect.SLOW
end
| gpl-3.0 |
Craige/prosody-modules | mod_statistics/stats.lib.lua | 32 | 4506 | local it = require "util.iterators";
local log = require "util.logger".init("stats");
local has_pposix, pposix = pcall(require, "util.pposix");
local human;
do
local tostring = tostring;
local s_format = string.format;
local m_floor = math.floor;
local m_max = math.max;
local prefixes = "kMGTPEZY";
local multiplier = 1024;
function human(num)
num = tonumber(num) or 0;
local m = 0;
while num >= multiplier and m < #prefixes do
num = num / multiplier;
m = m + 1;
end
return s_format("%0."..m_max(0,3-#tostring(m_floor(num))).."f%sB",
num, m > 0 and (prefixes:sub(m,m) .. "i") or "");
end
end
local last_cpu_wall, last_cpu_clock;
local get_time = require "socket".gettime;
local active_sessions, active_jids = {}, {};
local c2s_sessions, s2s_sessions;
if prosody and prosody.arg then
c2s_sessions, s2s_sessions = module:shared("/*/c2s/sessions", "/*/s2s/sessions");
end
local stats = {
total_users = {
get = function () return it.count(it.keys(bare_sessions)); end
};
total_c2s = {
get = function () return it.count(it.keys(full_sessions)); end
};
total_s2sin = {
get = function () local i = 0; for conn,sess in next,s2s_sessions do if sess.direction == "incoming" then i = i + 1 end end return i end
};
total_s2sout = {
get = function () local i = 0; for conn,sess in next,s2s_sessions do if sess.direction == "outgoing" then i = i + 1 end end return i end
};
total_s2s = {
get = function () return it.count(it.keys(s2s_sessions)); end
};
total_component = {
get = function ()
local count = 0;
for host, host_session in pairs(hosts) do
if host_session.type == "component" then
local c = host_session.modules.component;
if c and c.connected then -- 0.9 only
count = count + 1;
end
end
end
return count;
end
};
up_since = {
get = function () return prosody.start_time; end;
tostring = function (up_since)
return tostring(os.time()-up_since).."s";
end;
};
memory_lua = {
get = function () return math.ceil(collectgarbage("count")*1024); end;
tostring = human;
};
time = {
tostring = function () return os.date("%T"); end;
};
cpu = {
get = function ()
local new_wall, new_clock = get_time(), os.clock();
local pc = 0;
if last_cpu_wall then
pc = 100/((new_wall-last_cpu_wall)/(new_clock-last_cpu_clock));
end
last_cpu_wall, last_cpu_clock = new_wall, new_clock;
return math.ceil(pc);
end;
tostring = "%s%%";
};
};
if has_pposix and pposix.meminfo then
stats.memory_allocated = {
get = function () return math.ceil(pposix.meminfo().allocated); end;
tostring = human;
}
stats.memory_used = {
get = function () return math.ceil(pposix.meminfo().used); end;
tostring = human;
}
stats.memory_unused = {
get = function () return math.ceil(pposix.meminfo().unused); end;
tostring = human;
}
stats.memory_returnable = {
get = function () return math.ceil(pposix.meminfo().returnable); end;
tostring = human;
}
end
local add_statistics_filter; -- forward decl
if prosody and prosody.arg then -- ensures we aren't in prosodyctl
setmetatable(active_sessions, {
__index = function ( t, k )
local v = {
bytes_in = 0, bytes_out = 0;
stanzas_in = {
message = 0, presence = 0, iq = 0;
};
stanzas_out = {
message = 0, presence = 0, iq = 0;
};
}
rawset(t, k, v);
return v;
end
});
local filters = require "util.filters";
local function handle_stanza_in(stanza, session)
local s = active_sessions[session].stanzas_in;
local n = s[stanza.name];
if n then
s[stanza.name] = n + 1;
end
return stanza;
end
local function handle_stanza_out(stanza, session)
local s = active_sessions[session].stanzas_out;
local n = s[stanza.name];
if n then
s[stanza.name] = n + 1;
end
return stanza;
end
local function handle_bytes_in(bytes, session)
local s = active_sessions[session];
s.bytes_in = s.bytes_in + #bytes;
return bytes;
end
local function handle_bytes_out(bytes, session)
local s = active_sessions[session];
s.bytes_out = s.bytes_out + #bytes;
return bytes;
end
function add_statistics_filter(session)
filters.add_filter(session, "stanzas/in", handle_stanza_in);
filters.add_filter(session, "stanzas/out", handle_stanza_out);
filters.add_filter(session, "bytes/in", handle_bytes_in);
filters.add_filter(session, "bytes/out", handle_bytes_out);
end
end
return {
stats = stats;
active_sessions = active_sessions;
filter_hook = add_statistics_filter;
};
| mit |
gedads/Neodynamis | scripts/globals/items/truelove_chocolate.lua | 12 | 1219 | -----------------------------------------
-- ID: 5231
-- Item: truelove_chocolate
-- Food Effect: 4Hrs, All Races
-----------------------------------------
-- MP 10
-- MP Recovered While Healing 4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5231);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 10);
target:addMod(MOD_MPHEAL, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 10);
target:delMod(MOD_MPHEAL, 4);
end;
| gpl-3.0 |
O-P-E-N/CC-ROUTER | feeds/luci/applications/luci-app-asterisk/luasrc/model/cbi/asterisk/trunk_sip.lua | 68 | 2351 | -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local ast = require("luci.asterisk")
--
-- SIP trunk info
--
if arg[2] == "info" then
form = SimpleForm("asterisk", "SIP Trunk Information")
form.reset = false
form.submit = "Back to overview"
local info, keys = ast.sip.peer(arg[1])
local data = { }
for _, key in ipairs(keys) do
data[#data+1] = {
key = key,
val = type(info[key]) == "boolean"
and ( info[key] and "yes" or "no" )
or ( info[key] == nil or #info[key] == 0 )
and "(none)"
or tostring(info[key])
}
end
itbl = form:section(Table, data, "SIP Trunk %q" % arg[1])
itbl:option(DummyValue, "key", "Key")
itbl:option(DummyValue, "val", "Value")
function itbl.parse(...)
luci.http.redirect(
luci.dispatcher.build_url("admin", "asterisk", "trunks")
)
end
return form
--
-- SIP trunk config
--
elseif arg[1] then
cbimap = Map("asterisk", "Edit SIP Trunk")
peer = cbimap:section(NamedSection, arg[1])
peer.hidden = {
type = "peer",
qualify = "yes",
}
back = peer:option(DummyValue, "_overview", "Back to trunk overview")
back.value = ""
back.titleref = luci.dispatcher.build_url("admin", "asterisk", "trunks")
sipdomain = peer:option(Value, "host", "SIP Domain")
sipport = peer:option(Value, "port", "SIP Port")
function sipport.cfgvalue(...)
return AbstractValue.cfgvalue(...) or "5060"
end
username = peer:option(Value, "username", "Authorization ID")
password = peer:option(Value, "secret", "Authorization Password")
password.password = true
outboundproxy = peer:option(Value, "outboundproxy", "Outbound Proxy")
outboundport = peer:option(Value, "outboundproxyport", "Outbound Proxy Port")
register = peer:option(Flag, "register", "Register with peer")
register.enabled = "yes"
register.disabled = "no"
regext = peer:option(Value, "registerextension", "Extension to register (optional)")
regext:depends({register="1"})
didval = peer:option(ListValue, "_did", "Number of assigned DID numbers")
didval:value("", "(none)")
for i=1,24 do didval:value(i) end
dialplan = peer:option(ListValue, "context", "Dialplan Context")
dialplan:value(arg[1] .. "_inbound", "(default)")
cbimap.uci:foreach("asterisk", "dialplan",
function(s) dialplan:value(s['.name']) end)
return cbimap
end
| gpl-2.0 |
starlightknight/darkstar | scripts/globals/mobskills/earth_pounder.lua | 11 | 1039 | ---------------------------------------------
-- Earth Pounder
--
-- Description: Deals Earth damage to enemies within area of effect. Additional effect: Dexterity Down
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadows
-- Range: 15' radial
-- Notes:
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local typeEffect = dsp.effect.DEX_DOWN
MobStatusEffectMove(mob, target, typeEffect, 10, 3, 120)
local dmgmod = 1
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*4,dsp.magic.ele.EARTH,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.EARTH,MOBPARAM_WIPE_SHADOWS)
target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.EARTH)
return dmg
end
| gpl-3.0 |
Craige/prosody-modules | mod_register_web/mod_register_web.lua | 27 | 5718 | local captcha_options = module:get_option("captcha_options", {});
local nodeprep = require "util.encodings".stringprep.nodeprep;
local usermanager = require "core.usermanager";
local http = require "net.http";
local path_sep = package.config:sub(1,1);
module:depends"http";
local extra_fields = {
nick = true; name = true; first = true; last = true; email = true;
address = true; city = true; state = true; zip = true;
phone = true; url = true; date = true;
}
local template_path = module:get_option_string("register_web_template", "templates");
function template(data)
-- Like util.template, but deals with plain text
return { apply = function(values) return (data:gsub("{([^}]+)}", values)); end }
end
local function get_template(name)
local fh = assert(module:load_resource(template_path..path_sep..name..".html"));
local data = assert(fh:read("*a"));
fh:close();
return template(data);
end
local function render(template, data)
return tostring(template.apply(data));
end
local register_tpl = get_template "register";
local success_tpl = get_template "success";
if next(captcha_options) ~= nil then
local recaptcha_tpl = get_template "recaptcha";
function generate_captcha(display_options)
return recaptcha_tpl.apply(setmetatable({
recaptcha_display_error = display_options and display_options.recaptcha_error
and ("&error="..display_options.recaptcha_error) or "";
}, {
__index = function (t, k)
if captcha_options[k] then return captcha_options[k]; end
module:log("error", "Missing parameter from captcha_options: %s", k);
end
}));
end
function verify_captcha(request, form, callback)
http.request("https://www.google.com/recaptcha/api/verify", {
body = http.formencode {
privatekey = captcha_options.recaptcha_private_key;
remoteip = request.conn:ip();
challenge = form.recaptcha_challenge_field;
response = form.recaptcha_response_field;
};
}, function (verify_result, code)
local verify_ok, verify_err = verify_result:match("^([^\n]+)\n([^\n]+)");
if verify_ok == "true" then
callback(true);
else
callback(false, verify_err)
end
end);
end
else
module:log("debug", "No Recaptcha options set, using fallback captcha")
local random = math.random;
local hmac_sha1 = require "util.hashes".hmac_sha1;
local secret = require "util.uuid".generate()
local ops = { '+', '-' };
local captcha_tpl = get_template "simplecaptcha";
function generate_captcha()
local op = ops[random(1, #ops)];
local x, y = random(1, 9)
repeat
y = random(1, 9);
until x ~= y;
local answer;
if op == '+' then
answer = x + y;
elseif op == '-' then
if x < y then
-- Avoid negative numbers
x, y = y, x;
end
answer = x - y;
end
local challenge = hmac_sha1(secret, answer, true);
return captcha_tpl.apply {
op = op, x = x, y = y, challenge = challenge;
};
end
function verify_captcha(request, form, callback)
if hmac_sha1(secret, form.captcha_reply, true) == form.captcha_challenge then
callback(true);
else
callback(false, "Captcha verification failed");
end
end
end
function generate_page(event, display_options)
local request, response = event.request, event.response;
response.headers.content_type = "text/html; charset=utf-8";
return render(register_tpl, {
path = request.path; hostname = module.host;
notice = display_options and display_options.register_error or "";
captcha = generate_captcha(display_options);
})
end
function register_user(form, origin)
local prepped_username = nodeprep(form.username);
if not prepped_username then
return nil, "Username contains forbidden characters";
end
if #prepped_username == 0 then
return nil, "The username field was empty";
end
if usermanager.user_exists(prepped_username, module.host) then
return nil, "Username already taken";
end
local registering = { username = prepped_username , host = module.host, allowed = true }
module:fire_event("user-registering", registering);
if not registering.allowed then
return nil, "Registration not allowed";
end
local ok, err = usermanager.create_user(prepped_username, form.password, module.host);
if ok then
local extra_data = {};
for field in pairs(extra_fields) do
local field_value = form[field];
if field_value and #field_value > 0 then
extra_data[field] = field_value;
end
end
if next(extra_data) ~= nil then
datamanager.store(prepped_username, module.host, "account_details", extra_data);
end
module:fire_event("user-registered", {
username = prepped_username,
host = module.host,
source = module.name,
ip = origin.conn:ip(),
});
end
return ok, err;
end
function generate_success(event, form)
return render(success_tpl, { jid = nodeprep(form.username).."@"..module.host });
end
function generate_register_response(event, form, ok, err)
local message;
event.response.headers.content_type = "text/html; charset=utf-8";
if ok then
return generate_success(event, form);
else
return generate_page(event, { register_error = err });
end
end
function handle_form(event)
local request, response = event.request, event.response;
local form = http.formdecode(request.body);
verify_captcha(request, form, function (ok, err)
if ok then
local register_ok, register_err = register_user(form, request);
response:send(generate_register_response(event, form, register_ok, register_err));
else
response:send(generate_page(event, { register_error = err }));
end
end);
return true; -- Leave connection open until we respond above
end
module:provides("http", {
route = {
GET = generate_page;
["GET /"] = generate_page;
POST = handle_form;
["POST /"] = handle_form;
};
});
| mit |
gedads/Neodynamis | scripts/globals/abilities/earth_maneuver.lua | 4 | 1867 | -----------------------------------
-- Ability: Earth Maneuver
-- Enhances the effect of earth attachments. Must have animator equipped.
-- Obtained: Puppetmaster level 1
-- Recast Time: 10 seconds (shared with all maneuvers)
-- Duration: 1 minute
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:getWeaponSubSkillType(SLOT_RANGED) == 10 and
not player:hasStatusEffect(EFFECT_OVERLOAD) and
player:getPet()) then
return 0,0;
else
return 71,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local burden = 15;
if (target:getStat(MOD_VIT) < target:getPet():getStat(MOD_VIT)) then
burden = 20;
end
local overload = target:addBurden(ELE_EARTH-1, burden);
if (overload ~= 0 and
(player:getMod(MOD_PREVENT_OVERLOAD) > 0 or player:getPet():getMod(MOD_PREVENT_OVERLOAD) > 0) and
player:delStatusEffectSilent(EFFECT_WATER_MANEUVER)) then
overload = 0;
end
if (overload ~= 0) then
target:removeAllManeuvers();
target:addStatusEffect(EFFECT_OVERLOAD, 0, 0, overload);
else
local level;
if (target:getMainJob() == JOBS.PUP) then
level = target:getMainLvl()
else
level = target:getSubLvl()
end
local bonus = 1 + (level/15) + target:getMod(MOD_MANEUVER_BONUS);
if (target:getActiveManeuvers() == 3) then
target:removeOldestManeuver();
end
target:addStatusEffect(EFFECT_EARTH_MANEUVER, bonus, 0, 60);
end
return EFFECT_EARTH_MANEUVER;
end; | gpl-3.0 |
Microeinstein/ComputerCraftExe | craft.lua | 1 | 19162 | --AutoCraft for Turtles by Microeinstein
loadfile("stdturtle")()
local help = {
"Usage:",
" [-s] Scan bottom chest without move",
" [-t] Print only required items",
" recipeDir Recipe folder",
" objective Final recipe",
" [count] Amount of items"
}
args = {...}
argOnlyScan = false
argOnlyReq = false
argFolder = ""
argFinal = ""
argCount = 1
for k, v in pairs(args) do
if v == "-s" then
argOnlyScan = true
elseif v == "-t" then
argOnlyReq = true
elseif argFolder == "" then
argFolder = v
elseif argFinal == "" then
argFinal = v
elseif argCount == 1 then
argCount = math.max(tonumber(v) or 0, 1)
end
end
if argFolder == "" or argFinal == "" then
term.more(table.concat(help, "\n"))
return
end
nonil = { count = 0, name = "", damage = 0, lock = false }
files = {} --[path] = "content"
recipes = {} --[name~damage] = {recipe1, recipe2}
final = nil --recipe
recipeTree = {} --[[
{
"name~damage" = {
1 = {
required = <recipe1>,
branch = {
<loop>, ...
}
},
2 = {
required = <recipe2>,
branch = {
<loop>, ...
}
},
"selected" = 1
}
}
Final point: tree[item][tree[item].selected].required
]]--
objectives = {} --[i] = {name~damage, count, recipe}
nameCache = {} --[id] = name
items = {} --[i] = {name, count, damage}
slots = {} --[i] = {name, count, damage}
--noNeed = {} --[i] = {name, count, damage}
inverseDir = false
craft_debug = false
errors = {
directoryEmpty = "%s does not have recipes",
missingUpDown = "Expected top chest and bottom chest",
missingRecipe = "No recipes for %s",
noOtherRecipes = "There's no remaining recipes",
recursiveBreak = "No recipe for %s due to recursion",
noDrop = "Unable to free this slot",
noTake = "Unable to take items",
noItem = "Expected item details",
noItems = "Chests are empty",
noRecipe = "%s is not a recipe",
noCraft = "Unable to craft %s",
countMinor = "%s count (%d) is less than %d"
}
function stop(...)
if #arg > 0 then
term.printc(colors.white, colors.red, string.format(unpack(arg)))
end
error()
end
local function trace(txt, ...)
if craft_debug then
term.pausec(colors.white, colors.green, txt.."("..table.concat(arg, ",")..")")
end
end
--Recipes
function recipeID(recipe)
return getID(recipe.F)
end
function findRecipeGroup(ID)
local p1, p2 = getNameDamage(ID)
local _, rv = table.first(recipes,
function(rID,rec,nam,dam)
local knam, kdam = getNameDamage(rID)
return knam == nam and (dam == nil or kdam == dam)
end, p1, p2)
return rv
end
function recipeToXY(num)
return math.numToXY(num, 3)
end
function isNeedSlot(k)
return k ~= "F" and k ~= "w" and k ~= "h"
end
function fixRecipe(recipe)
local minimal = recipe ~= nil and recipe.F ~= nil and (
recipe[1] ~= nil or
recipe[2] ~= nil or
recipe[3] ~= nil or
recipe[4] ~= nil or
recipe[5] ~= nil or
recipe[6] ~= nil or
recipe[7] ~= nil or
recipe[8] ~= nil or
recipe[9] ~= nil
)
if minimal then
for i=1, 9 do
recipe[i] = recipe[i] or nonil
end
end
return minimal
end
function isRecipeComplete(recipe, amount)
trace("isRecipeComplete",recipe,amount)
local m = math.max(recipe.w, recipe.h)
local lowered = amount
for y=1, recipe.h do
for x=1, recipe.w do
local item = turtle.getItemDetailXY(x, y)
local slot = math.xyToNum(x, y, m)
local required = recipe[slot]
if item then
if not (item.name == required.name and (not required.lock or item.damage == required.damage)) then
return false
elseif item.count < required.count / recipe.F.count * amount then
lowered = math.min(lowered, amount - ((amount / recipe.F.count * required.count) - item.count))
end
elseif required.count > 0 and required.name ~= "" then
return false
end
end
end
return lowered == amount or lowered
end
function requiredItems(recipe, amount)
local required = {}
local ID
for k, item in pairs(recipe) do
if isNeedSlot(k) and (not string.isBlank(item.name)) and item.count > 0 then
ID = getID(item)
required[ID] = (required[ID] or 0) + math.ceil(item.count / recipe.F.count * amount)
end
end
return required
end
function missingItems(required)
local missing = {}
for item, count in pairs(required) do
local p1, p2 = getNameDamage(item)
if not table.exist(items,
function(k,v,id,variant,c)
return isNeedSlot(k) and v.name == id and v.count >= c and (variant == -1 or v.damage == variant)
end, p1, p2 or -1, count) then
missing[item] = (missing[item] or 0) + count
end
end
return missing
end
function loadRecipes()
local mex, obj1 = fs.readDir(argFolder, true)
if mex ~= fs.mex.okRead then
stop(mex)
end
files = obj1
print("Loading recipes...")
for path, content in pairs(files) do
local r = textutils.unserialize(content)
if fixRecipe(r) then
local id = getID(r.F)
print(string.format(" + %s", id))
local w, h = 3, 3
for x = 3, 1, -1 do
if r[x].name == "" and r[x + 3].name == "" and r[x + 6].name == "" then
w = w - 1
end
end
for y = 7, 1, -3 do
if r[y].name == "" and r[y + 1].name == "" and r[y + 2].name == "" then
h = h - 1
end
end
r.w = w
r.h = h
recipes[id] = recipes[id] or {}
table.insert(recipes[id], r)
if fs.getName(path) == argFinal then
final = r
end
else
print(string.format(" - "..errors.noRecipe, fs.getName(path)))
end
end
if table.len(recipes) == 0 then
stop(errors.directoryEmpty, argFolder)
end
if not final then
stop(fs.mex.notFound..": %s", argFinal)
end
end
--Logistic
function getID(details)
local r = details.name
--If lock doesn't exist (for items), else its value
if details.lock == nil or details.lock then
r = r.."~"..details.damage
end
return r;
end
function getNameDamage(ID)
local p1, p2 = unpack(string.split(ID, "~"))
return p1, tonumber(p2)
end
function getShortName(ID)
if not nameCache[ID] then
local colon = string.split(ID, ":")
local dot = string.split(colon[2], ".")
local underscore = string.split(dot[#dot], "_")
underscore[#underscore] = string.replace(underscore[#underscore], "~", ":")
local long = {}
for k, v in pairs(underscore) do
if #v > 1 then
table.insert(long, (#long > 0) and string.firstUpper(v) or v)
end
end
nameCache[ID] = string.format("%s %s", colon[1], table.concat(long))
end
return nameCache[ID]
end
function findItems(tabl, name, damage)
local rv = table.where(tabl,
function(k,v,nam,dam)
return v.name == nam and (v.lock == false or dam == nil or v.damage == dam)
end, name, damage)
return rv
end
function moveUp()
print("Moving items up...")
local get
repeat
get = turtle.suckDown()
if get and not turtle.dropUp() then
stop(errors.noDrop)
end
until not get
end
function moveDown()
print("Moving items down...")
local get
repeat
get = turtle.suckUp()
if get and not turtle.dropDown() then
stop(errors.noDrop)
end
until not get
end
function emptySlots()
print("Freeing slots...")
local drop = argOnlyScan and turtle.dropDown or turtle.dropUp
for s = 1, 16 do
if turtle.getItemCount(s) > 0 then
turtle.select(s)
if not drop() then
stop(errors.noDrop)
end
end
end
end
function addItem(details)
if details then
local id = getID(details)
local item = items[id]
if item then
item.count = item.count + details.count
else
items[id] = details
end
else
stop(errors.noItem)
end
end
function scanChest()
items = {}
--slots = {}
--noNeed = {}
print("Scanning bottom chest...")
local get, it, rcps
repeat
if not (turtle.detectUp() and turtle.detectDown()) then
stop(errors.missingUpDown)
end
get = turtle.suckDown()
if get then
it = turtle.getItemDetail()
addItem(it)
print(string.format(" + %d * %s", it.count, getShortName(getID(it))))
if not turtle.dropUp() then
stop(errors.noDrop)
end
elseif table.len(items) == 0 then
stop(errors.noItems)
end
until not get
--Chest is scanned
end
--Sorting
function makeTree(ID, amount, position, remainingItems, tab)
tab = tab or 0
if amount <= 0 then
return
end
local prnt = string.format("%s%d %s", string.rep(" ", tab), amount, getShortName(ID))
if argOnlyReq then
term.pause(prnt)
else
print(prnt)
os.sleep(0.05)
end
local recipes = findRecipeGroup(ID)
if not recipes or table.len(recipes) <= 0 then
return
end
position[ID] = {}
position[ID].selected = 1
for n, recipe in pairs(recipes) do
if n > 1 then
print(string.rep(" ", tab).."-OR-")
end
local required = requiredItems(recipe, amount)
--Remove already crafted items
if not argOnlyReq then
for rID, rAM in pairs(table.copy(required, false)) do
local requiredRecipes = findRecipeGroup(rID)
if requiredRecipes and table.len(requiredRecipes) > 0 then
local existent = findItems(remainingItems, getNameDamage(rID))
if existent then
--objDebug(existent,"exBefore")
for _, existem in pairs(existent) do
if existem.count > 0 then
local subtract = math.min(existem.count, rAM)
rAM = rAM - subtract
existem.count = existem.count - subtract
end
if rAM == 0 then
required[rID] = nil
elseif rAM > 0 then
required[rID] = rAM
else
stop(errors.countMinor, "am", rAM, 0)
end
end
--objDebug(existent,"exAfter")
end
end
end
end
position[ID][n] = {
required = required,
branch = {}
}
for rID, rAM in pairs(required) do
if rID ~= ID then
makeTree(rID, rAM, position[ID][n].branch, remainingItems, tab + 1)
else
stop(errors.recursiveBreak, ID)
end
end
end
end
function readTree(position)
local total = {}
--tree[item][tree[item].selected].required
for _, combos in pairs(position) do
local combo = combos[combos.selected]
for ID, AM in pairs(combo.required) do
if not combo.branch[ID] then
total[ID] = (total[ID] or 0) + AM
end
end
if table.len(combo.branch) > 0 then
local branch = readTree(combo.branch)
for ID, AM in pairs(branch) do
total[ID] = (total[ID] or 0) + AM
end
end
end
return total
end
function nextBranch(position)
local length = table.len(position)
local at = 0
for ID, combos in pairs(position) do
at = at + 1
local combo = combos[combos.selected]
--If combo has other combinations
if table.len(combo.branch) > 0 then
if nextBranch(combo.branch) then
return true
end
end
combos.selected = combos.selected + 1
if combos.selected >= table.len(combos) then
combos.selected = 1
if at >= length then
return false
end
else
return true
end
end
end
function selectObjectives()
local req, mis
local inc = 0
while true do
inc = inc + 1
print(string.format("Checking combination %d...", inc))
req = readTree(recipeTree)
mis = missingItems(req)
if table.len(mis) > 0 then
if not nextBranch(recipeTree) then
stop(errors.noOtherRecipes)
end
else
print("Checked and selected")
return true
end
end
end
function makeObjectives(branch, ID, count)
--print((branch and "table" or "nil").." "..ID.." "..count)
--[[local p1, p2 = getNameDamage(ID)
if p2 == nil then
ID = table.first(recipes,
function(k,v,id)
local pp1, pp2 = getNameDamage(k)
return pp1 == id
end, p1)
objDebug(ID)
end]]
local bri = branch[ID]
local sel = bri[bri.selected]
local rec = findRecipeGroup(ID)[bri.selected]
if table.len(sel.branch) > 0 then
for rid, ra in pairs(sel.required) do
local rec = findRecipeGroup(rid)
if rec and table.len(rec) > 0 then
makeObjectives(sel.branch, rid, ra)
end
end
end
print(string.format(" > %d %s", count, getShortName(ID)))
table.insert(objectives, {
ID = ID,
count = count,
recipe = rec
})
end
function showRequirements()
local inc = 0
while true do
inc = inc + 1
print(string.format("COMBINATION %d:", inc))
local requirements = readTree(recipeTree)
for rID, rAM in pairs(requirements) do
term.pause(" "..rAM.." "..getShortName(rID))
end
local otherCombos = nextBranch(recipeTree)
--fs.write("recipeTree.lua", textutils.serialise(recipeTree))
if not otherCombos then
return
end
print("\n")
end
end
--Move items
function slotsM(x, y, amount)
local itk, itv = table.first(slots, function(_,v,x,y) return v.x == x and v.y == y end, x, y)
if itv then
if amount then
itv.count = itv.count - amount
else
itv.count = turtle.getItemCountXY(x, y)
end
if itv.count <= 0 then
table.remove(slots, itk)
end
end
end
function slotsP(x, y)
local id = turtle.getItemDetailXY(x, y)
id.x = x
id.y = y
table.insert(slots, id)
end
function reserveSlots(recipe)
for y=1, recipe.h do
for x=1, recipe.w do
if turtle.getItemCountXY(x, y) > 0 then
if turtle.push(x, y, inverseDir and turtle.faces.D or turtle.faces.U) then
slotsM(x, y)
else
stop(errors.noDrop)
end
end
end
end
end
function transportBelt(recipe)
local slots = {}
for x=4, 1, -1 do
for y=1, 4 do
if recipe.w < x or recipe.h < y then
table.insert(slots, {x=x, y=y})
end
end
end
return slots
end
function roll(transport)
print("Rolling items...")
local rev = table.reverse(transport)
local to = inverseDir and turtle.faces.U or turtle.faces.D
for n, s in pairs(rev) do
if turtle.getItemCountXY(s.x, s.y) > 0 then
if not turtle.push(s.x, s.y, to) then
stop(errors.noDrop)
end
slotsM(s.x, s.y)
end
end
for n, s in pairs(rev) do
if not rollGetNext(s.x, s.y) then
break
end
end
end
function rollGetNext(x, y, recur)
recur = recur or false
if not turtle.pull(x, y, inverseDir and turtle.faces.D or turtle.faces.U) then
if recur then
return false
else
inverseDir = not inverseDir
return rollGetNext(x, y, true)
end
else
slotsP(x, y)
end
return true
end
--Crafting
function placeItem(slot, recipe, amount)
trace("placeItem",slot.x,slot.y,recipe.F.name,amount)
local slotK, slotItem = table.first(slots,
function(_,v,x,y) return v.x == x and v.y == y end,
slot.x, slot.y)
if not slotItem then
return
end
local requirements = findItems(table.where(recipe, isNeedSlot), slotItem.name, slotItem.damage)
if not requirements or table.len(requirements) < 1 then
return
end
local ID = getID(slotItem)
for k, required in pairs(requirements) do
local finalSlot = recipeToXY(k)
local alreadyPlaced = turtle.getItemDetailXY(finalSlot.x, finalSlot.y)
local placedCount = alreadyPlaced and alreadyPlaced.count or 0
if placedCount == 0 or ID.damage == alreadyPlaced.damage then
local moveAmount = math.min(turtle.getItemCountXY(slot.x, slot.y),
math.ceil(amount / recipe.F.count * required.count) - placedCount)
if moveAmount > 0 then
if items[ID].count < moveAmount then
stop(errors.countMinor, getShortName(ID), items[ID].count, moveAmount)
end
if slotItem.count > 0 then
slotItem.count = slotItem.count - moveAmount
if not items[ID] then
objDebug(ID,"ID")
objDebug(items,"items")
end
items[ID].count = items[ID].count - moveAmount
turtle.moveSlot(slot.x, slot.y, finalSlot.x, finalSlot.y, moveAmount)
else
table.remove(slots, slotK)
break
end
--items[ID].count
--elseif slotItem.count < moveAmount then
--amount = amount - (math.ceil(amount / recipe.F.count * required.count) - placedCount)
--objDebug(amount, "place_amount")
--stop(errors.countMinor, getShortName(ID), items[ID].count, moveAmount)
end
end
end
end
function reapItems(ID, slot)
if items[ID] and items[ID].count <= 0 then
items[ID] = nil
end
slotsM(slot.x, slot.y)
end
function reserveCraft(recipe, amount)
print("Emptying other slots...")
for y=1, 4 do
for x=1, 4 do
if (x > recipe.w or y > recipe.h) and turtle.getItemCountXY(x, y) > 0 then
if turtle.push(x, y, inverseDir and turtle.faces.D or turtle.faces.U) then
slotsM(x, y)
else
stop(errors.noDrop)
end
end
end
end
end
function craft(recipe)
turtle.setSlot(4, 1)
local fn = recipeID(recipe)
local ct = 0
repeat
local success = turtle.craft()
if success then
ct = ct + 1
for k, v in pairs(recipe) do
if k ~= "F" and k ~= "w" and k ~= "h" then
local ID = getID(v)
if items[ID] then
if items[ID].count == 0 then
items[ID] = nil
elseif items[ID].count < 0 then
stop(errors.countMinor, getShortName(ID), items[ID].count, 0)
end
end
end
end
addItem(turtle.getItemDetailXY(4, 1))
turtle.push(4, 1, inverseDir and turtle.faces.U or turtle.faces.D)
else
local ID = turtle.getItemDetail()
if (ID and ID.name ~= fn.name
and ID.count ~= fn.count
and ID.damage ~= fn.damage) or ct == 0 then
stop(errors.noCraft, getShortName(fn))
end
end
until not success
end
function reAddItems(recipe)
for y=1, recipe.h do
for x=1, recipe.w do
local item = turtle.getItemDetailXY(x, y)
if item and item.count > 0 then
addItem(item)
if not turtle.push(x, y, inverseDir and turtle.faces.D or turtle.faces.U) then
stop(errors.noDrop)
end
end
end
end
end
--Main
function followOjectives()
trace("followOjectives")
for n, obj in pairs(objectives) do
print(string.format("Making %d %s...", obj.count, getShortName(obj.ID)))
print("Allocating slots...")
reserveSlots(obj.recipe)
followSubObjective(transportBelt(obj.recipe), obj.recipe, obj.count)
print("\n")
end
end
function followSubObjective(transport, recipe, count)
local complete
repeat
roll(transport)
for _, slot in pairs(transport) do
placeItem(slot, recipe, count)
reapItems(recipeID(recipe), slot)
end
complete = isRecipeComplete(recipe, count)
if not isBool(complete) then
reserveCraft(recipe, complete)
craft(recipe)
--reAddItems(recipe)
count = count - complete
complete = false
end
until complete
reserveCraft(recipe, count)
craft(recipe)
end
function start()
term.wash()
term.printc(colors.yellow, nil, "AutoCraft by Microeinstein")
term.printc(colors.red, nil, "Please do not edit inventories during process.")
term.printc(colors.red, nil, "Hold CTRL+T to halt")
os.sleep(1.5)
term.printc(colors.blue, nil, "\n <Loading recipes>")
os.sleep(0.1)
loadRecipes()
if not argOnlyReq then
term.printc(colors.blue, nil, "\n <Loading items>")
os.sleep(0.1)
emptySlots()
if not argOnlyScan then
moveUp()
moveDown()
end
scanChest()
end
term.printc(colors.blue, nil, "\n <Building recipe tree>")
os.sleep(0.1)
makeTree(recipeID(final), argCount, recipeTree, table.copy(items, true))
--fs.write("recipeTree.lua", textutils.serialise(recipeTree))
if argOnlyReq then
term.printc(colors.blue, nil, "\n <Showing requirements>")
os.sleep(0.1)
showRequirements()
else
term.printc(colors.blue, nil, "\n <Finding right combination>")
os.sleep(0.1)
selectObjectives()
term.printc(colors.blue, nil, "\n <Making crafting order>")
os.sleep(0.1)
makeObjectives(recipeTree, recipeID(final), argCount)
term.printc(colors.green, nil, "\n <Crafting started>")
os.sleep(0.1)
followOjectives()
term.printc(colors.green, nil, "\nSUCCESS")
end
end
start()
stop() | mit |
starlightknight/darkstar | scripts/zones/East_Ronfaure/Zone.lua | 9 | 1700 | -----------------------------------
--
-- Zone: East_Ronfaure (101)
--
-----------------------------------
local ID = require("scripts/zones/East_Ronfaure/IDs")
require("scripts/globals/icanheararainbow");
require("scripts/globals/chocobo_digging");
require("scripts/globals/conquest");
require("scripts/globals/quests");
require("scripts/globals/helm")
require("scripts/globals/zone");
-----------------------------------
function onChocoboDig(player, precheck)
return dsp.chocoboDig.start(player, precheck)
end;
function onInitialize(zone)
dsp.helm.initZone(zone, dsp.helm.type.LOGGING)
end;
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(200.015,-3.187,-536.074,187);
end
if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow
cs = 21;
elseif (player:getCurrentMission(WINDURST) == dsp.mission.id.windurst.VAIN and player:getCharVar("MissionStatus") ==1) then
cs = 23;
end
return cs;
end;
function onConquestUpdate(zone, updatetype)
dsp.conq.onConquestUpdate(zone, updatetype)
end;
function onRegionEnter(player,region)
end;
function onEventUpdate(player,csid,option)
if (csid == 21) then
lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow
elseif (csid == 23) then
if (player:getYPos() >= -22) then
player:updateEvent(0,0,0,0,0,7);
else
player:updateEvent(0,0,0,0,0,6);
end
end
end;
function onEventFinish(player,csid,option)
if (csid == 21) then
lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow
end
end; | gpl-3.0 |
O-P-E-N/CC-ROUTER | feeds/luci/modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/network.lua | 48 | 2480 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
m = Map("network", translate("Interfaces"))
m.pageaction = false
m:section(SimpleSection).template = "admin_network/iface_overview"
-- Show ATM bridge section if we have the capabilities
if fs.access("/usr/sbin/br2684ctl") then
atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"),
translate("ATM bridges expose encapsulated ethernet in AAL5 " ..
"connections as virtual Linux network interfaces which can " ..
"be used in conjunction with DHCP or PPP to dial into the " ..
"provider network."))
atm.addremove = true
atm.anonymous = true
atm.create = function(self, section)
local sid = TypedSection.create(self, section)
local max_unit = -1
m.uci:foreach("network", "atm-bridge",
function(s)
local u = tonumber(s.unit)
if u ~= nil and u > max_unit then
max_unit = u
end
end)
m.uci:set("network", sid, "unit", max_unit + 1)
m.uci:set("network", sid, "atmdev", 0)
m.uci:set("network", sid, "encaps", "llc")
m.uci:set("network", sid, "payload", "bridged")
m.uci:set("network", sid, "vci", 35)
m.uci:set("network", sid, "vpi", 8)
return sid
end
atm:tab("general", translate("General Setup"))
atm:tab("advanced", translate("Advanced Settings"))
vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode"))
encaps:value("llc", translate("LLC"))
encaps:value("vc", translate("VC-Mux"))
atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number"))
unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number"))
payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode"))
payload:value("bridged", translate("bridged"))
payload:value("routed", translate("routed"))
m.pageaction = true
end
local network = require "luci.model.network"
if network:has_ipv6() then
local s = m:section(NamedSection, "globals", "globals", translate("Global network options"))
local o = s:option(Value, "ula_prefix", translate("IPv6 ULA-Prefix"))
o.datatype = "ip6addr"
o.rmempty = true
m.pageaction = true
end
return m
| gpl-2.0 |
gedads/Neodynamis | scripts/zones/Dangruf_Wadi/npcs/_5b1.lua | 3 | 2950 | -----------------------------------
-- Area: Dangruf Wadi
-- NPC: Strange Apparatus
-- !pos -494 -4 -100 191
-----------------------------------
package.loaded["scripts/zones/Dangruf_Wadi/TextIDs"] = nil;
require("scripts/zones/Dangruf_Wadi/TextIDs");
require("scripts/globals/strangeapparatus");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local trade = tradeToStrApp(player, trade);
if (trade ~= nil) then
if ( trade == 1) then -- good trade
local drop = player:getLocalVar("strAppDrop");
local dropQty = player:getLocalVar("strAppDropQty");
local docStatus = 0; -- Assistant
if (hasStrAppDocStatus(player)) then
docStatus = 1; -- Doctor
end
player:startEvent(0x0003, drop, dropQty, INFINITY_CORE, 0, 0, 0, docStatus, 0);
else -- wrong chip, spawn elemental nm
spawnElementalNM(player);
delStrAppDocStatus(player);
player:messageSpecial(SYS_OVERLOAD);
player:messageSpecial(YOU_LOST_THE, trade);
end
else -- Invalid trade, lose doctor status
delStrAppDocStatus(player);
player:messageSpecial(DEVICE_NOT_WORKING);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local docStatus = 0; -- Assistant
if (hasStrAppDocStatus(player)) then
docStatus = 1; -- Doctor
else
player:setLocalVar( "strAppPass", 1);
end
player:startEvent(0x0001, docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, player:getZoneID());
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u", option);
if (csid == 0x0001) then
if (hasStrAppDocStatus(player) == false) then
local docStatus = 1; -- Assistant
if ( option == strAppPass(player)) then -- Good password
docStatus = 0; -- Doctor
giveStrAppDocStatus(player);
end
player:updateEvent(docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, 0);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0003) then
local drop = player:getLocalVar("strAppDrop");
local dropQty = player:getLocalVar("strAppDropQty");
if (drop ~= 0) then
if ( dropQty == 0) then
dropQty = 1;
end
player:addItem(drop, dropQty);
player:setLocalVar("strAppDrop", 0);
player:setLocalVar("strAppDropQty", 0);
end
end
end; | gpl-3.0 |
gedads/Neodynamis | scripts/zones/Tavnazian_Safehold/Zone.lua | 12 | 3369 | -----------------------------------
--
-- Zone: Tavnazian_Safehold (26)
--
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/zones/Tavnazian_Safehold/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
zone:registerRegion(1, -5, -24, 18, 5, -20, 27);
zone:registerRegion(2, 104, -42, -88, 113, -38, -77);
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(27.971,-14.068,43.735,66);
end
if (player:getCurrentMission(COP) == AN_INVITATION_WEST) then
if (player:getVar("PromathiaStatus") == 1) then
cs = 0x0065;
end
elseif (player:getCurrentMission(COP) == SHELTERING_DOUBT and player:getVar("PromathiaStatus") == 0) then
cs = 0x006B;
elseif (player:getCurrentMission(COP) == CHAINS_AND_BONDS and player:getVar("PromathiaStatus") == 1) then
cs = 0x0072;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
switch (region:GetRegionID()): caseof
{
[1] = function (x)
if (player:getCurrentMission(COP) == AN_ETERNAL_MELODY and player:getVar("PromathiaStatus") == 2) then
player:startEvent(0x0069);
end
end,
[2] = function (x)
if (player:getCurrentMission(COP) == SLANDEROUS_UTTERINGS and player:getVar("PromathiaStatus") == 0) then
player:startEvent(0x0070);
end
end,
}
end;
-----------------------------------
-- onRegionLeave
-----------------------------------
function onRegionLeave(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0065) then
player:completeMission(COP,AN_INVITATION_WEST);
player:addMission(COP,THE_LOST_CITY);
player:setVar("PromathiaStatus",0);
elseif (csid == 0x0069) then
player:setVar("PromathiaStatus",0);
player:completeMission(COP,AN_ETERNAL_MELODY);
player:addMission(COP,ANCIENT_VOWS);
elseif (csid == 0x006B) then
player:setVar("PromathiaStatus",1);
elseif (csid == 0x0070) then
player:setVar("PromathiaStatus",1);
elseif (csid == 0x0072) then
player:setVar("PromathiaStatus",2);
end
end; | gpl-3.0 |
gedads/Neodynamis | scripts/zones/Windurst_Waters/npcs/Fuepepe.lua | 3 | 3822 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Fuepepe
-- Starts and Finishes Quest: Teacher's Pet
-- Involved in Quest: Making the grade, Class Reunion
-- !pos 161 -2 161 238
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Windurst_Waters/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(WINDURST,MAKING_THE_GRADE) == QUEST_ACCEPTED and player:getVar("QuestMakingTheGrade_prog") == 0) then
if (trade:hasItemQty(544,1) and trade:getItemCount() == 1 and trade:getGil() == 0) then
player:startEvent(0x01c7); -- Quest Progress: Test Papers Shown and told to deliver them to principal
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local gradestatus = player:getQuestStatus(WINDURST,MAKING_THE_GRADE);
local prog = player:getVar("QuestMakingTheGrade_prog");
-- 1 = answers found
-- 2 = gave test answers to principle
-- 3 = spoke to chomoro
if (player:getQuestStatus(WINDURST,TEACHER_S_PET) == QUEST_COMPLETED and gradestatus == QUEST_AVAILABLE and player:getFameLevel(WINDURST) >=3 and player:getQuestStatus(WINDURST,LET_SLEEPING_DOGS_LIE) ~= QUEST_ACCEPTED) then
player:startEvent(0x01ba); -- Quest Start
elseif (gradestatus == QUEST_ACCEPTED) then
if (prog == 0) then
player:startEvent(0x01bb); -- Get Test Sheets Reminder
elseif (prog == 1) then
player:startEvent(0x01c8); -- Deliver Test Sheets Reminder
elseif (prog == 2 or prog == 3) then
player:startEvent(0x01ca); -- Quest Finish
end
elseif (gradestatus == QUEST_COMPLETED and player:needToZone() == true) then
player:startEvent(0x01cb); -- After Quest
-------------------------------------------------------
-- Class Reunion
elseif (player:getQuestStatus(WINDURST,CLASS_REUNION) == QUEST_ACCEPTED and player:getVar("ClassReunionProgress") >= 3 and player:getVar("ClassReunion_TalkedToFupepe") ~= 1) then
player:startEvent(0x0331); -- he tells you about Uran-Mafran
-------------------------------------------------------
else
player:startEvent(0x1a7); -- 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 == 0x01ba and option == 1) then -- Quest Start
player:addQuest(WINDURST,MAKING_THE_GRADE);
elseif (csid == 0x01c7) then -- Quest Progress: Test Papers Shown and told to deliver them to principal
player:setVar("QuestMakingTheGrade_prog",1);
elseif (csid == 0x01ca) then -- Quest Finish
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4855);
else
player:completeQuest(WINDURST,MAKING_THE_GRADE);
player:addFame(WINDURST,75);
player:addItem(4855);
player:messageSpecial(ITEM_OBTAINED,4855);
player:setVar("QuestMakingTheGrade_prog",0);
player:needToZone(true);
end
elseif (csid == 0x0331) then
player:setVar("ClassReunion_TalkedToFupepe",1);
end
end;
| gpl-3.0 |
Craige/prosody-modules | mod_client_certs/mod_client_certs.lua | 27 | 13872 | -- XEP-0257: Client Certificates Management implementation for Prosody
-- Copyright (C) 2012 Thijs Alkemade
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local jid_split = require "util.jid".split;
local xmlns_saslcert = "urn:xmpp:saslcert:1";
local dm_load = require "util.datamanager".load;
local dm_store = require "util.datamanager".store;
local dm_table = "client_certs";
local x509 = require "ssl.x509";
local id_on_xmppAddr = "1.3.6.1.5.5.7.8.5";
local id_ce_subjectAltName = "2.5.29.17";
local digest_algo = "sha1";
local base64 = require "util.encodings".base64;
local function get_id_on_xmpp_addrs(cert)
local id_on_xmppAddrs = {};
for k,ext in pairs(cert:extensions()) do
if k == id_ce_subjectAltName then
for e,extv in pairs(ext) do
if e == id_on_xmppAddr then
for i,v in ipairs(extv) do
id_on_xmppAddrs[#id_on_xmppAddrs+1] = v;
end
end
end
end
end
module:log("debug", "Found JIDs: (%d) %s", #id_on_xmppAddrs, table.concat(id_on_xmppAddrs, ", "));
return id_on_xmppAddrs;
end
local function enable_cert(username, cert, info)
-- Check the certificate. Is it not expired? Does it include id-on-xmppAddr?
--[[ the method expired doesn't exist in luasec .. yet?
if cert:expired() then
module:log("debug", "This certificate is already expired.");
return nil, "This certificate is expired.";
end
--]]
if not cert:validat(os.time()) then
module:log("debug", "This certificate is not valid at this moment.");
end
local valid_id_on_xmppAddrs;
local require_id_on_xmppAddr = true;
if require_id_on_xmppAddr then
valid_id_on_xmppAddrs = get_id_on_xmpp_addrs(cert);
local found = false;
for i,k in pairs(valid_id_on_xmppAddrs) do
if jid_bare(k) == (username .. "@" .. module.host) then
found = true;
break;
end
end
if not found then
return nil, "This certificate has no valid id-on-xmppAddr field.";
end
end
local certs = dm_load(username, module.host, dm_table) or {};
info.pem = cert:pem();
local digest = cert:digest(digest_algo);
info.digest = digest;
certs[info.name] = info;
dm_store(username, module.host, dm_table, certs);
return true
end
local function disable_cert(username, name, disconnect)
local certs = dm_load(username, module.host, dm_table) or {};
local info = certs[name];
if not info then
return nil, "item-not-found"
end
certs[name] = nil;
if disconnect then
module:log("debug", "%s revoked a certificate! Disconnecting all clients that used it", username);
local sessions = hosts[module.host].sessions[username].sessions;
local disabled_cert_pem = info.pem;
for _, session in pairs(sessions) do
if session and session.conn then
local cert = session.conn:socket():getpeercertificate();
if cert and cert:pem() == disabled_cert_pem then
module:log("debug", "Found a session that should be closed: %s", tostring(session));
session:close{ condition = "not-authorized", text = "This client side certificate has been revoked."};
end
end
end
end
dm_store(username, module.host, dm_table, certs);
return info;
end
module:hook("iq/self/"..xmlns_saslcert..":items", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "get" then
module:log("debug", "%s requested items", origin.full_jid);
local reply = st.reply(stanza):tag("items", { xmlns = xmlns_saslcert });
local certs = dm_load(origin.username, module.host, dm_table) or {};
for digest,info in pairs(certs) do
reply:tag("item")
:tag("name"):text(info.name):up()
:tag("x509cert"):text(info.x509cert)
:up();
end
origin.send(reply);
return true
end
end);
module:hook("iq/self/"..xmlns_saslcert..":append", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local append = stanza:get_child("append", xmlns_saslcert);
local name = append:get_child_text("name", xmlns_saslcert);
local x509cert = append:get_child_text("x509cert", xmlns_saslcert);
if not x509cert or not name then
origin.send(st.error_reply(stanza, "cancel", "bad-request", "Missing fields.")); -- cancel? not modify?
return true
end
local can_manage = append:get_child("no-cert-management", xmlns_saslcert) ~= nil;
x509cert = x509cert:gsub("^%s*(.-)%s*$", "%1");
local cert = x509.load(
"-----BEGIN CERTIFICATE-----\n"
.. x509cert ..
"\n-----END CERTIFICATE-----\n");
if not cert then
origin.send(st.error_reply(stanza, "modify", "not-acceptable", "Could not parse X.509 certificate"));
return true;
end
local ok, err = enable_cert(origin.username, cert, {
name = name,
x509cert = x509cert,
no_cert_management = can_manage,
});
if not ok then
origin.send(st.error_reply(stanza, "cancel", "bad-request", err));
return true -- REJECT?!
end
module:log("debug", "%s added certificate named %s", origin.full_jid, name);
origin.send(st.reply(stanza));
return true
end
end);
local function handle_disable(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local disable = stanza.tags[1];
module:log("debug", "%s disabled a certificate", origin.full_jid);
local name = disable:get_child_text("name");
if not name then
origin.send(st.error_reply(stanza, "cancel", "bad-request", "No key specified."));
return true
end
disable_cert(origin.username, name, disable.name == "revoke");
origin.send(st.reply(stanza));
return true
end
end
module:hook("iq/self/"..xmlns_saslcert..":disable", handle_disable);
module:hook("iq/self/"..xmlns_saslcert..":revoke", handle_disable);
-- Ad-hoc command
local adhoc_new = module:require "adhoc".new;
local dataforms_new = require "util.dataforms".new;
local function generate_error_message(errors)
local errmsg = {};
for name, err in pairs(errors) do
errmsg[#errmsg + 1] = name .. ": " .. err;
end
return table.concat(errmsg, "\n");
end
local choose_subcmd_layout = dataforms_new {
title = "Certificate management";
instructions = "What action do you want to perform?";
{ name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/certs#subcmd" };
{ name = "subcmd", type = "list-single", label = "Actions", required = true,
value = { {label = "Add certificate", value = "add"},
{label = "List certificates", value = "list"},
{label = "Disable certificate", value = "disable"},
{label = "Revoke certificate", value = "revoke"},
};
};
};
local add_layout = dataforms_new {
title = "Adding a certificate";
instructions = "Enter the certificate in PEM format";
{ name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/certs#add" };
{ name = "name", type = "text-single", label = "Name", required = true };
{ name = "cert", type = "text-multi", label = "PEM certificate", required = true };
{ name = "manage", type = "boolean", label = "Can manage certificates", value = true };
};
local disable_layout_stub = dataforms_new { { name = "cert", type = "list-single", label = "Certificate", required = true } };
local function adhoc_handler(self, data, state)
if data.action == "cancel" then return { status = "canceled" }; end
if not state or data.action == "prev" then
return { status = "executing", form = choose_subcmd_layout, actions = { "next" } }, {};
end
if not state.subcmd then
local fields, errors = choose_subcmd_layout:data(data.form);
if errors then
return { status = "completed", error = { message = generate_error_message(errors) } };
end
local subcmd = fields.subcmd
if subcmd == "add" then
return { status = "executing", form = add_layout, actions = { "prev", "next", "complete" } }, { subcmd = "add" };
elseif subcmd == "list" then
local list_layout = dataforms_new {
title = "List of certificates";
};
local certs = dm_load(jid_split(data.from), module.host, dm_table) or {};
for digest, info in pairs(certs) do
list_layout[#list_layout + 1] = { name = info.name, type = "text-multi", label = info.name, value = info.x509cert };
end
return { status = "completed", result = list_layout };
else
local layout = dataforms_new {
{ name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/certs#" .. subcmd };
{ name = "cert", type = "list-single", label = "Certificate", required = true };
};
if subcmd == "disable" then
layout.title = "Disabling a certificate";
layout.instructions = "Select the certificate to disable";
elseif subcmd == "revoke" then
layout.title = "Revoking a certificate";
layout.instructions = "Select the certificate to revoke";
end
local certs = dm_load(jid_split(data.from), module.host, dm_table) or {};
local values = {};
for digest, info in pairs(certs) do
values[#values + 1] = { label = info.name, value = info.name };
end
return { status = "executing", form = { layout = layout, values = { cert = values } }, actions = { "prev", "next", "complete" } },
{ subcmd = subcmd };
end
end
if state.subcmd == "add" then
local fields, errors = add_layout:data(data.form);
if errors then
return { status = "completed", error = { message = generate_error_message(errors) } };
end
local name = fields.name;
local x509cert = fields.cert:gsub("^%s*(.-)%s*$", "%1");
local cert = x509.load(
"-----BEGIN CERTIFICATE-----\n"
.. x509cert ..
"\n-----END CERTIFICATE-----\n");
if not cert then
return { status = "completed", error = { message = "Could not parse X.509 certificate" } };
end
local ok, err = enable_cert(jid_split(data.from), cert, {
name = name,
x509cert = x509cert,
no_cert_management = not fields.manage
});
if not ok then
return { status = "completed", error = { message = err } };
end
module:log("debug", "%s added certificate named %s", data.from, name);
return { status = "completed", info = "Successfully added certificate " .. name .. "." };
else
local fields, errors = disable_layout_stub:data(data.form);
if errors then
return { status = "completed", error = { message = generate_error_message(errors) } };
end
local info = disable_cert(jid_split(data.from), fields.cert, state.subcmd == "revoke" );
if state.subcmd == "revoke" then
return { status = "completed", info = "Revoked certificate " .. info.name .. "." };
else
return { status = "completed", info = "Disabled certificate " .. info.name .. "." };
end
end
end
local cmd_desc = adhoc_new("Manage certificates", "http://prosody.im/protocol/certs", adhoc_handler, "user");
module:provides("adhoc", cmd_desc);
-- Here comes the SASL EXTERNAL stuff
local now = os.time;
module:hook("stream-features", function(event)
local session, features = event.origin, event.features;
if session.secure and session.type == "c2s_unauthed" then
local cert = session.conn:socket():getpeercertificate();
if not cert then
module:log("error", "No Client Certificate");
return
end
module:log("info", "Client Certificate: %s", cert:digest(digest_algo));
if not cert:validat(now()) then
module:log("debug", "Client has an expired certificate", cert:digest(digest_algo));
return
end
module:log("debug", "Stream features:\n%s", tostring(features));
local mechs = features:get_child("mechanisms", "urn:ietf:params:xml:ns:xmpp-sasl");
if mechs then
mechs:tag("mechanism"):text("EXTERNAL");
end
end
end, -1);
local sm_make_authenticated = require "core.sessionmanager".make_authenticated;
module:hook("stanza/urn:ietf:params:xml:ns:xmpp-sasl:auth", function(event)
local session, stanza = event.origin, event.stanza;
if session.type == "c2s_unauthed" and stanza.attr.mechanism == "EXTERNAL" then
if session.secure then
local cert = session.conn:socket():getpeercertificate();
local username_data = stanza:get_text();
local username = nil;
if username_data == "=" then
-- Check for either an id_on_xmppAddr
local jids = get_id_on_xmpp_addrs(cert);
if not (#jids == 1) then
module:log("debug", "Client tried to authenticate as =, but certificate has multiple JIDs.");
module:fire_event("authentication-failure", { session = session, condition = "not-authorized" });
session.send(st.stanza("failure", { xmlns="urn:ietf:params:xml:ns:xmpp-sasl"}):tag"not-authorized");
return true;
end
username = jids[1];
else
-- Check the base64 encoded username
username = base64.decode(username_data);
end
local user, host, resource = jid_split(username);
module:log("debug", "Inferred username: %s", user or "nil");
if (not username) or (not host == module.host) then
module:log("debug", "No valid username found for %s", tostring(session));
module:fire_event("authentication-failure", { session = session, condition = "not-authorized" });
session.send(st.stanza("failure", { xmlns="urn:ietf:params:xml:ns:xmpp-sasl"}):tag"not-authorized");
return true;
end
local certs = dm_load(user, module.host, dm_table) or {};
local digest = cert:digest(digest_algo);
local pem = cert:pem();
for name,info in pairs(certs) do
if info.digest == digest and info.pem == pem then
sm_make_authenticated(session, user);
module:fire_event("authentication-success", { session = session });
session.send(st.stanza("success", { xmlns="urn:ietf:params:xml:ns:xmpp-sasl"}));
session:reset_stream();
return true;
end
end
module:fire_event("authentication-failure", { session = session, condition = "not-authorized" });
session.send(st.stanza("failure", { xmlns="urn:ietf:params:xml:ns:xmpp-sasl"}):tag"not-authorized");
else
session.send(st.stanza("failure", { xmlns="urn:ietf:params:xml:ns:xmpp-sasl"}):tag"encryption-required");
end
return true;
end
end, 1);
| mit |
fz72/fancy_elevator | init.lua | 3 | 23605 | dofile(minetest.get_modpath("fancy_elevator").."/functions.lua")
dofile(minetest.get_modpath("fancy_elevator").."/doors.lua")
minetest.register_node("fancy_elevator:truss", {
description = "Truss Shaft",
tile_images = {"elevator_truss.png"},
drawtype = "nodebox",
paramtype = "light",
groups = {snappy=1, choppy=2, oddly_breakable_by_hand=2, shaft=1},
is_ground_content = true,
node_box = {
type = "fixed",
fixed = {
{1/2, -1/2, -1/2, 1/2, 1/2, 1/2},
{-1/2, 1/2, -1/2, 1/2, 1/2, 1/2},
{-1/2, -1/2, 1/2, 1/2, 1/2, 1/2},
{-1/2, -1/2, -1/2, -1/2, 1/2, 1/2},
{-1/2, -1/2, -1/2, 1/2, -1/2, 1/2},
{-1/2, -1/2, -1/2, 1/2, 1/2, -1/2}
}
},
selection_box = {
type = "fixed",
fixed = {-1/2, -1/2, -1/2, 1/2, 1/2, 1/2}
}
})
minetest.register_node("fancy_elevator:shaft", {
description = "Shaft",
tiles = {
"elevator_shaft_top.png", "elevator_shaft_top.png",
"elevator_shaft.png", "elevator_shaft.png"},
is_ground_content = true,
groups = {snappy=1, choppy=2, oddly_breakable_by_hand=2, shaft=1},
})
minetest.register_node("fancy_elevator:concrete", {
description = "Concrete Shaft",
tiles = {
"elevator_concrete.png", "elevator_concrete.png",
"elevator_concrete.png", "elevator_concrete.png"},
is_ground_content = true,
groups = {snappy=1, choppy=2, oddly_breakable_by_hand=2, shaft=1},
})
minetest.register_node("fancy_elevator:brick", {
description = "Brick Shaft",
tiles = {
"elevator_brick.png", "elevator_brick.png",
"elevator_brick.png", "elevator_brick.png"},
is_ground_content = true,
groups = {snappy=1, choppy=2, oddly_breakable_by_hand=2, shaft=1},
})
minetest.register_node("fancy_elevator:ground", {
description = "Elevator ground",
tiles = {"elevator_shaft_top.png", "elevator_shaft.png"},
is_ground_content = true,
groups = {snappy=1, choppy=2, oddly_breakable_by_hand=2, disable_jump=1, not_in_creative_inventory=1},
on_dig = function(pos)
minetest.remove_node(pos)
return
end
})
elevator_doors.register_door("fancy_elevator:door_gray", {
description = "Elevator Door",
tiles_bottom = {"elevator_door_gray_b.png", "elevator_door_gray.png"},
tiles_top = {"elevator_door_gray_a.png", "elevator_door_gray.png"},
inventory_image = "elevator_door.png",
groups = {snappy=1, choppy=2, oddly_breakable_by_hand=2, shaft=2},
})
minetest.register_craft({
output = "fancy_elevator:shaft",
recipe = {
{"default:stone","group:wood"},
{"group:wood","default:stone"}
}
})
minetest.register_craft({
output = "fancy_elevator:elevator",
recipe = {
{"group:wood","group:wood"},
{"default:steel_ingot","default:steel_ingot"},
{"group:wood","group:wood"}
}
})
minetest.register_craft({
output = "fancy_elevator:elevatorindustrial",
recipe = {
{"group:wood","group:wood",""},
{"default:steel_ingot","default:steel_ingot","default:steel_ingot"},
{"group:wood","group:wood",""}
}
})
minetest.register_craft({
output = "fancy_elevator:door_gray",
recipe = {
{"default:steel_ingot","default:steel_ingot"},
{"group:wood","default:steel_ingot"},
{"default:steel_ingot","default:steel_ingot"}
}
})
--TODO: -create a chest
-- -better textures
-- -write elevator name onto the door (sign like)
local elevator = {
physical = false,
collisionbox = {-0.49,-0.49,-0.5, 0.49,1.5,0.49},
visual = "mesh",
mesh = "elevator.obj",
visual_size = {x=1, y=1},
spritediv = {x=1,y=1},
textures = {"elevator.png"},
stepheight = 0,
driver = nil,
velocity = 0,
target = nil,
floor_pos = nil,
old_target = nil,
old_pos = nil,
old_velocity = nil,
floorlist = nil,
calling_floors = {},
selected_floor = nil,
speed_limit = 4, -- Limit of the velocity
}
local elevatorindustrial = {
physical = false,
collisionbox = {-0.49,-0.49,-0.5, 0.49,1.5,0.49},
visual = "mesh",
mesh = "elevator.obj",
visual_size = {x=1, y=1},
spritediv = {x=1,y=1},
textures = {"elevator_industrial.png"},
stepheight = 0,
driver = nil,
velocity = 0,
target = nil,
floor_pos = nil,
old_target = nil,
old_pos = nil,
old_velocity = nil,
floorlist = nil,
calling_floors = {},
selected_floor = nil,
speed_limit = 2, -- Limit of the velocity
}
function elevator:on_punch(puncher, time_from_last_punch, tool_capabilities, direction)
if not puncher or not puncher:is_player() then
return
end
if puncher:get_player_control().sneak then
self.object:remove()
local inv = puncher:get_inventory()
if minetest.setting_getbool("creative_mode") then
if not inv:contains_item("main", "fancy_elevator:elevator") then
inv:add_item("main", "fancy_elevator:elevator")
end
else
inv:add_item("main", "fancy_elevator:elevator")
end
return
end
end
function elevatorindustrial:on_punch(puncher, time_from_last_punch, tool_capabilities, direction)
if not puncher or not puncher:is_player() then
return
end
if puncher:get_player_control().sneak then
self.object:remove()
local inv = puncher:get_inventory()
if minetest.setting_getbool("creative_mode") then
if not inv:contains_item("main", "fancy_elevator:elevatorindustrial") then
inv:add_item("main", "fancy_elevator:elevatorindustrial")
end
else
inv:add_item("main", "fancy_elevator:elevatorindustrial")
end
return
end
end
local lastformbyplayer = {}
function elevator:on_rightclick(clicker)
if not clicker or not clicker:is_player() then
return
end
if not self.pos then
self.pos = self.object:getpos()
end
local elevator_pos = elevator_func:round_pos(self.pos)
local clicker_pos = elevator_func:round_pos(clicker:getpos())
if not self.floor_pos then
self.floor_pos = elevator_func:get_floor_pos(self.object:getyaw(), elevator_pos)
end
if ( clicker_pos.x ~= self.floor_pos.x
and clicker_pos.x ~= elevator_pos.x )
or clicker_pos.y ~= elevator_pos.y
or ( clicker_pos.z ~= self.floor_pos.z
and clicker_pos.z ~=elevator_pos.z ) then
return
end
lastformbyplayer[clicker:get_player_name()] = self
if self.velocity == 0 then
self.floorlist = elevator_func:get_floors(elevator_pos, self.floor_pos, 1)
else
self.floorlist = elevator_func:get_floors(elevator_pos, self.floor_pos)
end
local floors = nil
if self.floorlist ~= nil then
local line = ""
for _,floor in pairs(self.floorlist) do
line = floor.text
if floor.calling == "true" then
line = "#300000"..line
end
if floors == nil then
floors = line
else
floors = floors .."," .. line
end
end
end
if floors == nil then
floors = ""
end
local formspec =
"size[6,7]"..
"label[2,0;Elevator]"..
"label[0,1;Floors:]"..
"textlist[0,1;5.75,4.7;floors;" ..
floors.."]"..
"button_exit[0,6;2,1;goto;Goto]"..
"button_exit[2,6;2,1;exit;Exit]"..
"button_exit[4,6;2,1;cancel;Cancel]"
minetest.show_formspec(clicker:get_player_name(), "elevator:floor_choose", formspec)
self.selected_floor = 0
end
function elevatorindustrial:on_rightclick(clicker)
if not clicker or not clicker:is_player() then
return
end
if not self.pos then
self.pos = self.object:getpos()
end
local elevator_pos = elevator_func:round_pos(self.pos)
local clicker_pos = elevator_func:round_pos(clicker:getpos())
if not self.floor_pos then
self.floor_pos = elevator_func:get_floor_pos(self.object:getyaw(), elevator_pos)
end
if ( clicker_pos.x ~= self.floor_pos.x
and clicker_pos.x ~= elevator_pos.x )
or clicker_pos.y ~= elevator_pos.y
or ( clicker_pos.z ~= self.floor_pos.z
and clicker_pos.z ~=elevator_pos.z ) then
return
end
lastformbyplayer[clicker:get_player_name()] = self
if self.velocity == 0 then
self.floorlist = elevator_func:get_floors(elevator_pos, self.floor_pos, 1)
else
self.floorlist = elevator_func:get_floors(elevator_pos, self.floor_pos)
end
local floors = nil
if self.floorlist ~= nil then
local line = ""
for _,floor in pairs(self.floorlist) do
line = floor.text
if floor.calling == "true" then
line = "#300000"..line
end
if floors == nil then
floors = line
else
floors = floors .."," .. line
end
end
end
if floors == nil then
floors = ""
end
local formspec =
"size[6,7]"..
"label[2,0;Elevator]"..
"label[0,1;Floors:]"..
"textlist[0,1;5.75,4.7;floors;" ..
floors.."]"..
"button_exit[0,6;2,1;goto;Goto]"..
"button_exit[2,6;2,1;exit;Exit]"..
"button_exit[4,6;2,1;cancel;Cancel]"
minetest.show_formspec(clicker:get_player_name(), "elevator:floor_choose", formspec)
self.selected_floor = 0
end
minetest.register_on_player_receive_fields(function(player, formname, fields)
if formname == "elevator:floor_choose" then
-- if fields.quit then
-- return
-- end
local playername = player:get_player_name()
local entity = lastformbyplayer[playername]
if not entity then
return
end
if fields["floors"] ~= nil then
local event = minetest.explode_textlist_event(fields["floors"])
entity.selected_floor = event.index
return
end
if fields["goto"] ~= nil and entity.selected_floor > 0 then
if entity.floorlist[entity.selected_floor] then
if not entity.driver then
entity.driver = player
player:set_look_yaw(elevator_func:round_yaw(entity.object:getyaw(), 91))
--entity.object:set_animation({x=0, y=20})
player:set_attach(entity.object, "", {x=0, y=5, z=0}, {x=0, y=0, z=0})
--player:set_animation({x=0, y=5})
--entity.object:set_animation({x=0, y=-1})
player:set_eye_offset({x=0, y=-3, z=0}, {x=0, y=0, z=0})
end
if entity.driver == player then
local pos = entity.floorlist[entity.selected_floor].pos
entity:add_calling(pos)
end
lastformbyplayer[playername] = nil
end
return
elseif fields["exit"] ~= nil and entity.target == nil then
if entity.driver == player then
entity.driver = nil
local pos = entity.object:getpos()
local pos_to = {}
pos_to.x = entity.floor_pos.x
pos_to.z = entity.floor_pos.z
pos_to.y = pos.y
--print(minetest.pos_to_string(pos_to))
--print(minetest.pos_to_string(player:getpos()))
player:set_detach()
player:set_animation({x=0, y=-5})
player:moveto(pos_to)
player:set_eye_offset({x=0, y=0 ,z=0}, {x=0, y=0, z=0})
end
lastformbyplayer[playername] = nil
return
end
end
end)
function elevator:move_to(pos)
if pos.y ~= nil then
local round_pos = elevator_func:round_pos(self.object:getpos())
round_pos.y = round_pos.y - 1
if minetest.get_node(round_pos).name == "fancy_elevator:ground" then
minetest.remove_node(round_pos)
end
self.target = pos
return true
else
minetest.log("error","Elevator: Failed to locate target position")
return false
end
end
function elevatorindustrial:move_to(pos)
if pos.y ~= nil then
local round_pos = elevator_func:round_pos(self.object:getpos())
round_pos.y = round_pos.y - 1
if minetest.get_node(round_pos).name == "fancy_elevator:ground" then
minetest.remove_node(round_pos)
end
self.target = pos
return true
else
minetest.log("error","Elevator: Failed to locate target position")
return false
end
end
minetest.register_entity("fancy_elevator:elevator", elevator)
minetest.register_craftitem("fancy_elevator:elevator", {
description = "Elevator",
inventory_image = minetest.inventorycube("elevator_top.png", "elevator_side.png", "elevator_front.png"),
wield_image = "elevator_side.png",
on_place = function(itemstack, placer, pointed_thing)
if not pointed_thing.type == "node" then
return
end
local pos = minetest.get_pointed_thing_position(pointed_thing, true)
for vary = 0, 1, 1 do
if not elevator_func:is_shaft({x=pos.x,y=pos.y+vary,z=pos.z}) then
minetest.chat_send_player(placer:get_player_name(),"This is not a shaft!")
return
end
end
local elevators, added = elevator_func:get_elevater(pos)
if #elevators > 0 then
minetest.chat_send_player(placer:get_player_name(),
"In this shaft is already an elevator!")
if not minetest.setting_getbool("creative_mode") then
for i=1,added,1 do
itemstack:add_item("fancy_elevator:elevator")
end
return itemstack
else
return
end
end
local entity = minetest.add_entity(pos, "fancy_elevator:elevator")
if entity ~= nil then
local yaw = elevator_func:round_yaw(placer:get_look_yaw(), 180)
entity:setyaw(yaw)
local entity1 = entity:get_luaentity()
entity1.floor_pos = elevator_func:get_floor_pos(yaw, pos)
if not minetest.setting_getbool("creative_mode") then
itemstack:take_item()
end
return itemstack
end
end,
})
minetest.register_entity("fancy_elevator:elevatorindustrial", elevatorindustrial)
minetest.register_craftitem("fancy_elevator:elevatorindustrial", {
description = "Elevator (Industrial)",
inventory_image = minetest.inventorycube("elevator_top.png", "elevator_truss.png", "elevator_truss.png"),
wield_image = "elevator_truss.png",
on_place = function(itemstack, placer, pointed_thing)
if not pointed_thing.type == "node" then
return
end
local pos = minetest.get_pointed_thing_position(pointed_thing, true)
for vary = 0, 1, 1 do
if not elevator_func:is_shaft({x=pos.x,y=pos.y+vary,z=pos.z}) then
minetest.chat_send_player(placer:get_player_name(),"This is not a shaft!")
return
end
end
local elevators, added = elevator_func:get_elevater(pos)
if #elevators > 0 then
minetest.chat_send_player(placer:get_player_name(),
"In this shaft is already an elevator!")
if not minetest.setting_getbool("creative_mode") then
for i=1,added,1 do
itemstack:add_item("fancy_elevator:elevatorindustrial")
end
return itemstack
else
return
end
end
local entity = minetest.add_entity(pos, "fancy_elevator:elevatorindustrial")
if entity ~= nil then
local yaw = elevator_func:round_yaw(placer:get_look_yaw(), 180)
entity:setyaw(yaw)
local entity1 = entity:get_luaentity()
entity1.floor_pos = elevator_func:get_floor_pos(yaw, pos)
if not minetest.setting_getbool("creative_mode") then
itemstack:take_item()
end
return itemstack
end
end,
})
function elevator:on_activate(staticdata, dtime_s)
self.object:set_armor_groups({immortal=1})
self.driver = nil
self.old_pos = self.object:getpos()
self.object:setvelocity({x=0, y=0, z=0})
self.velocity = 0;
end
function elevator:organice()
if not self.pos then
self.pos = self.object:getpos()
end
if not self.floor_pos then
self.floor_pos = elevator_func:get_floor_pos(self.object:getyaw(), self.pos)
end
self.floorlist = elevator_func:get_floors(self.pos, self.floor_pos)
self.calling_floors = elevator_func:get_calling_floors(self.floorlist)
if #self.calling_floors > 0 then
if self.target == nil then
if self.old_target and elevator_doors.get_door_status(self.old_target) ~= 0 then
return
end
if self.pos.y == self.calling_floors[1].pos.y then
return
end
if #self.calling_floors > 0 then
--self.old_target = self.target --why?
self:move_to(self.calling_floors[1].pos)
end
end
end
end
function elevator:add_calling(calling_pos)
if self.pos == nil then
self.pos = self.object:getpos()
end
local meta = minetest.get_meta(calling_pos)
if self.pos.y == calling_pos.y then
meta:set_string("calling", "false")
meta:set_int("order", -1)
local name = minetest.get_node(calling_pos).name
name = name:sub(0,name:len()-4)
elevator_doors.open_door(calling_pos, 1, name, name.."_t_1", name.."_b_2", name.."_t_2", {1,2,3,0}, 1)
self:organice()
return
end
local round_pos = elevator_func:round_pos(self.pos)
if self.floor_pos == nil then
self.floor_pos = elevator_func:get_floor_pos(self.object:getyaw(), round_pos)
end
self.floorlist = elevator_func:get_floors(round_pos, self.floor_pos)
self.calling_floors = elevator_func:get_calling_floors(self.floorlist)
local calling_h = #self.calling_floors+1
local meta = minetest.get_meta(calling_pos)
meta:set_string("calling", "true")
meta:set_int("order", calling_h)
self:organice()
end
function elevator:on_step(dtime)
if self.target ~= nil then
self.pos = self.object:getpos()
self.pos.y = self.pos.y
if self.target.y ~= self.pos.y then
local diff = 0
if self.target.y > self.pos.y then
diff = self.target.y - self.pos.y
elseif self.target.y < self.pos.y then
diff = self.pos.y - self.target.y
end
if self.target.y > self.pos.y then
if self.velocity <= 0 then
self.velocity = 0.1
end
if diff > math.abs(self.velocity) then
self.velocity = self.velocity*2
else
self.velocity = self.velocity/2
if diff < 0.2 then
elevator:stop_at_target(self, elevator_func:round_pos(self.pos))
end
end
elseif self.target.y < self.pos.y then
if self.velocity >= 0 then
self.velocity = -0.1
end
if diff > math.abs(self.velocity) then
self.velocity = self.velocity*2
else
self.velocity = self.velocity/2
if diff < 0.2 then
elevator:stop_at_target(self, elevator_func:round_pos(self.pos))
end
end
end
if math.abs(self.velocity) > self.speed_limit then
if self.velocity > 0 then
self.velocity = self.speed_limit
else
self.velocity = self.speed_limit * -1
end
end
self.object:setvelocity({x=0, y=self.velocity, z=0})
self.old_pos = self.object:getpos()
self.old_velocity = self.velocity
else
self.target = nil
self.velocity = 0
self.old_pos = self.object:getpos()
self.old_velocity = self.velocity
self.object:setvelocity({x=0, y=self.velocity, z=0})
self:organice()
end
else
if self.velocity ~= 0 then
self.velocity = 0
self.old_pos = self.object:getpos()
self.old_velocity = self.velocity
self.object:setvelocity({x=0, y=self.velocity, z=0})
end
end
end
function elevatorindustrial:on_activate(staticdata, dtime_s)
self.object:set_armor_groups({immortal=1})
self.driver = nil
self.old_pos = self.object:getpos()
self.object:setvelocity({x=0, y=0, z=0})
self.velocity = 0;
end
function elevatorindustrial:organice()
if not self.pos then
self.pos = self.object:getpos()
end
if not self.floor_pos then
self.floor_pos = elevator_func:get_floor_pos(self.object:getyaw(), self.pos)
end
self.floorlist = elevator_func:get_floors(self.pos, self.floor_pos)
self.calling_floors = elevator_func:get_calling_floors(self.floorlist)
if #self.calling_floors > 0 then
if self.target == nil then
if self.old_target and elevator_doors.get_door_status(self.old_target) ~= 0 then
return
end
if self.pos.y == self.calling_floors[1].pos.y then
return
end
if #self.calling_floors > 0 then
--self.old_target = self.target --why?
self:move_to(self.calling_floors[1].pos)
end
end
end
end
function elevatorindustrial:add_calling(calling_pos)
if self.pos == nil then
self.pos = self.object:getpos()
end
local meta = minetest.get_meta(calling_pos)
if self.pos.y == calling_pos.y then
meta:set_string("calling", "false")
meta:set_int("order", -1)
local name = minetest.get_node(calling_pos).name
name = name:sub(0,name:len()-4)
elevator_doors.open_door(calling_pos, 1, name, name.."_t_1", name.."_b_2", name.."_t_2", {1,2,3,0}, 1)
self:organice()
return
end
local round_pos = elevator_func:round_pos(self.pos)
if self.floor_pos == nil then
self.floor_pos = elevator_func:get_floor_pos(self.object:getyaw(), round_pos)
end
self.floorlist = elevator_func:get_floors(round_pos, self.floor_pos)
self.calling_floors = elevator_func:get_calling_floors(self.floorlist)
local calling_h = #self.calling_floors+1
local meta = minetest.get_meta(calling_pos)
meta:set_string("calling", "true")
meta:set_int("order", calling_h)
self:organice()
end
function elevatorindustrial:on_step(dtime)
if self.target ~= nil then
self.pos = self.object:getpos()
self.pos.y = self.pos.y
if self.target.y ~= self.pos.y then
local diff = 0
if self.target.y > self.pos.y then
diff = self.target.y - self.pos.y
elseif self.target.y < self.pos.y then
diff = self.pos.y - self.target.y
end
if self.target.y > self.pos.y then
if self.velocity <= 0 then
self.velocity = 0.1
end
if diff > math.abs(self.velocity) then
self.velocity = self.velocity*2
else
self.velocity = self.velocity/2
if diff < 0.2 then
elevatorindustrial:stop_at_target(self, elevator_func:round_pos(self.pos))
end
end
elseif self.target.y < self.pos.y then
if self.velocity >= 0 then
self.velocity = -0.1
end
if diff > math.abs(self.velocity) then
self.velocity = self.velocity*2
else
self.velocity = self.velocity/2
if diff < 0.2 then
elevatorindustrial:stop_at_target(self, elevator_func:round_pos(self.pos))
end
end
end
if math.abs(self.velocity) > self.speed_limit then
if self.velocity > 0 then
self.velocity = self.speed_limit
else
self.velocity = self.speed_limit * -1
end
end
self.object:setvelocity({x=0, y=self.velocity, z=0})
self.old_pos = self.object:getpos()
self.old_velocity = self.velocity
else
self.target = nil
self.velocity = 0
self.old_pos = self.object:getpos()
self.old_velocity = self.velocity
self.object:setvelocity({x=0, y=self.velocity, z=0})
self:organice()
end
else
if self.velocity ~= 0 then
self.velocity = 0
self.old_pos = self.object:getpos()
self.old_velocity = self.velocity
self.object:setvelocity({x=0, y=self.velocity, z=0})
end
end
end
function elevator:stop_at_target(self, round_pos)
self.velocity = 0
self.object:setvelocity({x=0, y=0, z=0})
self.object:moveto({x=round_pos.x, y=self.target.y, z=round_pos.z})
local name = minetest.get_node(self.target).name
name = name:sub(0,name:len()-4)
self.old_target = self.target
self.target.y = self.target.y
elevator_doors.open_door(self.target, 1, name, name.."_t_1", name.."_b_2", name.."_t_2", {1,2,3,0}, 1)
local meta = minetest.get_meta(self.target)
meta:set_string("calling", "false")
meta:set_int("order", -1)
self.floorlist = elevator_func:get_floors(round_pos, self.floor_pos)
self.calling_floors = elevator_func:get_calling_floors(self.floorlist)
local floorname = nil
for i=1, #self.calling_floors, 1 do
meta = minetest.get_meta(self.calling_floors[i].pos)
meta:set_int("order",i)
end
self.target = nil
self.pos = self.object:getpos()
local pos = elevator_func:round_pos(self.pos)
pos.y = pos.y - 1
if minetest.get_node(pos).name == "air" then
minetest.set_node(pos, {name="fancy_elevator:ground"})
end
self:organice()
end
function elevatorindustrial:stop_at_target(self, round_pos)
self.velocity = 0
self.object:setvelocity({x=0, y=0, z=0})
self.object:moveto({x=round_pos.x, y=self.target.y, z=round_pos.z})
local name = minetest.get_node(self.target).name
name = name:sub(0,name:len()-4)
self.old_target = self.target
self.target.y = self.target.y
elevator_doors.open_door(self.target, 1, name, name.."_t_1", name.."_b_2", name.."_t_2", {1,2,3,0}, 1)
local meta = minetest.get_meta(self.target)
meta:set_string("calling", "false")
meta:set_int("order", -1)
self.floorlist = elevator_func:get_floors(round_pos, self.floor_pos)
self.calling_floors = elevator_func:get_calling_floors(self.floorlist)
local floorname = nil
for i=1, #self.calling_floors, 1 do
meta = minetest.get_meta(self.calling_floors[i].pos)
meta:set_int("order",i)
end
self.target = nil
self.pos = self.object:getpos()
local pos = elevator_func:round_pos(self.pos)
pos.y = pos.y - 1
if minetest.get_node(pos).name == "air" then
minetest.set_node(pos, {name="fancy_elevator:ground"})
end
self:organice()
end
| lgpl-2.1 |
starlightknight/darkstar | scripts/globals/spells/aquaveil.lua | 12 | 1319 | -----------------------------------------
-- Spell: Aquaveil
-- Reduces chance of having a spell interrupted.
-----------------------------------------
require("scripts/globals/magic")
require("scripts/globals/msg")
require("scripts/globals/settings")
require("scripts/globals/status")
-----------------------------------------
function onMagicCastingCheck(caster, target, spell)
return 0
end
function onSpellCast(caster, target, spell)
target:delStatusEffect(dsp.effect.AQUAVEIL)
-- duration is said to be based on enhancing skill with max 5 minutes, but I could find no
-- tests that quantify the relationship so I'm using 5 minutes for now.
local duration = calculateDuration(300, spell:getSkillType(), spell:getSpellGroup(), caster, target)
local power = AQUAVEIL_COUNTER + caster:getMod(dsp.mod.AQUAVEIL_COUNT)
if caster:getSkillLevel(dsp.skill.ENHANCING_MAGIC) >= 200 then -- cutoff point is estimated. https://www.bg-wiki.com/bg/Aquaveil
power = power + 1
end
power = math.max(power, 1) -- this shouldn't happen but it's probably best to prevent someone from accidentally underflowing the counter...
target:addStatusEffect(dsp.effect.AQUAVEIL, power, 0, duration)
spell:setMsg(dsp.msg.basic.MAGIC_GAIN_EFFECT)
return dsp.effect.AQUAVEIL
end
| gpl-3.0 |
starlightknight/darkstar | scripts/globals/abilities/pets/attachments/tension_spring_iii.lua | 11 | 1329 | -----------------------------------
-- Attachment: Tension Spring III
-----------------------------------
require("scripts/globals/automaton")
require("scripts/globals/status")
-----------------------------------
function onEquip(pet)
onUpdate(pet, 0)
end
function onUnequip(pet)
updateModPerformance(pet, dsp.mod.ATTP, 'tension_iii_attp', 0)
updateModPerformance(pet, dsp.mod.RATTP, 'tension_iii_rattp', 0)
end
function onManeuverGain(pet, maneuvers)
onUpdate(pet, maneuvers)
end
function onManeuverLose(pet, maneuvers)
onUpdate(pet, maneuvers - 1)
end
function onUpdate(pet, maneuvers)
if maneuvers == 0 then
updateModPerformance(pet, dsp.mod.ATTP, 'tension_iii_attp', 12)
updateModPerformance(pet, dsp.mod.RATTP, 'tension_iii_rattp', 12)
elseif maneuvers == 1 then
updateModPerformance(pet, dsp.mod.ATTP, 'tension_iii_attp', 15)
updateModPerformance(pet, dsp.mod.RATTP, 'tension_iii_rattp', 15)
elseif maneuvers == 2 then
updateModPerformance(pet, dsp.mod.ATTP, 'tension_iii_attp', 18)
updateModPerformance(pet, dsp.mod.RATTP, 'tension_iii_rattp', 18)
elseif maneuvers == 3 then
updateModPerformance(pet, dsp.mod.ATTP, 'tension_iii_attp', 21)
updateModPerformance(pet, dsp.mod.RATTP, 'tension_iii_rattp', 21)
end
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Windurst_Waters_[S]/npcs/Ponono.lua | 3 | 1059 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Ponono
-- Type: Standard NPC
-- @zone 94
-- !pos 156.069 -0.001 -15.667
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00c1);
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 |
gedads/Neodynamis | scripts/zones/Metalworks/npcs/Malduc.lua | 3 | 3690 | -----------------------------------
-- Area: Metalworks
-- NPC: Malduc
-- Type: Mission Giver
-- !pos 66.200 -14.999 4.426 237
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local CurrentMission = player:getCurrentMission(BASTOK);
local Count = trade:getItemCount();
if (CurrentMission ~= 255) then
if (CurrentMission == FETICHISM and player:hasCompletedMission(BASTOK,FETICHISM) == false and trade:hasItemQty(606,1) and trade:hasItemQty(607,1) and trade:hasItemQty(608,1) and trade:hasItemQty(609,1) and Count == 4) then
player:startEvent(0x03F0); -- Finish Mission "Fetichism" (First Time)
elseif (CurrentMission == FETICHISM and trade:hasItemQty(606,1) and trade:hasItemQty(607,1) and trade:hasItemQty(608,1) and trade:hasItemQty(609,1) and Count == 4) then
player:startEvent(0x03ED); -- Finish Mission "Fetichism" (Repeat)
elseif (CurrentMission == TO_THE_FORSAKEN_MINES and player:hasCompletedMission(BASTOK,TO_THE_FORSAKEN_MINES) == false and trade:hasItemQty(563,1) and Count == 1) then
player:startEvent(0x03F2); -- Finish Mission "To the forsaken mines" (First Time)
elseif (CurrentMission == TO_THE_FORSAKEN_MINES and trade:hasItemQty(563,1) and Count == 1) then
player:startEvent(0x03EE); -- Finish Mission "To the forsaken mines" (Repeat)
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getNation() ~= NATION_BASTOK) then
player:startEvent(0x03eb); -- For non-Bastokian
else
local CurrentMission = player:getCurrentMission(BASTOK);
local cs, p, offset = getMissionOffset(player,1,CurrentMission,player:getVar("MissionStatus"));
if (cs ~= 0 or offset ~= 0 or ((CurrentMission == 0 or CurrentMission == 16) and offset == 0)) then
if (CurrentMission <= 15 and cs == 0) then
player:showText(npc,ORIGINAL_MISSION_OFFSET + offset); -- dialog after accepting mission (Rank 1~5)
elseif (CurrentMission > 15 and cs == 0) then
player:showText(npc,EXTENDED_MISSION_OFFSET + offset); -- dialog after accepting mission (Rank 6~10)
else
player:startEvent(cs,p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8]);
end
elseif (player:getRank() == 1 and player:hasCompletedMission(BASTOK,THE_ZERUHN_REPORT) == false) then
player:startEvent(0x03E8); -- Start First Mission "The Zeruhn Report"
elseif (CurrentMission ~= 255) then
player:startEvent(0x03EA); -- Have mission already activated
else
local flagMission, repeatMission = getMissionMask(player);
player:startEvent(0x03E9,flagMission,0,0,0,0,repeatMission); -- Mission List
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
finishMissionTimeline(player,1,csid,option);
end; | gpl-3.0 |
starlightknight/darkstar | scripts/zones/RuLude_Gardens/npcs/_6r2.lua | 9 | 1933 | -----------------------------------
-- Area: Ru'Lude Gardens
-- Door: Bastokan Emb.
-- Bastok Missions 3.3 "Jeuno" and 4.1 "Magicite"
-----------------------------------
local ID = require("scripts/zones/RuLude_Gardens/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local pNation = player:getNation()
if pNation == dsp.nation.BASTOK then
local currentMission = player:getCurrentMission(pNation)
local MissionStatus = player:getCharVar("MissionStatus")
if currentMission == dsp.mission.id.bastok.JEUNO and MissionStatus == 4 then
player:startEvent(38)
elseif player:getRank() == 4 and
currentMission == dsp.mission.id.bastok.NONE and
getMissionRankPoints(player,13) == 1
then
if player:hasKeyItem(dsp.ki.ARCHDUCAL_AUDIENCE_PERMIT) then
player:startEvent(129,1)
else
player:startEvent(129)
end
elseif player:getRank() >= 4 then
player:messageSpecial(ID.text.RESTRICTED)
else
player:messageSpecial(ID.text.RESTRICTED+1) -- you have no letter of introduction
end
else
player:messageSpecial(ID.text.RESTRICTED+1) -- you have no letter of introduction
end
return 1
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if csid == 38 then
finishMissionTimeline(player,1,csid,option)
elseif csid == 129 and option == 1 then
player:setCharVar("MissionStatus",1)
if not player:hasKeyItem(dsp.ki.ARCHDUCAL_AUDIENCE_PERMIT) then
player:addKeyItem(dsp.ki.ARCHDUCAL_AUDIENCE_PERMIT)
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.ARCHDUCAL_AUDIENCE_PERMIT)
end
end
end | gpl-3.0 |
gedads/Neodynamis | scripts/zones/Arrapago_Reef/npcs/Meyaada.lua | 3 | 2736 | -----------------------------------
-- Area: Arrapago Reef
-- NPC: Meyaada
-- Type: Assault
-- !pos 22.446 -7.920 573.390 54
-----------------------------------
package.loaded["scripts/zones/Arrapago_Reef/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/zones/Arrapago_Reef/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local toauMission = player:getCurrentMission(TOAU);
local beginnings = player:getQuestStatus(AHT_URHGAN,BEGINNINGS);
-- IMMORTAL SENTRIES
if (toauMission == IMMORTAL_SENTRIES) then
if (player:hasKeyItem(SUPPLIES_PACKAGE)) then
player:startEvent(5);
elseif (player:getVar("AhtUrganStatus") == 1) then
player:startEvent(6);
end;
-- BEGINNINGS
elseif (beginnings == QUEST_ACCEPTED) then
if (not player:hasKeyItem(BRAND_OF_THE_SPRINGSERPENT)) then
player:startEvent(10); -- brands you
else
player:startEvent(11); -- a harsh road lies before you
end;
-- ASSAULT --
elseif (toauMission >= PRESIDENT_SALAHEEM) then
local IPpoint = player:getCurrency("imperial_standing");
if (player:hasKeyItem(ILRUSI_ASSAULT_ORDERS) and player:hasKeyItem(ASSAULT_ARMBAND) == false) then
player:startEvent(223,50,IPpoint);
else
player:startEvent(7);
-- player:delKeyItem(ASSAULT_ARMBAND);
end;
-- DEFAULT DIALOG
else
player:startEvent(4);
end;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- IMMORTAL SENTRIES
if (csid == 5 and option == 1) then
player:delKeyItem(SUPPLIES_PACKAGE);
player:setVar("AhtUrganStatus",1);
-- BEGINNINGS
elseif (csid == 10) then
player:addKeyItem(BRAND_OF_THE_SPRINGSERPENT);
player:messageSpecial(KEYITEM_OBTAINED,BRAND_OF_THE_SPRINGSERPENT);
-- ASSAULT --
elseif (csid == 223 and option == 1) then
player:delCurrency("imperial_standing", 50);
player:addKeyItem(ASSAULT_ARMBAND);
player:messageSpecial(KEYITEM_OBTAINED,ASSAULT_ARMBAND);
end;
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Jugner_Forest/npcs/Signpost.lua | 17 | 2835 | -----------------------------------
-- Area: Jugner Forest
-- NPC: Signpost
-- Involved in Quest: Grimy Signposts
-------------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local X = player:getXPos();
local Z = player:getZPos();
if ((X > -79.3 and X < -67.3) and (Z > 94.5 and Z < 106.5)) then
if (player:getQuestStatus(SANDORIA,GRIMY_SIGNPOSTS) == QUEST_ACCEPTED and not player:getMaskBit(player:getVar("CleanSignPost"),0)) then
player:startEvent(0x0006,1);
else
player:startEvent(0x0001);
end
elseif ((X > -266.2 and X < -254.2) and (Z > -29.2 and Z < -17.2)) then
if (player:getQuestStatus(SANDORIA,GRIMY_SIGNPOSTS) == QUEST_ACCEPTED and not player:getMaskBit(player:getVar("CleanSignPost"),1)) then
player:startEvent(0x0007,1);
else
player:startEvent(0x0002);
end
elseif ((X > -463.7 and X < -451.7) and (Z > -422.1 and Z < -410.1)) then
if (player:getQuestStatus(SANDORIA,GRIMY_SIGNPOSTS) == QUEST_ACCEPTED and not player:getMaskBit(player:getVar("CleanSignPost"),2)) then
player:startEvent(0x0008,1);
else
player:startEvent(0x0003);
end
elseif ((X > 295.4 and X < 307.3) and (Z > 412.8 and Z < 424.8)) then
if (player:getQuestStatus(SANDORIA,GRIMY_SIGNPOSTS) == QUEST_ACCEPTED and not player:getMaskBit(player:getVar("CleanSignPost"),3)) then
player:startEvent(0x0009,1);
else
player:startEvent(0x0004);
end
else
print("Unknown Signpost");
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 == 6 and option == 1) then
player:setMaskBit(player:getVar("CleanSignPost"),"CleanSignPost",0,true);
elseif (csid == 7 and option == 1) then
player:setMaskBit(player:getVar("CleanSignPost"),"CleanSignPost",1,true);
elseif (csid == 8 and option == 1) then
player:setMaskBit(player:getVar("CleanSignPost"),"CleanSignPost",2,true);
elseif (csid == 9 and option == 1) then
player:setMaskBit(player:getVar("CleanSignPost"),"CleanSignPost",3,true);
end
end; | gpl-3.0 |
gedads/Neodynamis | scripts/zones/Aht_Urhgan_Whitegate/npcs/Sajaaya.lua | 59 | 1060 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Sajaaya
-- Type: Weather Reporter
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01F6,0,0,0,0,0,0,0,VanadielTime());
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
gedads/Neodynamis | scripts/zones/Jugner_Forest/mobs/Sappy_Sycamore.lua | 3 | 1415 | ----------------------------------
-- Area: Jugner_Forest
-- NM: Sappy Sycamore
-----------------------------------
require("scripts/globals/msg");
-----------------------------------
-- onMobInitialize
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID());
mob:addMod(MOD_SLEEPRES,20);
mob:addMod(MOD_BINDRES,20);
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(mob,target,damage)
-- Guesstimating 1 in 4 chance to slow on melee.
if ((math.random(1,100) >= 25) or (target:hasStatusEffect(EFFECT_SLOW) == true)) then
return 0,0,0;
else
local duration = math.random(15,25);
target:addStatusEffect(EFFECT_SLOW,15,0,duration); -- sproud smack like
return SUBEFFECT_SLOW,msgBasic.ADD_EFFECT_STATUS,EFFECT_SLOW;
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
UpdateNMSpawnPoint(mob:getID());
mob:setRespawnTime(math.random(3600,4200)); -- repop 60-70min
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/globals/items/flame_sword.lua | 7 | 1035 | -----------------------------------------
-- ID: 16621
-- Item: Flame Sword
-- Additional Effect: Fire Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/msg");
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(3,10);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_FIRE, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_FIRE,0);
dmg = adjustForTarget(target,dmg,ELE_FIRE);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_FIRE,dmg);
local message = msgBasic.ADD_EFFECT_DMG;
if (dmg < 0) then
message = msgBasic.ADD_EFFECT_HEAL;
end
return SUBEFFECT_FIRE_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
starlightknight/darkstar | scripts/globals/items/fulm-long_salmon_sub.lua | 11 | 1197 | -----------------------------------------
-- ID: 4266
-- Item: fulm-long_salmon_sub
-- Food Effect: 60Min, All Races
-----------------------------------------
-- DEX +2
-- VIT +1
-- AGI +1
-- INT +2
-- MND -2
-- Ranged Accuracy +3
-----------------------------------------
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,3600,4266)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.DEX, 2)
target:addMod(dsp.mod.VIT, 1)
target:addMod(dsp.mod.AGI, 1)
target:addMod(dsp.mod.INT, 2)
target:addMod(dsp.mod.MND, -2)
target:addMod(dsp.mod.RACC, 3)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.DEX, 2)
target:delMod(dsp.mod.VIT, 1)
target:delMod(dsp.mod.AGI, 1)
target:delMod(dsp.mod.INT, 2)
target:delMod(dsp.mod.MND, -2)
target:delMod(dsp.mod.RACC, 3)
end
| gpl-3.0 |
bradparks/hammerspoon-config | _scratch/eventtest.lua | 2 | 10839 | --
-- Eventtap testing
--
-- This is a sample file for testing out eventtap modules.
-- Currently it only tests receiving events and displaying the details in the hs console.
--
-- Place this file in your ~/.hammerspoon directory. Then you can play with it from the hs
-- console as follows:
--
-- dofile("eventtest.lua")
--
-- a = e.new(et.key,f) -- capture only keyboard events
-- or
-- a = e.new(et.all,f) -- all defined events
-- or
-- a = e.new({eep.keydown, eep.keyup} ,f) -- capture only keydown and keyup events
-- (this differs from et.key in that flag changes (i.e. key modifiers) are not
-- sufficient to trigger an event by themselves.)
--
-- a:start()
--
e = require("hs.eventtap")
k = require("hs.keycodes")
i = require("hs.inspect")
eet = e.event.types
eep = e.event.properties
et = {
all = { eet.keyDown, eet.keyUp, eet.leftMouseDown, eet.leftMouseUp, eet.leftMouseDragged, eet.rightMouseDown, eet.rightMouseUp, eet.rightMouseDragged, eet.middleMouseDown, eet.middleMouseUp, eet.middleMouseDragged, eet.mouseMoved, eet.flagsChanged, eet.scrollWheel, eet.tabletPointer, eet.tabletProximity },
key = { eet.keyDown, eet.keyUp, eet.flagsChanged },
mouse = { eet.leftMouseDown, eet.leftMouseUp, eet.leftMouseDragged, eet.rightMouseDown, eet.rightMouseUp, eet.rightMouseDragged, eet.middleMouseDown, eet.middleMouseUp, eet.middleMouseDragged, eet.mouseMoved, eet.scrollWheel, eet.tabletPointer, eet.tabletProximity },
other = { "all", eet.keyDown, eet.keyUp, eet.leftMouseDown, eet.leftMouseUp, eet.leftMouseDragged, eet.rightMouseDown, eet.rightMouseUp, eet.rightMouseDragged, eet.middleMouseDown, eet.middleMouseUp, eet.middleMouseDragged, eet.mouseMoved, eet.flagsChanged, eet.scrollWheel, eet.tabletPointer, eet.tabletProximity, eet.nullEvent },
}
f = function(o)
local event_details = {
{ n_type = o:getType(), s_type = eet[o:getType()] },
{ t_flags = o:getFlags(), n_keycode = o:getKeyCode(), s_keycode = k.map[o:getKeyCode()] },
{
mouseEventNumber = o:getProperty(eep.mouseEventNumber) ~= 0 and o:getProperty(eep.mouseEventNumber) or nil,
mouseEventClickState = o:getProperty(eep.mouseEventClickState) ~= 0 and o:getProperty(eep.mouseEventClickState) or nil,
mouseEventPressure = o:getProperty(eep.mouseEventPressure) ~= 0 and o:getProperty(eep.mouseEventPressure) or nil,
mouseEventButtonNumber = o:getProperty(eep.mouseEventButtonNumber) ~= 0 and o:getProperty(eep.mouseEventButtonNumber) or nil,
mouseEventDeltaX = o:getProperty(eep.mouseEventDeltaX) ~= 0 and o:getProperty(eep.mouseEventDeltaX) or nil,
mouseEventDeltaY = o:getProperty(eep.mouseEventDeltaY) ~= 0 and o:getProperty(eep.mouseEventDeltaY) or nil,
mouseEventInstantMouser = o:getProperty(eep.mouseEventInstantMouser) ~= 0 and o:getProperty(eep.mouseEventInstantMouser) or nil,
mouseEventSubtype = o:getProperty(eep.mouseEventSubtype) ~= 0 and o:getProperty(eep.mouseEventSubtype) or nil,
keyboardEventAutorepeat = o:getProperty(eep.keyboardEventAutorepeat) ~= 0 and o:getProperty(eep.keyboardEventAutorepeat) or nil,
keyboardEventKeycode = o:getProperty(eep.keyboardEventKeycode) ~= 0 and o:getProperty(eep.keyboardEventKeycode) or nil,
keyboardEventKeyboardType = o:getProperty(eep.keyboardEventKeyboardType) ~= 0 and o:getProperty(eep.keyboardEventKeyboardType) or nil,
scrollWheelEventDeltaAxis1 = o:getProperty(eep.scrollWheelEventDeltaAxis1) ~= 0 and o:getProperty(eep.scrollWheelEventDeltaAxis1) or nil,
scrollWheelEventDeltaAxis2 = o:getProperty(eep.scrollWheelEventDeltaAxis2) ~= 0 and o:getProperty(eep.scrollWheelEventDeltaAxis2) or nil,
scrollWheelEventDeltaAxis3 = o:getProperty(eep.scrollWheelEventDeltaAxis3) ~= 0 and o:getProperty(eep.scrollWheelEventDeltaAxis3) or nil,
scrollWheelEventFixedPtDeltaAxis1 = o:getProperty(eep.scrollWheelEventFixedPtDeltaAxis1) ~= 0 and o:getProperty(eep.scrollWheelEventFixedPtDeltaAxis1) or nil,
scrollWheelEventFixedPtDeltaAxis2 = o:getProperty(eep.scrollWheelEventFixedPtDeltaAxis2) ~= 0 and o:getProperty(eep.scrollWheelEventFixedPtDeltaAxis2) or nil,
scrollWheelEventFixedPtDeltaAxis3 = o:getProperty(eep.scrollWheelEventFixedPtDeltaAxis3) ~= 0 and o:getProperty(eep.scrollWheelEventFixedPtDeltaAxis3) or nil,
scrollWheelEventPointDeltaAxis1 = o:getProperty(eep.scrollWheelEventPointDeltaAxis1) ~= 0 and o:getProperty(eep.scrollWheelEventPointDeltaAxis1) or nil,
scrollWheelEventPointDeltaAxis2 = o:getProperty(eep.scrollWheelEventPointDeltaAxis2) ~= 0 and o:getProperty(eep.scrollWheelEventPointDeltaAxis2) or nil,
scrollWheelEventPointDeltaAxis3 = o:getProperty(eep.scrollWheelEventPointDeltaAxis3) ~= 0 and o:getProperty(eep.scrollWheelEventPointDeltaAxis3) or nil,
scrollWheelEventInstantMouser = o:getProperty(eep.scrollWheelEventInstantMouser) ~= 0 and o:getProperty(eep.scrollWheelEventInstantMouser) or nil,
tabletEventPointX = o:getProperty(eep.tabletEventPointX) ~= 0 and o:getProperty(eep.tabletEventPointX) or nil,
tabletEventPointY = o:getProperty(eep.tabletEventPointY) ~= 0 and o:getProperty(eep.tabletEventPointY) or nil,
tabletEventPointZ = o:getProperty(eep.tabletEventPointZ) ~= 0 and o:getProperty(eep.tabletEventPointZ) or nil,
tabletEventPointButtons = o:getProperty(eep.tabletEventPointButtons) ~= 0 and o:getProperty(eep.tabletEventPointButtons) or nil,
tabletEventPointPressure = o:getProperty(eep.tabletEventPointPressure) ~= 0 and o:getProperty(eep.tabletEventPointPressure) or nil,
tabletEventTiltX = o:getProperty(eep.tabletEventTiltX) ~= 0 and o:getProperty(eep.tabletEventTiltX) or nil,
tabletEventTiltY = o:getProperty(eep.tabletEventTiltY) ~= 0 and o:getProperty(eep.tabletEventTiltY) or nil,
tabletEventRotation = o:getProperty(eep.tabletEventRotation) ~= 0 and o:getProperty(eep.tabletEventRotation) or nil,
tabletEventTangentialPressure = o:getProperty(eep.tabletEventTangentialPressure) ~= 0 and o:getProperty(eep.tabletEventTangentialPressure) or nil,
tabletEventDeviceID = o:getProperty(eep.tabletEventDeviceID) ~= 0 and o:getProperty(eep.tabletEventDeviceID) or nil,
tabletEventVendor1 = o:getProperty(eep.tabletEventVendor1) ~= 0 and o:getProperty(eep.tabletEventVendor1) or nil,
tabletEventVendor2 = o:getProperty(eep.tabletEventVendor2) ~= 0 and o:getProperty(eep.tabletEventVendor2) or nil,
tabletEventVendor3 = o:getProperty(eep.tabletEventVendor3) ~= 0 and o:getProperty(eep.tabletEventVendor3) or nil,
tabletProximityEventVendorID = o:getProperty(eep.tabletProximityEventVendorID) ~= 0 and o:getProperty(eep.tabletProximityEventVendorID) or nil,
tabletProximityEventTabletID = o:getProperty(eep.tabletProximityEventTabletID) ~= 0 and o:getProperty(eep.tabletProximityEventTabletID) or nil,
tabletProximityEventPointerID = o:getProperty(eep.tabletProximityEventPointerID) ~= 0 and o:getProperty(eep.tabletProximityEventPointerID) or nil,
tabletProximityEventDeviceID = o:getProperty(eep.tabletProximityEventDeviceID) ~= 0 and o:getProperty(eep.tabletProximityEventDeviceID) or nil,
tabletProximityEventSystemTabletID = o:getProperty(eep.tabletProximityEventSystemTabletID) ~= 0 and o:getProperty(eep.tabletProximityEventSystemTabletID) or nil,
tabletProximityEventVendorPointerType = o:getProperty(eep.tabletProximityEventVendorPointerType) ~= 0 and o:getProperty(eep.tabletProximityEventVendorPointerType) or nil,
tabletProximityEventVendorPointerSerialNumber = o:getProperty(eep.tabletProximityEventVendorPointerSerialNumber) ~= 0 and o:getProperty(eep.tabletProximityEventVendorPointerSerialNumber) or nil,
tabletProximityEventVendorUniqueID = o:getProperty(eep.tabletProximityEventVendorUniqueID) ~= 0 and o:getProperty(eep.tabletProximityEventVendorUniqueID) or nil,
tabletProximityEventCapabilityMask = o:getProperty(eep.tabletProximityEventCapabilityMask) ~= 0 and o:getProperty(eep.tabletProximityEventCapabilityMask) or nil,
tabletProximityEventPointerType = o:getProperty(eep.tabletProximityEventPointerType) ~= 0 and o:getProperty(eep.tabletProximityEventPointerType) or nil,
tabletProximityEventEnterProximity = o:getProperty(eep.tabletProximityEventEnterProximity) ~= 0 and o:getProperty(eep.tabletProximityEventEnterProximity) or nil,
eventTargetProcessSerialNumber = o:getProperty(eep.eventTargetProcessSerialNumber) ~= 0 and o:getProperty(eep.eventTargetProcessSerialNumber) or nil,
eventTargetUnixProcessID = o:getProperty(eep.eventTargetUnixProcessID) ~= 0 and o:getProperty(eep.eventTargetUnixProcessID) or nil,
eventSourceUnixProcessID = o:getProperty(eep.eventSourceUnixProcessID) ~= 0 and o:getProperty(eep.eventSourceUnixProcessID) or nil,
eventSourceUserData = o:getProperty(eep.eventSourceUserData) ~= 0 and o:getProperty(eep.eventSourceUserData) or nil,
eventSourceUserID = o:getProperty(eep.eventSourceUserID) ~= 0 and o:getProperty(eep.eventSourceUserID) or nil,
eventSourceGroupID = o:getProperty(eep.eventSourceGroupID) ~= 0 and o:getProperty(eep.eventSourceGroupID) or nil,
eventSourceStateID = o:getProperty(eep.eventSourceStateID) ~= 0 and o:getProperty(eep.eventSourceStateID) or nil,
scrollWheelEventIsContinuous = o:getProperty(eep.scrollWheelEventIsContinuous) ~= 0 and o:getProperty(eep.scrollWheelEventIsContinuous) or nil,
MouseButtons = {
o:getButtonState( 0), o:getButtonState( 1), o:getButtonState( 2), o:getButtonState( 3),
o:getButtonState( 4), o:getButtonState( 5), o:getButtonState( 6), o:getButtonState( 7),
o:getButtonState( 8), o:getButtonState( 9), o:getButtonState(10), o:getButtonState(11),
o:getButtonState(12), o:getButtonState(13), o:getButtonState(14), o:getButtonState(15),
o:getButtonState(16), o:getButtonState(17), o:getButtonState(18), o:getButtonState(19),
o:getButtonState(20), o:getButtonState(21), o:getButtonState(22), o:getButtonState(23),
o:getButtonState(24), o:getButtonState(25), o:getButtonState(26), o:getButtonState(27),
o:getButtonState(28), o:getButtonState(29), o:getButtonState(30), o:getButtonState(31),
},
},
}
print(os.date("%c",os.time()), i(event_details))
--local myFile = io.open("output.txt","a+") ; myFile:write(os.date("%c",os.time())..i(event_details).."\n") ; myFile:close()
return false
end
| mit |
starlightknight/darkstar | scripts/zones/Kazham-Jeuno_Airship/npcs/Oslam.lua | 12 | 1848 | -----------------------------------
-- Area: Kazham-Jeuno Airship
-- NPC: Oslam
-- Standard Info NPC
-----------------------------------
local ID = require("scripts/zones/Kazham-Jeuno_Airship/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local vHour = VanadielHour();
local vMin = VanadielMinute();
while vHour >= 1 do
vHour = vHour - 6;
end
local message = ID.text.WILL_REACH_KAZHAM;
if (vHour == -5) then
if (vMin >= 48) then
vHour = 3;
message = ID.text.WILL_REACH_JEUNO;
else
vHour = 0;
end
elseif (vHour == -4) then
vHour = 2;
message = ID.text.WILL_REACH_JEUNO;
elseif (vHour == -3) then
vHour = 1;
message = ID.text.WILL_REACH_JEUNO;
elseif (vHour == -2) then
if (vMin <= 49) then
vHour = 0;
message = ID.text.WILL_REACH_JEUNO;
else
vHour = 3;
end
elseif (vHour == -1) then
vHour = 2;
elseif (vHour == 0) then
vHour = 1;
end
local vMinutes = 0;
if (message == ID.text.WILL_REACH_JEUNO) then
vMinutes = (vHour * 60) + 49 - vMin;
else -- ID.text.WILL_REACH_KAZHAM
vMinutes = (vHour * 60) + 48 - vMin;
end
if (vMinutes <= 30) then
if ( message == ID.text.WILL_REACH_KAZHAM) then
message = ID.text.IN_KAZHAM_MOMENTARILY;
else -- ID.text.WILL_REACH_JEUNO
message = IN_JEUNO_MOMENTARILY;
end
elseif (vMinutes < 60) then
vHour = 0;
end
player:messageSpecial( message, math.floor((2.4 * vMinutes) / 60), math.floor( vMinutes / 60 + 0.5));
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end; | gpl-3.0 |
hades2013/openwrt-mtk | package/ralink/ui/luci-mtk/src/applications/luci-statistics/luasrc/statistics/rrdtool/definitions/disk.lua | 86 | 1449 | --[[
Luci statistics - df plugin diagram definition
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: df.lua 2274 2008-06-03 23:15:16Z jow $
]]--
module("luci.statistics.rrdtool.definitions.disk", package.seeall)
function rrdargs( graph, plugin, plugin_instance, dtype )
return {
{
title = "%H: Disk I/O operations on %pi",
vlabel = "Operations/s",
number_format = "%5.1lf%sOp/s",
data = {
types = { "disk_ops" },
sources = {
disk_ops = { "read", "write" },
},
options = {
disk_ops__read = {
title = "Reads",
color = "00ff00",
flip = false
},
disk_ops__write = {
title = "Writes",
color = "ff0000",
flip = true
}
}
}
},
{
title = "%H: Disk I/O bandwidth on %pi",
vlabel = "Bytes/s",
number_format = "%5.1lf%sB/s",
detail = true,
data = {
types = { "disk_octets" },
sources = {
disk_octets = { "read", "write" }
},
options = {
disk_octets__read = {
title = "Read",
color = "00ff00",
flip = false
},
disk_octets__write = {
title = "Write",
color = "ff0000",
flip = true
}
}
}
}
}
end
| gpl-2.0 |
telergybot/zspam | plugins/danbooru.lua | 616 | 1750 | do
local URL = "http://danbooru.donmai.us"
local URL_NEW = "/posts.json"
local URL_POP = "/explore/posts/popular.json"
local scale_day = "?scale=day"
local scale_week = "?scale=week"
local scale_month = "?scale=month"
local function get_post(url)
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local posts = json:decode(b)
return posts[math.random(#posts)]
end
local function run(msg, matches)
local url = URL
if matches[1] == "!danbooru" then
url = url .. URL_NEW
else
url = url .. URL_POP
if matches[1] == "d" then
url = url .. scale_day
elseif matches[1] == "w" then
url = url .. scale_week
elseif matches[1] == "m" then
url = url .. scale_month
end
end
local post = get_post(url)
if post then
vardump(post)
local img = URL .. post.large_file_url
send_photo_from_url(get_receiver(msg), img)
local txt = ''
if post.tag_string_artist ~= '' then
txt = 'Artist: ' .. post.tag_string_artist .. '\n'
end
if post.tag_string_character ~= '' then
txt = txt .. 'Character: ' .. post.tag_string_character .. '\n'
end
if post.file_size ~= '' then
txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url
end
return txt
end
end
return {
description = "Gets a random fresh or popular image from Danbooru",
usage = {
"!danbooru - gets a random fresh image from Danbooru π",
"!danboorud - random daily popular image π",
"!danbooruw - random weekly popular image π",
"!danboorum - random monthly popular image π"
},
patterns = {
"^!danbooru$",
"^!danbooru ?(d)$",
"^!danbooru ?(w)$",
"^!danbooru ?(m)$"
},
run = run
}
end | gpl-2.0 |
Maxsteam/4568584657657 | plugins/danbooru.lua | 616 | 1750 | do
local URL = "http://danbooru.donmai.us"
local URL_NEW = "/posts.json"
local URL_POP = "/explore/posts/popular.json"
local scale_day = "?scale=day"
local scale_week = "?scale=week"
local scale_month = "?scale=month"
local function get_post(url)
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local posts = json:decode(b)
return posts[math.random(#posts)]
end
local function run(msg, matches)
local url = URL
if matches[1] == "!danbooru" then
url = url .. URL_NEW
else
url = url .. URL_POP
if matches[1] == "d" then
url = url .. scale_day
elseif matches[1] == "w" then
url = url .. scale_week
elseif matches[1] == "m" then
url = url .. scale_month
end
end
local post = get_post(url)
if post then
vardump(post)
local img = URL .. post.large_file_url
send_photo_from_url(get_receiver(msg), img)
local txt = ''
if post.tag_string_artist ~= '' then
txt = 'Artist: ' .. post.tag_string_artist .. '\n'
end
if post.tag_string_character ~= '' then
txt = txt .. 'Character: ' .. post.tag_string_character .. '\n'
end
if post.file_size ~= '' then
txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url
end
return txt
end
end
return {
description = "Gets a random fresh or popular image from Danbooru",
usage = {
"!danbooru - gets a random fresh image from Danbooru π",
"!danboorud - random daily popular image π",
"!danbooruw - random weekly popular image π",
"!danboorum - random monthly popular image π"
},
patterns = {
"^!danbooru$",
"^!danbooru ?(d)$",
"^!danbooru ?(w)$",
"^!danbooru ?(m)$"
},
run = run
}
end | gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.