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 |
|---|---|---|---|---|---|
UnfortunateFruit/darkstar | scripts/zones/San_dOria-Jeuno_Airship/TextIDs.lua | 5 | 1088 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6382; -- Obtained: <item>
GIL_OBTAINED = 6383; -- Obtained <number> gil
KEYITEM_OBTAINED = 6385; -- Obtained key item: <keyitem>
-- Other
WILL_REACH_JEUNO = 7195; -- The airship will reach Jeuno in Multiple Choice (Parameter 1)[less than an hour/about 1 hour/about 2 hours/about 3 hours/about 4 hours/about 5 hours/about 6 hours/about 7 hours] ( Singular/Plural Choice (Parameter 0)[minute/minutes] in Earth time).
WILL_REACH_SANDORIA = 7196; -- The airship will reach San d'Oria in Multiple Choice (Parameter 1)[less than an hour/about 1 hour/about 2 hours/about 3 hours/about 4 hours/about 5 hours/about 6 hours/about 7 hours] ( Singular/Plural Choice (Parameter 0)[minute/minutes] in Earth time).
IN_JEUNO_MOMENTARILY = 7198; -- We will be arriving in Jeuno momentarily.
IN_SANDORIA_MOMENTARILY = 7199; -- We will be arriving in San d'Oria momentarily.
| gpl-3.0 |
nesstea/darkstar | scripts/zones/The_Eldieme_Necropolis/npcs/_5fa.lua | 13 | 1076 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: Odin's Gate
-- @pos 260 -34 -49 195
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Eldieme_Necropolis/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (npc:getAnimation() == 9) then
player:messageSpecial(SOLID_STONE);
end
return 0;
end;
--
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
bowlofstew/Macaroni | Next/Tests/Features/UnitTargets/project.lua | 2 | 4671 | description = [[
The goal of this test is to establish granularity within a library by compiling
a simple C++ app to the same degree of specificity as could be achieved by
Boost-Build.
The "manifest" build system was very broad; libraries were defines as blobs of
C++ files which all got combined. The problem was Macaroni never established
how to do this, so it was impossible to write generators to say something such
as "A.cpp is used by B.cpp, and has a single unit test called A-Test.cpp". The
goal with granular UnitTargets it to be able to generate build files and other
goodies that can figure this out in a compatable fashion.
]]
import("Macaroni", "ProjectTemplates", "1")
require "SimpleProject"
-- Added to init.lua:
boost_version = properties.boost.version
SimpleProject{
group="Macaroni.Tests",
project="Features-UnitTargets",
version="1.0.0.0",
src="src",
target="target",
dependencies = {
load("Macaroni", "Boost-headers", boost_version):Target("lib"),
load("Macaroni", "CppStd", "2003"):Target("lib")
},
};
-- project = context:Group("Macaroni.Tests")
-- :Project("Features-UnitTargets")
-- :Version("1.0.0.0");
-- boost = load("Macaroni", "Boost-headers", "1.46.1"):Target("lib")
-- cppstd = load("Macaroni", "CppStd", "2003"):Target("lib")
-- lib = project:Library{
-- name = "lib",
-- -- Important note: When the library sees a ProjectVersion as a
-- -- dependency, it automatically uses a target named "lib".
-- -- dependencies = {boost_regex_lib, boost_headers},
-- headers = pathList{"src", "target"},
-- sources = pathList{"src", ".mcpp$"},
-- dependencies = {
-- cppstd,
-- boost
-- }
-- }
-- -- This would work, except that PlainCTest.cpp is already added above.
-- -- local src = Macaroni.IO.Path.New("src")
-- -- lib:AddTest("PlainCTest", src:NewPathForceSlash("PlainCTest.cpp"))
-- porg = plugins:Get("Porg")
-- cpp = plugins:Get("Cpp")
-- html = plugins:Get("HtmlView")
-- bjam = plugins:Get("BoostBuild2")
-- targetDir = Macaroni.IO.Path.New("target")
-- -- This *needs* to run every single time, no matter what.
-- porg:Run("Generate", {target=lib})
-- function clean()
-- targetDir:ClearDirectoryContents();
-- end
-- generated = false
-- built = false
-- installed = false
-- function generate()
-- if generated then return end
-- local outputPath = filePath("target") --ath.New("target")
-- cpp:Run("Generate", { projectVersion=project, path=outputPath })
-- html:Run("Generate", { target=lib, path=outputPath})
-- bjam:Run("Generate", { jamroot=outputPath:NewPath("/jamroot.jam"),
-- projectVersion=project,
-- output=output
-- })
-- generated = true
-- end
-- function build()
-- if built then return end
-- generate()
-- os.execute("bjam " .. properties.bjam_options .. " target")
-- built = true
-- end
-- function install()
-- if installed then return end
-- sinstall(project, filePath("./"))
-- installed = true
-- -- So, here's a laugh: what you see below are half-completed attempts at
-- -- feeling out what the proper way to do this would look like.
-- -- Before the sloppy and easy way was found.
-- --[[
-- generate()
-- --cpp:Run("Install", { projectVersion=project, paths=pathList{"src", "target"}})
-- -- Somehow, go through library, copy all unit files correctly, and create
-- -- new jamroot.jam file with library.
-- ----bjam:Run("Install", { projectVersion=project } );--{ libraries={lib,} })
-- installer = install(project, {lib});
-- installer:install({lib});
-- -- From Lua, an installer is its own object which contains the following:
-- -- FinalProject - a ProjectVersion which is independent of what is being
-- -- installed, i.e. it is *NOT* the "project" varaible above.
-- -- OutputPath - The install directory.
-- bjam:Run("Install", {installer = installer})
-- -- This will take the installer, from which it will extract the
-- -- projectVersion from the "project" variable, then it will use the
-- -- "OutputPath" variable and make a new directory called bjam and put
-- -- everything there.
-- -- Creates the final install path
-- -- Goes through all targets and saves unit targets with cpp and h files
-- -- to "Source" directory.
-- -- Writes installer file.
-- -- project:Install{{targets={lib}, plugins={bjam}};
-- -- Targets may have a special way they get installed.
-- -- Plugins need to save whatever they generate, so for example bjam needs
-- -- to save its own stuff.
-- ]]--
-- end
| apache-2.0 |
focusworld/aabb | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/zones/Manaclipper/Zone.lua | 28 | 1617 | -----------------------------------
--
-- Zone: Manaclipper
--
-----------------------------------
package.loaded["scripts/zones/Manaclipper/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Manaclipper/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(0,-3,-8,60);
end
return cs;
end;
function onTransportEvent(player,transport)
player:startEvent(0x0064);
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;
-----------------------------------
-- 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 == 0x0064) then
player:setPos(0,0,0,0,4);
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/RuLude_Gardens/npcs/Laityn.lua | 13 | 1182 | -----------------------------------
-- Area: Ru'Lud Gardens
-- NPC: Laityn
-- Involved In Quest: Recollections
-----------------------------------
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(WINDURST,RECOLLECTIONS) == QUEST_ACCEPTED and player:getVar("recollectionsQuest") == 0) then
player:startEvent(0x2713); -- Option CS for "Recollections"
else
player:startEvent(0x2716);
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 == 0x2713) then
player:setVar("recollectionsQuest",1);
end
end; | gpl-3.0 |
abhinavmoudgil95/funnybot | src/LSTM.lua | 13 | 8765 | require 'torch'
require 'nn'
local layer, parent = torch.class('nn.LSTM', 'nn.Module')
--[[
If we add up the sizes of all the tensors for output, gradInput, weights,
gradWeights, and temporary buffers, we get that a SequenceLSTM stores this many
scalar values:
NTD + 6NTH + 8NH + 8H^2 + 8DH + 9H
For N = 100, D = 512, T = 100, H = 1024 and with 4 bytes per number, this comes
out to 305MB. Note that this class doesn't own input or gradOutput, so you'll
see a bit higher memory usage in practice.
--]]
function layer:__init(input_dim, hidden_dim)
parent.__init(self)
local D, H = input_dim, hidden_dim
self.input_dim, self.hidden_dim = D, H
self.weight = torch.Tensor(D + H, 4 * H)
self.gradWeight = torch.Tensor(D + H, 4 * H):zero()
self.bias = torch.Tensor(4 * H)
self.gradBias = torch.Tensor(4 * H):zero()
self:reset()
self.cell = torch.Tensor() -- This will be (N, T, H)
self.gates = torch.Tensor() -- This will be (N, T, 4H)
self.buffer1 = torch.Tensor() -- This will be (N, H)
self.buffer2 = torch.Tensor() -- This will be (N, H)
self.buffer3 = torch.Tensor() -- This will be (1, 4H)
self.grad_a_buffer = torch.Tensor() -- This will be (N, 4H)
self.h0 = torch.Tensor()
self.c0 = torch.Tensor()
self.remember_states = false
self.grad_c0 = torch.Tensor()
self.grad_h0 = torch.Tensor()
self.grad_x = torch.Tensor()
self.gradInput = {self.grad_c0, self.grad_h0, self.grad_x}
end
function layer:reset(std)
if not std then
std = 1.0 / math.sqrt(self.hidden_dim + self.input_dim)
end
self.bias:zero()
self.bias[{{self.hidden_dim + 1, 2 * self.hidden_dim}}]:fill(1)
self.weight:normal(0, std)
return self
end
function layer:resetStates()
self.h0 = self.h0.new()
self.c0 = self.c0.new()
end
local function check_dims(x, dims)
assert(x:dim() == #dims)
for i, d in ipairs(dims) do
assert(x:size(i) == d)
end
end
function layer:_unpack_input(input)
local c0, h0, x = nil, nil, nil
if torch.type(input) == 'table' and #input == 3 then
c0, h0, x = unpack(input)
elseif torch.type(input) == 'table' and #input == 2 then
h0, x = unpack(input)
elseif torch.isTensor(input) then
x = input
else
assert(false, 'invalid input')
end
return c0, h0, x
end
function layer:_get_sizes(input, gradOutput)
local c0, h0, x = self:_unpack_input(input)
local N, T = x:size(1), x:size(2)
local H, D = self.hidden_dim, self.input_dim
check_dims(x, {N, T, D})
if h0 then
check_dims(h0, {N, H})
end
if c0 then
check_dims(c0, {N, H})
end
if gradOutput then
check_dims(gradOutput, {N, T, H})
end
return N, T, D, H
end
--[[
Input:
- c0: Initial cell state, (N, H)
- h0: Initial hidden state, (N, H)
- x: Input sequence, (N, T, D)
Output:
- h: Sequence of hidden states, (N, T, H)
--]]
function layer:updateOutput(input)
self.recompute_backward = true
local c0, h0, x = self:_unpack_input(input)
local N, T, D, H = self:_get_sizes(input)
self._return_grad_c0 = (c0 ~= nil)
self._return_grad_h0 = (h0 ~= nil)
if not c0 then
c0 = self.c0
if c0:nElement() == 0 or not self.remember_states then
c0:resize(N, H):zero()
elseif self.remember_states then
local prev_N, prev_T = self.cell:size(1), self.cell:size(2)
assert(prev_N == N, 'batch sizes must be constant to remember states')
c0:copy(self.cell[{{}, prev_T}])
end
end
if not h0 then
h0 = self.h0
if h0:nElement() == 0 or not self.remember_states then
h0:resize(N, H):zero()
elseif self.remember_states then
local prev_N, prev_T = self.output:size(1), self.output:size(2)
assert(prev_N == N, 'batch sizes must be the same to remember states')
h0:copy(self.output[{{}, prev_T}])
end
end
local bias_expand = self.bias:view(1, 4 * H):expand(N, 4 * H)
local Wx = self.weight[{{1, D}}]
local Wh = self.weight[{{D + 1, D + H}}]
local h, c = self.output, self.cell
h:resize(N, T, H):zero()
c:resize(N, T, H):zero()
local prev_h, prev_c = h0, c0
self.gates:resize(N, T, 4 * H):zero()
for t = 1, T do
local cur_x = x[{{}, t}]
local next_h = h[{{}, t}]
local next_c = c[{{}, t}]
local cur_gates = self.gates[{{}, t}]
cur_gates:addmm(bias_expand, cur_x, Wx)
cur_gates:addmm(prev_h, Wh)
cur_gates[{{}, {1, 3 * H}}]:sigmoid()
cur_gates[{{}, {3 * H + 1, 4 * H}}]:tanh()
local i = cur_gates[{{}, {1, H}}]
local f = cur_gates[{{}, {H + 1, 2 * H}}]
local o = cur_gates[{{}, {2 * H + 1, 3 * H}}]
local g = cur_gates[{{}, {3 * H + 1, 4 * H}}]
next_h:cmul(i, g)
next_c:cmul(f, prev_c):add(next_h)
next_h:tanh(next_c):cmul(o)
prev_h, prev_c = next_h, next_c
end
return self.output
end
function layer:backward(input, gradOutput, scale)
self.recompute_backward = false
scale = scale or 1.0
assert(scale == 1.0, 'must have scale=1')
local c0, h0, x = self:_unpack_input(input)
if not c0 then c0 = self.c0 end
if not h0 then h0 = self.h0 end
local grad_c0, grad_h0, grad_x = self.grad_c0, self.grad_h0, self.grad_x
local h, c = self.output, self.cell
local grad_h = gradOutput
local N, T, D, H = self:_get_sizes(input, gradOutput)
local Wx = self.weight[{{1, D}}]
local Wh = self.weight[{{D + 1, D + H}}]
local grad_Wx = self.gradWeight[{{1, D}}]
local grad_Wh = self.gradWeight[{{D + 1, D + H}}]
local grad_b = self.gradBias
grad_h0:resizeAs(h0):zero()
grad_c0:resizeAs(c0):zero()
grad_x:resizeAs(x):zero()
local grad_next_h = self.buffer1:resizeAs(h0):zero()
local grad_next_c = self.buffer2:resizeAs(c0):zero()
for t = T, 1, -1 do
local next_h, next_c = h[{{}, t}], c[{{}, t}]
local prev_h, prev_c = nil, nil
if t == 1 then
prev_h, prev_c = h0, c0
else
prev_h, prev_c = h[{{}, t - 1}], c[{{}, t - 1}]
end
grad_next_h:add(grad_h[{{}, t}])
local i = self.gates[{{}, t, {1, H}}]
local f = self.gates[{{}, t, {H + 1, 2 * H}}]
local o = self.gates[{{}, t, {2 * H + 1, 3 * H}}]
local g = self.gates[{{}, t, {3 * H + 1, 4 * H}}]
local grad_a = self.grad_a_buffer:resize(N, 4 * H):zero()
local grad_ai = grad_a[{{}, {1, H}}]
local grad_af = grad_a[{{}, {H + 1, 2 * H}}]
local grad_ao = grad_a[{{}, {2 * H + 1, 3 * H}}]
local grad_ag = grad_a[{{}, {3 * H + 1, 4 * H}}]
-- We will use grad_ai, grad_af, and grad_ao as temporary buffers
-- to to compute grad_next_c. We will need tanh_next_c (stored in grad_ai)
-- to compute grad_ao; the other values can be overwritten after we compute
-- grad_next_c
local tanh_next_c = grad_ai:tanh(next_c)
local tanh_next_c2 = grad_af:cmul(tanh_next_c, tanh_next_c)
local my_grad_next_c = grad_ao
my_grad_next_c:fill(1):add(-1, tanh_next_c2):cmul(o):cmul(grad_next_h)
grad_next_c:add(my_grad_next_c)
-- We need tanh_next_c (currently in grad_ai) to compute grad_ao; after
-- that we can overwrite it.
grad_ao:fill(1):add(-1, o):cmul(o):cmul(tanh_next_c):cmul(grad_next_h)
-- Use grad_ai as a temporary buffer for computing grad_ag
local g2 = grad_ai:cmul(g, g)
grad_ag:fill(1):add(-1, g2):cmul(i):cmul(grad_next_c)
-- We don't need any temporary storage for these so do them last
grad_ai:fill(1):add(-1, i):cmul(i):cmul(g):cmul(grad_next_c)
grad_af:fill(1):add(-1, f):cmul(f):cmul(prev_c):cmul(grad_next_c)
grad_x[{{}, t}]:mm(grad_a, Wx:t())
grad_Wx:addmm(scale, x[{{}, t}]:t(), grad_a)
grad_Wh:addmm(scale, prev_h:t(), grad_a)
local grad_a_sum = self.buffer3:resize(1, 4 * H):sum(grad_a, 1)
grad_b:add(scale, grad_a_sum)
grad_next_h:mm(grad_a, Wh:t())
grad_next_c:cmul(f)
end
grad_h0:copy(grad_next_h)
grad_c0:copy(grad_next_c)
if self._return_grad_c0 and self._return_grad_h0 then
self.gradInput = {self.grad_c0, self.grad_h0, self.grad_x}
elseif self._return_grad_h0 then
self.gradInput = {self.grad_h0, self.grad_x}
else
self.gradInput = self.grad_x
end
return self.gradInput
end
function layer:clearState()
self.cell:set()
self.gates:set()
self.buffer1:set()
self.buffer2:set()
self.buffer3:set()
self.grad_a_buffer:set()
self.grad_c0:set()
self.grad_h0:set()
self.grad_x:set()
self.output:set()
end
function layer:updateGradInput(input, gradOutput)
if self.recompute_backward then
self:backward(input, gradOutput, 1.0)
end
return self.gradInput
end
function layer:accGradParameters(input, gradOutput, scale)
if self.recompute_backward then
self:backward(input, gradOutput, scale)
end
end
function layer:__tostring__()
local name = torch.type(self)
local din, dout = self.input_dim, self.hidden_dim
return string.format('%s(%d -> %d)', name, din, dout)
end
| mit |
ShaTelTeam/MegaZs | libs/redis.lua | 566 | 1214 | local Redis = require 'redis'
local FakeRedis = require 'fakeredis'
local params = {
host = os.getenv('REDIS_HOST') or '127.0.0.1',
port = tonumber(os.getenv('REDIS_PORT') or 6379)
}
local database = os.getenv('REDIS_DB')
local password = os.getenv('REDIS_PASSWORD')
-- Overwrite HGETALL
Redis.commands.hgetall = Redis.command('hgetall', {
response = function(reply, command, ...)
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
})
local redis = nil
-- Won't launch an error if fails
local ok = pcall(function()
redis = Redis.connect(params)
end)
if not ok then
local fake_func = function()
print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m')
end
fake_func()
fake = FakeRedis.new()
print('\27[31mRedis addr: '..params.host..'\27[39m')
print('\27[31mRedis port: '..params.port..'\27[39m')
redis = setmetatable({fakeredis=true}, {
__index = function(a, b)
if b ~= 'data' and fake[b] then
fake_func(b)
end
return fake[b] or fake_func
end })
else
if password then
redis:auth(password)
end
if database then
redis:select(database)
end
end
return redis
| gpl-2.0 |
FailcoderAddons/supervillain-ui | SVUI_!Core/libs/AceGUI-3.0/widgets/AceGUIContainer-TreeGroup.lua | 10 | 19926 | --[[-----------------------------------------------------------------------------
TreeGroup Container
Container that uses a tree control to switch between groups.
-------------------------------------------------------------------------------]]
local Type, Version = "TreeGroup", 40
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local next, pairs, ipairs, assert, type = next, pairs, ipairs, assert, type
local math_min, math_max, floor = math.min, math.max, floor
local select, tremove, unpack, tconcat = select, table.remove, unpack, table.concat
-- WoW APIs
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: GameTooltip, FONT_COLOR_CODE_CLOSE
-- Recycling functions
local new, del
do
local pool = setmetatable({},{__mode='k'})
function new()
local t = next(pool)
if t then
pool[t] = nil
return t
else
return {}
end
end
function del(t)
for k in pairs(t) do
t[k] = nil
end
pool[t] = true
end
end
local DEFAULT_TREE_WIDTH = 175
local DEFAULT_TREE_SIZABLE = true
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function GetButtonUniqueValue(line)
local parent = line.parent
if parent and parent.value then
return GetButtonUniqueValue(parent).."\001"..line.value
else
return line.value
end
end
local function UpdateButton(button, treeline, selected, canExpand, isExpanded)
local self = button.obj
local toggle = button.toggle
local frame = self.frame
local text = treeline.text or ""
local icon = treeline.icon
local iconCoords = treeline.iconCoords
local level = treeline.level
local value = treeline.value
local uniquevalue = treeline.uniquevalue
local disabled = treeline.disabled
button.treeline = treeline
button.value = value
button.uniquevalue = uniquevalue
if selected then
button:LockHighlight()
button.selected = true
else
button:UnlockHighlight()
button.selected = false
end
local normalTexture = button:GetNormalTexture()
local line = button.line
button.level = level
if ( level == 1 ) then
button:SetNormalFontObject("GameFontNormal")
button:SetHighlightFontObject("GameFontHighlight")
button.text:SetPoint("LEFT", (icon and 16 or 0) + 8, 2)
else
button:SetNormalFontObject("GameFontHighlightSmall")
button:SetHighlightFontObject("GameFontHighlightSmall")
button.text:SetPoint("LEFT", (icon and 16 or 0) + 8 * level, 2)
end
if disabled then
button:EnableMouse(false)
button.text:SetText("|cff808080"..text..FONT_COLOR_CODE_CLOSE)
else
button.text:SetText(text)
button:EnableMouse(true)
end
if icon then
button.icon:SetTexture(icon)
button.icon:SetPoint("LEFT", 8 * level, (level == 1) and 0 or 1)
else
button.icon:SetTexture(nil)
end
if iconCoords then
button.icon:SetTexCoord(unpack(iconCoords))
else
button.icon:SetTexCoord(0, 1, 0, 1)
end
if canExpand then
if not isExpanded then
toggle:SetNormalTexture("Interface\\Buttons\\UI-PlusButton-UP")
toggle:SetPushedTexture("Interface\\Buttons\\UI-PlusButton-DOWN")
else
toggle:SetNormalTexture("Interface\\Buttons\\UI-MinusButton-UP")
toggle:SetPushedTexture("Interface\\Buttons\\UI-MinusButton-DOWN")
end
toggle:Show()
else
toggle:Hide()
end
end
local function ShouldDisplayLevel(tree)
local result = false
for k, v in ipairs(tree) do
if v.children == nil and v.visible ~= false then
result = true
elseif v.children then
result = result or ShouldDisplayLevel(v.children)
end
if result then return result end
end
return false
end
local function addLine(self, v, tree, level, parent)
local line = new()
line.value = v.value
line.text = v.text
line.icon = v.icon
line.iconCoords = v.iconCoords
line.disabled = v.disabled
line.tree = tree
line.level = level
line.parent = parent
line.visible = v.visible
line.uniquevalue = GetButtonUniqueValue(line)
if v.children then
line.hasChildren = true
else
line.hasChildren = nil
end
self.lines[#self.lines+1] = line
return line
end
--fire an update after one frame to catch the treeframes height
local function FirstFrameUpdate(frame)
local self = frame.obj
frame:SetScript("OnUpdate", nil)
self:RefreshTree()
end
local function BuildUniqueValue(...)
local n = select('#', ...)
if n == 1 then
return ...
else
return (...).."\001"..BuildUniqueValue(select(2,...))
end
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Expand_OnClick(frame)
local button = frame.button
local self = button.obj
local status = (self.status or self.localstatus).groups
status[button.uniquevalue] = not status[button.uniquevalue]
self:RefreshTree()
end
local function Button_OnClick(frame)
local self = frame.obj
self:Fire("OnClick", frame.uniquevalue, frame.selected)
if not frame.selected then
self:SetSelected(frame.uniquevalue)
frame.selected = true
frame:LockHighlight()
self:RefreshTree()
end
AceGUI:ClearFocus()
end
local function Button_OnDoubleClick(button)
local self = button.obj
local status = self.status or self.localstatus
local status = (self.status or self.localstatus).groups
status[button.uniquevalue] = not status[button.uniquevalue]
self:RefreshTree()
end
local function Button_OnEnter(frame)
local self = frame.obj
self:Fire("OnButtonEnter", frame.uniquevalue, frame)
if self.enabletooltips then
GameTooltip:SetOwner(frame, "ANCHOR_NONE")
GameTooltip:SetPoint("LEFT",frame,"RIGHT")
GameTooltip:SetText(frame.text:GetText() or "", 1, .82, 0, true)
GameTooltip:Show()
end
end
local function Button_OnLeave(frame)
local self = frame.obj
self:Fire("OnButtonLeave", frame.uniquevalue, frame)
if self.enabletooltips then
GameTooltip:Hide()
end
end
local function OnScrollValueChanged(frame, value)
if frame.obj.noupdate then return end
local self = frame.obj
local status = self.status or self.localstatus
status.scrollvalue = floor(value + 0.5)
self:RefreshTree()
AceGUI:ClearFocus()
end
local function Tree_OnSizeChanged(frame)
frame.obj:RefreshTree()
end
local function Tree_OnMouseWheel(frame, delta)
local self = frame.obj
if self.showscroll then
local scrollbar = self.scrollbar
local min, max = scrollbar:GetMinMaxValues()
local value = scrollbar:GetValue()
local newvalue = math_min(max,math_max(min,value - delta))
if value ~= newvalue then
scrollbar:SetValue(newvalue)
end
end
end
local function Dragger_OnLeave(frame)
frame:SetBackdropColor(1, 1, 1, 0)
end
local function Dragger_OnEnter(frame)
frame:SetBackdropColor(1, 1, 1, 0.8)
end
local function Dragger_OnMouseDown(frame)
local treeframe = frame:GetParent()
treeframe:StartSizing("RIGHT")
end
local function Dragger_OnMouseUp(frame)
local treeframe = frame:GetParent()
local self = treeframe.obj
local frame = treeframe:GetParent()
treeframe:StopMovingOrSizing()
--treeframe:SetScript("OnUpdate", nil)
treeframe:SetUserPlaced(false)
--Without this :GetHeight will get stuck on the current height, causing the tree contents to not resize
treeframe:SetHeight(0)
treeframe:SetPoint("TOPLEFT", frame, "TOPLEFT",0,0)
treeframe:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT",0,0)
local status = self.status or self.localstatus
status.treewidth = treeframe:GetWidth()
treeframe.obj:Fire("OnTreeResize",treeframe:GetWidth())
-- recalculate the content width
treeframe.obj:OnWidthSet(status.fullwidth)
-- update the layout of the content
treeframe.obj:DoLayout()
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetTreeWidth(DEFAULT_TREE_WIDTH, DEFAULT_TREE_SIZABLE)
self:EnableButtonTooltips(true)
self.frame:SetScript("OnUpdate", FirstFrameUpdate)
end,
["OnRelease"] = function(self)
self.status = nil
for k, v in pairs(self.localstatus) do
if k == "groups" then
for k2 in pairs(v) do
v[k2] = nil
end
else
self.localstatus[k] = nil
end
end
self.localstatus.scrollvalue = 0
self.localstatus.treewidth = DEFAULT_TREE_WIDTH
self.localstatus.treesizable = DEFAULT_TREE_SIZABLE
end,
["EnableButtonTooltips"] = function(self, enable)
self.enabletooltips = enable
end,
["CreateButton"] = function(self)
local num = AceGUI:GetNextWidgetNum("TreeGroupButton")
local button = CreateFrame("Button", ("AceGUI30TreeButton%d"):format(num), self.treeframe, "OptionsListButtonTemplate")
button.obj = self
local icon = button:CreateTexture(nil, "OVERLAY")
icon:SetWidth(14)
icon:SetHeight(14)
button.icon = icon
button:SetScript("OnClick",Button_OnClick)
button:SetScript("OnDoubleClick", Button_OnDoubleClick)
button:SetScript("OnEnter",Button_OnEnter)
button:SetScript("OnLeave",Button_OnLeave)
button.toggle.button = button
button.toggle:SetScript("OnClick",Expand_OnClick)
button.text:SetHeight(14) -- Prevents text wrapping
return button
end,
["SetStatusTable"] = function(self, status)
assert(type(status) == "table")
self.status = status
if not status.groups then
status.groups = {}
end
if not status.scrollvalue then
status.scrollvalue = 0
end
if not status.treewidth then
status.treewidth = DEFAULT_TREE_WIDTH
end
if status.treesizable == nil then
status.treesizable = DEFAULT_TREE_SIZABLE
end
self:SetTreeWidth(status.treewidth,status.treesizable)
self:RefreshTree()
end,
--sets the tree to be displayed
["SetTree"] = function(self, tree, filter)
self.filter = filter
if tree then
assert(type(tree) == "table")
end
self.tree = tree
self:RefreshTree()
end,
["BuildLevel"] = function(self, tree, level, parent)
local groups = (self.status or self.localstatus).groups
local hasChildren = self.hasChildren
for i, v in ipairs(tree) do
if v.children then
if not self.filter or ShouldDisplayLevel(v.children) then
local line = addLine(self, v, tree, level, parent)
if groups[line.uniquevalue] then
self:BuildLevel(v.children, level+1, line)
end
end
elseif v.visible ~= false or not self.filter then
addLine(self, v, tree, level, parent)
end
end
end,
["RefreshTree"] = function(self,scrollToSelection)
local buttons = self.buttons
local lines = self.lines
for i, v in ipairs(buttons) do
v:Hide()
end
while lines[1] do
local t = tremove(lines)
for k in pairs(t) do
t[k] = nil
end
del(t)
end
if not self.tree then return end
--Build the list of visible entries from the tree and status tables
local status = self.status or self.localstatus
local groupstatus = status.groups
local tree = self.tree
local treeframe = self.treeframe
status.scrollToSelection = status.scrollToSelection or scrollToSelection -- needs to be cached in case the control hasn't been drawn yet (code bails out below)
self:BuildLevel(tree, 1)
local numlines = #lines
local maxlines = (floor(((self.treeframe:GetHeight()or 0) - 20 ) / 18))
if maxlines <= 0 then return end
local first, last
scrollToSelection = status.scrollToSelection
status.scrollToSelection = nil
if numlines <= maxlines then
--the whole tree fits in the frame
status.scrollvalue = 0
self:ShowScroll(false)
first, last = 1, numlines
else
self:ShowScroll(true)
--scrolling will be needed
self.noupdate = true
self.scrollbar:SetMinMaxValues(0, numlines - maxlines)
--check if we are scrolled down too far
if numlines - status.scrollvalue < maxlines then
status.scrollvalue = numlines - maxlines
end
self.noupdate = nil
first, last = status.scrollvalue+1, status.scrollvalue + maxlines
--show selection?
if scrollToSelection and status.selected then
local show
for i,line in ipairs(lines) do -- find the line number
if line.uniquevalue==status.selected then
show=i
end
end
if not show then
-- selection was deleted or something?
elseif show>=first and show<=last then
-- all good
else
-- scrolling needed!
if show<first then
status.scrollvalue = show-1
else
status.scrollvalue = show-maxlines
end
first, last = status.scrollvalue+1, status.scrollvalue + maxlines
end
end
if self.scrollbar:GetValue() ~= status.scrollvalue then
self.scrollbar:SetValue(status.scrollvalue)
end
end
local buttonnum = 1
for i = first, last do
local line = lines[i]
local button = buttons[buttonnum]
if not button then
button = self:CreateButton()
buttons[buttonnum] = button
button:SetParent(treeframe)
button:SetFrameLevel(treeframe:GetFrameLevel()+1)
button:ClearAllPoints()
if buttonnum == 1 then
if self.showscroll then
button:SetPoint("TOPRIGHT", -22, -10)
button:SetPoint("TOPLEFT", 0, -10)
else
button:SetPoint("TOPRIGHT", 0, -10)
button:SetPoint("TOPLEFT", 0, -10)
end
else
button:SetPoint("TOPRIGHT", buttons[buttonnum-1], "BOTTOMRIGHT",0,0)
button:SetPoint("TOPLEFT", buttons[buttonnum-1], "BOTTOMLEFT",0,0)
end
end
UpdateButton(button, line, status.selected == line.uniquevalue, line.hasChildren, groupstatus[line.uniquevalue] )
button:Show()
buttonnum = buttonnum + 1
end
end,
["SetSelected"] = function(self, value)
local status = self.status or self.localstatus
if status.selected ~= value then
status.selected = value
self:Fire("OnGroupSelected", value)
end
end,
["Select"] = function(self, uniquevalue, ...)
self.filter = false
local status = self.status or self.localstatus
local groups = status.groups
local path = {...}
for i = 1, #path do
groups[tconcat(path, "\001", 1, i)] = true
end
status.selected = uniquevalue
self:RefreshTree(true)
self:Fire("OnGroupSelected", uniquevalue)
end,
["SelectByPath"] = function(self, ...)
self:Select(BuildUniqueValue(...), ...)
end,
["SelectByValue"] = function(self, uniquevalue)
self:Select(uniquevalue, ("\001"):split(uniquevalue))
end,
["ShowScroll"] = function(self, show)
self.showscroll = show
if show then
self.scrollbar:Show()
if self.buttons[1] then
self.buttons[1]:SetPoint("TOPRIGHT", self.treeframe,"TOPRIGHT",-22,-10)
end
else
self.scrollbar:Hide()
if self.buttons[1] then
self.buttons[1]:SetPoint("TOPRIGHT", self.treeframe,"TOPRIGHT",0,-10)
end
end
end,
["OnWidthSet"] = function(self, width)
local content = self.content
local treeframe = self.treeframe
local status = self.status or self.localstatus
status.fullwidth = width
local contentwidth = width - status.treewidth - 20
if contentwidth < 0 then
contentwidth = 0
end
content:SetWidth(contentwidth)
content.width = contentwidth
local maxtreewidth = math_min(400, width - 50)
if maxtreewidth > 100 and status.treewidth > maxtreewidth then
self:SetTreeWidth(maxtreewidth, status.treesizable)
end
treeframe:SetMaxResize(maxtreewidth, 1600)
end,
["OnHeightSet"] = function(self, height)
local content = self.content
local contentheight = height - 20
if contentheight < 0 then
contentheight = 0
end
content:SetHeight(contentheight)
content.height = contentheight
end,
["SetTreeWidth"] = function(self, treewidth, resizable)
if not resizable then
if type(treewidth) == 'number' then
resizable = false
elseif type(treewidth) == 'boolean' then
resizable = treewidth
treewidth = DEFAULT_TREE_WIDTH
else
resizable = false
treewidth = DEFAULT_TREE_WIDTH
end
end
self.treeframe:SetWidth(treewidth)
self.dragger:EnableMouse(resizable)
local status = self.status or self.localstatus
status.treewidth = treewidth
status.treesizable = resizable
-- recalculate the content width
if status.fullwidth then
self:OnWidthSet(status.fullwidth)
end
end,
["GetTreeWidth"] = function(self)
local status = self.status or self.localstatus
return status.treewidth or DEFAULT_TREE_WIDTH
end,
["LayoutFinished"] = function(self, width, height)
if self.noAutoHeight then return end
self:SetHeight((height or 0) + 20)
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local PaneBackdrop = {
bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 3, right = 3, top = 5, bottom = 3 }
}
local DraggerBackdrop = {
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = nil,
tile = true, tileSize = 16, edgeSize = 0,
insets = { left = 3, right = 3, top = 7, bottom = 7 }
}
local function Constructor()
local num = AceGUI:GetNextWidgetNum(Type)
local frame = CreateFrame("Frame", nil, UIParent)
local treeframe = CreateFrame("Frame", nil, frame)
treeframe:SetPoint("TOPLEFT")
treeframe:SetPoint("BOTTOMLEFT")
treeframe:SetWidth(DEFAULT_TREE_WIDTH)
treeframe:EnableMouseWheel(true)
treeframe:SetBackdrop(PaneBackdrop)
treeframe:SetBackdropColor(0.1, 0.1, 0.1, 0.5)
treeframe:SetBackdropBorderColor(0.4, 0.4, 0.4)
treeframe:SetResizable(true)
treeframe:SetMinResize(100, 1)
treeframe:SetMaxResize(400, 1600)
treeframe:SetScript("OnUpdate", FirstFrameUpdate)
treeframe:SetScript("OnSizeChanged", Tree_OnSizeChanged)
treeframe:SetScript("OnMouseWheel", Tree_OnMouseWheel)
local dragger = CreateFrame("Frame", nil, treeframe)
dragger:SetWidth(8)
dragger:SetPoint("TOP", treeframe, "TOPRIGHT")
dragger:SetPoint("BOTTOM", treeframe, "BOTTOMRIGHT")
dragger:SetBackdrop(DraggerBackdrop)
dragger:SetBackdropColor(1, 1, 1, 0)
dragger:SetScript("OnEnter", Dragger_OnEnter)
dragger:SetScript("OnLeave", Dragger_OnLeave)
dragger:SetScript("OnMouseDown", Dragger_OnMouseDown)
dragger:SetScript("OnMouseUp", Dragger_OnMouseUp)
local scrollbar = CreateFrame("Slider", ("AceConfigDialogTreeGroup%dScrollBar"):format(num), treeframe, "UIPanelScrollBarTemplate")
scrollbar:SetScript("OnValueChanged", nil)
scrollbar:SetPoint("TOPRIGHT", -10, -26)
scrollbar:SetPoint("BOTTOMRIGHT", -10, 26)
scrollbar:SetMinMaxValues(0,0)
scrollbar:SetValueStep(1)
scrollbar:SetValue(0)
scrollbar:SetWidth(16)
scrollbar:SetScript("OnValueChanged", OnScrollValueChanged)
local scrollbg = scrollbar:CreateTexture(nil, "BACKGROUND")
scrollbg:SetAllPoints(scrollbar)
scrollbg:SetColorTexture(0,0,0,0.4)
local border = CreateFrame("Frame",nil,frame)
border:SetPoint("TOPLEFT", treeframe, "TOPRIGHT")
border:SetPoint("BOTTOMRIGHT")
border:SetBackdrop(PaneBackdrop)
border:SetBackdropColor(0.1, 0.1, 0.1, 0.5)
border:SetBackdropBorderColor(0.4, 0.4, 0.4)
--Container Support
local content = CreateFrame("Frame", nil, border)
content:SetPoint("TOPLEFT", 10, -10)
content:SetPoint("BOTTOMRIGHT", -10, 10)
local widget = {
frame = frame,
lines = {},
levels = {},
buttons = {},
hasChildren = {},
localstatus = { groups = {}, scrollvalue = 0 },
filter = false,
treeframe = treeframe,
dragger = dragger,
scrollbar = scrollbar,
border = border,
content = content,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
treeframe.obj, dragger.obj, scrollbar.obj = widget, widget, widget
return AceGUI:RegisterAsContainer(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| mit |
dpino/snabbswitch | lib/pflua/src/pf/regalloc.lua | 7 | 16379 | -- Implements register allocation for pflua's native backend
--
-- Follows the algorithm described in:
-- "Linear scan register allocation"
-- Poletto and Sarkar
-- https://dl.acm.org/citation.cfm?id=330250
--
-- The result of register allocation is a table that describes
-- the register allocated for the given virtual registers, e.g.:
--
-- { v1 = 1, -- %rcx
-- v2 = 2, -- %rdx
-- r3 = 0, -- %rax
-- len = 6, -- %rsi
-- callee_saves = {},
-- spills = { v3 = 0, v4 = 1 },
-- spill_registers = { 3, 4 }
-- }
--
-- The callee_saves field lists the callee-save registers that are
-- used in the allocation. This lets the code generation pass easily
-- generate any push/pops that are needed.
--
-- Register numbers are based on DynASM's Rq() register mapping.
--
-- The following registers are reserved and not allocated:
-- * %rdi to store the packet pointer argument
--
-- The allocator should first prioritize using caller-save registers
-- * %rax, %rcx, %rdx, %r8-%r11
--
-- before using callee-save registers
-- * %rbx, %r12-%r15
--
-- The spills and spill_registers fields are used for spilling registers
-- to memory if that becomes necessary. When the first register is spilled,
-- two additional registers are spilled (and put into spill_registers) so
-- that they can be used to move data from/to memory and registers.
--
-- The spills field keeps track of the stack slots (numbered from 0)
-- that are used for spilled registers. Variables should only be mapped
-- in one of the main allocation table or in the spills table.
module(...,package.seeall)
local utils = require('pf.utils')
local verbose = os.getenv("PF_VERBOSE");
-- returns the registers that a given instruction reads
local function reads_from(instr)
local itype = instr[1]
local function maybe_reg(reg)
if type(reg) == "number" then
return nil
else
return reg
end
end
if itype == "mov" or itype == "mov64" then
return { maybe_reg(instr[3]) }
elseif itype == "ntohs" or itype == "ntohl" or itype == "uint32" then
return { instr[2] }
elseif itype == "cjmp" or itype == "jmp" or itype == "ret-true" or
itype == "ret-false" or itype == "nop" or itype == "label" then
return {}
else
-- instructions don't have immediates in the first arg
return { instr[2], maybe_reg(instr[3]) }
end
end
-- Update the ends of intervals based on variable occurrences in
-- the "control" ast
local function find_live_in_control(label, control, intervals)
-- the head of an ast is always an operation name, so skip
for i = 2, #control do
local ast_type = type(control[i])
if ast_type == "string" then
for _, interval in ipairs(intervals) do
if control[i] == interval.name then
interval.finish = label
end
end
elseif ast_type == "table" then
find_live_in_control(label, control[i], intervals)
end
end
end
-- The lack of loops and unique register names for each load
-- in the instruction IR makes finding live intervals easy.
--
-- A live interval is a table
-- { name = String, start = number, finish = number }
--
-- The start and finish fields are indices into the instruction
-- array
--
local function live_intervals(instrs)
local len = { name = "len", start = 1, finish = 1 }
local order = { len }
local intervals = { len = len }
for idx, instr in ipairs(instrs) do
local itype = instr[1]
-- movs and loads are the only instructions that result in
-- new live intervals
if itype == "load" or itype == "mov" or itype == "mov64" then
local name = instr[2]
local interval = { name = name,
start = idx,
finish = idx }
intervals[name] = interval
table.insert(order, interval)
end
for _, reg in ipairs(reads_from(instr)) do
intervals[reg].finish = idx
end
end
-- we need the resulting allocations to be ordered by starting
-- point, so we emit the ordered sequence rather than the map
return order
end
-- All available registers, tied to unix x64 ABI
local caller_regs = {11, 10, 9, 8, 6, 2, 1, 0}
local callee_regs = {15, 14, 13, 12, 3}
local num_regs = #caller_regs + #callee_regs
-- Check if a register is free in the freelist
local function is_free(seq, reg)
for _, val in ipairs(seq) do
if val == reg then
return true
end
end
return false
end
-- Remove the given register from the freelist
local function remove_free(freelist, reg)
for idx, reg2 in ipairs(freelist) do
if reg2 == reg then
table.remove(freelist, idx)
return
end
end
end
-- Insert an interval sorted by increasing finish
local function insert_active(active, interval)
local finish = interval.finish
for idx, interval2 in ipairs(active) do
if interval2.finish > finish then
table.insert(active, idx, interval)
return
end
end
table.insert(active, interval)
end
-- Optimize movs from a register to the same one
local function delete_useless_movs(ir, alloc)
for idx, instr in ipairs(ir) do
if instr[1] == "mov" then
if alloc[instr[2]] == alloc[instr[3]] then
-- It's faster just to convert these to
-- nops than to re-number the table
ir[idx] = { "nop" }
end
end
end
end
-- Do register allocation with the given IR
-- Returns a register allocation and potentially mutates
-- the ir for optimizations
function allocate(ir)
local intervals = live_intervals(ir)
local active = {}
local next_spill = 0
-- caller-save registers, use these first
local free_caller = utils.dup(caller_regs)
-- callee-save registers, if we have to
local free_callee = utils.dup(callee_regs)
local allocation = { len = 6, -- %rsi
callee_saves = {},
spills = {} }
remove_free(free_caller, 6)
local function expire_old(interval)
local to_expire = {}
for idx, active_interval in ipairs(active) do
if active_interval.finish > interval.start then
break
else
local name = active_interval.name
local reg = allocation[name]
table.insert(to_expire, idx)
-- figure out which free list this register is supposed to be on
if is_free(caller_regs, reg) then
table.insert(free_caller, reg)
elseif is_free(callee_regs, reg) then
table.insert(free_callee, reg)
else
error("unknown register")
end
end
end
for i=1, #to_expire do
table.remove(active, to_expire[#to_expire - i + 1])
end
end
local function spill_at(interval)
-- when there's a first spill, pick two additional variables
-- to spill to the stack and reserve their registers for accessing
-- spilled variables via movs
if next_spill == 0 then
local i1, i2 = active[#active], active[#active-1]
local reg1 = allocation[i1.name]
local reg2 = allocation[i2.name]
table.remove(active); table.remove(active)
allocation[i1.name] = nil
allocation[i2.name] = nil
allocation.spills[i1.name] = 0
allocation.spills[i2.name] = 1
allocation.spill_registers = { reg1, reg2 }
next_spill = next_spill + 2
end
local to_spill = active[#active]
if to_spill.finish > interval.finish then
allocation[interval.name] = allocation[to_spill.name]
allocation[to_spill.name] = nil
allocation.spills[to_spill.name] = next_spill
table.remove(active)
insert_active(active, interval)
else
allocation.spills[interval.name] = next_spill
end
next_spill = next_spill + 1
end
for _, interval in pairs(intervals) do
local name = interval.name
expire_old(interval)
-- because we prefill some registers, check first if
-- we need to allocate for this interval
if not allocation[name] then
if #free_caller == 0 and #free_callee == 0 then
spill_at(interval)
-- newly freed registers are put at the end, so allocating from
-- the end will tend to produce better results since we want to
-- try eliminate movs with the same destination/source register
elseif #free_caller ~= 0 then
allocation[name] = free_caller[#free_caller]
table.remove(free_caller)
insert_active(active, interval)
else
local idx = #free_callee
allocation[name] = free_callee[idx]
allocation.callee_saves[free_callee[idx]] = true
table.remove(free_callee)
insert_active(active, interval)
end
else
insert_active(active, interval)
end
end
delete_useless_movs(ir, allocation)
if verbose then
utils.pp({ "register_allocation", allocation })
end
return allocation
end
function selftest()
local function test(instrs, expected)
utils.assert_equals(expected, live_intervals(instrs))
end
-- part of `tcp`, see pf.selection
local example_1 =
{ { "label", 0 },
{ "cmp", "len", 34 },
{ "cjmp", "<", 4 },
{ "label", 3 },
{ "load", "v1", 12, 2 },
{ "cmp", "v1", 8 },
{ "cjmp", "!=", 6 },
{ "label", 5 },
{ "load", "r1", 23, 1 },
{ "cmp", "r1", 6 },
{ "cjmp", "=", "true-label" },
{ "ret-false" },
{ "label", 6 },
{ "cmp", "len", 54 },
{ "cjmp", "<", 8 },
{ "label", 7 },
{ "cmp", "v1", 56710 },
{ "cjmp", "!=", 10 },
{ "label", 9 },
{ "load", "v2", 20, 1 },
{ "cmp", "v2", 6 },
{ "cjmp", "!=", 12 } }
local example_2 =
{ { "label", 1 },
{ "load", "r1", 12, 2 },
{ "load", "r2", 14, 2 },
{ "mov", "r3", "r1" },
{ "mul", "r3", "r2" },
{ "cmp", "r3", 1 },
{ "cjmp", "!=", 4 },
{ "cmp", "len", 1 } }
-- this example isn't from real code, but tests what happens when
-- there is higher register pressure
local example_3 =
{ { "label", 1 },
{ "load", "r1", 12, 2 },
{ "load", "r2", 14, 2 },
{ "load", "r3", 15, 2 },
{ "load", "r4", 16, 2 },
{ "load", "r5", 17, 2 },
{ "load", "r6", 18, 2 },
{ "load", "r7", 19, 2 },
{ "load", "r8", 20, 2 },
{ "load", "r9", 21, 2 },
{ "cmp", "r1", 1 },
{ "cmp", "r2", 1 },
{ "cmp", "r3", 1 },
{ "cmp", "r4", 1 },
{ "cmp", "r5", 1 },
{ "cmp", "r6", 1 },
{ "cmp", "r7", 1 },
{ "cmp", "r8", 1 },
{ "cmp", "r9", 1 } }
-- test that tries to make movs use same dst/src
local example_4 =
{ { "label", 1 },
{ "load", "v1", 12, 2 },
{ "cmp", "v1", 1 },
{ "load", "r1", 12, 2 },
{ "mov", "r2", "r1" },
{ "cmp", "r2", 1 },
{ "cmp", "len", 1 } }
-- full `tcp` example from more recent instruction selection
local example_5 =
{ { "label", 0 },
{ "cmp", "len", 34 },
{ "cjmp", "<", 4 },
{ "label", 3 },
{ "load", "r1", 12, 2 },
{ "mov", "v1", "r1" },
{ "cmp", "v1", 8 },
{ "cjmp", "!=", 6 },
{ "label", 5 },
{ "load", "r2", 23, 1 },
{ "cmp", "r2", 6 },
{ "cjmp", "=", "true-label" },
{ "ret-false" },
{ "label", 6 },
{ "cmp", "len", 54 },
{ "cjmp", "<", 8 },
{ "label", 7 },
{ "cmp", "v1", 56710 },
{ "cjmp", "!=", 10 },
{ "label", 9 },
{ "load", "r3", 20, 1 },
{ "mov", "v2", "r3" },
{ "cmp", "v2", 6 },
{ "cjmp", "!=", 12 },
{ "label", 11 },
{ "ret-true" },
{ "label", 12 },
{ "cmp", "len", 55 },
{ "cjmp", "<", 14 },
{ "label", 13 },
{ "cmp", "v2", 44 },
{ "cjmp", "!=", 16 },
{ "label", 15 },
{ "load", "r4", 54, 1 },
{ "cmp", "r4", 6 },
{ "cjmp", "=", "true-label" },
{ "ret-false" },
{ "label", 16 },
{ "ret-false" },
{ "label", 14 },
{ "ret-false" },
{ "label", 10 },
{ "ret-false" },
{ "label", 8 },
{ "ret-false" },
{ "label", 4 },
{ "ret-false" } }
-- test that variables in load offsets are properly accounted for
local example_6 =
{ { "label", 0 },
{ "mov", "r1", 5 },
{ "load", "v2", 12, 2 },
{ "load", "v1", "r1", 2 },
{ "cmp", "v1", 1 },
{ "cmp", "v2", 2 } }
-- another test with high register pressure, should be high enough
-- to require spilling
local example_7 =
{ { "label", 1 },
{ "load", "r1", 12, 2 },
{ "load", "r2", 14, 2 },
{ "load", "r3", 15, 2 },
{ "load", "r4", 16, 2 },
{ "load", "r5", 17, 2 },
{ "load", "r6", 18, 2 },
{ "load", "r7", 19, 2 },
{ "load", "r8", 20, 2 },
{ "load", "r9", 21, 2 },
{ "load", "r10", 22, 2 },
{ "load", "r11", 23, 2 },
{ "load", "r12", 24, 2 },
{ "load", "r13", 25, 2 },
{ "load", "r14", 26, 2 },
{ "cmp", "r1", 1 },
{ "cmp", "r2", 1 },
{ "cmp", "r3", 1 },
{ "cmp", "r4", 1 },
{ "cmp", "r5", 1 },
{ "cmp", "r6", 1 },
{ "cmp", "r7", 1 },
{ "cmp", "r8", 1 },
{ "cmp", "r9", 1 },
{ "cmp", "r10", 1 },
{ "cmp", "r11", 1 },
{ "cmp", "r12", 1 },
{ "cmp", "r13", 1 },
{ "cmp", "r14", 1 } }
test(example_1,
{ { name = "len", start = 1, finish = 14 },
{ name = "v1", start = 5, finish = 17 },
{ name = "r1", start = 9, finish = 10 },
{ name = "v2", start = 20, finish = 21 } })
test(example_2,
{ { name = "len", start = 1, finish = 8 },
{ name = "r1", start = 2, finish = 4 },
{ name = "r2", start = 3, finish = 5 },
{ name = "r3", start = 4, finish = 6 } })
test(example_5,
{ { name = "len", start = 1, finish = 28 },
{ name = "r1", start = 5, finish = 6 },
{ name = "v1", start = 6, finish = 18 },
{ name = "r2", start = 10, finish = 11 },
{ name = "r3", start = 21, finish = 22 },
{ name = "v2", start = 22, finish = 31 },
{ name = "r4", start = 34, finish = 35 } })
test(example_6,
{ { name = "len", start = 1, finish = 1 },
{ name = "r1", start = 2, finish = 4 },
{ name = "v2", start = 3, finish = 6 },
{ name = "v1", start = 4, finish = 5 } })
local function test(instrs, expected)
utils.assert_equals(expected, allocate(instrs))
end
test(example_1,
{ v1 = 0, r1 = 1, len = 6, v2 = 0,
callee_saves = {}, spills = {} })
-- mutates example_2
test(example_2,
{ r1 = 0, r2 = 1, r3 = 0, len = 6,
callee_saves = {}, spills = {} })
utils.assert_equals(example_2,
{ { "label", 1 },
{ "load", "r1", 12, 2 },
{ "load", "r2", 14, 2 },
{ "nop" },
{ "mul", "r3", "r2" },
{ "cmp", "r3", 1 },
{ "cjmp", "!=", 4 },
{ "cmp", "len", 1 } })
test(example_3,
{ r1 = 6, r2 = 0, r3 = 1, r4 = 2, r5 = 8, r6 = 9,
r7 = 10, r8 = 11, r9 = 3, len = 6,
callee_saves = utils.set(3), spills = {} })
test(example_4,
{ v1 = 0, r1 = 0, len = 6, r2 = 0, callee_saves = {},
spills = {} })
test(example_5,
{ len = 6, r1 = 0, v1 = 0, r2 = 1, r3 = 0,
v2 = 0, r4 = 0, callee_saves = {},
spills = {} })
test(example_7,
{ r1 = 6, r2 = 0, r3 = 1, r4 = 2, r5 = 8, r6 = 9,
r7 = 10, r8 = 11, r9 = 3, r10 = 12, r11 = 13,
spills = { r12 = 1, r13 = 0, r14 = 2 },
len = 6, callee_saves = utils.set(3, 12, 13, 14, 15),
spill_registers = { 15, 14 } })
end
| apache-2.0 |
UnfortunateFruit/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Dhea_Prandoleh.lua | 16 | 1048 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Dhea Prandoleh
-- Type: Standard NPC
-- @zone: 94
-- @pos 3.167 -2 15.545
--
-- 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(0x00a0);
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 |
nesstea/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/HomePoint#1.lua | 27 | 1280 | -----------------------------------
-- Area: Windurst_Waters_[S]
-- NPC: HomePoint#1
-- @pos -32 -5 131 94
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Windurst_Waters_[S]/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 70);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Chateau_dOraguille/npcs/Mistaravant.lua | 13 | 1064 | -----------------------------------
-- Area: Chateau d'Oraguille
-- NPC: Mistaravant
-- Type: Standard NPC
-- @zone: 233
-- @pos 7.097 -3.999 67.988
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x020c);
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 |
dpino/snabbswitch | src/program/packetblaster/synth/synth.lua | 14 | 1360 | -- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local config = require("core.config")
local main = require("core.main")
local Synth = require("apps.test.synth").Synth
local lib = require("core.lib")
local packetblaster = require("program.packetblaster.packetblaster")
local long_opts = {
duration = "D",
help = "h",
src = "s",
dst = "d",
sizes = "S",
}
local function show_usage (code)
print(require("program.packetblaster.synth.README_inc"))
main.exit(code)
end
function run (args)
local c = config.new()
local handlers = {}
local opts = {}
function handlers.D (arg)
opts.duration = assert(tonumber(arg), "duration is not a number!")
end
function handlers.h ()
show_usage(0)
end
local source
local destination
local sizes
function handlers.s (arg) source = arg end
function handlers.d (arg) destination = arg end
function handlers.S (arg)
sizes = {}
for size in string.gmatch(arg, "%d+") do
sizes[#sizes+1] = tonumber(size)
end
end
args = lib.dogetopt(args, handlers, "hD:s:d:S:", long_opts)
config.app(c, "source", Synth, { sizes = sizes,
src = source, dst = destination })
packetblaster.run_loadgen(c, args, opts)
end
| apache-2.0 |
MuhammadWang/MCServer | lib/tolua++/src/bin/lua/declaration.lua | 2 | 15143 | -- tolua: declaration class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id: $
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- Declaration class
-- Represents variable, function, or argument declaration.
-- Stores the following fields:
-- mod = type modifiers
-- type = type
-- ptr = "*" or "&", if representing a pointer or a reference
-- name = name
-- dim = dimension, if a vector
-- def = default value, if any (only for arguments)
-- ret = "*" or "&", if value is to be returned (only for arguments)
classDeclaration = {
mod = '',
type = '',
ptr = '',
name = '',
dim = '',
ret = '',
def = ''
}
classDeclaration.__index = classDeclaration
setmetatable(classDeclaration,classFeature)
-- Create an unique variable name
function create_varname ()
if not _varnumber then _varnumber = 0 end
_varnumber = _varnumber + 1
return "tolua_var_".._varnumber
end
-- Check declaration name
-- It also identifies default values
function classDeclaration:checkname ()
if strsub(self.name,1,1) == '[' and not findtype(self.type) then
self.name = self.type..self.name
local m = split(self.mod,'%s%s*')
self.type = m[m.n]
self.mod = concat(m,1,m.n-1)
end
local t = split(self.name,'=')
if t.n==2 then
self.name = t[1]
self.def = find_enum_var(t[t.n])
end
local b,e,d = strfind(self.name,"%[(.-)%]")
if b then
self.name = strsub(self.name,1,b-1)
self.dim = find_enum_var(d)
end
if self.type ~= '' and self.type ~= 'void' and self.name == '' then
self.name = create_varname()
elseif self.kind=='var' then
if self.type=='' and self.name~='' then
self.type = self.type..self.name
self.name = create_varname()
elseif findtype(self.name) then
if self.type=='' then self.type = self.name
else self.type = self.type..' '..self.name end
self.name = create_varname()
end
end
-- adjust type of string
if self.type == 'char' and self.dim ~= '' then
self.type = 'char*'
end
if self.kind and self.kind == 'var' then
self.name = string.gsub(self.name, ":.*$", "") -- ???
end
end
-- Check declaration type
-- Substitutes typedef's.
function classDeclaration:checktype ()
-- check if there is a pointer to basic type
local basic = isbasic(self.type)
if self.kind == 'func' and basic=='number' and string.find(self.ptr, "%*") then
self.type = '_userdata'
self.ptr = ""
end
if basic and self.ptr~='' then
self.ret = self.ptr
self.ptr = nil
if isbasic(self.type) == 'number' then
self.return_userdata = true
end
end
-- check if there is array to be returned
if self.dim~='' and self.ret~='' then
error('#invalid parameter: cannot return an array of values')
end
-- restore 'void*' and 'string*'
if self.type == '_userdata' then self.type = 'void*'
elseif self.type == '_cstring' then self.type = 'char*'
elseif self.type == '_lstate' then self.type = 'lua_State*'
end
-- resolve types inside the templates
if self.type then
self.type = resolve_template_types(self.type)
end
--
-- -- if returning value, automatically set default value
-- if self.ret ~= '' and self.def == '' then
-- self.def = '0'
-- end
--
end
function resolve_template_types(type)
if isbasic(type) then
return type
end
local b,_,m = string.find(type, "(%b<>)")
if b then
m = split_c_tokens(string.sub(m, 2, -2), ",")
for i=1, table.getn(m) do
m[i] = string.gsub(m[i],"%s*([%*&])", "%1")
if not isbasic(m[i]) then
if not isenum(m[i]) then _, m[i] = applytypedef("", m[i]) end
m[i] = findtype(m[i]) or m[i]
m[i] = resolve_template_types(m[i])
end
end
local b,i
type,b,i = break_template(type)
--print("concat is ",concat(m, 1, m.n))
local template_part = "<"..concat(m, 1, m.n, ",")..">"
type = rebuild_template(type, b, template_part)
type = string.gsub(type, ">>", "> >")
end
return type
end
function break_template(s)
local b,e,timpl = string.find(s, "(%b<>)")
if timpl then
s = string.gsub(s, "%b<>", "")
return s, b, timpl
else
return s, 0, nil
end
end
function rebuild_template(s, b, timpl)
if b == 0 then
return s
end
return string.sub(s, 1, b-1)..timpl..string.sub(s, b, -1)
end
-- Print method
function classDeclaration:print (ident,close)
print(ident.."Declaration{")
print(ident.." mod = '"..self.mod.."',")
print(ident.." type = '"..self.type.."',")
print(ident.." ptr = '"..self.ptr.."',")
print(ident.." name = '"..self.name.."',")
print(ident.." dim = '"..self.dim.."',")
print(ident.." def = '"..self.def.."',")
print(ident.." ret = '"..self.ret.."',")
print(ident.."}"..close)
end
-- check if array of values are returned to Lua
function classDeclaration:requirecollection (t)
if self.mod ~= 'const' and
self.dim and self.dim ~= '' and
not isbasic(self.type) and
self.ptr == '' and self:check_public_access() then
local type = gsub(self.type,"%s*const%s+","")
t[type] = "tolua_collect_" .. clean_template(type)
return true
end
return false
end
-- declare tag
function classDeclaration:decltype ()
self.type = typevar(self.type)
if strfind(self.mod,'const') then
self.type = 'const '..self.type
self.mod = gsub(self.mod,'const%s*','')
end
end
-- output type checking
function classDeclaration:outchecktype (narg)
local def
local t = isbasic(self.type)
if self.def~='' then
def = 1
else
def = 0
end
if self.dim ~= '' then
--if t=='string' then
-- return 'tolua_isstringarray(tolua_S,'..narg..','..def..',&tolua_err)'
--else
return '!tolua_istable(tolua_S,'..narg..',0,&tolua_err)'
--end
elseif isenumtype(self.type) ~= nil then
return '!tolua_is'..self.type..'(tolua_S,'..narg..','..def..',&tolua_err)'
elseif t then
return '!tolua_is'..t..'(tolua_S,'..narg..','..def..',&tolua_err)'
else
local is_func = get_is_function(self.type)
if self.ptr == '&' or self.ptr == '' then
return '(tolua_isvaluenil(tolua_S,'..narg..',&tolua_err) || !'..is_func..'(tolua_S,'..narg..',"'..self.type..'",'..def..',&tolua_err))'
else
return '!'..is_func..'(tolua_S,'..narg..',"'..self.type..'",'..def..',&tolua_err)'
end
end
end
function classDeclaration:builddeclaration (narg, cplusplus)
local array = self.dim ~= '' and tonumber(self.dim)==nil
local line = ""
local ptr = ''
local mod
local type = self.type
local nctype = gsub(self.type,'const%s+','')
if self.dim ~= '' then
type = gsub(self.type,'const%s+','') -- eliminates const modifier for arrays
end
if self.ptr~='' and not isbasic(type) then ptr = '*' end
line = concatparam(line," ",self.mod,type,ptr)
if array then
line = concatparam(line,'*')
end
line = concatparam(line,self.name)
if self.dim ~= '' then
if tonumber(self.dim)~=nil then
line = concatparam(line,'[',self.dim,'];')
else
if cplusplus then
line = concatparam(line,' = Mtolua_new_dim(',type,ptr,', '..self.dim..');')
else
line = concatparam(line,' = (',type,ptr,'*)',
'malloc((',self.dim,')*sizeof(',type,ptr,'));')
end
end
else
local t = isbasic(type)
line = concatparam(line,' = ')
if t == 'state' then
line = concatparam(line, 'tolua_S;')
else
--print("t is "..tostring(t)..", ptr is "..tostring(self.ptr))
if t == 'number' and string.find(self.ptr, "%*") then
t = 'userdata'
end
if not t and ptr=='' then line = concatparam(line,'*') end
line = concatparam(line,'((',self.mod,type)
if not t then
line = concatparam(line,'*')
end
line = concatparam(line,') ')
if isenum(nctype) then
line = concatparam(line,'(int) ')
end
local def = 0
if self.def ~= '' then
def = self.def
if (ptr == '' or self.ptr == '&') and not t then
def = "(void*)&(const "..type..")"..def
end
end
if t then
line = concatparam(line,'tolua_to'..t,'(tolua_S,',narg,',',def,'));')
else
local to_func = get_to_function(type)
line = concatparam(line,to_func..'(tolua_S,',narg,',',def,'));')
end
end
end
return line
end
-- Declare variable
function classDeclaration:declare (narg)
if self.dim ~= '' and tonumber(self.dim)==nil then
output('#ifdef __cplusplus\n')
output(self:builddeclaration(narg,true))
output('#else\n')
output(self:builddeclaration(narg,false))
output('#endif\n')
else
output(self:builddeclaration(narg,false))
end
end
-- Get parameter value
function classDeclaration:getarray (narg)
if self.dim ~= '' then
local type = gsub(self.type,'const ','')
output(' {')
output('#ifndef TOLUA_RELEASE\n')
local def; if self.def~='' then def=1 else def=0 end
local t = isbasic(type)
if (t) then
output(' if (!tolua_is'..t..'array(tolua_S,',narg,',',self.dim,',',def,',&tolua_err))')
else
output(' if (!tolua_isusertypearray(tolua_S,',narg,',"',type,'",',self.dim,',',def,',&tolua_err))')
end
output(' goto tolua_lerror;')
output(' else\n')
output('#endif\n')
output(' {')
output(' int i;')
output(' for(i=0; i<'..self.dim..';i++)')
local t = isbasic(type)
local ptr = ''
if self.ptr~='' then ptr = '*' end
output(' ',self.name..'[i] = ')
if not t and ptr=='' then output('*') end
output('((',type)
if not t then
output('*')
end
output(') ')
local def = 0
if self.def ~= '' then def = self.def end
if t then
output('tolua_tofield'..t..'(tolua_S,',narg,',i+1,',def,'));')
else
output('tolua_tofieldusertype(tolua_S,',narg,',i+1,',def,'));')
end
output(' }')
output(' }')
end
end
-- Get parameter value
function classDeclaration:setarray (narg)
if not strfind(self.type,'const%s+') and self.dim ~= '' then
local type = gsub(self.type,'const ','')
output(' {')
output(' int i;')
output(' for(i=0; i<'..self.dim..';i++)')
local t,ct = isbasic(type)
if t then
output(' tolua_pushfield'..t..'(tolua_S,',narg,',i+1,(',ct,')',self.name,'[i]);')
else
if self.ptr == '' then
output(' {')
output('#ifdef __cplusplus\n')
output(' void* tolua_obj = Mtolua_new((',type,')(',self.name,'[i]));')
output(' tolua_pushfieldusertype_and_takeownership(tolua_S,',narg,',i+1,tolua_obj,"',type,'");')
output('#else\n')
output(' void* tolua_obj = tolua_copy(tolua_S,(void*)&',self.name,'[i],sizeof(',type,'));')
output(' tolua_pushfieldusertype(tolua_S,',narg,',i+1,tolua_obj,"',type,'");')
output('#endif\n')
output(' }')
else
output(' tolua_pushfieldusertype(tolua_S,',narg,',i+1,(void*)',self.name,'[i],"',type,'");')
end
end
output(' }')
end
end
-- Free dynamically allocated array
function classDeclaration:freearray ()
if self.dim ~= '' and tonumber(self.dim)==nil then
output('#ifdef __cplusplus\n')
output(' Mtolua_delete_dim(',self.name,');')
output('#else\n')
output(' free(',self.name,');')
output('#endif\n')
end
end
-- Pass parameter
function classDeclaration:passpar ()
if self.ptr=='&' and not isbasic(self.type) then
output('*'..self.name)
elseif self.ret=='*' then
output('&'..self.name)
else
output(self.name)
end
end
-- Return parameter value
function classDeclaration:retvalue ()
if self.ret ~= '' then
local t,ct = isbasic(self.type)
if t and t~='' then
output(' tolua_push'..t..'(tolua_S,(',ct,')'..self.name..');')
else
local push_func = get_push_function(self.type)
output(' ',push_func,'(tolua_S,(void*)'..self.name..',"',self.type,'");')
end
return 1
end
return 0
end
-- Internal constructor
function _Declaration (t)
setmetatable(t,classDeclaration)
t:buildnames()
t:checkname()
t:checktype()
local ft = findtype(t.type) or t.type
if not isenum(ft) then
t.mod, t.type = applytypedef(t.mod, ft)
end
if t.kind=="var" and (string.find(t.mod, "tolua_property%s") or string.find(t.mod, "tolua_property$")) then
t.mod = string.gsub(t.mod, "tolua_property", "tolua_property__"..get_property_type())
end
return t
end
-- Constructor
-- Expects the string declaration.
-- The kind of declaration can be "var" or "func".
function Declaration (s,kind,is_parameter)
-- eliminate spaces if default value is provided
s = gsub(s,"%s*=%s*","=")
s = gsub(s, "%s*<", "<")
local defb,tmpdef
defb,_,tmpdef = string.find(s, "(=.*)$")
if defb then
s = string.gsub(s, "=.*$", "")
else
tmpdef = ''
end
if kind == "var" then
-- check the form: void
if s == '' or s == 'void' then
return _Declaration{type = 'void', kind = kind, is_parameter = is_parameter}
end
end
-- check the form: mod type*& name
local t = split_c_tokens(s,'%*%s*&')
if t.n == 2 then
if kind == 'func' then
error("#invalid function return type: "..s)
end
--local m = split(t[1],'%s%s*')
local m = split_c_tokens(t[1],'%s+')
return _Declaration{
name = t[2]..tmpdef,
ptr = '*',
ret = '&',
--type = rebuild_template(m[m.n], tb, timpl),
type = m[m.n],
mod = concat(m,1,m.n-1),
is_parameter = is_parameter,
kind = kind
}
end
-- check the form: mod type** name
t = split_c_tokens(s,'%*%s*%*')
if t.n == 2 then
if kind == 'func' then
error("#invalid function return type: "..s)
end
--local m = split(t[1],'%s%s*')
local m = split_c_tokens(t[1],'%s+')
return _Declaration{
name = t[2]..tmpdef,
ptr = '*',
ret = '*',
--type = rebuild_template(m[m.n], tb, timpl),
type = m[m.n],
mod = concat(m,1,m.n-1),
is_parameter = is_parameter,
kind = kind
}
end
-- check the form: mod type& name
t = split_c_tokens(s,'&')
if t.n == 2 then
--local m = split(t[1],'%s%s*')
local m = split_c_tokens(t[1],'%s+')
return _Declaration{
name = t[2]..tmpdef,
ptr = '&',
--type = rebuild_template(m[m.n], tb, timpl),
type = m[m.n],
mod = concat(m,1,m.n-1),
is_parameter = is_parameter,
kind = kind
}
end
-- check the form: mod type* name
local s1 = gsub(s,"(%b\[\])",function (n) return gsub(n,'%*','\1') end)
t = split_c_tokens(s1,'%*')
if t.n == 2 then
t[2] = gsub(t[2],'\1','%*') -- restore * in dimension expression
--local m = split(t[1],'%s%s*')
local m = split_c_tokens(t[1],'%s+')
return _Declaration{
name = t[2]..tmpdef,
ptr = '*',
type = m[m.n],
--type = rebuild_template(m[m.n], tb, timpl),
mod = concat(m,1,m.n-1) ,
is_parameter = is_parameter,
kind = kind
}
end
if kind == 'var' then
-- check the form: mod type name
--t = split(s,'%s%s*')
t = split_c_tokens(s,'%s+')
local v
if findtype(t[t.n]) then v = create_varname() else v = t[t.n]; t.n = t.n-1 end
return _Declaration{
name = v..tmpdef,
--type = rebuild_template(t[t.n], tb, timpl),
type = t[t.n],
mod = concat(t,1,t.n-1),
is_parameter = is_parameter,
kind = kind
}
else -- kind == "func"
-- check the form: mod type name
--t = split(s,'%s%s*')
t = split_c_tokens(s,'%s+')
local v = t[t.n] -- last word is the function name
local tp,md
if t.n>1 then
tp = t[t.n-1]
md = concat(t,1,t.n-2)
end
--if tp then tp = rebuild_template(tp, tb, timpl) end
return _Declaration{
name = v,
type = tp,
mod = md,
is_parameter = is_parameter,
kind = kind
}
end
end
| apache-2.0 |
nesstea/darkstar | scripts/zones/Jugner_Forest/npcs/Geruru_WW.lua | 13 | 3323 | -----------------------------------
-- Area: Jugner Forest
-- NPC: Geruru, W.W.
-- Type: Border Conquest Guards
-- @pos 570.732 -2.637 553.508 104
-----------------------------------
package.loaded["scripts/zones/Jugner_Forest/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Jugner_Forest/TextIDs");
local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = NORVALLEN;
local csid = 0x7ff6;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Windurst_Woods/npcs/Zahsa_Syalmhaia.lua | 13 | 1067 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Zahsa Syalmhaia
-- Type: Great War Veteran NPC
-- @zone: 241
-- @pos 13.710 1.422 -83.198
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x031d);
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 |
Cyumus/NutScript | plugins/recognition.lua | 4 | 4031 | PLUGIN.name = "Recognition"
PLUGIN.author = "Chessnut"
PLUGIN.desc = "Adds the ability to recognize people."
do
local character = nut.meta.character
if (SERVER) then
function character:recognize(id)
if (type(id) != "number" and id.getID) then
id = id:getID()
end
local recognized = self:getData("rgn", "")
if (recognized != "" and recognized:find(","..id..",")) then
return false;
end;
self:setData("rgn", recognized..","..id..",")
return true
end
end
function character:doesRecognize(id)
if (type(id) != "number" and id.getID) then
id = id:getID()
end
return hook.Run("IsCharRecognised", self, id)
end
function PLUGIN:IsCharRecognised(char, id)
local other = nut.char.loaded[id]
if (other) then
local faction = nut.faction.indices[other:getFaction()]
if (faction and faction.isGloballyRecognized) then
return true
end
end
local recognized = char:getData("rgn", "")
if (recognized == "") then
return false
end
return recognized:find(","..id..",") != nil and true or false
end
end
if (CLIENT) then
CHAT_RECOGNIZED = CHAT_RECOGNIZED or {}
CHAT_RECOGNIZED["ic"] = true
CHAT_RECOGNIZED["y"] = true
CHAT_RECOGNIZED["w"] = true
CHAT_RECOGNIZED["me"] = true
function PLUGIN:IsRecognizedChatType(chatType)
return CHAT_RECOGNIZED[chatType]
end
function PLUGIN:GetDisplayedDescription(client)
if (client:getChar() and client != LocalPlayer() and !LocalPlayer():getChar():doesRecognize(client:getChar()) and !hook.Run("IsPlayerRecognized", client)) then
return L"noRecog"
end
end
function PLUGIN:ShouldAllowScoreboardOverride(client)
if (nut.config.get("sbRecog")) then
return true
end
end
function PLUGIN:GetDisplayedName(client, chatType)
if (client != LocalPlayer()) then
local character = client:getChar()
local ourCharacter = LocalPlayer():getChar()
if (ourCharacter and character and !ourCharacter:doesRecognize(character) and !hook.Run("IsPlayerRecognized", client)) then
if (chatType and hook.Run("IsRecognizedChatType", chatType)) then
local description = character:getDesc()
if (#description > 40) then
description = description:utf8sub(1, 37).."..."
end
return "["..description.."]"
elseif (!chatType) then
return L"unknown"
end
end
end
end
netstream.Hook("rgnMenu", function()
local menu = DermaMenu()
menu:AddOption(L"rgnLookingAt", function()
netstream.Start("rgn", 1)
end)
menu:AddOption(L"rgnWhisper", function()
netstream.Start("rgn", 2)
end)
menu:AddOption(L"rgnTalk", function()
netstream.Start("rgn", 3)
end)
menu:AddOption(L"rgnYell", function()
netstream.Start("rgn", 4)
end)
menu:Open()
menu:MakePopup()
menu:Center()
end)
netstream.Hook("rgnDone", function()
hook.Run("OnCharRecognized", client, id)
end)
function PLUGIN:OnCharRecognized(client, recogCharID)
surface.PlaySound("buttons/button17.wav")
end
else
function PLUGIN:ShowSpare1(client)
if (client:getChar()) then
netstream.Start(client, "rgnMenu")
end
end
netstream.Hook("rgn", function(client, level)
local targets = {}
if (level < 2) then
local entity = client:GetEyeTraceNoCursor().Entity
if (IsValid(entity) and entity:IsPlayer() and entity:getChar() and nut.chat.classes.ic.onCanHear(client, entity)) then
targets[1] = entity
end
else
local class = "w"
if (level == 3) then
class = "ic"
elseif (level == 4) then
class = "y"
end
class = nut.chat.classes[class]
for k, v in ipairs(player.GetAll()) do
if (client != v and v:getChar() and class.onCanHear(client, v)) then
targets[#targets + 1] = v
end
end
end
if (#targets > 0) then
local id = client:getChar():getID()
local i = 0
for k, v in ipairs(targets) do
if (v:getChar():recognize(id)) then
i = i + 1
end
end
if (i > 0) then
netstream.Start(client, "rgnDone")
hook.Run("OnCharRecognized", client, id)
end
end
end)
end
| mit |
nesstea/darkstar | scripts/globals/spells/esuna.lua | 33 | 4143 | -----------------------------------------
-- Spell: Esuna
--
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
if (caster:getID() == target:getID()) then -- much of this should only run once per cast, otherwise it would only delete the debuffs from the caster.
local statusNum = -1;
local removables = {EFFECT_FLASH, EFFECT_BLINDNESS, EFFECT_PARALYSIS, EFFECT_POISON, EFFECT_CURSE_I, EFFECT_CURSE_II, EFFECT_DISEASE, EFFECT_PLAGUE};
if (caster:hasStatusEffect(EFFECT_AFFLATUS_MISERY)) then -- add extra statuses to the list of removables. Elegy and Requiem are specifically absent.
removables = {EFFECT_FLASH, EFFECT_BLINDNESS, EFFECT_PARALYSIS, EFFECT_POISON, EFFECT_CURSE_I, EFFECT_CURSE_II, EFFECT_DISEASE, EFFECT_PLAGUE, EFFECT_WEIGHT, EFFECT_BIND, EFFECT_BIO, EFFECT_DIA, EFFECT_BURN, EFFECT_FROST, EFFECT_CHOKE, EFFECT_RASP, EFFECT_SHOCK, EFFECT_DROWN, EFFECT_STR_DOWN, EFFECT_DEX_DOWN, EFFECT_VIT_DOWN, EFFECT_AGI_DOWN, EFFECT_INT_DOWN, EFFECT_MND_DOWN, EFFECT_CHR_DOWN, EFFECT_ADDLE, EFFECT_SLOW, EFFECT_HELIX, EFFECT_ACCURACY_DOWN, EFFECT_ATTACK_DOWN, EFFECT_EVASION_DOWN, EFFECT_DEFENSE_DOWN, EFFECT_MAGIC_ACC_DOWN, EFFECT_MAGIC_ATK_DOWN, EFFECT_MAGIC_EVASION_DOWN, EFFECT_MAGIC_DEF_DOWN, EFFECT_MAX_TP_DOWN, EFFECT_MAX_MP_DOWN, EFFECT_MAX_HP_DOWN};
end;
local has = {};
-- collect a list of what caster currently has
for i, effect in ipairs(removables) do
if (caster:hasStatusEffect(effect)) then
statusNum = statusNum + 1
has[statusNum] = removables[i];
end;
end;
if (statusNum >= 0) then -- make sure this happens once instead of for every target
local delEff = math.random(0,statusNum); -- pick a random status to delete
caster:setLocalVar("esunaDelEff",has[delEff]); -- this can't be a local because it would only delete from the caster if it were.
else -- clear it if the caster has no eligible statuses, otherwise it will remove the status from others if it was previously removed.
caster:setLocalVar("esunaDelEff",0);
caster:setLocalVar("esunaDelEffMis",0); -- again, this can't be a local because it would only delete from the caster if it were. For extra status deletion under Misery
end;
if (statusNum >= 1 and caster:hasStatusEffect(EFFECT_AFFLATUS_MISERY)) then -- Misery second status removal.
caster:delStatusEffect(has[delEff]); -- delete the first selected effect so it doesn't get selected again. Won't impact the ability to delete it from others at this point.
local statusNumMis = - 1 -- need a new var to track the amount of debuffs for the array
-- collect a list of what caster currently has, again.
has = {}
for i, effect in ipairs(removables) do
if (caster:hasStatusEffect(effect)) then
statusNumMis = statusNumMis + 1
has[statusNumMis] = removables[i];
end;
end;
local delEffMis = math.random(0,statusNumMis); -- pick another random status to delete
caster:setLocalVar("esunaDelEffMis",has[delEffMis]);
else
caster:setLocalVar("esunaDelEffMis",0);
end;
end;
local statusDel = caster:getLocalVar("esunaDelEff")
local statusDelMis = caster:getLocalVar("esunaDelEffMis")
if (statusDel == 0) then -- this gets set to 0 if there's no status to delete.
spell:setMsg(75); -- no effect
elseif (statusDelMis ~= 0) then -- no need to check for statusDelMis because it can't be 0 if this isn't
target:delStatusEffect(statusDel);
target:delStatusEffect(statusDelMis);
else
target:delStatusEffect(statusDel);
end;
return statusDel;
end; | gpl-3.0 |
nesstea/darkstar | scripts/globals/summon.lua | 6 | 11157 |
require("scripts/globals/common");
require("scripts/globals/status");
SUMMONING_MAGIC_SKILL = 38
MSG_NONE = 0; -- display nothing
MSG_NO_EFFECT = 189;
MSG_DAMAGE = 185; -- player uses, target takes 10 damage. DEFAULT
MSG_MISS = 188;
MSG_RESIST = 85;
function AvatarPhysicalMove(avatar,target,skill,numberofhits,accmod,dmgmod1,dmgmodsubsequent,tpeffect,mtp100,mtp200,mtp300)
returninfo = {};
--Damage = (D+fSTR) * dmgmod * PDIF
-- printf("str: %f, vit: %f", avatar:getStat(MOD_STR), target:getStat(MOD_VIT));
fstr = avatarFSTR(avatar:getStat(MOD_STR), target:getStat(MOD_VIT));
lvluser = avatar:getMainLvl();
lvltarget = target:getMainLvl();
local master = avatar:getMaster();
local bonusacc = utils.clamp(master:getSkillLevel(SKILL_SUM) - master:getMaxSkillLevel(avatar:getMainLvl(), JOB_SMN, SUMMONING_SKILL), 0, 200);
acc = avatar:getACC() + bonusacc;
eva = target:getEVA();
local base = avatar:getWeaponDmg() + fstr;
local ratio = avatar:getStat(MOD_ATT)/target:getStat(MOD_DEF);
lvldiff = lvluser - lvltarget;
--work out hit rate for mobs (bias towards them)
hitrate = (acc*accmod) - eva;
if (lvluser > lvltarget) then
hitrate = hitrate + ((lvluser-lvltarget)*5);
end
if (lvltarget > lvluser) then
hitrate = hitrate + ((lvltarget-lvluser)*3);
end
if (hitrate > 95) then
hitrate = 95;
end
if (hitrate < 20) then
hitrate = 20;
end
if (base < 1) then
base = 1;
end
hitdamage = base * dmgmod1;
subsequenthitdamage = base * dmgmodsubsequent;
if (ratio<=1) then
maxRatio = 1;
minRatio = 1/3;
elseif (ratio<1.6) then
maxRatio = ((4/6) * ratio) + (2/6);
minRatio = ((7/9) * ratio) - (4/9);
elseif (ratio<=1.8) then
maxRatio = 1.8;
minRatio = 1;
elseif (ratio<3.6) then
maxRatio = (2.4 * ratio) - 2.52;
minRatio = ((5/3) * ratio) - 2;
else
maxRatio = 4.2;
minRatio = 4;
end
if (tpeffect==TP_DMG_BONUS) then
hitdamage = hitdamage * avatarFTP(skill:getTP(), mtp100, mtp200, mtp300);
end
--Applying pDIF
local pdif = 0;
-- start the hits
local hitchance = math.random();
finaldmg = 0;
hitsdone = 1; hitslanded = 0;
--add on native crit hit rate (guesstimated, it actually follows an exponential curve)
nativecrit = (avatar:getStat(MOD_DEX) - target:getStat(MOD_AGI))*0.005; --assumes +0.5% crit rate per 1 dDEX
nativecrit = nativecrit + (avatar:getMod(MOD_CRITHITRATE)/100);
if (nativecrit > 0.2) then --caps!
nativecrit = 0.2;
elseif (nativecrit < 0.05) then
nativecrit = 0.05;
end
local critchance = math.random();
local hitchance = 0;
local crit = false;
if critchance <= nativecrit then
crit = true;
else
hitchance = math.random();
end
if crit == true or hitchance*100 <= 95 then
pdif = math.random((minRatio * 1000), (maxRatio * 1000));
pdif = pdif/1000;
if crit == true then
pdif = pdif + 1;
if pdif > 4.2 then
pdif = 4.2
end
end
finaldmg = finaldmg + hitdamage * pdif;
hitslanded = hitslanded + 1;
end
while (hitsdone < numberofhits) do
chance = math.random();
if ((chance*100)<=hitrate) then
pdif = math.random((minRatio * 1000), (maxRatio * 1000));
pdif = pdif/1000;
finaldmg = finaldmg + subsequenthitdamage * pdif;
hitslanded = hitslanded + 1;
end
hitsdone = hitsdone + 1;
end
-- all hits missed
if (hitslanded == 0 or finaldmg == 0) then
finaldmg = 0;
hitslanded = 0;
skill:setMsg(MSG_MISS);
end
if finaldmg > 0 then
target:wakeUp()
end
returninfo.dmg = finaldmg;
returninfo.hitslanded = hitslanded;
return returninfo;
end;
--Given the attacker's str and the mob's vit, fSTR is calculated
function avatarFSTR(atk_str,def_vit)
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< -1) then
fSTR2 = -1;
elseif (fSTR2>8) then
fSTR2 = 8;
end
return fSTR2;
end;
function AvatarFinalAdjustments(dmg,mob,skill,target,skilltype,skillparam,shadowbehav)
-- physical attack missed, skip rest
if (skilltype == MOBSKILL_PHYSICAL and dmg == 0) then
return 0;
end
-- set message to damage
-- this is for AoE because its only set once
skill:setMsg(MSG_DAMAGE);
--Handle shadows depending on shadow behaviour / skilltype
if (shadowbehav < 5 and shadowbehav ~= MOBPARAM_IGNORE_SHADOWS) then --remove 'shadowbehav' shadows.
targShadows = target:getMod(MOD_UTSUSEMI);
shadowType = MOD_UTSUSEMI;
if (targShadows==0) then --try blink, as utsusemi always overwrites blink this is okay
targShadows = target:getMod(MOD_BLINK);
shadowType = MOD_BLINK;
end
if (targShadows>0) then
--Blink has a VERY high chance of blocking tp moves, so im assuming its 100% because its easier!
if (targShadows >= shadowbehav) then --no damage, just suck the shadows
skill:setMsg(31);
target:setMod(shadowType,(targShadows-shadowbehav));
if (shadowType == MOD_UTSUSEMI) then --update icon
effect = target:getStatusEffect(EFFECT_COPY_IMAGE);
if (effect ~= nil) then
if ((targShadows-shadowbehav) == 0) then
target:delStatusEffect(EFFECT_COPY_IMAGE);
target:delStatusEffect(EFFECT_BLINK);
elseif ((targShadows-shadowbehav) == 1) then
effect:setIcon(EFFECT_COPY_IMAGE);
elseif ((targShadows-shadowbehav) == 2) then
effect:setIcon(EFFECT_COPY_IMAGE_2);
elseif ((targShadows-shadowbehav) == 3) then
effect:setIcon(EFFECT_COPY_IMAGE_3);
end
end
end
return shadowbehav;
else --less shadows than this move will take, remove all and factor damage down
dmg = dmg * ((shadowbehav-targShadows)/shadowbehav);
target:setMod(MOD_UTSUSEMI,0);
target:setMod(MOD_BLINK,0);
target:delStatusEffect(EFFECT_COPY_IMAGE);
target:delStatusEffect(EFFECT_BLINK);
end
end
elseif (shadowbehav == MOBPARAM_WIPE_SHADOWS) then --take em all!
target:setMod(MOD_UTSUSEMI,0);
target:setMod(MOD_BLINK,0);
target:delStatusEffect(EFFECT_COPY_IMAGE);
target:delStatusEffect(EFFECT_BLINK);
end
--handle Third Eye using shadowbehav as a guide
teye = target:getStatusEffect(EFFECT_THIRD_EYE);
if (teye ~= nil and skilltype==MOBSKILL_PHYSICAL) then --T.Eye only procs when active with PHYSICAL stuff
if (shadowbehav == MOBPARAM_WIPE_SHADOWS) then --e.g. aoe moves
target:delStatusEffect(EFFECT_THIRD_EYE);
elseif (shadowbehav ~= MOBPARAM_IGNORE_SHADOWS) then --it can be absorbed by shadows
--third eye doesnt care how many shadows, so attempt to anticipate, but reduce
--chance of anticipate based on previous successful anticipates.
prevAnt = teye:getPower();
if (prevAnt == 0) then
--100% proc
teye:setPower(1);
skill:setMsg(30);
return 0;
end
if ( (math.random()*100) < (80-(prevAnt*10)) ) then
--anticipated!
teye:setPower(prevAnt+1);
skill:setMsg(30);
return 0;
end
target:delStatusEffect(EFFECT_THIRD_EYE);
end
end
--TODO: Handle anything else (e.g. if you have Magic Shield and its a Magic skill, then do 0 damage.
if (skilltype == MOBSKILL_PHYSICAL and target:hasStatusEffect(EFFECT_PHYSICAL_SHIELD)) then
return 0;
end
if (skilltype == MOBSKILL_RANGED and target:hasStatusEffect(EFFECT_ARROW_SHIELD)) then
return 0;
end
-- handle elemental resistence
if (skilltype == MOBSKILL_MAGICAL and target:hasStatusEffect(EFFECT_MAGIC_SHIELD)) then
return 0;
end
--handling phalanx
dmg = dmg - target:getMod(MOD_PHALANX);
if (dmg<0) then
return 0;
end
--handle invincible
if (target:hasStatusEffect(EFFECT_INVINCIBLE) and skilltype==MOBSKILL_PHYSICAL) then
return 0;
end
--handle pd
if ((target:hasStatusEffect(EFFECT_PERFECT_DODGE) or target:hasStatusEffect(EFFECT_ALL_MISS) )
and skilltype==MOBSKILL_PHYSICAL) then
return 0;
end
--handling stoneskin
skin = target:getMod(MOD_STONESKIN);
if (skin>0) then
if (skin >= dmg) then --absorb all damage
target:delMod(MOD_STONESKIN,dmg);
if (target:getMod(MOD_STONESKIN)==0) then
target:delStatusEffect(EFFECT_STONESKIN);
end
return 0;
else --absorbs some damage then wear
target:delMod(MOD_STONESKIN,skin);
target:delStatusEffect(EFFECT_STONESKIN);
return dmg - skin;
end
end
return dmg;
end;
-- returns true if mob attack hit
-- used to stop tp move status effects
function AvatarPhysicalHit(skill, dmg)
-- if message is not the default. Then there was a miss, shadow taken etc
return skill:getMsg() == MSG_DAMAGE;
end;
function avatarFTP(tp,ftp1,ftp2,ftp3)
if (tp<1000) then
tp=1000;
end
if (tp>=1000 and tp<2000) then
return ftp1 + ( ((ftp2-ftp1)/100) * (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)/100) * (tp-2000));
end
return 1; --no ftp mod
end;
--------
-- Checks if the summoner is in a Trial Size Avatar Mini Fight (used to restrict summoning while in bcnm)
--------
function avatarMiniFightCheck(caster)
local result = 0;
local bcnmid;
if (caster:hasStatusEffect(EFFECT_BATTLEFIELD) == true) then
bcnmid = caster:getStatusEffect(EFFECT_BATTLEFIELD):getPower();
if (bcnmid == 418 or bcnmid == 609 or bcnmid == 450 or bcnmid == 482 or bcnmid == 545 or bcnmid == 578) then -- Mini Avatar Fights
result = 40; -- Cannot use <spell> in this area.
end
end
return result;
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Port_Windurst/npcs/Thubu_Parohren.lua | 44 | 1821 | -----------------------------------
-- Area: Port Windurst
-- NPC: Thubu Parohren
-- Type: Fishing Guild Master
-- @pos -182.230 -3.835 61.373 240
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local newRank = tradeTestItem(player,npc,trade,SKILL_FISHING);
if (newRank ~= 0) then
player:setSkillRank(SKILL_FISHING,newRank);
player:startEvent(0x271a,0,0,0,0,newRank);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local getNewRank = 0;
local craftSkill = player:getSkillLevel(SKILL_FISHING);
local testItem = getTestItem(player,npc,SKILL_FISHING);
local guildMember = isGuildMember(player,5);
if (guildMember == 1) then guildMember = 150995375; end
if (canGetNewRank(player,craftSkill,SKILL_FISHING) == 1) then getNewRank = 100; end
player:startEvent(0x2719,testItem,getNewRank,30,guildMember,44,0,0,0);
end;
-- 0x2719 0x271a 0x0253 0x0255
-----------------------------------
-- 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 == 0x2719 and option == 1) then
signupGuild(player,32);
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Lower_Jeuno/npcs/Zauko.lua | 18 | 5455 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Zauko
-- Involved in Quests: Save the Clock Tower, Community Service
-- @zone 245
-- @pos -3 0 11
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
----- Save The Clock Tower Quest -----
if (trade:hasItemQty(555,1) == true and trade:getItemCount() == 1) then
a = player:getVar("saveTheClockTowerNPCz2"); -- NPC Zone2
if (a == 0 or (a ~= 256 and a ~= 288 and a ~= 320 and a ~= 384 and a ~= 768 and a ~= 352 and a ~= 896 and a ~= 416 and
a ~= 832 and a ~= 448 and a ~= 800 and a ~= 480 and a ~= 864 and a ~= 928 and a ~= 960 and a ~= 992)) then
player:startEvent(0x0032,10 - player:getVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hour = VanadielHour();
local cService = player:getVar("cService");
questServerVar = GetServerVariable("[JEUNO]CommService");
----- Community Service Quest -----
-- The reason for all the Default Dialogue "else"s is because of all the different checks needed and to keep default dialogue
-- If they're not there then the player will keep triggering the Quest Complete (Repeat) Cutscene
-- Please leave them here unless you can find a way to fix this but the quest as it should do.
-- Quest Start --
if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_AVAILABLE and player:getFameLevel(JEUNO) >=1) then
if (hour >= 18 and hour < 21) then
if (questServerVar == 0) then
player:startEvent(0x0074,questServerVar+1); -- Quest Start Dialogue (NOTE: The Cutscene says somebody else is working on it but it still adds the quest)
else
player:startEvent(0x0074,questServerVar);
end
else
player:startEvent(0x0076); -- Default Dialogue
end
-- Task Failed --
elseif (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then
if (cService >= 1 and cService < 12 == true) then -- If the quest is accepted but all lamps are NOT lit
if (hour >= 18 and hour < 23) then
player:startEvent(0x0077); -- Task Failed Dialogue
else
player:startEvent(0x0076);
end
-- Quest Complete --
else
player:startEvent(0x0075); -- Quest Complete Dialogue
end
-- Repeat Quest --
elseif (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED and cService == 18) then
if (hour >= 18 and hour < 21) then
player:startEvent(0x0074,1) -- Quest Start (Repeat)
else
player:startEvent(0x0076); -- Default Dialogue
end
-- Repeat Quest Task Failed --
elseif (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then
if (cService >= 14 and cService < 24 == true) then
if (hour >= 18 and hour < 23) then -- If Quest Repeat is accepted but lamps are not lit
player:startEvent(0x0077); -- Task Failed Dialogue
end
elseif (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED and cService == 0) then
player:startEvent(0x0076);
-- Repeat Quest Complete --
else
player:startEvent(0x0071); -- Quest Complete (Repeat)
end
else
player:startEvent(0x0076);
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);
-- ClockTower Quest --
if (csid == 0x0032) then
player:setVar("saveTheClockTowerVar",player:getVar("saveTheClockTowerVar") + 1);
player:setVar("saveTheClockTowerNPCz2",player:getVar("saveTheClockTowerNPCz2") + 256);
---- Community Service Quest ----
elseif (csid == 0x0074 and option == 0) then -- Quest Start
if (questServerVar == 0) then
player:addQuest(JEUNO,COMMUNITY_SERVICE);
SetServerVariable("[JEUNO]CommService",1);
end
elseif (csid == 0x0075) then -- Quest Finish
player:completeQuest(JEUNO,COMMUNITY_SERVICE);
player:addFame(JEUNO,30);
player:setVar("cService",13)
player:addTitle(TORCHBEARER);
elseif (csid == 0x0071) then -- Quest Finish (Repeat)
player:addKeyItem(LAMP_LIGHTERS_MEMBERSHIP_CARD); -- Lamp Lighter's Membership Card
player:messageSpecial(KEYITEM_OBTAINED,LAMP_LIGHTERS_MEMBERSHIP_CARD);
player:addFame(JEUNO, 15);
player:setVar("cService",0);
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Mhaura/npcs/Kotan-Purutan.lua | 19 | 2411 | -----------------------------------
-- Area: Mhaura
-- NPC: Kotan-Purutan
-- Involved in Quest: Overnight Delivery
-- @pos 40.323 -8.999 44.242 249
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local OvernightDelivery = player:getQuestStatus(WINDURST,OVERNIGHT_DELIVERY);
local KenapaOvernight = player:getVar("Kenapa_Overnight_var"); -- Variable to track progress for Overnight Delivery
local KenapaOvernightDay = player:getVar("Kenapa_Overnight_Day_var"); -- Variable to track the day the quest is started.
local KenapaOvernightHour = player:getVar("Kenapa_Overnight_Hour_var"); -- Variable to track the hour the quest is started.
local HourOfTheDay = VanadielHour();
if(OvernightDelivery == QUEST_ACCEPTED and player:hasKeyItem(SMALL_BAG) == false and (KenapaOvernight >= 4 and KenapaOvernight <= 7) and (HourOfTheDay < 6 or HourOfTheDay >= 18)) then
player:startEvent(0x008d); -- Gives Key Item at correct times of night
elseif(OvernightDelivery == QUEST_ACCEPTED and player:hasKeyItem(SMALL_BAG) == false and (KenapaOvernight >= 4 and KenapaOvernight <= 7) and (HourOfTheDay >= 6 or HourOfTheDay < 18)) then
player:startEvent(0x0090); -- Only at night
elseif(player:hasKeyItem(SMALL_BAG) == true) then
player:startEvent(0x008e); -- Reminder Dialogue
elseif(OvernightDelivery == QUEST_COMPLETED) then
player:startEvent(0x008f); -- Post quest
else
player:startEvent(0x008c); -- Standard
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 == 0x008d) then
player:addKeyItem(SMALL_BAG);
player:setVar("Kenapa_Overnight_Day_var",VanadielDayOfTheYear());
player:setVar("Kenapa_Overnight_Hour_var",VanadielHour());
player:messageSpecial(KEYITEM_OBTAINED,SMALL_BAG);
end
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Mhaura/npcs/Graine.lua | 13 | 1626 | -----------------------------------
-- Area: Mhaura
-- NPC: Graine
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mhaura/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,GRAINE_SHOP_DIALOG);
stock = {0x3098,457, --Leather Bandana
0x30a0,174, --Bronze Cap
0x30a1,1700, --Brass Cap
0x3118,698, --Leather Vest
0x3120,235, --Bronze Harness
0x3121,2286, --Brass Harness
0x3198,374, --Leather Gloves
0x31a0,128, --Bronze Mittens
0x31a1,1255, --Brass Mittens
0x3218,557, --Leather Trousesrs
0x3220,191, --Bronze Subligar
0x3221,1840, --Brass Subligar
0x3298,349, --Leather Highboots
0x32a0,117, --Bronze Leggings
0x32a1,1140} --Brass Leggings
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Northern_San_dOria/npcs/Chaupire.lua | 17 | 1259 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Chaupire
-- Guild Merchant NPC: Woodworking Guild
-- @pos -174.476 3.999 281.854 231
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:sendGuild(5132,6,21,0)) then
player:showText(npc,CHAUPIRE_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Lower_Jeuno/npcs/Shashan-Mishan.lua | 59 | 1043 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Shashan-Mishan
-- Type: Weather Reporter
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x8271C,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 |
UnfortunateFruit/darkstar | scripts/zones/Bhaflau_Thickets/mobs/Marid.lua | 25 | 1326 | -----------------------------------
-- Area: Bhaflau Thickets
-- MOB: Marid
-- Note: Place holder Mahishasura
-----------------------------------
require("scripts/zones/Bhaflau_Thickets/MobIDs");
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
-- Get Marid ID and check if it is a PH of Mahishasura
mob = mob:getID();
-- Check if Marid is within the Mahishasura_PH table
if (Mahishasura_PH[mob] ~= nil) then
-- printf("%u is a PH",mob);
-- Get Mahishasura's previous ToD
Mahishasura_ToD = GetServerVariable("[POP]Mahishasura");
-- Check if Mahishasura window is open, and there is not an Mahishasura popped already(ACTION_NONE = 0)
if (Mahishasura_ToD <= os.time(t) and GetMobAction(Mahishasura) == 0) then
-- printf("Mahishasura window open");
-- Give Marid 5 percent chance to pop Mahishasura
if (math.random(1,20) == 5) then
-- printf("Mahishasura will pop");
UpdateNMSpawnPoint(Mahishasura);
GetMobByID(Mahishasura):setRespawnTime(GetMobRespawnTime(mob));
SetServerVariable("[PH]Mahishasura", mob);
DeterMob(mob, true);
end
end
end
end;
| gpl-3.0 |
hnakamur/luvit-hsm | tests/flat1.lua | 1 | 1397 | local exports = {}
local string = require('string')
local hsm = require('../hsm')
local StateMachine = hsm.StateMachine
exports['flat1'] = function (test)
local Keyboard = StateMachine:extend()
function Keyboard:initialize()
self:defineStates{
Default = {},
CapsLocked = {}
}
self.state = self.states.Default
end
function Keyboard:_reactDefault(keyName)
if keyName == 'CAPS_LOCK' then
return self.states.CapsLocked
else
self:_handleLowerCaseScanCode(keyName)
return self.states.Default
end
end
function Keyboard:_reactCapsLocked(keyName)
if keyName == 'CAPS_LOCK' then
return self.states.Default
else
self:_handleUpperCaseScanCode(keyName)
return self.states.CapsLocked
end
end
function Keyboard:_handleLowerCaseScanCode(keyName)
self.output = string.lower(keyName)
end
function Keyboard:_handleUpperCaseScanCode(keyName)
self.output = string.upper(keyName)
end
local keyboard = Keyboard:new()
keyboard:react('a')
test.equal(keyboard.output, 'a')
keyboard:react('b')
test.equal(keyboard.output, 'b')
keyboard:react('CAPS_LOCK')
keyboard:react('c')
test.equal(keyboard.output, 'C')
keyboard:react('d')
test.equal(keyboard.output, 'D')
keyboard:react('CAPS_LOCK')
keyboard:react('e')
test.equal(keyboard.output, 'e')
test.done()
end
return exports
| mit |
UnfortunateFruit/darkstar | scripts/globals/items/acorn_cookie.lua | 35 | 1338 | -----------------------------------------
-- ID: 4510
-- Item: Acorn Cookie
-- Food Effect: 3Min, All Races
-----------------------------------------
-- Magic Regen While Healing 3
-- Aquan Killer 5
-- Sleep Resist 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,180,4510);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MPHEAL, 3);
target:addMod(MOD_AQUAN_KILLER, 5);
target:addMod(MOD_SLEEPRES, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MPHEAL, 3);
target:delMod(MOD_AQUAN_KILLER, 5);
target:delMod(MOD_SLEEPRES, 5);
end;
| gpl-3.0 |
reonZ/project-arena | game/dota_addons/project_arenas/scripts/vscripts/abilities/royal_guard/royal_guard_retaliation.lua | 1 | 6464 | local c_mana_switch = 'mana_switch'
local c_mana_per_sec = 'mana_per_sec'
local c_incoming_damage = 'incoming_damage'
local c_outgoing_damage = 'outgoing_damage'
local c_aggro_bonus = 'aggro_bonus'
local c_passive_tick = 0.1
local c_is_tanking_sound = 'DOTA_Item.MedallionOfCourage.Activate'
local c_declares = {
MODIFIER_CUSTOM_INCOMING_PHYSICAL_CONSTANT,
MODIFIER_CUSTOM_INCOMING_MAGICAL_CONSTANT,
MODIFIER_CUSTOM_OUTGOING_PHYSICAL_CONSTANT,
MODIFIER_CUSTOM_AGGRO_MULT
}
local c_modifier_on = 'modifier_retaliation'
local c_modifier_off = 'modifier_retaliation_off'
local c_modifier_passive = 'modifier_retaliation_passive'
local c_modifier_mana_drain = 'modifier_retaliation_mana_drain'
local c_modifier_in_combat = 'modifier_hero_in_combat'
local c_modifier_is_tanking = 'modifier_hero_is_tanking'
LinkLuaModifier( c_modifier_on , 'abilities/royal_guard/royal_guard_retaliation', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( c_modifier_off , 'abilities/royal_guard/royal_guard_retaliation', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( c_modifier_passive , 'abilities/royal_guard/royal_guard_retaliation', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( c_modifier_mana_drain , 'abilities/royal_guard/royal_guard_retaliation', LUA_MODIFIER_MOTION_NONE )
---------------------------------------------------------------------------------------------------
royal_guard_retaliation = class( {} )
function royal_guard_retaliation:GetIntrinsicModifierName()
return c_modifier_passive
end
function royal_guard_retaliation:OnSpellStart()
local hCaster = self:GetCaster()
local fMana = hCaster:GetMana()
local fManaSwitch = self:GetSpecialValueFor( c_mana_switch )
local bIsActive = hCaster:HasModifier( c_modifier_on )
local sActive = bIsActive and c_modifier_off or c_modifier_on
local sInactive = bIsActive and c_modifier_on or c_modifier_off
hCaster:AddNewModifier( hCaster, self, sActive, nil )
hCaster:RemoveModifierByName( sInactive )
if fMana > fManaSwitch then
hCaster:SetMana( fManaSwitch )
end
EmitSoundOn( c_is_tanking_sound, hCaster )
end
function royal_guard_retaliation:ActiveGlobalCooldown()
return false
end
function royal_guard_retaliation:SufferGlobalCooldown()
return false
end
---------------------------------------------------------------------------------------------------
modifier_retaliation = class( {} )
function modifier_retaliation:OnCreated( args )
local hAbility = self:GetAbility()
local hParent = self:GetParent()
self.incoming_damage = hAbility:GetSpecialValueFor( c_incoming_damage )
self.outgoing_damage = hAbility:GetSpecialValueFor( c_outgoing_damage )
self.aggro_bonus = hAbility:GetSpecialValueFor( c_aggro_bonus )
if IsServer() then
hParent:AddNewModifier( hParent, hAbility, c_modifier_is_tanking, nil)
DeclareCustomModifier( hParent, self, c_declares )
ListenToGameEvent( 'damage_dealt', Dynamic_Wrap( modifier_retaliation, 'OnDamageDealt' ), self )
end
end
function modifier_retaliation:OnDestroy( args )
if IsServer() then
local hParent = self:GetParent()
hParent:RemoveModifierByName( c_modifier_is_tanking )
RemoveCustomModifier( hParent, self, c_declares )
StopListeningToAllGameEvents( self )
end
end
function modifier_retaliation:OnDamageDealt( args )
if IsServer() then
local hParent = self:GetParent()
local iParent = hParent:entindex()
if args.target == iParent and args.damage then
local fManaFactor = args.damage * 0.2
hParent:GiveMana( fManaFactor )
end
end
end
function modifier_retaliation:GetOutgoingPhysical_Constant()
return self.outgoing_damage
end
function modifier_retaliation:GetIncomingPhysical_Constant()
return self.incoming_damage
end
function modifier_retaliation:GetIncomingMagical_Constant()
return self.incoming_damage
end
function modifier_retaliation:GetAggro_Mult()
return self.aggro_bonus
end
---------------------------------------------------------------------------------------------------
modifier_retaliation_off = class( {} )
function modifier_retaliation_off:IsHidden()
return true
end
function modifier_retaliation_off:OnCreated( args )
if IsServer() then
ListenToGameEvent( 'damage_dealt', Dynamic_Wrap( modifier_retaliation_off, 'OnDamageDealt' ), self )
end
end
function modifier_retaliation_off:OnDestroy( args )
if IsServer() then
StopListeningToAllGameEvents( self )
end
end
function modifier_retaliation_off:OnDamageDealt( args )
if IsServer() then
local hParent = self:GetParent()
local iParent = hParent:entindex()
if args.caster == iParent and args.damage then
local fManaFactor = args.damage * 0.1
hParent:GiveMana( fManaFactor )
end
end
end
---------------------------------------------------------------------------------------------------
modifier_retaliation_passive = class ( {} )
function modifier_retaliation_passive:IsHidden()
return true
end
function modifier_retaliation_passive:OnCreated( args )
if IsServer() then
local hParent = self:GetParent()
hParent:AddNewModifier( hParent, self, c_modifier_off, nil)
self:StartIntervalThink( c_passive_tick )
self:OnIntervalThink()
end
end
function modifier_retaliation_passive:OnIntervalThink()
if IsServer() then
local hParent = self:GetParent()
local hAbility = self:GetAbility()
local bIsInCombat = hParent:HasModifier( c_modifier_in_combat )
local bIsDraining = hParent:HasModifier( c_modifier_mana_drain )
if not bIsInCombat and not bIsDraining then
hParent:AddNewModifier( hParent, hAbility, c_modifier_mana_drain, nil)
elseif bIsInCombat and bIsDraining then
hParent:RemoveModifierByName( c_modifier_mana_drain )
end
end
end
---------------------------------------------------------------------------------------------------
modifier_retaliation_mana_drain = class( {} )
function modifier_retaliation_mana_drain:DeclareFunctions()
return {
MODIFIER_PROPERTY_MANA_REGEN_CONSTANT,
}
end
function modifier_retaliation_mana_drain:IsHidden()
return true
end
function modifier_retaliation_mana_drain:OnCreated( args )
local hAbility = self:GetAbility()
self.mana_per_sec = hAbility:GetSpecialValueFor( c_mana_per_sec )
end
function modifier_retaliation_mana_drain:GetModifierConstantManaRegen()
return self.mana_per_sec
end
---------------------------------------------------------------------------------------------------
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/zones/Stellar_Fulcrum/npcs/_4z0.lua | 12 | 1593 | -----------------------------------
-- Area: Stellar Fulcrum
-- Door: Qe'Lov Gate
-- @pos -520 -4 17 179
-------------------------------------
package.loaded["scripts/zones/Stellar_Fulcrum/TextIDs"] = nil;
package.loaded["scripts/globals/bcnm"] = nil;
-------------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/missions");
require("scripts/zones/Stellar_Fulcrum/TextIDs");
-- events:
-- 7D00 : BC menu
-- Param 4 is a bitmask for the choice of battlefields in the menu:
-- 1/0: Zilart Mission 8
-- 2/1:
-- 3/2:
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrade(player,npc,trade)
if(TradeBCNM(player,player:getZoneID(),trade,npc))then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(EventTriggerBCNM(player,npc))then
return 1;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdate CSID: %u",csid);
--printf("onUpdate RESULT: %u",option);
if(EventUpdateBCNM(player,csid,option))then
return;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if(EventFinishBCNM(player,csid,option))then
return;
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Castle_Oztroja/npcs/_47l.lua | 13 | 1612 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _47l (Torch Stand)
-- Notes: Opens door _471 near password #3
-- @pos -45.228 -17.832 22.392 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Castle_Oztroja/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local DoorID = npc:getID() - 3;
local DoorA = GetNPCByID(DoorID):getAnimation();
local TorchStandA = npc:getAnimation();
local Torch1 = npc:getID();
local Torch2 = npc:getID() + 1;
if (DoorA == 9 and TorchStandA == 9) then
player:startEvent(0x000a);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
local Torch1 = GetNPCByID(17396173):getID();
local Torch2 = GetNPCByID(Torch1):getID() + 1;
local DoorID = GetNPCByID(Torch1):getID() - 3;
if (option == 1) then
GetNPCByID(Torch1):openDoor(10); -- Torch Lighting
GetNPCByID(Torch2):openDoor(10); -- Torch Lighting
GetNPCByID(DoorID):openDoor(6);
end
end;
--printf("CSID: %u",csid);
--printf("RESULT: %u",option); | gpl-3.0 |
nesstea/darkstar | scripts/globals/items/plate_of_witch_risotto.lua | 18 | 1528 | -----------------------------------------
-- ID: 4330
-- Item: witch_risotto
-- Food Effect: 4hours, All Races
-----------------------------------------
-- Magic Points 35
-- Strength -1
-- Vitality 3
-- Mind 3
-- MP Recovered While Healing 2
-- Enmity -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,14400,4330);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 35);
target:addMod(MOD_STR, -1);
target:addMod(MOD_VIT, 3);
target:addMod(MOD_MND, 3);
target:addMod(MOD_MPHEAL, 2);
target:addMod(MOD_ENMITY, -1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 35);
target:delMod(MOD_STR, -1);
target:delMod(MOD_VIT, 3);
target:delMod(MOD_MND, 3);
target:delMod(MOD_MPHEAL, 2);
target:delMod(MOD_ENMITY, -1);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Walk_of_Echoes/Zone.lua | 17 | 1065 | -----------------------------------
--
-- Zone: Walk_of_Echoes
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Walk_of_Echoes/TextIDs"] = nil;
require("scripts/zones/Walk_of_Echoes/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Northern_San_dOria/npcs/Gulmama.lua | 12 | 5604 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Gulmama
-- Starts and Finishes Quest: Trial by Ice
-- Involved in Quest: Class Reunion
-- @pos -186 0 107 231
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local TrialByIce = player:getQuestStatus(SANDORIA,TRIAL_BY_ICE);
local WhisperOfFrost = player:hasKeyItem(WHISPER_OF_FROST);
local realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day
local ClassReunion = player:getQuestStatus(WINDURST,CLASS_REUNION);
local ClassReunionProgress = player:getVar("ClassReunionProgress");
------------------------------------------------------------
-- Class Reunion
if (ClassReunion == 1 and ClassReunionProgress == 4) then
player:startEvent(0x02c9,0,1171,0,0,0,0,0,0); -- he gives you an ice pendulum and wants you to go to Cloister of Frost
elseif (ClassReunion == 1 and ClassReunionProgress == 5 and player:hasItem(1171) == false) then
player:startEvent(0x02c8,0,1171,0,0,0,0,0,0); -- lost the ice pendulum need another one
------------------------------------------------------------
elseif ((TrialByIce == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 6) or (TrialByIce == QUEST_COMPLETED and realday ~= player:getVar("TrialByIce_date"))) then
player:startEvent(0x02c2,0,TUNING_FORK_OF_ICE); -- Start and restart quest "Trial by ice"
elseif (TrialByIce == QUEST_ACCEPTED and player:hasKeyItem(TUNING_FORK_OF_ICE) == false and WhisperOfFrost == false) then
player:startEvent(0x02ce,0,TUNING_FORK_OF_ICE); -- Defeat against Shiva : Need new Fork
elseif (TrialByIce == QUEST_ACCEPTED and WhisperOfFrost == false) then
player:startEvent(0x02c3,0,TUNING_FORK_OF_ICE,4);
elseif (TrialByIce == QUEST_ACCEPTED and WhisperOfFrost) then
local numitem = 0;
if (player:hasItem(17492)) then numitem = numitem + 1; end -- Shiva's Claws
if (player:hasItem(13242)) then numitem = numitem + 2; end -- Ice Belt
if (player:hasItem(13561)) then numitem = numitem + 4; end -- Ice Ring
if (player:hasItem(1207)) then numitem = numitem + 8; end -- Rust 'B' Gone
if (player:hasSpell(302)) then numitem = numitem + 32; end -- Ability to summon Shiva
player:startEvent(0x02c5,0,TUNING_FORK_OF_ICE,4,0,numitem);
else
player:startEvent(0x02c6); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x02c2 and option == 1) then
if (player:getQuestStatus(SANDORIA,TRIAL_BY_ICE) == QUEST_COMPLETED) then
player:delQuest(SANDORIA,TRIAL_BY_ICE);
end
player:addQuest(SANDORIA,TRIAL_BY_ICE);
player:setVar("TrialByIce_date", 0);
player:addKeyItem(TUNING_FORK_OF_ICE);
player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_ICE);
elseif (csid == 0x02ce) then
player:addKeyItem(TUNING_FORK_OF_ICE);
player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_ICE);
elseif (csid == 0x02c5) then
local item = 0;
if (option == 1) then item = 17492; -- Shiva's Claws
elseif (option == 2) then item = 13242; -- Ice Belt
elseif (option == 3) then item = 13561; -- Ice Ring
elseif (option == 4) then item = 1207; -- Rust 'B' Gone
end
if (player:getFreeSlotsCount() == 0 and (option ~= 5 or option ~= 6)) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,item);
else
if (option == 5) then
player:addGil(GIL_RATE*10000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*10000); -- Gil
elseif (option == 6) then
player:addSpell(302); -- Avatar
player:messageSpecial(SHIVA_UNLOCKED,0,0,4);
else
player:addItem(item);
player:messageSpecial(ITEM_OBTAINED,item); -- Item
end
player:addTitle(HEIR_OF_THE_GREAT_ICE);
player:delKeyItem(WHISPER_OF_FROST); --Whisper of Frost, as a trade for the above rewards
player:setVar("TrialByIce_date", os.date("%j")); -- %M for next minute, %j for next day
player:addFame(SANDORIA,30);
player:completeQuest(SANDORIA,TRIAL_BY_ICE);
end
elseif (csid == 0x02c9 or csid == 0x02c8) then
if (player:getFreeSlotsCount() ~= 0) then
player:addItem(1171);
player:messageSpecial(ITEM_OBTAINED,1171);
player:setVar("ClassReunionProgress",5);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1171);
end;
end;
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Bastok_Mines/npcs/Rodellieux.lua | 36 | 1462 | -----------------------------------
-- Area: Bastok_Mines
-- NPC: Rodellieux
-- Only sells when Bastok controlls Fauregandi Region
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(FAUREGANDI);
if (RegionOwner ~= BASTOK) then
player:showText(npc,RODELLIEUX_CLOSED_DIALOG);
else
player:showText(npc,RODELLIEUX_OPEN_DIALOG);
stock = {
0x11db, 90, --Beaugreens
0x110b, 39, --Faerie Apple
0x02b3, 54 --Maple Log
}
showShop(player,BASTOK,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 |
UnfortunateFruit/darkstar | scripts/globals/items/uberkuchen.lua | 35 | 1465 | -----------------------------------------
-- ID: 5615
-- Item: uberkuchen
-- Food Effect: 4Hrs, All Races
-----------------------------------------
-- HP 10
-- MP % 3 (cap 13)
-- Intelligence 3
-- MP Recovered 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,14400,5615);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 10);
target:addMod(MOD_FOOD_MPP, 3);
target:addMod(MOD_FOOD_MP_CAP, 13);
target:addMod(MOD_MPHEAL, 1);
target:addMod(MOD_INT, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 10);
target:delMod(MOD_FOOD_MPP, 3);
target:delMod(MOD_FOOD_MP_CAP, 13);
target:delMod(MOD_MPHEAL, 1);
target:delMod(MOD_INT, 3);
end;
| gpl-3.0 |
inmation/library | inmation/data-structures.lua | 1 | 1215 | -- inmation.data-structures
-- inmation Script Library Lua Script
--
-- (c) 2017 inmation
--
-- Version history:
--
-- 20170706.1 Initial release.
--
--------------------------------------------------------------------------------
local Queue = {}
Queue.__index = Queue
function Queue.new(existing)
local queue = existing or { first = 0, last = -1, values = {} }
setmetatable(queue, Queue)
return queue
end
function Queue:length()
local first = self.first
local last = self.last
if first > last then return 0 end
return last - first + 1
end
function Queue:peek()
local last = self.last
if self.first > last then return nil end
local value = self.values[last]
return value
end
function Queue:pop()
local last = self.last
if self.first > last then error("queue is empty", 2) end
local value = self.values[last]
self.values[last] = nil -- to allow garbage collection
self.last = last - 1
return value
end
function Queue:push(value)
local first = self.first - 1
self.first = first
self.values[first] = value
end
--------------------------------------------------------------------------------
return {
Queue = Queue
} | mit |
UnfortunateFruit/darkstar | scripts/globals/abilities/pets/thunder_iv.lua | 20 | 1161 | ---------------------------------------------------
-- Aero 2
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/globals/magic");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill)
local spell = getSpell(167);
--calculate raw damage
local dmg = calculateMagicDamage(541,2,pet,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false);
--get resist multiplier (1x if no resist)
local resist = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL,ELE_LIGHTNING);
--get the resisted damage
dmg = dmg*resist;
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = mobAddBonuses(pet,spell,target,dmg, 6);
--add on TP bonuses
local tp = skill:getTP();
if tp < 100 then
tp = 100;
end
dmg = dmg * tp / 100;
--add in final adjustments
dmg = finalMagicAdjustments(pet,target,spell,dmg);
return dmg;
end | gpl-3.0 |
nesstea/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Dynamis_Lord.lua | 2 | 2048 | -----------------------------------
-- Area: Dynamis Xarcabard
-- NM: Dynamis_Lord
--
-- In OLD Dynamis, he is spawned by killing 15 Kindred NMs..
-- ..NOT by killing Ying and Yang.
--
-- In Neo Dynamis, he is spawned by trading
-- a Shrouded Bijou to the ??? in front of Castle Zvahl.
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/titles");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
local YingID = 17330183;
local YangID = 17330184;
if (mob:getBattleTime() % 90 == 0 and mob:getBattleTime() >= 90) then
if (GetMobAction(YingID) == ACTION_NONE and GetMobAction(YangID) == ACTION_NONE) then
GetMobByID(YingID):setSpawn(-414.282,-44,20.427); -- These come from DL's spawn point when he spawns them.
GetMobByID(YangID):setSpawn(-414.282,-44,20.427);
SpawnMob(YingID):updateEnmity(target); -- Respawn the dragons after 90sec
SpawnMob(YangID):updateEnmity(target);
end
end
if (GetMobAction(YingID) == ACTION_ROAMING) then -- ensure that it's always going after someone, can't kite it away!
GetMobByID(YingID):updateEnmity(target);
end
if (GetMobAction(YangID) == ACTION_ROAMING) then
GetMobByID(YangID):updateEnmity(target);
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
local npc = GetNPCByID(17330781); -- ID of the '???' target.
ally:addTitle(LIFTER_OF_SHADOWS);
npc:setPos(mob:getXPos(),mob:getYPos(),mob:getZPos());
npc:setStatus(0); -- Spawn the '???'
DespawnMob(17330183); -- despawn dragons
DespawnMob(17330184);
end; | gpl-3.0 |
nesstea/darkstar | scripts/globals/items/seito.lua | 42 | 1047 | -----------------------------------------
-- ID: 17797
-- Item: Seito
-- Additional Effect: Silence
-- TODO: Enchantment: Ensilence
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10;
if (math.random(0,99) >= chance or applyResistanceAddEffect(player,target,ELE_WIND,0) <= 0.5) then
return 0,0,0;
else
if (not target:hasStatusEffect(EFFECT_SILENCE)) then
target:addStatusEffect(EFFECT_SILENCE, 1, 0, 60);
end
return SUBEFFECT_SILENCE, MSGBASIC_ADD_EFFECT_STATUS, EFFECT_SILENCE;
end
end;
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
end;
| gpl-3.0 |
dpino/snabbswitch | src/lib/protocol/header.lua | 9 | 11831 | -- Use of this source code is governed by the Apache 2.0 license; see COPYING.
-- Protocol header base class
--
-- This is an abstract class (should not be instantiated)
--
-- Derived classes must implement the following class variables
--
-- _name a string that describes the header type in a
-- human readable form
--
-- _ulp a table that holds information about the "upper
-- layer protocols" supported by the header. It
-- contains two keys
-- method the name of the method of the header
-- class whose result identifies the ULP
-- and is used as key for the class_map
-- table
-- class_map a table whose keys must represent
-- valid return values of the instance
-- method given by the 'method' name
-- above. The corresponding value must
-- be the name of the header class that
-- parses this particular ULP
--
-- In the simplest case, a protocol header consists of a single data
-- structure of a fixed size, e.g. an untagged Ethernet II header.
-- Such headers are supported by this framework in a straight forward
-- manner. More complex headers may have representations that differ
-- in size and structure, depending on the use-case, e.g. GRE.
-- Headers of that kind can be supported as long as all variants can
-- be enumerated and represented by a separate fixed-sized data
-- structure. This requirement is necessary because all data
-- structures must be pre-allocated for performance reasons and to
-- support the instance recycling mechanism of the class framework.
-- Each header is described by a ctype object that serves as a
-- template for the header.
--
-- A protocol header can be created in two different manners. In the
-- first case (provided by the new() constructor method), the protocol
-- instance contains the header structure itself, where as in the
-- second case (provided by the new_from_mem() constructor), the
-- protocol instance contains a pointer to an arbitrary location in
-- memory where the actual header resides (usually a packet buffer).
-- The pointer is cast to the appropriate ctype to access the fields
-- of the header.
--
-- To support the second mode of creation for protocols with variable
-- header structures, one of the headers must be designated as the
-- "base header". It must be chosen such that it contains enough
-- information to determine the actual header that is present in
-- memory.
--
-- The constructors in the header base class deal exclusively with the
-- base header, i.e. the instances created by the new() and
-- new_from_mem() methods only provide access to the fields present in
-- the base header. Protocols that implement variable headers must
-- extend the base methods to select the appropriate header variant.
--
-- The header class uses the following data structures to support this
-- mechanism. Each header variant is described by a table with the
-- following elements
--
-- t the ctype that represents the header itself
-- ptr_t a ctype constructed by ffi.typeof("$*", ctype) used for
-- casting of pointers
-- box_t a ctype that represents a "box" to store a ptr_t, i.e.
-- ffi.typeof("$[1]", ptr_t)
--
-- These tables are stored as an array in the class variable _headers,
-- where, by definition, the first element designates the base header.
--
-- This array is initialized by the class method init(), which must be
-- called by every derived class.
--
-- When a new instance of a protocol class is created, it receives its
-- own, private array of headers stored in the instance variable of
-- the same name. The elements from the header tables stored in the
-- class are inherited by the instance by means of setmetatable().
-- For each header, one instance of the header itself and one instance
-- of a box are created from the t and box_t ctypes, respectively.
-- These objects are stored in the keys "data" and "box" and are
-- private to the instance. The following schematic should make the
-- relationship clearer
--
-- class._headers = {
-- [1] = { t = ...,
-- ptr_t = ...,
-- box_t = ...,
-- }, <---------------+
-- [2] = { t = ..., |
-- ptr_t = ..., |
-- box_t = ..., |
-- }, <------------+ |
-- ... | |
-- } | |
-- | |
-- instance._headers = { | |
-- [1] = { data = t(), | |
-- box = box_t()| |
-- }, ----------------+ metatable
-- [2] = { data = t(), |
-- box = box_t()|
-- }, -------------+ metatable
-- ...
-- }
--
-- The constructors of the base class store a reference to the base
-- header (i.e. _headers[1]) in the instance variable _header. In
-- other words, the box and data can be accessed by dereferencing
-- _header.data and _header.box, respectively.
--
-- This initialization is common to both constructors. The difference
-- lies in the contents of the pointer stored in the box. The new()
-- constructor stores a pointer to the data object, i.e.
--
-- _header.box[0] = ffi.cast(_header.ptr_t, _header.data)
--
-- where as the new_from_mem() constructor stores the pointer to the
-- region of memory supplied as argument to the method call, i.e.
--
-- _header.box[0] = ffi.cast(_header.ptr_t, mem)
--
-- In that case, the _header.data object is not used at all.
--
-- When a derived class overrides these constructors, it should first
-- call the construcor of the super class, which will initialize the
-- base header as described above. An extension of the new() method
-- will replace the reference to the base header stored in _header by
-- a reference to the header variant selected by the configuration
-- passed as arguments to the method, i.e. it will eventually do
--
-- _header = _headers[foo]
--
-- where <foo> is the index of the selected header.
--
-- An extension of the new_from_mem() constructor uses the base header
-- to determine the actual header variant to use and override the base
-- header with it.
--
-- Refer to the lib.protocol.ethernet and lib.protocol.gre classes for
-- examples.
--
-- For convenience, the class variable class._header exists as well
-- and contains a reference to the base header class._headers[1].
-- This promotes the instance methods sizeof() and ctype() to class
-- methods, which will provide the size and ctype of a protocol's base
-- header from the class itself. For example, the size of an ethernet
-- header can be obtained by
--
-- local ethernet = require("lib.protocol.ethernet")
-- local ether_size = ethernet:sizeof()
--
-- without creating an instance first.
module(..., package.seeall)
local ffi = require("ffi")
local header = subClass(nil)
-- Class methods
-- Initialize a subclass with a set of headers, which must contain at
-- least one element (the base header).
function header:init (headers)
assert(self and headers and #headers > 0)
self._singleton_p = #headers == 1
local _headers = {}
for i = 1, #headers do
local header = {}
local ctype = headers[i]
header.t = ctype
header.ptr_t = ffi.typeof("$*", ctype)
header.box_t = ffi.typeof("$*[1]", ctype)
header.meta = { __index = header }
_headers[i] = header
end
self._headers = _headers
self._header = _headers[1]
end
-- Initialize an instance of the class. If the instance is new (has
-- not been recycled), an instance of each header struct and a box
-- that holds a pointer to it are allocated. A reference to the base
-- header is installed in the _header instance variable.
local function _new (self)
local o = header:superClass().new(self)
if not o._recycled then
-- Allocate boxes and headers for all variants of the
-- classe's header structures
o._headers = {}
for i = 1, #self._headers do
-- This code is only executed when a new instance is created
-- via the class construcor, i.e. self is the class itself
-- (as opposed to the case when an instance is recycled by
-- calling the constructor as an instance method, in which
-- case self would be the instance instead of the class).
-- This is why it is safe to use self._headers[i].meta as
-- metatable here. The effect is that the ctypes are
-- inherited from the class while the data and box table are
-- private to the instance.
local _header = setmetatable({}, self._headers[i].meta)
_header.data = _header.t()
_header.box = _header.box_t()
o._headers[i] = _header
end
end
-- Make the base header the active header
o._header = o._headers[1]
return o
end
-- Initialize the base protocol header with 0 and store a pointer to
-- it in the header box.
function header:new ()
local o = _new(self)
local header = o._header
ffi.fill(header.data, ffi.sizeof(header.t))
header.box[0] = ffi.cast(header.ptr_t, header.data)
return o
end
-- This alternative constructor creates a protocol header from a chunk
-- of memory by "overlaying" a header structure. In this mode, the
-- protocol ctype _header.data is unused and _header.box stores the
-- pointer to the memory location supplied by the caller.
function header:new_from_mem (mem, size)
local o = _new(self)
local header = o._header
if ffi.sizeof(header.t) > size then
o:free()
return nil
end
header.box[0] = ffi.cast(header.ptr_t, mem)
return o
end
-- Instance methods
-- Return a reference to the header
function header:header ()
return self._header.box[0][0]
end
-- Return a pointer to the header
function header:header_ptr ()
return self._header.box[0]
end
-- Return the ctype of header
function header:ctype ()
return self._header.t
end
-- Return the size of the header
function header:sizeof ()
return ffi.sizeof(self._header.t)
end
-- Return true if <other> is of the same type and contains identical
-- data, false otherwise.
function header:eq (other)
local ctype = self:ctype()
local size = self:sizeof()
local other_ctype = other:ctype()
return (ctype == other_ctype and
ffi.string(self:header_ptr(), size) ==
ffi.string(other:header_ptr(), size))
end
-- Copy the header to some location in memory (usually a packet
-- buffer). The caller must make sure that there is enough space at
-- the destination. If relocate is a true value, the copy is promoted
-- to be the active storage of the header.
function header:copy (dst, relocate)
ffi.copy(dst, self:header_ptr(), self:sizeof())
if relocate then
self._header.box[0] = ffi.cast(self._header.ptr_t, dst)
end
end
-- Create a new protocol instance that is a copy of this instance.
-- This is horribly inefficient and should not be used in the fast
-- path.
function header:clone ()
local header = self:ctype()()
local sizeof = ffi.sizeof(header)
ffi.copy(header, self:header_ptr(), sizeof)
return self:class():new_from_mem(header, sizeof)
end
-- Return the class that can handle the upper layer protocol or nil if
-- the protocol is not supported or the protocol has no upper-layer.
function header:upper_layer ()
local method = self._ulp.method
if not method then return nil end
local class = self._ulp.class_map[self[method](self)]
if class then
if package.loaded[class] then
return package.loaded[class]
else
return require(class)
end
else
return nil
end
end
return header
| apache-2.0 |
rhaen/octogreen | src/ds18b20.lua | 18 | 3492 | --------------------------------------------------------------------------------
-- DS18B20 one wire module for NODEMCU
-- NODEMCU TEAM
-- LICENCE: http://opensource.org/licenses/MIT
-- Vowstar <vowstar@nodemcu.com>
-- 2015/02/14 sza2 <sza2trash@gmail.com> Fix for negative values
--------------------------------------------------------------------------------
-- Set module name as parameter of require
local modname = ...
local M = {}
_G[modname] = M
--------------------------------------------------------------------------------
-- Local used variables
--------------------------------------------------------------------------------
-- DS18B20 dq pin
local pin = nil
-- DS18B20 default pin
local defaultPin = 9
--------------------------------------------------------------------------------
-- Local used modules
--------------------------------------------------------------------------------
-- Table module
local table = table
-- String module
local string = string
-- One wire module
local ow = ow
-- Timer module
local tmr = tmr
-- Limited to local environment
setfenv(1,M)
--------------------------------------------------------------------------------
-- Implementation
--------------------------------------------------------------------------------
C = 'C'
F = 'F'
K = 'K'
function setup(dq)
pin = dq
if(pin == nil) then
pin = defaultPin
end
ow.setup(pin)
end
function addrs()
setup(pin)
tbl = {}
ow.reset_search(pin)
repeat
addr = ow.search(pin)
if(addr ~= nil) then
table.insert(tbl, addr)
end
tmr.wdclr()
until (addr == nil)
ow.reset_search(pin)
return tbl
end
function readNumber(addr, unit)
result = nil
setup(pin)
flag = false
if(addr == nil) then
ow.reset_search(pin)
count = 0
repeat
count = count + 1
addr = ow.search(pin)
tmr.wdclr()
until((addr ~= nil) or (count > 100))
ow.reset_search(pin)
end
if(addr == nil) then
return result
end
crc = ow.crc8(string.sub(addr,1,7))
if (crc == addr:byte(8)) then
if ((addr:byte(1) == 0x10) or (addr:byte(1) == 0x28)) then
-- print("Device is a DS18S20 family device.")
ow.reset(pin)
ow.select(pin, addr)
ow.write(pin, 0x44, 1)
-- tmr.delay(1000000)
present = ow.reset(pin)
ow.select(pin, addr)
ow.write(pin,0xBE,1)
-- print("P="..present)
data = nil
data = string.char(ow.read(pin))
for i = 1, 8 do
data = data .. string.char(ow.read(pin))
end
-- print(data:byte(1,9))
crc = ow.crc8(string.sub(data,1,8))
-- print("CRC="..crc)
if (crc == data:byte(9)) then
t = (data:byte(1) + data:byte(2) * 256)
if (t > 32767) then
t = t - 65536
end
if (addr:byte(1) == 0x28) then
t = t * 625 -- DS18B20, 4 fractional bits
else
t = t * 5000 -- DS18S20, 1 fractional bit
end
if(unit == nil or unit == 'C') then
-- do nothing
elseif(unit == 'F') then
t = t * 1.8 + 320000
elseif(unit == 'K') then
t = t + 2731500
else
return nil
end
t = t / 10000
return t
end
tmr.wdclr()
else
-- print("Device family is not recognized.")
end
else
-- print("CRC is not valid!")
end
return result
end
function read(addr, unit)
t = readNumber(addr, unit)
if (t == nil) then
return nil
else
return t
end
end
-- Return module table
return M
| mit |
plajjan/snabbswitch | lib/luajit/src/host/genlibbc.lua | 51 | 4965 | ----------------------------------------------------------------------------
-- Lua script to dump the bytecode of the library functions written in Lua.
-- The resulting 'buildvm_libbc.h' is used for the build process of LuaJIT.
----------------------------------------------------------------------------
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
local ffi = require("ffi")
local bit = require("bit")
local vmdef = require("jit.vmdef")
local bcnames = vmdef.bcnames
local format = string.format
local isbe = (string.byte(string.dump(function() end), 5) % 2 == 1)
local function usage(arg)
io.stderr:write("Usage: ", arg and arg[0] or "genlibbc",
" [-o buildvm_libbc.h] lib_*.c\n")
os.exit(1)
end
local function parse_arg(arg)
local outfile = "-"
if not (arg and arg[1]) then
usage(arg)
end
if arg[1] == "-o" then
outfile = arg[2]
if not outfile then usage(arg) end
table.remove(arg, 1)
table.remove(arg, 1)
end
return outfile
end
local function read_files(names)
local src = ""
for _,name in ipairs(names) do
local fp = assert(io.open(name))
src = src .. fp:read("*a")
fp:close()
end
return src
end
local function transform_lua(code)
local fixup = {}
local n = -30000
code = string.gsub(code, "CHECK_(%w*)%((.-)%)", function(tp, var)
n = n + 1
fixup[n] = { "CHECK", tp }
return format("%s=%d", var, n)
end)
code = string.gsub(code, "PAIRS%((.-)%)", function(var)
fixup.PAIRS = true
return format("nil, %s, 0", var)
end)
return "return "..code, fixup
end
local function read_uleb128(p)
local v = p[0]; p = p + 1
if v >= 128 then
local sh = 7; v = v - 128
repeat
local r = p[0]
v = v + bit.lshift(bit.band(r, 127), sh)
sh = sh + 7
p = p + 1
until r < 128
end
return p, v
end
-- ORDER LJ_T
local name2itype = {
str = 5, func = 9, tab = 12, int = 14, num = 15
}
local BC = {}
for i=0,#bcnames/6-1 do
BC[string.gsub(string.sub(bcnames, i*6+1, i*6+6), " ", "")] = i
end
local xop, xra = isbe and 3 or 0, isbe and 2 or 1
local xrc, xrb = isbe and 1 or 2, isbe and 0 or 3
local function fixup_dump(dump, fixup)
local buf = ffi.new("uint8_t[?]", #dump+1, dump)
local p = buf+5
local n, sizebc
p, n = read_uleb128(p)
local start = p
p = p + 4
p = read_uleb128(p)
p = read_uleb128(p)
p, sizebc = read_uleb128(p)
local rawtab = {}
for i=0,sizebc-1 do
local op = p[xop]
if op == BC.KSHORT then
local rd = p[xrc] + 256*p[xrb]
rd = bit.arshift(bit.lshift(rd, 16), 16)
local f = fixup[rd]
if f then
if f[1] == "CHECK" then
local tp = f[2]
if tp == "tab" then rawtab[p[xra]] = true end
p[xop] = tp == "num" and BC.ISNUM or BC.ISTYPE
p[xrb] = 0
p[xrc] = name2itype[tp]
else
error("unhandled fixup type: "..f[1])
end
end
elseif op == BC.TGETV then
if rawtab[p[xrb]] then
p[xop] = BC.TGETR
end
elseif op == BC.TSETV then
if rawtab[p[xrb]] then
p[xop] = BC.TSETR
end
elseif op == BC.ITERC then
if fixup.PAIRS then
p[xop] = BC.ITERN
end
end
p = p + 4
end
return ffi.string(start, n)
end
local function find_defs(src)
local defs = {}
for name, code in string.gmatch(src, "LJLIB_LUA%(([^)]*)%)%s*/%*(.-)%*/") do
local env = {}
local tcode, fixup = transform_lua(code)
local func = assert(load(tcode, "", nil, env))()
defs[name] = fixup_dump(string.dump(func, true), fixup)
defs[#defs+1] = name
end
return defs
end
local function gen_header(defs)
local t = {}
local function w(x) t[#t+1] = x end
w("/* This is a generated file. DO NOT EDIT! */\n\n")
w("static const int libbc_endian = ") w(isbe and 1 or 0) w(";\n\n")
local s = ""
for _,name in ipairs(defs) do
s = s .. defs[name]
end
w("static const uint8_t libbc_code[] = {\n")
local n = 0
for i=1,#s do
local x = string.byte(s, i)
w(x); w(",")
n = n + (x < 10 and 2 or (x < 100 and 3 or 4))
if n >= 75 then n = 0; w("\n") end
end
w("0\n};\n\n")
w("static const struct { const char *name; int ofs; } libbc_map[] = {\n")
local m = 0
for _,name in ipairs(defs) do
w('{"'); w(name); w('",'); w(m) w('},\n')
m = m + #defs[name]
end
w("{NULL,"); w(m); w("}\n};\n\n")
return table.concat(t)
end
local function write_file(name, data)
if name == "-" then
assert(io.write(data))
assert(io.flush())
else
local fp = io.open(name)
if fp then
local old = fp:read("*a")
fp:close()
if data == old then return end
end
fp = assert(io.open(name, "w"))
assert(fp:write(data))
assert(fp:close())
end
end
local outfile = parse_arg(arg)
local src = read_files(arg)
local defs = find_defs(src)
local hdr = gen_header(defs)
write_file(outfile, hdr)
| apache-2.0 |
nesstea/darkstar | scripts/zones/Windurst_Waters/npcs/Puroiko-Maiko_WW.lua | 12 | 5545 | -----------------------------------
-- Area: Windurst Water
-- NPC: Puroiko-Maiko, W.W.
-- X Grant Signet
-- X Recharge Emperor Band, Empress Band, or Chariot Band
-- X Accepts traded Crystals to fill up the Rank bar to open new Missions.
-- X Sells items in exchange for Conquest Points
-- X Start Supply Run Missions and offers a list of already-delivered supplies.
-- Start an Expeditionary Force by giving an E.F. region insignia to you.
-------------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/conquest");
require("scripts/globals/common");
require("scripts/zones/Windurst_Waters/TextIDs");
local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, JEUNO
local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border
local size = table.getn(WindInv);
local inventory = WindInv;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then
player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies."
local region = player:getVar("supplyQuest_region");
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region));
player:setVar("supplyQuest_started",0);
player:setVar("supplyQuest_region",0);
player:setVar("supplyQuest_fresh",0);
else
Menu1 = getArg1(guardnation,player);
Menu2 = getExForceAvailable(guardnation,player);
Menu3 = conquestRanking();
Menu4 = getSupplyAvailable(guardnation,player);
Menu5 = player:getNationTeleport(guardnation);
Menu6 = getArg6(player);
Menu7 = player:getCP();
Menu8 = getRewardExForce(guardnation,player);
player:startEvent(0x7ff7,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdateCSID: %u",csid);
-- printf("onUpdateOPTION: %u",option);
if (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
CPVerify = 1;
if (player:getCP() >= inventory[Item + 1]) then
CPVerify = 0;
end;
player:updateEvent(2,CPVerify,inventory[Item + 2]);
break;
end;
end;
end;
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinishCSID: %u",csid);
-- printf("onFinishOPTION: %u",option);
if (option == 1) then
duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
if (player:getFreeSlotsCount() >= 1) then
-- Logic to impose limits on exp bands
if (option >= 32933 and option <= 32935) then
if (checkConquestRing(player) > 0) then
player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]);
break;
else
player:setVar("CONQUEST_RING_TIMER",getConquestTally());
end
end
if (player:getNation() == guardnation) then
itemCP = inventory[Item + 1];
else
if (inventory[Item + 1] <= 8000) then
itemCP = inventory[Item + 1] * 2;
else
itemCP = inventory[Item + 1] + 8000;
end;
end;
if (player:hasItem(inventory[Item + 2]) == false) then
player:delCP(itemCP);
player:addItem(inventory[Item + 2],1);
player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end;
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end;
break;
end;
end;
elseif (option >= 65541 and option <= 65565) then -- player chose supply quest.
local region = option - 65541;
player:addKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region));
player:setVar("supplyQuest_started",vanaDay());
player:setVar("supplyQuest_region",region);
player:setVar("supplyQuest_fresh",getConquestTally());
end;
end; | gpl-3.0 |
FailcoderAddons/supervillain-ui | SVUI_UnitFrames/elements/essentials.lua | 2 | 28918 | --[[
##########################################################
S V U I By: Failcoder
##########################################################
LOCALIZED LUA FUNCTIONS
##########################################################
]]--
local _G = _G;
--LUA
local unpack = _G.unpack;
local select = _G.select;
local assert = _G.assert;
local type = _G.type;
local error = _G.error;
local pcall = _G.pcall;
local print = _G.print;
local ipairs = _G.ipairs;
local pairs = _G.pairs;
local next = _G.next;
local rawset = _G.rawset;
local rawget = _G.rawget;
local tostring = _G.tostring;
local tonumber = _G.tonumber;
local getmetatable = _G.getmetatable;
local setmetatable = _G.setmetatable;
--STRING
local string = _G.string;
local upper = string.upper;
local format = string.format;
local find = string.find;
local match = string.match;
local gsub = string.gsub;
--MATH
local math = _G.math;
local random = math.random;
local floor = math.floor;
local ceil = math.ceil;
local min = math.min;
local CreateFrame = _G.CreateFrame;
local InCombatLockdown = _G.InCombatLockdown;
local IsLoggedIn = _G.IsLoggedIn;
local GameTooltip = _G.GameTooltip;
local UnitClass = _G.UnitClass;
local UnitIsPlayer = _G.UnitIsPlayer;
local UnitReaction = _G.UnitReaction;
local UnitIsConnected = _G.UnitIsConnected;
local UnitIsDeadOrGhost = _G.UnitIsDeadOrGhost;
local UnitClassBase = _G.UnitClassBase;
local UnitPowerType = _G.UnitPowerType;
local UnitPlayerControlled = _G.UnitPlayerControlled;
local UnitThreatSituation = _G.UnitThreatSituation;
local UnitAffectingCombat = _G.UnitAffectingCombat;
local GetThreatStatusColor = _G.GetThreatStatusColor;
local UnitAlternatePowerInfo = _G.UnitAlternatePowerInfo;
--[[
##########################################################
GET ADDON DATA
##########################################################
]]--
local SV = _G['SVUI']
local L = SV.L;
local LSM = _G.LibStub("LibSharedMedia-3.0")
local MOD = SV.UnitFrames
if(not MOD) then return end
local oUF_SVUI = MOD.oUF
assert(oUF_SVUI, "SVUI UnitFrames: unable to locate oUF.")
--[[
##########################################################
LOCALS
##########################################################
]]--
local FontMapping = {
["player"] = "SVUI_Font_Unit",
["target"] = "SVUI_Font_Unit",
["targettarget"] = "SVUI_Font_Unit_Small",
["pet"] = "SVUI_Font_Unit",
["pettarget"] = "SVUI_Font_Unit_Small",
["focus"] = "SVUI_Font_Unit",
["focustarget"] = "SVUI_Font_Unit_Small",
["boss"] = "SVUI_Font_Unit",
["arena"] = "SVUI_Font_Unit",
["party"] = "SVUI_Font_Unit_Small",
["raid"] = "SVUI_Font_Unit_Small",
["raidpet"] = "SVUI_Font_Unit_Small",
["tank"] = "SVUI_Font_Unit_Small",
["assist"] = "SVUI_Font_Unit_Small",
};
local ThreatMapping = {
["player"] = true,
["pet"] = true,
["focus"] = true,
["party"] = true,
["raid"] = true,
["raidpet"] = true,
["tank"] = true,
["assist"] = true,
};
local _hook_ActionPanel_OnSizeChanged = function(self)
local width,height = self:GetSize()
local widthScale = min(128, width)
local heightScale = widthScale * 0.25
self.special[1]:SetSize(widthScale, heightScale)
self.special[2]:SetSize(widthScale, heightScale)
--self.special[3]:SetSize(height * 0.5, height)
end
-- local MISSING_MODEL_FILE = [[Spells\Blackmagic_precast_base.m2]];
-- local MISSING_MODEL_FILE = [[Spells\Crow_baked.m2]];
-- local MISSING_MODEL_FILE = [[Spells\monsterlure01.m2]];
-- local MISSING_MODEL_FILE = [[interface\buttons\talktome_gears.m2]];
-- local MISSING_MODEL_FILE = [[creature\Ghostlyskullpet\ghostlyskullpet.m2]];
-- local MISSING_MODEL_FILE = [[creature\ghost\ghost.m2]];
-- local MISSING_MODEL_FILE = [[Spells\Monk_travelingmist_missile.m2]];
local ELITE_TOP = [[Interface\Addons\SVUI_UnitFrames\assets\Border\ELITE-TOP]];
local ELITE_BOTTOM = [[Interface\Addons\SVUI_UnitFrames\assets\Border\ELITE-BOTTOM]];
local ELITE_RIGHT = [[Interface\Addons\SVUI_UnitFrames\assets\Border\ELITE-RIGHT]];
local STUNNED_ANIM = [[Interface\Addons\SVUI_UnitFrames\assets\UNIT-STUNNED]];
local AGGRO_TEXTURE = [[Interface\AddOns\SVUI_UnitFrames\assets\UNIT-AGGRO]];
local token = {[0] = "MANA", [1] = "RAGE", [2] = "FOCUS", [3] = "ENERGY", [6] = "RUNIC_POWER"}
--[[
##########################################################
ACTIONPANEL
##########################################################
]]--
local UpdateThreat = function(self, event, unit)
if(not unit or (self.unit ~= unit) or not IsLoggedIn()) then return end
local threat = self.Threat
local status = UnitThreatSituation(unit)
local r, g, b
if(status and status > 0) then
r, g, b = GetThreatStatusColor(status)
threat:SetBackdropBorderColor(r, g, b)
threat:Show()
else
threat:SetBackdropBorderColor(0, 0, 0, 0.5)
threat:Hide()
end
end
local UpdatePlayerThreat = function(self, event, unit)
if(unit ~= "player" or not IsLoggedIn()) then return end
local threat = self.Threat;
local aggro = self.Aggro;
local useAggro = aggro.isEnabled;
local status = UnitThreatSituation(unit)
local r, g, b
if(status and status > 0) then
r, g, b = GetThreatStatusColor(status)
threat:SetBackdropBorderColor(r, g, b)
if(useAggro and (status > 1) and (not aggro:IsShown())) then
self.Combat:Hide()
aggro:Show()
end
threat:Show()
else
threat:SetBackdropBorderColor(0, 0, 0, 0.5)
if(useAggro and aggro:IsShown()) then
aggro:Hide()
if(UnitAffectingCombat('player')) then
self.Combat:Show()
end
end
threat:Hide()
end
end
local function CreateThreat(frame, unit)
if(not frame.ActionPanel) then return; end
local threat = CreateFrame("Frame", nil, frame.ActionPanel)
threat:SetPoint("TOPLEFT", frame.ActionPanel, "TOPLEFT", -3, 3)
threat:SetPoint("BOTTOMRIGHT", frame.ActionPanel, "BOTTOMRIGHT", 3, -3)
threat:SetBackdrop({
edgeFile = SV.media.border.shadow,
edgeSize = 3,
insets =
{
left = 2,
right = 2,
top = 2,
bottom = 2,
},
});
threat:SetBackdropBorderColor(0,0,0,0.5)
if(unit == "player") then
local aggro = CreateFrame("Frame", "SVUI_PlayerThreatAlert", frame)
aggro:SetFrameStrata("HIGH")
aggro:SetFrameLevel(30)
aggro:SetSize(40,40)
aggro:SetPoint("BOTTOMLEFT", frame, "TOPRIGHT", -6, -6)
aggro.texture = aggro:CreateTexture(nil, "OVERLAY")
aggro.texture:SetAllPoints(aggro)
aggro.texture:SetTexture(AGGRO_TEXTURE)
SV.Animate:Pulse(aggro)
aggro:SetScript("OnShow", function(this)
this.anim:Play()
end);
aggro:Hide();
aggro.isEnabled = true;
frame.Aggro = aggro
threat.Override = UpdatePlayerThreat
else
threat.Override = UpdateThreat
end
return threat
end
local function CreateNameText(frame, unitName)
local db = SV.db.UnitFrames
if(SV.db.UnitFrames[unitName] and SV.db.UnitFrames[unitName].name) then
db = SV.db.UnitFrames[unitName].name
end
local name = frame:CreateFontString(nil, "OVERLAY")
name:SetFont(LSM:Fetch("font", db.font), db.fontSize, db.fontOutline)
name:SetShadowOffset(1.5, -1.5)
name:SetShadowColor(0, 0, 0, 0.5)
if unitName == "target" then
name:SetPoint("RIGHT", frame)
name:SetJustifyH("RIGHT")
name:SetJustifyV("MIDDLE")
else
name:SetPoint("CENTER", frame)
name:SetJustifyH("CENTER")
name:SetJustifyV("MIDDLE")
end
return name;
end
local function ADDInfoBG(frame)
local bg = frame.InfoPanel:CreateTexture(nil, "BACKGROUND")
bg:SetPoint("TOPLEFT", frame.InfoPanel, "TOPLEFT", 0, 1)
bg:SetPoint("BOTTOMRIGHT", frame.InfoPanel, "BOTTOMRIGHT", 0, 1)
bg:SetColorTexture(1, 1, 1, 1)
bg:SetGradientAlpha("VERTICAL", 0, 0, 0, 0, 0, 0, 0, 0.7)
frame.InfoPanelBG = bg
local left = frame.InfoPanel:CreateTexture(nil, "BACKGROUND")
left:SetPoint("TOPLEFT", frame.InfoPanel, "TOPLEFT", 0, -1)
left:SetPoint("BOTTOMLEFT", frame.InfoPanel, "BOTTOMLEFT", 0, -2)
left:SetWidth(2)
left:SetColorTexture(1, 1, 1, 1)
left:SetGradientAlpha("VERTICAL", 0, 0, 0, 0, 0, 0, 0, 1)
frame.InfoPanelLeft = left
local right = frame.InfoPanel:CreateTexture(nil, "BACKGROUND")
right:SetPoint("TOPRIGHT", frame.InfoPanel, "TOPRIGHT", 0, -1)
right:SetPoint("BOTTOMRIGHT", frame.InfoPanel, "BOTTOMRIGHT", 0, -2)
right:SetWidth(2)
right:SetColorTexture(1, 1, 1, 1)
right:SetGradientAlpha("VERTICAL", 0, 0, 0, 0, 0, 0, 0, 1)
frame.InfoPanelRight = right
end
function MOD:SetActionPanel(frame, unit, noHealthText, noPowerText, noMiscText)
if(frame.ActionPanel) then return; end
frame:SetStyle("Frame", "ActionPanel")
frame.ActionPanel = frame.Panel
local baseSize = SV.media.shared.font.unitprimary.size / 0.48;
if(unit and (unit == "target" or unit == "player")) then
local info = CreateFrame("Frame", nil, frame)
info:SetFrameStrata("BACKGROUND")
info:SetFrameLevel(0)
info:SetPoint("TOPLEFT", frame, "BOTTOMLEFT", 0, 1)
info:SetPoint("TOPRIGHT", frame, "BOTTOMRIGHT", 0, 1)
info:SetHeight(baseSize)
frame.TextGrip = CreateFrame("Frame", nil, info)
frame.TextGrip:SetFrameStrata("LOW")
frame.TextGrip:SetFrameLevel(20)
frame.TextGrip:SetAllPoints(info)
frame.InfoPanel = info;
ADDInfoBG(frame)
if(unit == "target") then
frame.ActionPanel:SetFrameLevel(1)
if(SV.db.UnitFrames.themed) then
frame.ActionPanel.special = CreateFrame("Frame", nil, frame.ActionPanel)
frame.ActionPanel.special:SetAllPoints(frame)
frame.ActionPanel.special:SetFrameStrata("BACKGROUND")
frame.ActionPanel.special:SetFrameLevel(0)
frame.ActionPanel.special[1] = frame.ActionPanel.special:CreateTexture(nil, "OVERLAY", nil, 1)
frame.ActionPanel.special[1]:SetPoint("BOTTOMRIGHT", frame.ActionPanel.special, "TOPRIGHT", 0, 0)
frame.ActionPanel.special[1]:SetWidth(frame.ActionPanel:GetWidth())
frame.ActionPanel.special[1]:SetHeight(frame.ActionPanel:GetWidth() * 0.25)
frame.ActionPanel.special[1]:SetTexture(ELITE_TOP)
frame.ActionPanel.special[1]:SetVertexColor(1, 0.75, 0)
frame.ActionPanel.special[1]:SetBlendMode("BLEND")
frame.ActionPanel.special[2] = frame.ActionPanel.special:CreateTexture(nil, "OVERLAY", nil, 1)
frame.ActionPanel.special[2]:SetPoint("TOPRIGHT", frame.ActionPanel.special, "BOTTOMRIGHT", 0, 0)
frame.ActionPanel.special[2]:SetWidth(frame.ActionPanel:GetWidth())
frame.ActionPanel.special[2]:SetHeight(frame.ActionPanel:GetWidth() * 0.25)
frame.ActionPanel.special[2]:SetTexture(ELITE_BOTTOM)
frame.ActionPanel.special[2]:SetVertexColor(1, 0.75, 0)
frame.ActionPanel.special[2]:SetBlendMode("BLEND")
-- frame.ActionPanel.special[3] = frame.ActionPanel.special:CreateTexture(nil, "OVERLAY", nil, 1)
-- frame.ActionPanel.special[3]:SetPoint("LEFT", frame.ActionPanel.special, "RIGHT", 0, 0)
-- frame.ActionPanel.special[3]:SetHeight(frame.ActionPanel:GetHeight())
-- frame.ActionPanel.special[3]:SetWidth(frame.ActionPanel:GetHeight() * 0.5)
-- frame.ActionPanel.special[3]:SetTexture(ELITE_RIGHT)
-- frame.ActionPanel.special[3]:SetVertexColor(1, 0.75, 0)
-- frame.ActionPanel.special[3]:SetBlendMode("BLEND")
frame.ActionPanel.special:SetAlpha(0.7)
frame.ActionPanel.special:Hide()
frame.ActionPanel:SetScript("OnSizeChanged", _hook_ActionPanel_OnSizeChanged)
end
frame.ActionPanel.class = CreateFrame("Frame", nil, frame.TextGrip)
frame.ActionPanel.class:SetSize(18, 18)
frame.ActionPanel.class:SetPoint("TOPLEFT", frame.ActionPanel, "TOPLEFT", 2, -2)
frame.ActionPanel.class:SetStyle("Frame", "Default", true, 2, 0, 0)
frame.ActionPanel.class.texture = frame.ActionPanel.class.Panel:CreateTexture(nil, "BORDER")
frame.ActionPanel.class.texture:SetAllPoints(frame.ActionPanel.class.Panel)
frame.ActionPanel.class.texture:SetTexture([[Interface\Glues\CharacterCreate\UI-CharacterCreate-Classes]])
local border1 = frame.ActionPanel.class:CreateTexture(nil, "OVERLAY")
border1:SetColorTexture(0, 0, 0)
border1:SetPoint("TOPLEFT")
border1:SetPoint("TOPRIGHT")
border1:SetHeight(2)
local border2 = frame.ActionPanel.class:CreateTexture(nil, "OVERLAY")
border2:SetColorTexture(0, 0, 0)
border2:SetPoint("BOTTOMLEFT")
border2:SetPoint("BOTTOMRIGHT")
border2:SetHeight(2)
local border3 = frame.ActionPanel.class:CreateTexture(nil, "OVERLAY")
border3:SetColorTexture(0, 0, 0)
border3:SetPoint("TOPRIGHT")
border3:SetPoint("BOTTOMRIGHT")
border3:SetWidth(2)
local border4 = frame.ActionPanel.class:CreateTexture(nil, "OVERLAY")
border4:SetColorTexture(0, 0, 0)
border4:SetPoint("TOPLEFT")
border4:SetPoint("BOTTOMLEFT")
border4:SetWidth(2)
else
frame.LossOfControl = CreateFrame("Frame", nil, frame.TextGrip)
frame.LossOfControl:SetAllPoints(frame)
frame.LossOfControl:SetFrameStrata("DIALOG")
frame.LossOfControl:SetFrameLevel(99)
local stunned = frame.LossOfControl:CreateTexture(nil, "OVERLAY", nil, 1)
stunned:SetPoint("CENTER", frame, "CENTER", 0, 0)
stunned:SetSize(96, 96)
stunned:SetTexture(STUNNED_ANIM)
stunned:SetBlendMode("ADD")
SV.Animate:Sprite4(stunned, 0.12, false, true)
frame.LossOfControl.stunned = stunned
frame.LossOfControl:SetParent(LossOfControlFrame)
end
elseif(unit and (unit == 'pet' or unit == 'targettarget')) then
local info = CreateFrame("Frame", nil, frame)
info:SetFrameStrata("BACKGROUND")
info:SetFrameLevel(0)
info:SetPoint("TOPLEFT", frame, "BOTTOMLEFT", 0, 1)
info:SetPoint("TOPRIGHT", frame, "BOTTOMRIGHT", 0, 1)
info:SetHeight(baseSize)
frame.InfoPanel = info;
ADDInfoBG(frame)
frame.TextGrip = CreateFrame("Frame", nil, info)
-- frame.TextGrip:SetFrameStrata("LOW")
frame.TextGrip:SetFrameLevel(20)
frame.TextGrip:SetAllPoints(info)
else
local info = CreateFrame("Frame", nil, frame)
info:SetFrameLevel(20)
info:SetAllPoints(frame)
frame.TextGrip = CreateFrame("Frame", nil, info)
--frame.TextGrip:SetFrameStrata("LOW")
frame.TextGrip:SetAllPoints(info)
end
frame.TextGrip.Name = CreateNameText(frame.TextGrip, unit)
local reverse = unit and (unit == "target" or unit == "focus" or unit == "boss" or unit == "arena") or false;
local offset, direction
local fontgroup = FontMapping[unit]
if(not noHealthText) then
frame.TextGrip.Health = frame.TextGrip:CreateFontString(nil, "OVERLAY")
frame.TextGrip.Health:SetFontObject(_G[fontgroup])
offset = reverse and 2 or -2;
direction = reverse and "LEFT" or "RIGHT";
frame.TextGrip.Health:SetPoint(direction, frame.TextGrip, direction, offset, 0)
end
if(not noPowerText) then
frame.TextGrip.Power = frame.TextGrip:CreateFontString(nil, "OVERLAY")
frame.TextGrip.Power:SetFontObject(_G[fontgroup])
offset = reverse and -2 or 2;
direction = reverse and "RIGHT" or "LEFT";
frame.TextGrip.Power:SetPoint(direction, frame.TextGrip, direction, offset, 0)
end
if(not noMiscText) then
frame.TextGrip.Misc = frame.TextGrip:CreateFontString(nil, "OVERLAY")
frame.TextGrip.Misc:SetFontObject(_G[fontgroup])
frame.TextGrip.Misc:SetPoint("CENTER", frame, "CENTER", 0, 0)
end
frame.StatusPanel = CreateFrame("Frame", nil, frame)
frame.StatusPanel:EnableMouse(false)
if(unit and (unit == "player" or unit == "pet" or unit == "target" or unit == "targettarget" or unit == "focus" or unit == "focustarget")) then
frame.StatusPanel:SetAllPoints(frame)
frame.StatusPanel.media = {
[[Interface\Addons\SVUI_UnitFrames\assets\TARGET-DC]],
[[Interface\Addons\SVUI_UnitFrames\assets\TARGET-DEAD]],
[[Interface\Addons\SVUI_UnitFrames\assets\TARGET-TAPPED]]
}
else
frame.StatusPanel:SetSize(50, 50)
frame.StatusPanel:SetPoint("CENTER", frame, "CENTER", 0, 0)
frame.StatusPanel.media = {
[[Interface\Addons\SVUI_UnitFrames\assets\UNIT-DC]],
[[Interface\Addons\SVUI_UnitFrames\assets\UNIT-DEAD]],
[[Interface\Addons\SVUI_UnitFrames\assets\UNIT-TAPPED]]
}
end
frame.StatusPanel:SetFrameStrata("LOW")
frame.StatusPanel:SetFrameLevel(32)
frame.StatusPanel.texture = frame.StatusPanel:CreateTexture(nil, "OVERLAY")
frame.StatusPanel.texture:SetAllPoints()
if(ThreatMapping[unit]) then
frame.Threat = CreateThreat(frame, unit)
end
end
function MOD:UpdateStatusMedia(frame)
if(not frame.StatusPanel) then return end
local width,height = frame.ActionPanel:GetSize()
frame.StatusPanel:ClearAllPoints()
if((height > (width * 0.5)) or (width < 75)) then
frame.StatusPanel:SetSize(height * 1.25, height * 1.25)
frame.StatusPanel:SetPoint("CENTER", frame.ActionPanel, "CENTER", 0, 0)
frame.StatusPanel.media = {
[[Interface\Addons\SVUI_UnitFrames\assets\UNIT-DC]],
[[Interface\Addons\SVUI_UnitFrames\assets\UNIT-DEAD]],
[[Interface\Addons\SVUI_UnitFrames\assets\UNIT-TAPPED]]
}
else
frame.StatusPanel:SetAllPoints(frame)
frame.StatusPanel.media = {
[[Interface\Addons\SVUI_UnitFrames\assets\TARGET-DC]],
[[Interface\Addons\SVUI_UnitFrames\assets\TARGET-DEAD]],
[[Interface\Addons\SVUI_UnitFrames\assets\TARGET-TAPPED]]
}
end
frame.StatusPanel.texture:ClearAllPoints()
frame.StatusPanel.texture:SetAllPoints()
end
--[[
##########################################################
HEALTH ANIMATIONS
##########################################################
]]--
local Anim_OnUpdate = function(self)
local parent = self.parent
local coord = self._coords;
parent:SetTexCoord(coord[1],coord[2],coord[3],coord[4])
end
local Anim_OnPlay = function(self)
local parent = self.parent
parent:SetAlpha(1)
if not parent:IsShown() then
parent:Show()
end
end
local Anim_OnStop = function(self)
local parent = self.parent
parent:SetAlpha(0)
if parent:IsShown() then
parent:Hide()
end
end
local function SetNewAnimation(frame, animType, parent)
local anim = frame:CreateAnimation(animType)
anim.parent = parent
return anim
end
local function SetAnim(frame, parent)
local speed = 0.08
frame.anim = frame:CreateAnimationGroup("Sprite")
frame.anim.parent = parent;
frame.anim:SetScript("OnPlay", Anim_OnPlay)
frame.anim:SetScript("OnFinished", Anim_OnStop)
frame.anim:SetScript("OnStop", Anim_OnStop)
frame.anim[1] = SetNewAnimation(frame.anim, "Translation", frame)
frame.anim[1]:SetOrder(1)
frame.anim[1]:SetDuration(speed)
frame.anim[1]._coords = {0,0.5,0,0.25}
frame.anim[1]:SetScript("OnUpdate", Anim_OnUpdate)
frame.anim[2] = SetNewAnimation(frame.anim, "Translation", frame)
frame.anim[2]:SetOrder(2)
frame.anim[2]:SetDuration(speed)
frame.anim[2]._coords = {0.5,1,0,0.25}
frame.anim[2]:SetScript("OnUpdate", Anim_OnUpdate)
frame.anim[3] = SetNewAnimation(frame.anim, "Translation", frame)
frame.anim[3]:SetOrder(3)
frame.anim[3]:SetDuration(speed)
frame.anim[3]._coords = {0,0.5,0.25,0.5}
frame.anim[3]:SetScript("OnUpdate", Anim_OnUpdate)
frame.anim[4] = SetNewAnimation(frame.anim, "Translation", frame)
frame.anim[4]:SetOrder(4)
frame.anim[4]:SetDuration(speed)
frame.anim[4]._coords = {0.5,1,0.25,0.5}
frame.anim[4]:SetScript("OnUpdate", Anim_OnUpdate)
frame.anim[5] = SetNewAnimation(frame.anim, "Translation", frame)
frame.anim[5]:SetOrder(5)
frame.anim[5]:SetDuration(speed)
frame.anim[5]._coords = {0,0.5,0.5,0.75}
frame.anim[5]:SetScript("OnUpdate", Anim_OnUpdate)
frame.anim[6] = SetNewAnimation(frame.anim, "Translation", frame)
frame.anim[6]:SetOrder(6)
frame.anim[6]:SetDuration(speed)
frame.anim[6]._coords = {0.5,1,0.5,0.75}
frame.anim[6]:SetScript("OnUpdate", Anim_OnUpdate)
frame.anim[7] = SetNewAnimation(frame.anim, "Translation", frame)
frame.anim[7]:SetOrder(7)
frame.anim[7]:SetDuration(speed)
frame.anim[7]._coords = {0,0.5,0.75,1}
frame.anim[7]:SetScript("OnUpdate", Anim_OnUpdate)
frame.anim[8] = SetNewAnimation(frame.anim, "Translation", frame)
frame.anim[8]:SetOrder(8)
frame.anim[8]:SetDuration(speed)
frame.anim[8]._coords = {0.5,1,0.75,1}
frame.anim[8]:SetScript("OnUpdate", Anim_OnUpdate)
frame.anim:SetLooping("REPEAT")
end
--[[
##########################################################
HEALTH
##########################################################
]]--
local function CreateAbsorbBar(parent, unit)
local absorbBar = CreateFrame("StatusBar", nil, parent)
absorbBar:SetFrameStrata("LOW")
absorbBar:SetFrameLevel(3)
absorbBar:SetStatusBarTexture(SV.media.statusbar.default);
absorbBar:SetMinMaxValues(0, 100)
absorbBar:SetAllPoints(parent)
absorbBar:SetScript("OnUpdate", function(self)
if unit then
local hpMax = UnitHealthMax(unit)
local currentHP = UnitHealth(unit)
local absorb = UnitGetTotalAbsorbs(unit)
local effectiveHP = absorb + currentHP
if effectiveHP > hpMax then effectiveHP = hpMax end
self:SetMinMaxValues(0, hpMax)
self:SetValue(effectiveHP)
end
end)
return absorbBar
end
local OverlayHealthUpdate = function(health, unit, min, max)
local disconnected = not UnitIsConnected(unit)
health:SetMinMaxValues(-max, 0)
health:SetValue(disconnected and 0 or -min)
local invisible = ((min == max) or UnitIsDeadOrGhost(unit) or disconnected);
if invisible then health.lowAlerted = false end
if health.fillInverted then
health:SetReverseFill(true)
end
health.percent = invisible and 100 or ((min / max) * 100)
health.disconnected = disconnected
local bg = health.bg;
local mu = 0;
if(max ~= 0) then
mu = (min / max)
end
if(invisible or not health.overlayAnimation) then
health.animation[1].anim:Stop()
health.animation[1]:SetAlpha(0)
end
if(invisible) then
health:SetStatusBarColor(0.6,0.4,1,0.5)
health.animation[1]:SetVertexColor(0.8,0.3,1,0.4)
elseif(health.colorOverlay) then
local t = oUF_SVUI.colors.health
health:SetStatusBarColor(t[1], t[2], t[3], 0.9)
else
health:SetStatusBarColor(1-(0.65 * mu), 0.15 * mu, 0, 0.85)
health.animation[1]:SetVertexColor(1, 0.1 * mu, 0, 0.5)
end
if(health.overlayAnimation and not invisible) then
if(mu <= 0.25) then
health.animation[1]:SetAlpha(1)
health.animation[1].anim:Play()
else
health.animation[1].anim:Stop()
health.animation[1]:SetAlpha(0)
end
end
end
local RefreshHealthBar = function(self, overlay)
local db = SV.db.UnitFrames[self.unit]
local absorbBarEnabled = false
if db and db.health.absorbsBar then
absorbBarEnabled = true
end
if(overlay) then
self.Health.bg:SetVertexColor(0, 0, 0, 0)
self.Health.PreUpdate = OverlayHealthUpdate;
else
self.Health.bg:SetVertexColor(0.4, 0.1, 0.1, 0.8)
self.Health.PreUpdate = nil;
end
if absorbBarEnabled then
local absorbBar
if self.Health.absorbBar then
absorbBar = self.Health.absorbBar
else
absorbBar = CreateAbsorbBar(self.Health, self.unit)
end
self.Health.bg:SetParent(absorbBar)
absorbBar:Show()
else
self.Health.bg:SetParent(self.Health)
if self.Health.absorbBar then
self.Health.absorbBar:Hide()
end
end
end
function MOD:CreateHealthBar(frame, hasbg)
local db = SV.db.UnitFrames[frame.unit]
local enableAbsorbsBar = false
if db and db.health.absorbsBar then
enableAbsorbsBar = true
end
local healthBar = CreateFrame("StatusBar", nil, frame)
healthBar:SetFrameStrata("LOW")
healthBar:SetFrameLevel(4)
healthBar:SetStatusBarTexture(SV.media.statusbar.default);
if enableAbsorbsBar then
local absorbBar = CreateAbsorbBar(healthBar, frame.unit)
healthBar.absorbBar = absorbBar
end
if hasbg then
if not enableAbsorbsBar then
healthBar.bg = healthBar:CreateTexture(nil, "BORDER")
else
healthBar.bg = healthBar.absorbBar:CreateTexture(nil, "BORDER")
end
healthBar.bg:SetAllPoints()
healthBar.bg:SetTexture(SV.media.statusbar.gradient)
healthBar.bg:SetVertexColor(0.4, 0.1, 0.1)
healthBar.bg.multiplier = 0.25
end
local flasher = CreateFrame("Frame", nil, frame)
flasher:SetFrameLevel(3)
flasher:SetAllPoints(healthBar)
flasher[1] = flasher:CreateTexture(nil, "OVERLAY", nil, 1)
flasher[1]:SetTexture([[Interface\Addons\SVUI_UnitFrames\assets\UNIT-HEALTH-ANIMATION]])
flasher[1]:SetTexCoord(0, 0.5, 0, 0.25)
flasher[1]:SetVertexColor(1, 0.3, 0.1, 0.5)
flasher[1]:SetBlendMode("ADD")
flasher[1]:SetAllPoints(flasher)
SetAnim(flasher[1], flasher)
flasher:Hide()
healthBar.animation = flasher
healthBar.noupdate = false;
healthBar.fillInverted = false;
healthBar.gridMode = false;
healthBar.colorTapping = true;
healthBar.colorDisconnected = true;
frame.RefreshHealthBar = RefreshHealthBar
return healthBar
end
--[[
##########################################################
POWER
##########################################################
]]--
local PostUpdateAltPower = function(self, min, current, max)
local remaining = floor(current / max * 100)
local parent = self:GetParent()
if remaining < 35 then
self:SetStatusBarColor(0, 1, 0)
elseif remaining < 70 then
self:SetStatusBarColor(1, 1, 0)
else
self:SetStatusBarColor(1, 0, 0)
end
local unit = parent.unit;
if(unit == "player" and self.text) then
local apInfo = select(10, UnitAlternatePowerInfo(unit))
if remaining > 0 then
self.text:SetText(apInfo..": "..format("%d%%", remaining))
else
self.text:SetText(apInfo..": 0%")
end
elseif(unit and unit:find("boss%d") and self.text) then
self.text:SetTextColor(self:GetStatusBarColor())
if not parent.TextGrip.Power:GetText() or parent.TextGrip.Power:GetText() == "" then
self.text:SetPoint("BOTTOMRIGHT", parent.Health, "BOTTOMRIGHT")
else
self.text:SetPoint("RIGHT", parent.TextGrip.Power, "LEFT", 2, 0)
end
if remaining > 0 then
self.text:SetText("|cffD7BEA5[|r"..format("%d%%", remaining).."|cffD7BEA5]|r")
else
self.text:SetText(nil)
end
end
end
function MOD:CreatePowerBar(frame)
local power = CreateFrame("StatusBar", nil, frame)
power:SetStatusBarTexture(SV.media.statusbar.default)
power:SetFrameStrata("LOW")
power:SetFrameLevel(6)
power:SetStyle("Frame", "Bar")
power.bg = power:CreateTexture(nil, "BORDER")
power.bg:SetAllPoints()
power.bg:SetTexture(SV.media.statusbar.gradient)
power.bg:SetVertexColor(0.4, 0.1, 0.1)
power.bg.multiplier = 0.25
power.colorDisconnected = false;
power.colorTapping = false;
power.PostUpdate = MOD.PostUpdatePower;
return power
end
function MOD:CreateAltPowerBar(frame)
local altPower = CreateFrame("StatusBar", nil, frame)
altPower:SetStatusBarTexture(SV.media.statusbar.default)
altPower:SetStyle("Frame", "Bar")
altPower:GetStatusBarTexture():SetHorizTile(false)
altPower:SetFrameStrata("LOW")
altPower:SetFrameLevel(8)
altPower.text = altPower:CreateFontString(nil, "OVERLAY")
altPower.text:SetPoint("CENTER")
altPower.text:SetJustifyH("CENTER")
altPower.text:SetFontObject(SVUI_Font_Unit)
altPower.PostUpdate = PostUpdateAltPower;
return altPower
end
function MOD:PostUpdatePower(unit, value, max)
local db = SV.db.UnitFrames[unit]
local powerType, powerToken = UnitPowerType(unit)
local parent = self:GetParent()
if parent.isForced then
value = random(1, max)
powerType = random(0, 4)
self:SetValue(value)
end
local colors = oUF_SVUI.colors.power[powerToken]
local mult = self.bg.multiplier or 1;
local isPlayer = UnitPlayerControlled(unit)
if isPlayer and self.colorClass then
local _, class = UnitClassBase(unit);
colors = oUF_SVUI["colors"].class[class]
elseif(not isPlayer and (powerType and powerType == 1 and value == 0)) then
colors = nil
end
if(not colors) then
self:Hide()
else
if(not self:IsShown()) then self:Show() end
self:SetStatusBarColor(colors[1], colors[2], colors[3])
self.bg:SetVertexColor(colors[1] * mult, colors[2] * mult, colors[3] * mult)
end
end
--[[
##########################################################
PORTRAIT
##########################################################
]]--
function MOD:CreatePortrait(frame,smallUnit,isPlayer)
-- 3D Portrait
local portrait3D = CreateFrame("PlayerModel",nil,frame)
portrait3D:SetFrameStrata("LOW")
portrait3D:SetFrameLevel(2)
if smallUnit then
portrait3D:SetStyle("Frame", "UnitSmall")
else
portrait3D:SetStyle("Frame", "UnitLarge")
end
portrait3D.Outline = CreateFrame("Frame", nil, portrait3D)
portrait3D.Outline:WrapPoints(portrait3D)
portrait3D.Outline:SetStyle("Frame", "ActionPanel")
portrait3D.UserRotation = 0;
portrait3D.UserCamDistance = 1.3;
-- 2D Portrait
local portrait2Danchor = CreateFrame('Frame', nil, frame)
portrait2Danchor:SetFrameStrata("LOW")
portrait2Danchor:SetFrameLevel(2)
portrait2Danchor:SetStyle("Frame")
portrait2Danchor:SetPanelColor("darkest")
portrait2Danchor.Outline = CreateFrame("Frame", nil, portrait2Danchor)
portrait2Danchor.Outline:WrapPoints(portrait2Danchor)
portrait2Danchor.Outline:SetStyle("Frame", "ActionPanel")
local portrait2D = portrait2Danchor:CreateTexture(nil,'OVERLAY')
portrait2D:SetAllPoints()
portrait2D:SetTexCoord(0.15,0.85,0.15,0.85)
portrait2D:SetBlendMode("ADD")
-- Assign To Frame
frame.PortraitModel = portrait3D;
frame.PortraitTexture = portrait2D;
end
| mit |
UnfortunateFruit/darkstar | scripts/globals/items/yellow_curry_bun_+1.lua | 35 | 2002 | -----------------------------------------
-- ID: 5763
-- Item: yellow_curry_bun_+1
-- Food Effect: 30minutes, All Races
-----------------------------------------
-- Health Points 30
-- Strength 5
-- Agility 2
-- Vitality 2
-- Intelligence -2
-- Attack 23% (caps @ 80)
-- Ranged Attack 23% (caps @ 80)
-- Resist Sleep
-- Resist Stun
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5763);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 30);
target:addMod(MOD_STR, 5);
target:addMod(MOD_AGI, 2);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_INT, -2);
target:addMod(MOD_FOOD_ATTP, 23);
target:addMod(MOD_FOOD_ATT_CAP, 80);
target:addMod(MOD_FOOD_RATTP, 23);
target:addMod(MOD_FOOD_RATT_CAP, 80);
target:addMod(MOD_SLEEPRES, 5);
target:addMod(MOD_STUNRES, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 30);
target:delMod(MOD_STR, 5);
target:delMod(MOD_AGI, 2);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_INT, -2);
target:delMod(MOD_FOOD_ATTP, 23);
target:delMod(MOD_FOOD_ATT_CAP, 80);
target:delMod(MOD_FOOD_RATTP, 23);
target:delMod(MOD_FOOD_RATT_CAP, 80);
target:delMod(MOD_SLEEPRES, 5);
target:delMod(MOD_STUNRES, 5);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Northern_San_dOria/npcs/Nouveil.lua | 13 | 2236 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Nouveil
-- Type: General
-- @zone: 231
-- @pos 123 0 106
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) == true and trade:getItemCount() == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
if (player:getQuestStatus(SANDORIA,WATER_OF_THE_CHEVAL) == QUEST_ACCEPTED) then
if (trade:getGil() >= 10) then
player:startEvent(0x023b);
end;
end;
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(SANDORIA,WATER_OF_THE_CHEVAL) == QUEST_ACCEPTED) then
if (player:hasItem(603) == true) then
player:startEvent(0x023d);
elseif (player:hasItem(602) == true) then
player:startEvent(0x023c);
else
player:startEvent(0x023f);
end;
else
player:startEvent(0x023e);
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);
-- Waters of the Cheval, recieve blessed waterskin
if (csid == 0x023b) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 602);
else
player:delGil(10);
player:addItem(602);
player:messageSpecial(ITEM_OBTAINED, 602);
end;
end;
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/RuAun_Gardens/npcs/HomePoint#3.lua | 12 | 1250 | -----------------------------------
-- Area: RuAun_Gardens
-- NPC: HomePoint#3
-- @pos -312 -42 -422 130
-----------------------------------
package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/RuAun_Gardens/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fe, 61);
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 == 0x21fe) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/items/spicy_cracker.lua | 35 | 1335 | -----------------------------------------
-- ID: 4466
-- Item: spicy_cracker
-- Food Effect: 3Min, All Races
-----------------------------------------
-- HP Recovered While Healing 7
-- Beast Killer
-- Resist Sleep
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,180,4466);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HPHEAL, 7);
target:addMod(MOD_BEAST_KILLER, 5);
target:addMod(MOD_SLEEPRES, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HPHEAL, 7);
target:delMod(MOD_BEAST_KILLER, 5);
target:delMod(MOD_SLEEPRES, 5);
end;
| gpl-3.0 |
plajjan/snabbswitch | src/lib/protocol/icmp/header.lua | 6 | 2149 | -- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local ffi = require("ffi")
local C = ffi.C
local header = require("lib.protocol.header")
local lib = require("core.lib")
local ipsum = require("lib.checksum").ipsum
-- XXX IPv4 and IPv6 use the same ICMP header format but distinct
-- number spaces for type and code. This class needs to be subclassed
-- accordingly.
local icmp = subClass(header)
-- Class variables
icmp._name = "icmp"
icmp._ulp = {
class_map = { [135] = "lib.protocol.icmp.nd.ns",
[136] = "lib.protocol.icmp.nd.na" },
method = "type" }
icmp:init(
{
[1] = ffi.typeof[[
struct {
uint8_t type;
uint8_t code;
int16_t checksum;
} __attribute__((packed))
]]
})
-- Class methods
function icmp:new (type, code)
local o = icmp:superClass().new(self)
o:type(type)
o:code(code)
return o
end
-- Instance methods
function icmp:type (type)
if type ~= nil then
self:header().type = type
else
return self:header().type
end
end
function icmp:code (code)
if code ~= nil then
self:header().code = code
else
return self:header().code
end
end
local function checksum(header, payload, length, ipv6)
local csum = 0
if ipv6 then
-- Checksum IPv6 pseudo-header
local ph = ipv6:pseudo_header(length + ffi.sizeof(header), 58)
csum = ipsum(ffi.cast("uint8_t *", ph), ffi.sizeof(ph), 0)
end
-- Add ICMP header
local csum_rcv = header.checksum
header.checksum = 0
csum = ipsum(ffi.cast("uint8_t *", header),
ffi.sizeof(header), bit.bnot(csum))
header.checksum = csum_rcv
-- Add ICMP payload
return ipsum(payload, length, bit.bnot(csum))
end
function icmp:checksum (payload, length, ipv6)
local header = self:header()
header.checksum = lib.htons(checksum(header, payload, length, ipv6))
end
function icmp:checksum_check (payload, length, ipv6)
return checksum(self:header(), payload, length, ipv6) == lib.ntohs(self:header().checksum)
end
return icmp
| apache-2.0 |
nesstea/darkstar | scripts/zones/Gusgen_Mines/Zone.lua | 13 | 1881 | -----------------------------------
--
-- Zone: Gusgen_Mines (196)
--
-----------------------------------
package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil;
----------------------------------
require("scripts/globals/settings");
require("scripts/globals/zone");
require("scripts/zones/Gusgen_Mines/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local tomes = {17580412,17580413,17580414};
SetGroundsTome(tomes);
UpdateTreasureSpawnPoint(17580399);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(100.007,-61.63,-237.441,187);
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
ld-test/lovetoys | src/Component.lua | 2 | 1080 | -- Collection of utilities for handling Components
Component = {}
Component.all = {}
-- Create a Component class with the specified name and fields
-- which will automatically get a constructor accepting the fields as arguments
function Component.create(name, fields, defaults)
local component = class(name)
if fields then
defaults = defaults or {}
component.initialize = function(self, ...)
local args = {...}
for index, field in ipairs(fields) do
self[field] = args[index] or defaults[field]
end
end
end
Component.register(component)
return component
end
-- Register a Component to make it available to Component.load
function Component.register(componentClass)
Component.all[componentClass.name] = componentClass
end
-- Load multiple components and populate the calling functions namespace with them
-- This should only be called from the top level of a file!
function Component.load(names)
local components = {}
for _, name in pairs(names) do
components[#components+1] = Component.all[name]
end
return unpack(components)
end
| mit |
mahdib9/9 | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
shayanchabok007/antispamteleseed | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/zones/Port_Jeuno/npcs/Shami.lua | 17 | 18277 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Shami
-- Orb Seller (BCNM)
-- @pos -14 8 44 246
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local NumberItem = trade:getItemCount();
local BeastmensSeal = player:getSeals(0);
local KindredsSeal = player:getSeals(1);
local KindredsCrest = player:getSeals(2);
local HighKindredsCrest = player:getSeals(3);
local SacredKindredsCrest = player:getSeals(4);
----------------------------------------------------------------------------------------------------------------------------
-------- Trading Seals/Crests to Shami -------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------
if(trade:hasItemQty(1126,NumberItem) and trade:getItemCount() == NumberItem) then
player:startEvent(0x0141,0,BeastmensSeal + NumberItem); -- Giving Shami Beastmen's Seal
player:addSeals(NumberItem,0);
player:tradeComplete(trade);
elseif(trade:hasItemQty(1127,NumberItem) and trade:getItemCount() == NumberItem) then
player:startEvent(0x0141,1,KindredsSeal + NumberItem); -- Giving Shami Kindred's Seal
player:addSeals(NumberItem,1);
player:tradeComplete(trade);
elseif(trade:hasItemQty(2955,NumberItem) and trade:getItemCount() == NumberItem) then
player:startEvent(0x0141,2,KindredsCrest + NumberItem); -- Giving Shami Kindred's Crest
player:addSeals(NumberItem,2);
player:tradeComplete(trade);
elseif(trade:hasItemQty(2956,NumberItem) and trade:getItemCount() == NumberItem) then
player:startEvent(0x0141,3,HighKindredsCrest + NumberItem); -- Giving Shami High Kindred's Crest
player:addSeals(NumberItem,3);
player:tradeComplete(trade);
elseif(trade:hasItemQty(2957,NumberItem) and trade:getItemCount() == NumberItem) then
player:startEvent(0x0141,3,SacredKindredsCrest + NumberItem); -- Giving Shami High Kindred's Crest
player:addSeals(NumberItem,4);
player:tradeComplete(trade);
----------------------------------------------------------------------------------------------------------------------------
-------- Trading Cracked BCNM Orbs or checking where you can bring the Orb ------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------
elseif(trade:hasItemQty(1551,1) and NumberItem == 1) then
if (player:getVar("CloudyOrbIsCracked") == 1) then
player:startEvent(0x0016); -- Cloudy Orb is Cracked
player:setVar("CloudyOrbIsCracked",0);
else
player:startEvent(0x0005); -- Cloudy Orb is ok, List where you can take the orb.
end
elseif(trade:hasItemQty(1552,1) and NumberItem == 1) then
if(player:getVar("SkyOrbIsCracked") == 1) then
player:startEvent(0x0016); -- Sky Orb is Cracked
player:setVar("SkyOrbIsCracked",0);
else
player:startEvent(0x0009); -- Sky Orb is ok, List where you can take the orb.
end
elseif(trade:hasItemQty(1131,1) and NumberItem == 1) then
if(player:getVar("StarOrbIsCracked") == 1) then
player:startEvent(0x0016); -- Star Orb is Cracked
player:setVar("StarOrbIsCracked",0);
else
player:startEvent(0x0009); -- Star Orb is ok, List where you can take the orb.
end
elseif(trade:hasItemQty(1177,1) and NumberItem == 1) then
if(player:getVar("CometOrbIsCracked") == 1) then
player:startEvent(0x0016); -- Comet Orb is Cracked
player:setVar("CometOrbIsCracked",0);
else
player:startEvent(0x0009); -- Comet Orb is ok, List where you can take the orb.
end
elseif(trade:hasItemQty(1130,1) and NumberItem == 1) then
if(player:getVar("MoonOrbIsCracked") == 1) then
player:startEvent(0x0016); -- Moon Orb is Cracked
player:setVar("MoonOrbIsCracked",0);
else
player:startEvent(0x0009); -- Moon Orb is ok, List where you can take the orb.
end
----------------------------------------------------------------------------------------------------------------------------
-------- Trading Cracked KSNM Orbs or checking where you can bring the Orb -------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------
elseif(trade:hasItemQty(1180,1) and NumberItem == 1) then
if(player:getVar("AtroposOrbIsCracked") == 1) then
player:startEvent(0x0016); -- Atropos Orb is Cracked
player:setVar("AtroposOrbIsCracked",0);
else
player:startEvent(0x0009); -- Atropos Orb is ok, List where you can take the orb.
end
elseif(trade:hasItemQty(1175,1) and NumberItem == 1) then
if(player:getVar("ClothoOrbIsCracked") == 1) then
player:startEvent(0x0016); -- Clotho Orb is Cracked
player:setVar("ClothoOrbIsCracked",0);
else
player:startEvent(0x0009); -- Clotho Orb is ok, List where you can take the orb.
end
elseif(trade:hasItemQty(1178,1) and NumberItem == 1) then
if(player:getVar("LachesisOrbIsCracked") == 1) then
player:startEvent(0x0016) -- Lachesis Orb is Cracked
player:setVar("LachesisOrbIsCracked",0);
else
player:startEvent(0x0009); -- Lachesis Orb is ok, List where you can take the orb.
end
elseif(trade:hasItemQty(1553,1) and NumberItem == 1) then
if(player:getVar("ThemisOrbIsCracked") == 1) then
player:startEvent(0x0016); -- Themis Orb is Cracked
player:setVar("ThemisOrbIsCracked",0);
else
player:startEvent(0x000b); -- Themis Orb is ok, List where you can take the orb.
end
-- TODO : Add in trade-in for cracked Kindred Crest orbs (and High Kindred Crest) and find cutscene that tells you where you can bring it
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local oldBeastmensSeal = player:getVar("ShamiBeastmensSeal");
local oldKindredsSeal = player:getVar("ShamiKindredsSeal");
local oldKindredsCrest = player:getVar("ShamiKindredsCrest");
local oldHighKindredsCrest = player:getVar("ShamiHighKindredsCrest");
local BeastmensSeal = player:getSeals(0);
local KindredsSeal = player:getSeals(1);
local KindredsCrest = player:getSeals(2);
local HighKindredsCrest = player:getSeals(3);
local SacredKindredsCrest = player:getSeals(4);
local WildcatJeuno = player:getVar("WildcatJeuno");
if (oldBeastmensSeal > 0) then
player:addSeals(oldBeastmensSeal,0);
player:setVar("ShamiBeastmensSeal",0);
end
if (oldKindredsSeal > 0) then
player:addSeals(oldKindredsSeal,1);
player:setVar("ShamiKindredsSeal",0);
end
if (oldKindredsCrest > 0) then
player:addSeals(oldKindredsCrest,2);
player:setVar("ShamiKindredsCrest",0);
end
if (oldHighKindredsCrest > 0) then
player:addSeals(oldHighKindredsCrest,3);
player:setVar("ShamiHighKindredsCrest",0);
end
-- TODO: player:startEvent(0x0142,0,0,0,0,1,0,1) -- First time talking to him WITH beastmen seal in inventory
if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,17) == false) then
player:startEvent(317);
elseif(BeastmensSeal + KindredsSeal + KindredsCrest + HighKindredsCrest == 0) then
player:startEvent(0x0017); -- Standard dialog ?
else
player:startEvent(0x0142,(KindredsSeal * 65536) + BeastmensSeal,(HighKindredsCrest * 65536) + KindredsCrest,SacredKindredsCrest,0,1,0,0); -- Standard dialog with menu
end
end;
-- 0x0032 : 30 sceau conférie : choix entre clotho et lachésis
-- 0x0018 : Après achat d'un orb (qu'bia, yughott, palborough, giddeus)
-- 0x0008 : Après achat d'un orb (yughott, palborough, giddeus, qu'bia, ghelsba)
-- 0x0004 : Après achat d'un orb (yughott, palborough, giddeus, ghelsba)
-- 0x000a : Après achat d'un orb (yughott, palborough, giddeus)
-- 0x0009 : Trade d'un orb ? (yughott, palborough, giddeus, ghelsba)
-- 0x0005 : Trade d'un orb ? (yughott, palborough, giddeus, ghelsba)
-- 0x000b : Trade d'un orb ? (yughott, palborough, giddeus)
-- 0x001a : Trade d'un orb ? (qu'bia, yughott, palborough, giddeus)
-- 0x001b : Trade d'un orb ? (qu'bia, chambre des oracles)
-- 0x0016 : Trade d'un orb utilisé (il le recup)
-- 0x0019 : Un seul échange autorisé par semaine
-- 0x0141 : trade sceau + nombre player:startEvent(0x0141,0,15);
-- 0 shbete, 1 s-confrerie, 2 s-demons, 3 s-seigneurdes hombre
-----------------------------------
-- 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);
local BeastmensSeal = player:getSeals(0);
local KindredsSeal = player:getSeals(1);
local KindredsCrest = player:getSeals(2);
local HighKindredsCrest = player:getSeals(3);
local SacredKindredsCrest = player:getSeals(4);
if (csid == 0x0016) then -- Player gave Shami a cracked orb
player:tradeComplete();
elseif (option >= 508 and option ~= 1073741824) then -- Player has asked to retrieve seals (1073741824 means someone hit escape during cutscene, don't remove this or people will get free seals)
local takingSealCount = 0;
if ((option + 2)% 256 == 0) then
if (player:getFreeSlotsCount() >=1) then
takingSealCount = (option + 2)/256 - 1; -- Every seal requested adds 256 to the option value. The lowest is one seal which sets the option to 510, two seals would be 510 + 256. etc
player:delSeals(takingSealCount,0);
player:addItem(1126,takingSealCount);
player:messageSpecial(ITEM_OBTAINED,1126);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1126);
end
elseif((option + 1)% 256 == 0) then
if (player:getFreeSlotsCount() >=1) then
takingSealCount = (option + 1)/256 - 1; -- Every seal requested adds 256 to the option value. The lowest is one seal which sets the option to 511, two seals would be 511 + 256. etc
player:delSeals(takingSealCount,1);
player:addItem(1127,takingSealCount);
player:messageSpecial(ITEM_OBTAINED,1127);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1127);
end
elseif((option + 3)% 256 == 0) then
if (player:getFreeSlotsCount() >=1) then
takingSealCount = (option + 3)/256 - 1; -- Every seal requested adds 256 to the option value. The lowest is one seal which sets the option to 509, two seals would be 509 + 256. etc
player:delSeals(takingSealCount,2);
player:addItem(2955,takingSealCount);
player:messageSpecial(ITEM_OBTAINED,2955);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2955);
end
elseif((option + 4)% 256 == 0) then
if (player:getFreeSlotsCount() >=1) then
takingSealCount = (option + 4)/256 - 1; -- Every seal requested adds 256 to the option value. The lowest is one seal which sets the option to 508, two seals would be 508 + 256. etc
player:delSeals(takingSealCount,3);
player:addItem(2956,takingSealCount);
player:messageSpecial(ITEM_OBTAINED,2956);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2956);
end
elseif((option + 5)% 256 == 0) then
if (player:getFreeSlotsCount() >=1) then
takingSealCount = (option + 5)/256 - 1; -- Every seal requested adds 256 to the option value. The lowest is one seal which sets the option to 508, two seals would be 508 + 256. etc
player:delSeals(takingSealCount,4);
player:addItem(2957,takingSealCount);
player:messageSpecial(ITEM_OBTAINED,2957);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2957);
end
end
----------------------------------------------------------------------------------------------------------------------------
-------- Begin BCNM orb Handout --------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------
elseif (csid == 0x0142) then
if (option == 1 and BeastmensSeal >= 20) then -- Player asked for Cloudy orb
if(player:getFreeSlotsCount() >= 1 and player:hasItem(1551) == false) then
player:delSeals(20,0);
player:addItem(1551);
player:messageSpecial(ITEM_OBTAINED,1551);
player:setVar("CloudyOrbIsCracked",0);
elseif(player:hasItem(1551))then
player:addItem(1551); -- does not add the item but forces it to send the "you cannot carry anymore of these" message.
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1551);
end
elseif (option == 2 and BeastmensSeal >= 30) then -- Player asked for Sky orb
if(player:getFreeSlotsCount() >= 1 and player:hasItem(1552) == false) then
player:delSeals(30,0);
player:addItem(1552);
player:messageSpecial(ITEM_OBTAINED,1552);
player:setVar("SkyOrbIsCracked",0);
elseif(player:hasItem(1552))then
player:addItem(1552); -- does not add the item but forces it to send the "you cannot carry anymore of these" message.
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1552);
end
elseif (option == 3 and BeastmensSeal >= 40) then -- Player asked for Star orb
if(player:getFreeSlotsCount() >= 1 and player:hasItem(1131) == false) then
player:delSeals(40,0);
player:addItem(1131);
player:messageSpecial(ITEM_OBTAINED,1131);
player:setVar("StarOrbIsCracked",0);
elseif(player:hasItem(1131) == true)then
player:addItem(1131); -- does not add the item but forces it to send the "you cannot carry anymore of these" message.
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1131);
end
elseif (option == 4 and BeastmensSeal >= 50) then -- Player asked for Comet orb
if(player:getFreeSlotsCount() >= 1 and player:hasItem(1177) == false) then
player:delSeals(50,0);
player:addItem(1177);
player:messageSpecial(ITEM_OBTAINED,1177);
player:setVar("CometOrbIsCracked",0);
elseif(player:hasItem(1177))then
player:addItem(1177); -- does not add the item but forces it to send the "you cannot carry anymore of these" message.
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1177);
end
elseif (option == 5 and BeastmensSeal >= 60) then -- Player asked for Moon orb
if(player:getFreeSlotsCount() >= 1 and player:hasItem(1130) == false) then
player:delSeals(60,0);
player:addItem(1130);
player:messageSpecial(ITEM_OBTAINED,1130);
player:setVar("MoonOrbIsCracked",0);
elseif(player:hasItem(1130)) then
player:addItem(1130); -- does not add the item but forces it to send the "you cannot carry anymore of these" message.
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1130);
end
----------------------------------------------------------------------------------------------------------------------------
-------- Begin KSNM orb Handout --------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------
elseif (option == 6 and KindredsSeal >= 30) then -- Player asked for Clotho Orb
if(player:getFreeSlotsCount() >= 1 and player:hasItem(1175) == false) then
player:delSeals(30,1);
player:addItem(1175);
player:messageSpecial(ITEM_OBTAINED,1175);
player:setVar("ClothoOrbIsCracked",0);
elseif(player:hasItem(1175))then
player:addItem(1175); -- does not add the item but forces it to send the "you cannot carry anymore of these" message.
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1175);
end
elseif (option == 7 and KindredsSeal >= 30) then -- Player asked for Lachesis Orb
if(player:getFreeSlotsCount() >= 1 and player:hasItem(1178) == false) then
player:delSeals(30,1);
player:addItem(1178);
player:messageSpecial(ITEM_OBTAINED,1178);
player:setVar("LachesisOrbIsCracked",0);
elseif(player:hasItem(1178) == true)then
player:addItem(1178); -- does not add the item but forces it to send the "you cannot carry anymore of these" message.
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1178);
end
elseif (option == 8 and KindredsSeal >= 30) then -- Player asked for Atropos Orb
if(player:getFreeSlotsCount() >= 1 and player:hasItem(1180) == false) then
player:delSeals(30,1);
player:addItem(1180);
player:messageSpecial(ITEM_OBTAINED,1180);
player:setVar("AtroposOrbIsCracked",0);
elseif(player:hasItem(1180))then
player:addItem(1180); -- does not add the item but forces it to send the "you cannot carry anymore of these" message.
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1180);
end
elseif (option == 9 and KindredsSeal >= 99) then -- Player asked for Themis Orb
if(player:getFreeSlotsCount() >= 1 and player:hasItem(1553) == false) then
player:delSeals(99,1);
player:addItem(1553);
player:messageSpecial(ITEM_OBTAINED,1553);
player:setVar("ThemisOrbIsCracked",0);
elseif(player:hasItem(1553))then
player:addItem(1553); -- does not add the item but forces it to send the "you cannot carry anymore of these" message.
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1553);
end
end
-- TODO : Add in orbs for Kindred Crest exhcange (and High Kindred Crest) and find cutscene that tells you where you can bring it.
elseif (csid == 317) then
player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",17,true);
end
end; | gpl-3.0 |
FailcoderAddons/supervillain-ui | SVUI_UnitFrames/libs/Plugins/oUF_Reputation/oUF_Reputation.lua | 4 | 2908 | --GLOBAL NAMESPACE
local _G = _G;
--LUA
local unpack = _G.unpack;
local select = _G.select;
local assert = _G.assert;
local error = _G.error;
local print = _G.print;
local pairs = _G.pairs;
local next = _G.next;
local tostring = _G.tostring;
local type = _G.type;
--STRING
local string = _G.string;
local format = string.format;
--MATH
local math = _G.math;
local floor = math.floor
--BLIZZARD API
local UnitXP = _G.UnitXP;
local UnitXPMax = _G.UnitXPMax;
local GetXPExhaustion = _G.GetXPExhaustion;
local UnitSex = _G.UnitSex;
local GetText = _G.GetText;
local GetWatchedFactionInfo = _G.GetWatchedFactionInfo;
local FACTION_BAR_COLORS = _G.FACTION_BAR_COLORS;
local __, ns = ...
local oUF = ns.oUF or oUF
assert(oUF, 'oUF Reputation was unable to locate oUF install')
for tag, func in pairs({
['currep'] = function()
local __, __, min, __, value = GetWatchedFactionInfo()
return value - min
end,
['maxrep'] = function()
local __, __, min, max = GetWatchedFactionInfo()
return max - min
end,
['perrep'] = function()
local __, __, min, max, value = GetWatchedFactionInfo()
return math.floor((value - min) / (max - min) * 100 + 0.5)
end,
['standing'] = function()
local __, standing = GetWatchedFactionInfo()
return GetText('FACTION_STANDING_LABEL' .. standing, UnitSex('player'))
end,
['reputation'] = function()
return GetWatchedFactionInfo()
end,
}) do
oUF.Tags.Methods[tag] = func
oUF.Tags.Events[tag] = 'UPDATE_FACTION'
end
oUF.Tags.SharedEvents.UPDATE_FACTION = true
local function Update(self, event, unit)
local reputation = self.Reputation
local name, standing, min, max, value = GetWatchedFactionInfo()
if(not name) then
return reputation:Hide()
else
reputation:Show()
end
reputation:SetMinMaxValues(0, max - min)
reputation:SetValue(value - min)
if(reputation.colorStanding) then
local color = FACTION_BAR_COLORS[standing]
reputation:SetStatusBarColor(color.r, color.g, color.b)
end
if(reputation.PostUpdate) then
return reputation:PostUpdate(unit, name, standing, min, max, value)
end
end
local function Path(self, ...)
return (self.Reputation.Override or Update) (self, ...)
end
local function ForceUpdate(element)
return Path(element.__owner, 'ForceUpdate', element.__owner.unit)
end
local function Enable(self, unit)
local reputation = self.Reputation
if(reputation) then
reputation.__owner = self
reputation.ForceUpdate = ForceUpdate
self:RegisterEvent('UPDATE_FACTION', Path)
if(not reputation:GetStatusBarTexture()) then
reputation:SetStatusBarTexture([=[Interface\TargetingFrame\UI-StatusBar]=])
end
return true
end
end
local function Disable(self)
if(self.Reputation) then
self:UnregisterEvent('UPDATE_FACTION', Path)
end
end
oUF:AddElement('Reputation', Path, Enable, Disable)
| mit |
focusworld/aabb | plugins/lyrics.lua | 695 | 2113 | do
local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs'
local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5'
local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect'
local function getInfo(query)
print('Getting info of ' .. query)
local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY
..'&q='..URL.escape(query)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local result = json:decode(b)
local artist = result[1].artist.name
local track = result[1].title
return artist, track
end
local function getLyrics(query)
local artist, track = getInfo(query)
if artist and track then
local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist)
..'&song='..URL.escape(track)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local xml = require("xml")
local result = xml.load(b)
if not result then
return nil
end
if xml.find(result, 'LyricSong') then
track = xml.find(result, 'LyricSong')[1]
end
if xml.find(result, 'LyricArtist') then
artist = xml.find(result, 'LyricArtist')[1]
end
local lyric
if xml.find(result, 'Lyric') then
lyric = xml.find(result, 'Lyric')[1]
else
lyric = nil
end
local cover
if xml.find(result, 'LyricCovertArtUrl') then
cover = xml.find(result, 'LyricCovertArtUrl')[1]
else
cover = nil
end
return artist, track, lyric, cover
else
return nil
end
end
local function run(msg, matches)
local artist, track, lyric, cover = getLyrics(matches[1])
if track and artist and lyric then
if cover then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, cover)
end
return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric
else
return 'Oops! Lyrics not found or something like that! :/'
end
end
return {
description = 'Getting lyrics of a song',
usage = '!lyrics [track or artist - track]: Search and get lyrics of the song',
patterns = {
'^!lyrics? (.*)$'
},
run = run
}
end
| gpl-2.0 |
nesstea/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Khaf_Jhifanm.lua | 13 | 1349 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Khaf Jhifanm
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,KHAFJHIFANM_SHOP_DIALOG);
stock = {0x15BF,200, -- Dried Date
0x15C8,800, -- Ayran
0x15D6,3750, -- balik Sandvici
0x08BB,320, -- Wildgrass Seeds
0x13D3,4400, -- Scroll of Raptor Mazurka
0x0b38,10000} -- Empire Waystone
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Windurst_Waters/npcs/Chamama.lua | 12 | 6577 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Chamama
-- Involved In Quest: Inspector's Gadget
-- Starts Quest: In a Pickle
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Windurst_Waters/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/globals/titles");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
FakeMoustache = player:hasKeyItem(FAKE_MOUSTACHE);
InvisibleManSticker = player:hasKeyItem(INVISIBLE_MAN_STICKER);
InAPickle = player:getQuestStatus(WINDURST,IN_A_PICKLE);
count = trade:getItemCount();
gil = trade:getGil();
if ((InAPickle == QUEST_ACCEPTED or InAPickle == QUEST_COMPLETED) and trade:hasItemQty(583,1) == true and count == 1 and gil == 0) then
rand = math.random(1,4);
if (rand <= 2) then
if (InAPickle == QUEST_ACCEPTED) then
player:startEvent(0x0293); -- IN A PICKLE: Quest Turn In (1st Time)
elseif (InAPickle == QUEST_COMPLETED) then
player:startEvent(0x0296,200);
end
elseif (rand == 3) then
player:startEvent(0x0291); -- IN A PICKLE: Too Light
player:tradeComplete(trade);
elseif (rand == 4) then
player:startEvent(0x0292); -- IN A PICKLE: Too Small
player:tradeComplete(trade);
end
elseif (FakeMoustache == false) then
InspectorsGadget = player:getQuestStatus(WINDURST,INSPECTOR_S_GADGET);
if (InspectorsGadget == QUEST_ACCEPTED) then
count = trade:getItemCount();
SarutaCotton = trade:hasItemQty(834,4);
if (SarutaCotton == true and count == 4) then
player:startEvent(0x0228);
end
end
elseif (InvisibleManSticker == false) then
ThePromise = player:getQuestStatus(WINDURST,THE_PROMISE);
if (ThePromise == QUEST_ACCEPTED) then
count = trade:getItemCount();
ShoalWeed = trade:hasItemQty(1148,1);
if (ShoalWeed == true and count == 1) then
player:startEvent(0x031f,0,0,INVISIBLE_MAN_STICKER);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
InspectorsGadget = player:getQuestStatus(WINDURST,INSPECTOR_S_GADGET);
ThePromise = player:getQuestStatus(WINDURST,THE_PROMISE);
InAPickle = player:getQuestStatus(WINDURST,IN_A_PICKLE);
NeedToZone = player:needToZone();
if (ThePromise == QUEST_ACCEPTED) then
InvisibleManSticker = player:hasKeyItem(INVISIBLE_MAN_STICKER);
if (InvisibleManSticker == true) then
player:startEvent(0x0320);
else
ThePromiseVar = player:getVar("ThePromise");
if (ThePromiseVar == 1) then
player:startEvent(0x031e,0,1148,INVISIBLE_MAN_STICKER);
else
player:startEvent(0x031d,0,1148,INVISIBLE_MAN_STICKER);
end
end
elseif (InspectorsGadget == QUEST_ACCEPTED) then
FakeMoustache = player:hasKeyItem(FAKE_MOUSTACHE);
printf("mustach check");
if (FakeMoustache == true) then
player:startEvent(0x0229);
else
player:startEvent(0x0227,0,FAKE_MOUSTACHE);
end
elseif (InAPickle == QUEST_AVAILABLE and NeedToZone == false) then
rand = math.random(1,2);
if (rand == 1) then
player:startEvent(0x028e,0,4444); -- IN A PICKLE + RARAB TAIL: Quest Begin
else
player:startEvent(0x028b); -- Standard Conversation
end
elseif (InAPickle == QUEST_ACCEPTED or player:getVar("QuestInAPickle_var") == 1) then
player:startEvent(0x028f,0,4444); -- IN A PICKLE + RARAB TAIL: Quest Objective Reminder
elseif (InAPickle == QUEST_COMPLETED and NeedToZone) then
player:startEvent(0x0294); -- IN A PICKLE: After Quest
elseif (InAPickle == QUEST_COMPLETED and NeedToZone == false and player:getVar("QuestInAPickle_var") ~= 1) then
rand = math.random(1,2)
if (rand == 1) then
player:startEvent(0x0295); -- IN A PICKLE: Repeatable Quest Begin
else
player:startEvent(0x028b); -- Standard Conversation
end
else
player:startEvent(0x028b); -- Standard Conversation
end
-- player:delQuest(WINDURST,IN_A_PICKLE); [[[[[[[[[[[[[ FOR TESTING ONLY ]]]]]]]]]]]]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0228) then
player:tradeComplete();
player:addKeyItem(FAKE_MOUSTACHE);
player:messageSpecial(KEYITEM_OBTAINED,FAKE_MOUSTACHE);
elseif (csid == 0x031d) then
player:setVar("ThePromise",1);
elseif (csid == 0x031f) then
player:tradeComplete();
player:addKeyItem(INVISIBLE_MAN_STICKER);
player:messageSpecial(KEYITEM_OBTAINED,INVISIBLE_MAN_STICKER);
elseif (csid == 0x028e and option == 1) then -- IN A PICKLE + RARAB TAIL: Quest Begin
player:addQuest(WINDURST,IN_A_PICKLE);
elseif (csid == 0x0293) then -- IN A PICKLE: Quest Turn In (1st Time)
player:tradeComplete(trade);
player:completeQuest(WINDURST,IN_A_PICKLE);
player:needToZone(true);
player:addItem(12505);
player:messageSpecial(ITEM_OBTAINED,12505);
player:addGil(GIL_RATE*200);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*200);
player:addFame(WINDURST,75);
elseif (csid == 0x0295 and option == 1) then
player:setVar("QuestInAPickle_var",1)
elseif (csid == 0x0296) then -- IN A PICKLE + 200 GIL: Repeatable Quest Turn In
player:tradeComplete(trade);
player:needToZone(true);
player:addGil(GIL_RATE*200);
player:addFame(WINDURST,8);
player:setVar("QuestInAPickle_var",0)
end
end;
| gpl-3.0 |
hussian/hell_iraq | plugins/ar-h3.lua | 2 | 2072 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY(@AHMED_ALOBIDE) ▀▄ ▄▀
▀▄ ▄▀ BY(@hussian_9) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ (ملف الاوامر 3) ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
do
local function run(msg, matches)
if is_momod(msg) and matches[1]== "اوامر 3" then
return [[
💀THE LAND OF THE FIRE💀
➖➖➖➖➖➖➖➖➖➖
◻️اوامر المطورين فقط لتلعب بكيفك◻️
➖➖➖➖➖➖➖➖➖➖
🔲ترقيه سوبر (لترقية المجموعه سوبر)
🔲تفعيل (لتفعيل البوت ب المجموعه)
🔲تعطيل(لتعطيل البوت ب المجموعه)
🔲رفع المدير (لرفع مدير للمجموعه)
🔲رفع اداري(لرفع اداري للمجموعه)
🔲اذاعه (لنشر كلمة بجميع مجموعات البوت)
🔲تشغيل البوت (لتشغيل البوت بالمجموعة)
🔲اطفاء البوت (لاطفاء البوت بالمجموعه)
🔲اضف مطور (لاضافة مطور)
🔲طرد البوت (لطرد البوت من المجموعه)
🔲جلب ملف (لجلب ملف من السيرفر)
🔲اصدار (لعرض محتويات البوت)
🔲اضف بوت + الرابط لضافة البوت للمجموعة)
🔲صنع مجموعه + اسم لعمل مجموعه
➖➖➖➖➖➖➖➖➖➖
🕵المطور @AHMED_ALOBIDE
🕵المطور @hussian_9
]]
end
if not is_momod(msg) then
return "مو شغلك ودعبل 😎🖕🏿"
end
end
return {
description = "Help list",
usage = "Help list",
patterns = {
"(اوامر 3)"
},
run = run
}
end | gpl-2.0 |
nesstea/darkstar | scripts/zones/Dynamis-Windurst/Zone.lua | 21 | 2390 | -----------------------------------
--
-- Zone: Dynamis-Windurst
--
-----------------------------------
package.loaded["scripts/zones/Dynamis-Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Dynamis-Windurst/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaWindurst]UniqueID")) then
if (player:isBcnmsFull() == 1) then
if (player:hasStatusEffect(EFFECT_DYNAMIS, 0) == false) then
inst = player:addPlayerToDynamis(1282);
if (inst == 1) then
player:bcnmEnter(1282);
else
cs = 0;
end
else
player:bcnmEnter(1282);
end
else
inst = player:bcnmRegister(1282);
if (inst == 1) then
player:bcnmEnter(1282);
else
cs = 0;
end
end
else
cs = 0;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0) then
player:setPos(-217.000,1.000,-119.000,94,0xEF);
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Animated_Staff.lua | 7 | 1502 | -----------------------------------
-- Area: Dynamis Xarcabard
-- MOB: Animated Staff
-----------------------------------
require("scripts/globals/status");
require("scripts/zones/Dynamis-Xarcabard/TextIDs");
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if (mob:AnimationSub() == 3) then
SetDropRate(115,1582,1000);
else
SetDropRate(115,1582,0);
end
target:showText(mob,ANIMATED_STAFF_DIALOG);
SpawnMob(17330337,120):updateEnmity(target);
SpawnMob(17330338,120):updateEnmity(target);
SpawnMob(17330339,120):updateEnmity(target);
SpawnMob(17330347,120):updateEnmity(target);
SpawnMob(17330348,120):updateEnmity(target);
SpawnMob(17330349,120):updateEnmity(target);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
-- TODO: add battle dialog
end;
-----------------------------------
-- onMobDisengage
-----------------------------------
function onMobDisengage(mob)
mob:showText(mob,ANIMATED_STAFF_DIALOG+2);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
ally:showText(mob,ANIMATED_STAFF_DIALOG+1);
DespawnMob(17330337);
DespawnMob(17330338);
DespawnMob(17330339);
DespawnMob(17330347);
DespawnMob(17330348);
DespawnMob(17330349);
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/La_Vaule_[S]/Zone.lua | 22 | 1316 | -----------------------------------
--
-- Zone: La_Vaule_[S] (85)
--
-----------------------------------
package.loaded["scripts/zones/La_Vaule_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/La_Vaule_[S]/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(236.547,-2.25,20,120);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Palborough_Mines/npcs/qm1.lua | 8 | 1290 | -----------------------------------
-- Area: Palborough Mines
-- NPC: ???
-- Involved In Quest: The Talekeeper's Truth
-- @zone 143
-- @pos 15 -31 -94
-----------------------------------
package.loaded["scripts/zones/Palborough_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Palborough_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getVar("theTalekeeperTruthCS") == 3) then
player:messageSpecial(SENSE_OF_FOREBODING);
SpawnMob(17363318,180):updateClaim(player);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
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 |
mhmspm/z | plugins/fun.lua | 1 | 14432 |
--Special Thx To @To0fan
--------------------------------
local function run_bash(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
return result
end
--------------------------------
local api_key = nil
local base_api = "https://maps.googleapis.com/maps/api"
--------------------------------
local function get_latlong(area)
local api = base_api .. "/geocode/json?"
local parameters = "address=".. (URL.escape(area) or "")
if api_key ~= nil then
parameters = parameters .. "&key="..api_key
end
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
lat = data.results[1].geometry.location.lat
lng = data.results[1].geometry.location.lng
acc = data.results[1].geometry.location_type
types= data.results[1].types
return lat,lng,acc,types
end
end
--------------------------------
local function get_staticmap(area)
local api = base_api .. "/staticmap?"
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
--------------------------------
local function get_weather(location)
print("Finding weather in ", location)
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local url = BASE_URL
url = url..'?q='..location..'&APPID=eedbc05ba060c787ab0614cad1f2e12b'
url = url..'&units=metric'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'دمای شهر '..city..' هم اکنون '..weather.main.temp..' درجه سانتی گراد می باشد\n____________________\n :)'
local conditions = 'شرایط فعلی آب و هوا : '
if weather.weather[1].main == 'Clear' then
conditions = conditions .. 'آفتابی☀'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. 'ابری ☁☁'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. 'بارانی ☔'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. 'طوفانی ☔☔☔☔'
elseif weather.weather[1].main == 'Mist' then
conditions = conditions .. 'مه 💨'
end
return temp .. '\n' .. conditions
end
--------------------------------
local function calc(exp)
url = 'http://api.mathjs.org/v1/'
url = url..'?expr='..URL.escape(exp)
b,c = http.request(url)
text = nil
if c == 200 then
text = 'Result = '..b..'\n____________________\n :)'
elseif c == 400 then
text = b
else
text = 'Unexpected error\n'
..'Is api.mathjs.org up?'
end
return text
end
--------------------------------
function exi_file(path, suffix)
local files = {}
local pth = tostring(path)
local psv = tostring(suffix)
for k, v in pairs(scandir(pth)) do
if (v:match('.'..psv..'$')) then
table.insert(files, v)
end
end
return files
end
--------------------------------
function file_exi(name, path, suffix)
local fname = tostring(name)
local pth = tostring(path)
local psv = tostring(suffix)
for k,v in pairs(exi_file(pth, psv)) do
if fname == v then
return true
end
end
return false
end
--------------------------------
function run(msg, matches)
if matches[1]:lower() == "calc" and matches[2] then
if msg.to.type == "pv" then
return
end
return calc(matches[2])
end
--------------------------------
if matches[1]:lower() == 'praytime' or matches[1] == 'azan' then
if matches[2] then
city = matches[2]
elseif not matches[2] then
city = 'Tehran'
end
local lat,lng,url = get_staticmap(city)
local dumptime = run_bash('date +%s')
local code = http.request('http://api.aladhan.com/timings/'..dumptime..'?latitude='..lat..'&longitude='..lng..'&timezonestring=Asia/Tehran&method=7')
local jdat = json:decode(code)
local data = jdat.data.timings
local text = 'شهر: '..city
text = text..'\nاذان صبح: '..data.Fajr
text = text..'\nطلوع آفتاب: '..data.Sunrise
text = text..'\nاذان ظهر: '..data.Dhuhr
text = text..'\nغروب آفتاب: '..data.Sunset
text = text..'\nاذان مغرب: '..data.Maghrib
text = text..'\nعشاء : '..data.Isha
text = text..'\n\n'
return tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html')
end
--------------------------------
if matches[1]:lower() == 'tophoto' and msg.reply_id then
function tophoto(arg, data)
function tophoto_cb(arg,data)
if data.content_.sticker_ then
local file = data.content_.sticker_.sticker_.path_
local secp = tostring(tcpath)..'/data/sticker/'
local ffile = string.gsub(file, '-', '')
local fsecp = string.gsub(secp, '-', '')
local name = string.gsub(ffile, fsecp, '')
local sname = string.gsub(name, 'webp', 'jpg')
local pfile = 'data/photos/'..sname
local pasvand = 'webp'
local apath = tostring(tcpath)..'/data/sticker'
if file_exi(tostring(name), tostring(apath), tostring(pasvand)) then
os.rename(file, pfile)
tdcli.sendPhoto(msg.to.id, 0, 0, 1, nil, pfile, "", dl_cb, nil)
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This sticker does not exist. Send sticker again._', 1, 'md')
end
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This is not a sticker._', 1, 'md')
end
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = data.id_ }, tophoto_cb, nil)
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = msg.reply_id }, tophoto, nil)
end
--------------------------------
if matches[1]:lower() == 'tosticker' and msg.reply_id then
function tosticker(arg, data)
function tosticker_cb(arg,data)
if data.content_.ID == 'MessagePhoto' then
file = data.content_.photo_.id_
local pathf = tcpath..'/data/photo/'..file..'_(1).jpg'
local pfile = 'data/photos/'..file..'.webp'
if file_exi(file..'_(1).jpg', tcpath..'/data/photo', 'jpg') then
os.rename(pathf, pfile)
tdcli.sendDocument(msg.chat_id_, 0, 0, 1, nil, pfile, '', dl_cb, nil)
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This photo does not exist. Send photo again._', 1, 'md')
end
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This is not a photo._', 1, 'md')
end
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = data.id_ }, tosticker_cb, nil)
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = msg.reply_id }, tosticker, nil)
end
--------------------------------
if matches[1]:lower() == 'weather' then
city = matches[2]
local wtext = get_weather(city)
if not wtext then
wtext = 'مکان وارد شده صحیح نیست'
end
return wtext
end
--------------------------------
if matches[1]:lower() == 'time' then
local url , res = http.request('http://api.gpmod.ir/time/')
if res ~= 200 then
return "No connection"
end
local colors = {'blue','green','yellow','magenta','Orange','DarkOrange','red'}
local fonts = {'mathbf','mathit','mathfrak','mathrm'}
local jdat = json:decode(url)
local url = 'http://latex.codecogs.com/png.download?'..'\\dpi{600}%20\\huge%20\\'..fonts[math.random(#fonts)]..'{{\\color{'..colors[math.random(#colors)]..'}'..jdat.ENtime..'}}'
local file = download_to_file(url,'time.webp')
tdcli.sendDocument(msg.to.id, 0, 0, 1, nil, file, '', dl_cb, nil)
end
--------------------------------
if matches[1] == 'voice' then
local text = matches[2]
textc = text:gsub(' ','.')
if msg.to.type == 'pv' then
return nil
else
local url = "http://tts.baidu.com/text2audio?lan=en&ie=UTF-8&text="..textc
local file = download_to_file(url,'BD-Reborn.mp3')
tdcli.sendDocument(msg.to.id, 0, 0, 1, nil, file, '', dl_cb, nil)
end
end
--------------------------------
if matches[1] == "tr" then
url = https.request('https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20160119T111342Z.fd6bf13b3590838f.6ce9d8cca4672f0ed24f649c1b502789c9f4687a&format=plain&lang='..URL.escape(matches[2])..'&text='..URL.escape(matches[3]))
data = json:decode(url)
return 'زبان : '..data.lang..'\nترجمه : '..data.text[1]..'\n____________________\n :)'
end
--------------------------------
if matches[1]:lower() == 'short' then
if matches[2]:match("[Hh][Tt][Tt][Pp][Ss]://") then
shortlink = matches[2]
elseif not matches[2]:match("[Hh][Tt][Tt][Pp][Ss]://") then
shortlink = "https://"..matches[2]
end
local yon = http.request('http://api.yon.ir/?url='..URL.escape(shortlink))
local jdat = json:decode(yon)
local bitly = https.request('https://api-ssl.bitly.com/v3/shorten?access_token=f2d0b4eabb524aaaf22fbc51ca620ae0fa16753d&longUrl='..URL.escape(shortlink))
local data = json:decode(bitly)
local yeo = http.request('http://yeo.ir/api.php?url='..URL.escape(shortlink)..'=')
local opizo = http.request('http://api.gpmod.ir/shorten/?url='..URL.escape(shortlink)..'&username=mersad565@gmail.com')
local u2s = http.request('http://u2s.ir/?api=1&return_text=1&url='..URL.escape(shortlink))
local llink = http.request('http://llink.ir/yourls-api.php?signature=a13360d6d8&action=shorturl&url='..URL.escape(shortlink)..'&format=simple')
local text = ' 🌐لینک اصلی :\n'..check_markdown(data.data.long_url)..'\n\nلینکهای کوتاه شده با 6 سایت کوتاه ساز لینک : \n》کوتاه شده با bitly :\n___________________________\n'..check_markdown(data.data.url)..'\n___________________________\n》کوتاه شده با yeo :\n'..check_markdown(yeo)..'\n___________________________\n》کوتاه شده با اوپیزو :\n'..check_markdown(opizo)..'\n___________________________\n》کوتاه شده با u2s :\n'..check_markdown(u2s)..'\n___________________________\n》کوتاه شده با llink : \n'..check_markdown(llink)..'\n___________________________\n》لینک کوتاه شده با yon : \nyon.ir/'..check_markdown(jdat.output)..'\n____________________\n :)'
return tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html')
end
--------------------------------
if matches[1]:lower() == "sticker" then
local eq = URL.escape(matches[2])
local w = "500"
local h = "500"
local txtsize = "100"
local txtclr = "ff2e4357"
if matches[3] then
txtclr = matches[3]
end
if matches[4] then
txtsize = matches[4]
end
if matches[5] and matches[6] then
w = matches[5]
h = matches[6]
end
local url = "https://assets.imgix.net/examples/clouds.jpg?blur=150&w="..w.."&h="..h.."&fit=crop&txt="..eq.."&txtsize="..txtsize.."&txtclr="..txtclr.."&txtalign=middle,center&txtfont=Futura%20Condensed%20Medium&mono=ff6598cc"
local receiver = msg.to.id
local file = download_to_file(url,'text.webp')
tdcli.sendDocument(msg.to.id, 0, 0, 1, nil, file, '', dl_cb, nil)
end
--------------------------------
if matches[1]:lower() == "photo" then
local eq = URL.escape(matches[2])
local w = "500"
local h = "500"
local txtsize = "100"
local txtclr = "ff2e4357"
if matches[3] then
txtclr = matches[3]
end
if matches[4] then
txtsize = matches[4]
end
if matches[5] and matches[6] then
w = matches[5]
h = matches[6]
end
local url = "https://assets.imgix.net/examples/clouds.jpg?blur=150&w="..w.."&h="..h.."&fit=crop&txt="..eq.."&txtsize="..txtsize.."&txtclr="..txtclr.."&txtalign=middle,center&txtfont=Futura%20Condensed%20Medium&mono=ff6598cc"
local receiver = msg.to.id
local file = download_to_file(url,'text.jpg')
tdcli.sendPhoto(msg.to.id, 0, 0, 1, nil, file, "", dl_cb, nil)
end
--------------------------------
if matches[1] == "helpfun" then
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not lang then
helpfun = [[
_ Fun Help Commands:_
*!time*
_Get time in a sticker_
*!short* `[link]`
_Make short url_
*!voice* `[text]`
_Convert text to voice_
*!tr* `[lang] [word]`
_Translates FA to EN and EN to FA_
_Example:_
*!tr fa hi*
*!sticker* `[word]`
_Convert text to sticker_
*!photo* `[word]`
_Convert text to photo_
*!azan* `[city]`
_Get Azan time for your city_
*!calc* `[number]`
Calculator
*!praytime* `[city]`
_Get Patent (Pray Time)_
*!tosticker* `[reply]`
_Convert photo to sticker_
*!tophoto* `[reply]`
_Convert text to photo_
*!weather* `[city]`
_Get weather_
_You can use_ *[!/#]* _at the beginning of commands._
*Good luck ;)*]]
tdcli.sendMessage(msg.chat_id_, 0, 1, helpfun, 1, 'md')
else
helpfun = [[
_راهنمای فان ربات:_
*!time*
_دریافت ساعت به صورت استیکر_
*!short* `[link]`
_کوتاه کننده لینک_
*!voice* `[text]`
_تبدیل متن به صدا_
*!tr* `[lang]` `[word]`
_ترجمه متن فارسی به انگلیسی وبرعکس_
_مثال:_
_!tr en سلام_
*!sticker* `[word]`
_تبدیل متن به استیکر_
*!photo* `[word]`
_تبدیل متن به عکس_
*!azan* `[city]`
_دریافت اذان_
*!calc* `[number]`
_ماشین حساب_
*!praytime* `[city]`
_اعلام ساعات شرعی_
*!tosticker* `[reply]`
_تبدیل عکس به استیکر_
*!tophoto* `[reply]`
_تبدیل استیکربه عکس_
*!weather* `[city]`
_دریافت اب وهوا_
*شما میتوانید از [!/#] در اول دستورات برای اجرای آنها بهره بگیرید*
موفق باشید ;)]]
tdcli.sendMessage(msg.chat_id_, 0, 1, helpfun, 1, 'md')
end
end
end
--------------------------------
return {
patterns = {
"^[!/#](helpfun)$",
"^[!/#](weather) (.*)$",
"^[!/](calc) (.*)$",
"^[#!/](time)$",
"^[#!/](tophoto)$",
"^[#!/](tosticker)$",
"^[!/#](voice) +(.*)$",
"^[/!#]([Pp]raytime) (.*)$",
"^[/!#](praytime)$",
"^[/!#]([Aa]zan) (.*)$",
"^[/!#](azan)$",
"^[!/]([Tt]r) ([^%s]+) (.*)$",
"^[!/]([Ss]hort) (.*)$",
"^[!/](photo) (.+)$",
"^[!/](sticker) (.+)$"
},
run = run,
}
| gpl-3.0 |
ielnehc/ltmh | tools/waf/init.lua | 1 | 5783 | require 'config'
local match = string.match
local ngxmatch=ngx.re.match
local unescape=ngx.unescape_uri
local get_headers = ngx.req.get_headers
local optionIsOn = function (options) return options == "on" and true or false end
logpath = logdir
rulepath = RulePath
UrlDeny = optionIsOn(UrlDeny)
PostCheck = optionIsOn(postMatch)
CookieCheck = optionIsOn(cookieMatch)
WhiteCheck = optionIsOn(whiteModule)
PathInfoFix = optionIsOn(PathInfoFix)
attacklog = optionIsOn(attacklog)
CCDeny = optionIsOn(CCDeny)
Redirect=optionIsOn(Redirect)
function getClientIp()
IP = ngx.req.get_headers()["X-Real-IP"]
if IP == nil then
IP = ngx.var.remote_addr
end
if IP == nil then
IP = "unknown"
end
return IP
end
function write(logfile,msg)
local fd = io.open(logfile,"ab")
if fd == nil then return end
fd:write(msg)
fd:flush()
fd:close()
end
function log(method,url,data,ruletag)
if attacklog then
local realIp = getClientIp()
local ua = ngx.var.http_user_agent
local servername=ngx.var.server_name
local time=ngx.localtime()
if ua then
line = realIp.." ["..time.."] \""..method.." "..servername..url.."\" \""..data.."\" \""..ua.."\" \""..ruletag.."\"\n"
else
line = realIp.." ["..time.."] \""..method.." "..servername..url.."\" \""..data.."\" - \""..ruletag.."\"\n"
end
local filename = logpath..'/'..servername.."_"..ngx.today().."_sec.log"
write(filename,line)
end
end
------------------------------------规则读取函数-------------------------------------------------------------------
function read_rule(var)
file = io.open(rulepath..'/'..var,"r")
if file==nil then
return
end
t = {}
for line in file:lines() do
table.insert(t,line)
end
file:close()
return(t)
end
urlrules=read_rule('url')
argsrules=read_rule('args')
uarules=read_rule('user-agent')
wturlrules=read_rule('whiteurl')
postrules=read_rule('post')
ckrules=read_rule('cookie')
function say_html()
if Redirect then
ngx.header.content_type = "text/html"
ngx.say(html)
ngx.exit(200)
end
end
function whiteurl()
if WhiteCheck then
if wturlrules ~=nil then
for _,rule in pairs(wturlrules) do
if ngxmatch(ngx.var.request_uri,rule,"imjo") then
return true
end
end
end
end
return false
end
function args()
for _,rule in pairs(argsrules) do
local args = ngx.req.get_uri_args()
for key, val in pairs(args) do
if type(val)=='table' then
data=table.concat(val, " ")
else
data=val
end
if data and type(data) ~= "boolean" and rule ~="" and ngxmatch(unescape(data),rule,"imjo") then
log('GET',ngx.var.request_uri,"-",rule)
say_html()
return true
end
end
end
return false
end
function url()
if UrlDeny then
for _,rule in pairs(urlrules) do
if rule ~="" and ngxmatch(ngx.var.request_uri,rule,"imjo") then
log('GET',ngx.var.request_uri,"-",rule)
say_html()
return true
end
end
end
return false
end
function ua()
local ua = ngx.var.http_user_agent
if ua ~= nil then
for _,rule in pairs(uarules) do
if rule ~="" and ngxmatch(ua,rule,"imjo") then
log('UA',ngx.var.request_uri,"-",rule)
say_html()
return true
end
end
end
return false
end
function body(data)
for _,rule in pairs(postrules) do
if rule ~="" and ngxmatch(unescape(data),rule,"imjo") then
log('POST',ngx.var.request_uri,data,rule)
say_html()
return true
end
end
return false
end
function cookie()
local ck = ngx.var.http_cookie
if CookieCheck and ck then
for _,rule in pairs(ckrules) do
if rule ~="" and ngxmatch(ck,rule,"imjo") then
log('Cookie',ngx.var.request_uri,"-",rule)
say_html()
return true
end
end
end
return false
end
function denycc()
if CCDeny then
local uri=ngx.var.uri
CCcount=tonumber(string.match(CCrate,'(.*)/'))
CCseconds=tonumber(string.match(CCrate,'/(.*)'))
local token = getClientIp()..uri
local limit = ngx.shared.limit
local req,_=limit:get(token)
if req then
if req > CCcount then
ngx.exit(503)
return true
else
limit:incr(token,1)
end
else
limit:set(token,1,CCseconds)
end
end
return false
end
function get_boundary()
local header = get_headers()["content-type"]
if not header then
return nil
end
if type(header) == "table" then
header = header[1]
end
local m = match(header, ";%s*boundary=\"([^\"]+)\"")
if m then
return m
end
return match(header, ";%s*boundary=([^\",;]+)")
end
function whiteip()
if next(ipWhitelist) ~= nil then
for _,ip in pairs(ipWhitelist) do
if getClientIp()==ip then
return true
end
end
end
return false
end
function blockip()
if next(ipBlocklist) ~= nil then
for _,ip in pairs(ipBlocklist) do
if getClientIp()==ip then
ngx.exit(403)
return true
end
end
end
return false
end
| mit |
nesstea/darkstar | scripts/zones/Gusgen_Mines/npcs/_5g7.lua | 13 | 2971 | -----------------------------------
-- Area: Gusgen Mines
-- NPC: Strange Apparatus
-- @pos: 219 -39 255 196
-----------------------------------
package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil;
require("scripts/zones/Gusgen_Mines/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(0x0002, 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(0x0000, 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 == 0x0000) 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 == 0x0002) 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 |
UnfortunateFruit/darkstar | scripts/zones/Ghelsba_Outpost/bcnms/holy_crest.lua | 13 | 2115 | -----------------------------------
-- Area: Ghelsba Outpost
-- Name: Holy Crest - DRG flag quest
-- @pos -162 -11 78 140
-----------------------------------
package.loaded["scripts/zones/Ghelsba_Outpost/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/pets");
require("scripts/zones/Ghelsba_Outpost/TextIDs");
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print(leave code ..leavecode);
if(leavecode == 2) then --play end CS. Need time and battle id for record keeping + storage
if(player:getQuestStatus(SANDORIA,THE_HOLY_CREST) == QUEST_ACCEPTED) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,1);
end
elseif(leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print(bc update csid ..csid.. and option ..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid: "..csid.."and option: "..option);
if(csid == 0x7d01 and option ~= 0 and player:hasKeyItem(DRAGON_CURSE_REMEDY) == true) then
player:addTitle(HEIR_TO_THE_HOLY_CREST);
player:delKeyItem(DRAGON_CURSE_REMEDY);
player:unlockJob(14);
player:messageSpecial(YOU_CAN_NOW_BECOME_A_DRAGOON);
player:setVar("TheHolyCrest_Event",0);
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,THE_HOLY_CREST);
player:setPetName(PETTYPE_WYVERN,option);
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/RuLude_Gardens/npcs/Rainhard.lua | 13 | 1052 | -----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: Rainhard
-- Type: Standard NPC
-- @zone: 243
-- @pos -2.397 -5.999 68.749
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0022);
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 |
nesstea/darkstar | scripts/globals/weaponskills/tachi_kagero.lua | 9 | 1534 | -----------------------------------
-- Tachi Kagero
-- Great Katana weapon skill
-- Skill Level: 100
-- Deals fire elemental damage to enemy. Damage varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Flame Gorget.
-- Aligned with the Flame Belt.
-- Element: Fire
-- Modifiers: STR:75%
-- 100%TP 200%TP 300%TP
-- .5 .75 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 0.5; params.ftp200 = 0.75; params.ftp300 = 1;
params.str_wsc = 0.75; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
aekazakov/narrative | docker/proxy_mgr.lua | 4 | 46066 | --
-- REST based HTTP service that allows you to query/modify the contents of an
-- nginx shared memory DICT object.
--
-- bind this via an access_by_lua_file directive in nginx.conf
-- make sure that there is an nginx variable called uri_base in the current
-- context - it is used in parsing out the URI path
-- Used to implement a dynamic reverse proxy for KBase Narrative project
--
-- The following ngx.shared.DICT need to be declared in the main config, or
-- else use different names and pass them in during initialization:
--
-- session_map
-- docker_map
-- token_cache
-- proxy_mgr
--
-- author: Steve Chan sychan@lbl.gov
--
-- Copyright 2013 The Regents of the University of California,
-- Lawrence Berkeley National Laboratory
-- United States Department of Energy
-- The DOE Systems Biology Knowledgebase (KBase)
-- Made available under the KBase Open Source License
--
--
local M = {}
local auth_cookie_name = "kbase_session"
local lock_opts = {
exptime = 5,
timeout = 5
}
-- regexes for matching/validating keys and ids
local key_regex = "[%w_%-%.]+"
local id_regex = "%x+"
-- packages to load
local json = require('json')
local p = require('pl.pretty')
local notemgr = require('notelauncher')
local locklib = require("resty.lock")
local httplib = require("resty.http")
local httpclient = httplib:new()
-- forward declare the functions in this module
local est_connections
local sweeper
local check_sweeper
local marker
local check_marker
local provisioner
local check_provisioner
local initialize
local narrative_shutdown
local set_proxy
local url_decode
local get_session
local sync_sessions
local sync_containers
local new_container
local assign_container
local use_proxy
-- this are name/value pairs referencing ngx.shared.DICT objects
-- that we use to track docker containers. The ngx.shared.DICT
-- implementation only supports basic scalar types, so we need a
-- couple of these instead of using a common table object
-- session_map maps a session key (kbase token userid) to a whitespace seperated list of:
-- 1. ip/port proxy target (eg. '127.0.0.1:49000')
-- 2. docker ID
-- docker_map maps a docker ID to a whitespace seperated list of:
-- 1. state of container: 'queued', 'active', 'idle'
-- 2. ip/port of container
-- 3. session assigned to container (same as in session_map), '*' if none
-- 4. time value (os.time) of last activity
-- 5. IP that last connected
-- token_cache is cache of validated tokens
local session_map = nil
local docker_map = nil
local token_cache = nil
-- This is a dictionary for storing proxy manager internal state
-- The following names are currently supported
-- 'next_sweep' - this stores the next time() the sweeper is scheduled
-- to be run. It is cleared when the sweeper runs, and
-- set when the sweeper is rescheduled. If we notice that
-- 'next_sweep' is either relatively far in the past, or
-- not set, we generate a warning in the logs and schedule
-- an semi-immediate asynchronous sweeper run
-- 'next_mark' - this stores the next time() the marker is scheduled
-- to be run. It is cleared when the marker runs, and
-- set when the marker is rescheduled. If we notice that
-- 'next_mark' is either relatively far in the past, or
-- not set, we generate a warning in the logs and schedule
-- an immediate marker run
-- 'next_provision' - this stores the next time() the provisioner is scheduled
-- to be run. It is cleared when the provisioner runs, and
-- set when the provisioner is rescheduled. If we notice that
-- 'next_provision' is either relatively far in the past, or
-- not set, we generate a warning in the logs and schedule
-- an immediate provisioner run
local proxy_mgr = nil
-- strangely, init_by_lua seems to run the initialize() method twice,
-- use this flag to avoid reinitializing
local initialized = nil
-- Command to run in order to get netstat info for tcp connections in
-- pure numeric form (no DNS or service name lookups)
local NETSTAT = 'netstat -nt'
-- Base URL for Globus Online Nexus API
-- the non-clocking client library we are using, resty.http, doesn't
-- support https, so we depend on a locally configured Nginx
-- reverse proxy to actually perform the request
nexus_url = 'http://127.0.0.1:65001/users/'
-- name of shared dict for locking library
M.lock_name = "lock_map"
-- How often (in seconds) does the sweeper wake up to delete dead containers
M.sweep_interval = 600
-- How often (in seconds) does the marker wake up to mark containers for deletion
M.mark_interval = 120
-- How long (in seconds) since last activity on a container should we wait before shutting it down
M.timeout = 300
-- How often (in seconds) does the provisioner wake up to provision new containers
M.provision_interval = 30
-- How many provisioned (un-assigned) containers should we have on stand-by
M.provision_count = 20
-- The max number of docker containers to have running, including provisioned
M.container_max = 5000
-- Default URL for authentication failure redirect, nil means just error out without redirect
M.auth_redirect = "/?redirect=%s"
M.load_redirect = "/loading.html?n=%s"
--
-- Function that runs a netstat and returns a table of foreign IP:PORT
-- combinations and the number of observed ESTABLISHED connetions (at
-- least 1)
--
est_connections = function()
local connections = {}
local handle = io.popen( NETSTAT, 'r')
if handle then
netstat = handle:read('*a')
handle:close()
for conn in string.gmatch(netstat,"[%d%.]+:[%d]+ + ESTABLISHED") do
ipport = string.match(conn, "[%d%.]+:[%d]+")
if connections[ipport] then
connections[ipport] = connections[ipport] + 1
else
connections[ipport] = 1
end
end
else
ngx.log(ngx.ERR, string.format("Error trying to execute %s", NETSTAT))
end
return connections
end
--
-- Reaper function that looks in the docker_map for instances that need to be
-- removed and removes them
sweeper = function()
ngx.log(ngx.INFO, "sweeper running")
-- get locker
local dock_lock = locklib:new(M.lock_name, lock_opts)
-- loop through ids
local ids = docker_map:get_keys()
for num = 1, #ids do
id = ids[num]
-- lock docker map before read/write
elapsed, err = dock_lock:lock(id)
if elapsed then -- lock worked
local val = docker_map:get(id) -- make sure its still there
if val then
ngx.log(ngx.DEBUG, "ID "..id..": "..val)
-- info = { state, ip:port, session, last_time, last_ip }
local info = notemgr:split(val)
-- this is assigned to be reaped
if info[1] == "idle" then
ngx.log(ngx.INFO, "Sweeper removing "..info[3]..", "..id)
local ok, err = pcall(notemgr.remove_notebook, id)
if ok then
docker_map:delete(id)
session_map:delete(info[3])
ngx.log(ngx.INFO, "Notebook "..id.." removed")
elseif string.find(err, "does not exist") then
docker_map:delete(id)
session_map:delete(info[3])
ngx.log(ngx.WARN, "Notebook "..id.." nonexistent - removing references")
else
ngx.log(ngx.ERR, "Error: "..err)
end
end
end
dock_lock:unlock() -- unlock if it worked
end
end
-- reset sweeper
proxy_mgr:delete('next_sweep')
-- enqueue ourself again
check_sweeper()
end
-- This function just checks to make sure there is a sweeper function in the queue
-- returns true if there was one, false otherwise
check_sweeper = function(self)
local sweep_lock = locklib:new(M.lock_name, lock_opts)
local next_run = proxy_mgr:get('next_sweep')
if next_run == nil then -- no sweeper in the queue, put one into the queue!
-- lock it
elapsed, err = sweep_lock:lock('next_sweep')
if elapsed == nil then
ngx.log(ngx.ERR, "Error acquiring sweeper lock: "..err)
return false
end
-- retry get, if still nil then reset
next_run = proxy_mgr:get('next_sweep')
if next_run == nil then
ngx.log(ngx.INFO, "Enqueuing sweeper to run in "..M.sweep_interval.." seconds")
local success, err = ngx.timer.at(M.sweep_interval, sweeper)
if success then
proxy_mgr:set('next_sweep', os.time() + M.sweep_interval)
else
ngx.log(ngx.ERR, "Error enqueuing sweeper to run in "..M.sweep_interval.." seconds: "..err)
end
sweep_lock:unlock()
return false
end
sweep_lock:unlock()
return true
end
return true
end
--
-- Reaper function that examines containers to see if they have been idle for longer than
-- M.timeout and then marks them for cleanup
-- updates those with active connections
--
marker = function()
ngx.log(ngx.INFO, "marker running")
local now = os.time()
local timeout = now - M.timeout
-- get locker
local dock_lock = locklib:new(M.lock_name, lock_opts)
-- fetch currently open connections
local conn = est_connections()
-- loop through ids
local ids = docker_map:get_keys()
for num = 1, #ids do
id = ids[num]
-- lock docker map before read/write
elapsed, err = dock_lock:lock(id)
if elapsed then -- lock worked
local val = docker_map:get(id) -- make sure its still there
if val then
-- info = { state, ip:port, session, last_time, last_ip }
local info = notemgr:split(val)
-- this is assigned to a session
if info[1] ~= "queued" then
-- currently has connection, update
if conn[info[2]] then
info[4] = now
success, err = docker_map:set(id, table.concat(info, " "))
if not success then
ngx.log(ngx.ERR, "Error setting "..info[3].." from established connections: "..err)
end
-- past due, mark for reaping
elseif tonumber(info[4]) <= timeout then
ngx.log(ngx.INFO, "Marking "..info[3].." for reaping - last seen "..os.date("%c", tonumber(info[4])))
info[1] = "idle"
success, err = docker_map:set(id, table.concat(info, " "))
if not success then
ngx.log(ngx.ERR, "Error setting "..info[3].." as idle: "..err)
end
end
end
end
dock_lock:unlock() -- unlock if it worked
end
end
-- reset marker
proxy_mgr:delete('next_mark')
-- enqueue sweeper
check_sweeper()
-- requeue ourselves
check_marker()
end
-- This function just checks to make sure there is a marker function in the queue
-- returns true if there was one, false otherwise
check_marker = function(self)
local mark_lock = locklib:new(M.lock_name, lock_opts)
local next_run = proxy_mgr:get('next_mark')
if next_run == nil then -- no marker in the queue, put one into the queue!
-- lock it
elapsed, err = mark_lock:lock('next_mark')
if elapsed == nil then
ngx.log(ngx.ERR, "Error acquiring marker lock: "..err)
return false
end
-- retry get, if still nil then reset
next_run = proxy_mgr:get('next_mark')
if next_run == nil then
ngx.log(ngx.INFO, "Enqueuing marker to run in "..M.mark_interval.." seconds")
local success, err = ngx.timer.at(M.mark_interval, marker)
if success then
proxy_mgr:set('next_mark', os.time() + M.mark_interval)
else
ngx.log(ngx.ERR, "Error enqueuing marker to run in "..M.mark_interval.." seconds: "..err)
end
mark_lock:unlock()
return false
end
mark_lock:unlock()
return true
end
return true
end
--
-- Provisoning function that looks in the docker_map to identify how many provisioned
-- containers there are, if less than provion_count, spawns more
-- do not provision containers that would cause total to be > than container_max
provisioner = function()
ngx.log(ngx.INFO, "provisioner running")
-- sync maps with existing containers
sync_containers()
local queued = 0
local total = 0
-- get locker
local dock_lock = locklib:new(M.lock_name, lock_opts)
-- loop through ids
local ids = docker_map:get_keys()
for num = 1, #ids do
id = ids[num]
-- lock docker map before read/write
elapsed, err = dock_lock:lock(id)
if elapsed then -- lock worked
local val = docker_map:get(id) -- make sure its still there
if val then
-- info = { state, ip:port, session, last_time, last_ip }
total = total + 1
local info = notemgr:split(val)
if info[1] == "queued" then
queued = queued + 1
end
end
dock_lock:unlock() -- unlock if it worked
end
end
if queued < M.provision_count then
local to_spawn = M.provision_count - queued
if (to_spawn + total) > M.container_max then
to_spawn = M.container_max - total
end
if to_spawn > 0 then
ngx.log(ngx.INFO, "Provisioner spawning "..to_spawn.." containers")
for i = 1, to_spawn do
new_container()
end
else
ngx.log(ngx.WARN, "Unable to provision containers, currently running "..total.." for max of "..M.container_max)
end
end
-- reset provisioner
proxy_mgr:delete('next_provision')
-- enqueue self
check_provisioner()
end
-- This function just checks to make sure there is a provisioner function in the queue
-- returns true if there was one, false otherwise
check_provisioner = function(self, now)
local interval = M.provision_interval
if now then
interval = now
end
local prov_lock = locklib:new(M.lock_name, lock_opts)
local next_run = proxy_mgr:get('next_provision')
if next_run == nil then -- no provisioner in the queue, put one into the queue!
-- lock it
elapsed, err = prov_lock:lock('next_provision')
if elapsed == nil then
ngx.log(ngx.ERR, "Error acquiring provisioner lock: "..err)
return false
end
-- retry get, if still nil then reset
next_run = proxy_mgr:get('next_provision')
if next_run == nil then
ngx.log(ngx.INFO, "Enqueuing provisioner to run in "..interval.." seconds")
local success, err = ngx.timer.at(interval, provisioner)
if success then
proxy_mgr:set('next_provision', os.time() + interval)
else
ngx.log(ngx.ERR, "Error enqueuing provisioner to run in "..interval.." seconds: "..err)
end
prov_lock:unlock()
return false
end
prov_lock:unlock()
return true
end
return true
end
--
-- Do some initialization for the proxy manager.
--
initialize = function(self, conf)
if conf then
for k,v in pairs(conf) do
ngx.log(ngx.INFO, string.format("conf(%s) = %s",k,tostring(v)))
end
else
conf = {}
end
if not initialized then
initialized = os.time()
M.sweep_interval = conf.sweep_interval or M.sweep_interval
M.mark_interval = conf.mark_interval or M.mark_interval
M.provision_interval = conf.provision_interval or M.provision_interval
M.timeout = conf.idle_timeout or M.timeout
M.auth_redirect = conf.auth_redirect or M.auth_redirect
M.provision_count = conf.provision_count or M.provision_count
M.container_max = conf.container_max or M.container_max
M.lock_name = conf.lock_name or M.lock_name
session_map = conf.session_map or ngx.shared.session_map
docker_map = conf.docker_map or ngx.shared.docker_map
token_cache = conf.token_cache or ngx.shared.token_cache
proxy_mgr = conf.proxy_mgr or ngx.shared.proxy_mgr
ngx.log(ngx.INFO, string.format("Initializing proxy manager: sweep_interval %d mark_interval %d idle_timeout %d auth_redirect %s",
M.sweep_interval, M.mark_interval, M.timeout, tostring(M.auth_redirect)))
else
ngx.log(ngx.INFO, string.format("Initialized at %d, skipping", initialized))
end
end
-- This function will shut down a running Narrative Docker container immediately
-- Once that's done, the user's token is removed from the cache.
-- The intent is that this is a fast, specific reaping process, accessible from outside.
-- It's set up as a REST call, but a valid user token is required, and that token must come
-- from the user who's instance it's trying to shut down.
-- Only the GET and DELETE methods are implemented. GET returns some info, and DELETE
-- will shutdown the container under 2 conditions:
-- 1. A valid KBase auth token is given in the cookie given by auth_cookie_name
-- 2. The user specified by that cookie is shutting down their own Narrative instance
narrative_shutdown = function(self)
local uri_key_rx = ngx.var.uri_base.."/("..key_regex..")"
local method = ngx.req.get_method()
local response = {}
if method == "GET" then
ngx.say(json.encode(response))
elseif method == "DELETE" then
local session_id, err = get_session()
if session_id then
local key = string.match(ngx.var.uri, uri_key_rx)
if key then
if key == session_id then
local target = session_map:get(key)
if target == nil then
ngx.status = ngx.HTTP_NOT_FOUND
response = "Session does not exist: "..key
else
local dock_lock = locklib:new(M.lock_name, lock_opts)
local session = notemgr:split(target)
id = session[2]
-- lock docker map before read/write
elapsed, err = dock_lock:lock(id)
if elapsed then -- lock worked
response = "Reaping container"
ngx.log(ngx.NOTICE, "Manual shutdown of "..id.." by user "..key)
local ok, err = pcall(notemgr.remove_notebook, id)
if ok then
docker_map:delete(id)
session_map:delete(key)
ngx.log(ngx.INFO, "Notebook "..id.." removed")
elseif string.find(err, "does not exist") then
docker_map:delete(id)
session_map:delete(key)
ngx.log(ngx.WARN, "Notebook "..id.." nonexistent - removing references")
else
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.log(ngx.ERR, "Error: "..err)
response = "Error: "..err
end
dock_lock:unlock() -- unlock if it worked
else
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.log(ngx.ERR, "Error: "..err)
response = "Error: "..err
end
end
else
ngx.status = ngx.HTTP_UNAUTHORIZED
ngx.log(ngx.WARN, "Unauthorized user "..session_id.." attempting to shutdown a Narrative owned by "..key)
response = "You do not have permission to shut down this Narrative"
end
else
ngx.status = ngx.HTTP_NOT_FOUND
response = "No key specified"
end
else
ngx.status = ngx.HTTP_UNAUTHORIZED
ngx.log(ngx.WARN, "Unauthorized user attempting to shutdown a Narrative")
response = "Must provide user credentials to shutdown a running server!"
end
ngx.say(json.encode(response))
else
ngx.exit(ngx.HTTP_METHOD_NOT_IMPLEMENTED)
end
end
-- This function is used to implement the rest interface
set_proxy = function(self)
local uri_key_rx = ngx.var.uri_base.."/("..key_regex ..")"
local uri_id_rx = ngx.var.uri_base.."/("..id_regex ..")"
local uri_pair_rx = ngx.var.uri_base.."/"..key_regex .."/".."("..id_regex..")$"
local client_ip = ngx.var.remote_addr
local method = ngx.req.get_method()
local new_flag = false
-- get the provisioning / reaper functions into the run queue if not already
-- the workers sometimes crash and having it here guarentees it will be running
check_provisioner()
check_marker()
if method == "POST" then
local response = {}
-- POST method takes a session key and assigns a queued container to it
-- If no key given it enqueues a new container
local key = string.match(ngx.var.uri, uri_key_rx)
if key then
local target = session_map:get(key)
if target == nil then
target = assign_container(key, client_ip)
-- if assignment fails, launch new container and try again
if target == nil then
ngx.log(ngx.WARN, "No queued containers to assign, launching new")
res = new_container()
if res then
target = assign_container(key, client_ip)
end
end
if target then
new_container() -- if a queued container is assigned, enqueue another
local session = notemgr:split(target)
response["msg"] = "Assigned container "..session[2].." to "..key
else
response["error"] = "No available docker containers!"
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
end
else
response["error"] = "Entry already exists: "..key
ngx.status = ngx.HTTP_BAD_REQUEST
end
else
res = new_container()
if res then
response["msg"] = "Launched new container: "..res
else
response["error"] = "Unable to launch a docker container"
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
end
end
ngx.say(json.encode(response))
elseif method == "GET" then
local response = {}
-- Check URI to see if a specific session key or container id is asked for,
-- if so return that record, else we return all records
-- info = { state, ip:port, session, last_time, last_ip }
local key = string.match(ngx.var.uri, uri_key_rx)
local id = string.match(ngx.var.uri, uri_id_rx)
local cid = nil
-- return all records
if (not key) and (not id) then
local ids = docker_map:get_keys()
for num = 1, #ids do
local id = ids[num]
local val = docker_map:get(id)
if val then
local info = notemgr:split(val)
table.insert(response, {
docker_id = id,
state = info[1],
proxy_target = info[2],
session_id = info[3],
last_seen = os.date("%c", tonumber(info[4])),
last_ip = info[5]
})
end
end
-- return a single record
else
if key then
local target = session_map:get(key)
if target then
local session = notemgr:split(target)
cid = session[2]
end
end
if id and (not cid) then
cid = id
end
if cid then
local val = docker_map:get(cid)
if val then
local info = notemgr:split(val)
response = {
docker_id = cid,
state = info[1],
proxy_target = info[2],
session_id = info[3],
last_seen = os.date("%c", tonumber(info[4])),
last_ip = info[5]
}
end
else
response["error"] = "No valid session key or container Id specified"
ngx.status = ngx.HTTP_NOT_FOUND
end
end
ngx.say(json.encode(response))
elseif method == "PUT" then
local response = {}
-- PUT method performs changes on memory maps
-- Check URI for action to perform
local action = string.match(ngx.var.uri, uri_key_rx)
if action then
if action == "sync" then
-- sync maps with existing containers
sync_containers()
response["msg"] = "Synced docker memory map with docker container state"
else
response["error"] = "Invalid action specified: "..action
ngx.status = ngx.HTTP_BAD_REQUEST
end
else
response["error"] = "No action specified"
ngx.status = ngx.HTTP_NOT_FOUND
end
ngx.say(json.encode(response))
elseif method == "DELETE" then
local response = {}
-- Check URI to make sure a specific container id is being asked for,
-- then queues it for deletion, along with any session thats bound to it
local key = string.match(ngx.var.uri, uri_key_rx)
if key then
-- immediatly delete all provisioned containers
if key == "provisioned" then
response = { msg = "", deleted = {}, error = {} }
-- get locker
local dock_lock = locklib:new(M.lock_name, lock_opts)
-- loop through ids
local ids = docker_map:get_keys()
local del = 0
for num = 1, #ids do
id = ids[num]
-- lock docker map before read/write
elapsed, err = dock_lock:lock(id)
if elapsed then -- lock worked
local val = docker_map:get(id) -- make sure its still there
if val then
-- info = { state, ip:port, session, last_time, last_ip }
local info = notemgr:split(val)
-- this is provisioned / unassigned
if info[1] == "queued" then
ngx.log(ngx.INFO, "Atempting to kill container "..id)
local ok, err = pcall(notemgr.remove_notebook, id)
if ok then
del = del + 1
table.insert(response.deleted, id)
docker_map:delete(id)
ngx.log(ngx.INFO, "Container "..id.." removed")
elseif string.find(err, "does not exist") then
del = del + 1
table.insert(response.deleted, id)
docker_map:delete(id)
ngx.log(ngx.WARN, "Notebook "..id.." nonexistent - removing references")
else
table.insert(response.error, id)
ngx.log(ngx.ERR, "Error: "..err)
end
end
end
dock_lock:unlock() -- unlock if it worked
response["msg"] = "Sucessfully killed "..del.." containers"
else
ngx.log(ngx.ERR, "Error: "..err)
response["msg"] = "Error: "..err
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
end
end
-- mark for deletion container associated with session key
else
local target = session_map:get(key)
if target then
local session = notemgr:split(target)
local val = docker_map:get(session[2])
if val then
-- info = { state, ip:port, session, last_time, last_ip }
local info = notemgr:split(val)
-- mark the proxy instance for deletion
info[1] = "idle"
local success, err, forcible = docker_map:set(id, table.concat(info, " "))
if success then
response["msg"] = "Marked for reaping"
ngx.log(ngx.INFO, "Marked for reaping: "..key..", "..session[2])
else
response["error"] = err
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
end
else
response["error"] = "Docker container "..session[2].." does not exist"
ngx.status = ngx.HTTP_NOT_FOUND
end
else
response["error"] = "Session key "..key.." does not exist"
ngx.status = ngx.HTTP_NOT_FOUND
end
end
else
response["error"] = "No valid session key specified"
ngx.status = ngx.HTTP_NOT_FOUND
end
ngx.say(json.encode(response))
else
ngx.exit(ngx.HTTP_METHOD_NOT_IMPLEMENTED)
end
end
--
-- simple URL decode function
url_decode = function(str)
str = string.gsub (str, "+", " ")
str = string.gsub (str, "%%(%x%x)", function(h) return string.char(tonumber(h,16)) end)
str = string.gsub (str, "\r\n", "\n")
return str
end
--
-- Examines the current request to validate it and return a
-- session identifier. You can perform authentication here
-- and only return a session id if the authentication is legit
-- returns nil, err if a session cannot be found/created
--
-- In the current implementation we take the token (if given) and
-- try to query Globus Online for the user profile, if it comes back
-- then the token is good and we put an entry in the token_cache
-- table for it
--
-- session identifier is parsed out of token from user name (un=) value
get_session = function()
local hdrs = ngx.req.get_headers()
local cheader = ngx.unescape_uri(hdrs['Cookie'])
local token = {}
local session_id = nil; -- nil return value by default
if cheader then
-- ngx.log( ngx.DEBUG, string.format("cookie = %s",cheader))
local session = string.match(cheader, auth_cookie_name.."=([%S]+);?")
if session then
-- ngx.log( ngx.DEBUG, string.format("kbase_session = %s",session))
session = string.gsub(session, ";$", "")
session = url_decode(session)
for k, v in string.gmatch(session, "([%w_]+)=([^|]+);?") do
token[k] = v
end
if token['token'] then
token['token'] = string.gsub(token['token'], "PIPESIGN", "|")
token['token'] = string.gsub(token['token'], "EQUALSSIGN", "=")
-- ngx.log( ngx.DEBUG, string.format("token[token] = %s",token['token']))
end
end
end
if token['un'] then
local cached = token_cache:get(token['kbase_sessionid'])
-- we have to cache either the token itself, or a hash of the token
-- because this method gets called for every GET for something as
-- trivial as a .png or .css file, calculating and comparing an MD5
-- hash of the token would start to be costly given how many GETs
-- there are on a given page load.
-- So we cache the token itself. This is a security vulnerability,
-- however the exposure would require a hacker of fairly high end
-- skills (or someone who has read the source code...)
if cached and cached == token['token'] then
return token['un']
end
-- lock and try again
local token_lock = locklib:new(M.lock_name)
elapsed, err = token_lock:lock(token['kbase_sessionid'])
if elapsed == nil then
ngx.log(ngx.ERR, "Error: failed to update token cache: "..err)
return nil
end
cached = token_cache:get(token['kbase_sessionid'])
if cached and cached == token['token'] then
token_lock:unlock()
return token['un']
-- still missing, now get from globus
else
ngx.log(ngx.WARN, "Token cache miss: ", token['kbase_sessionid'])
local req = {
url = nexus_url .. token['un'],
method = "GET",
headers = { Authorization = "Globus-Goauthtoken "..token['token'] }
}
--ngx.log( ngx.DEBUG, "request.url = " .. req.url)
local ok,code,headers,status,body = httpclient:request(req)
--ngx.log( ngx.DEBUG, "Response - code: ", code)
if code >= 200 and code < 300 then
local profile = json.decode(body)
ngx.log(ngx.INFO, "Token validated for "..profile.fullname.." ("..profile.username..")")
if profile.username == token.un then
ngx.log(ngx.INFO, "Token username matches cookie identity, inserting session_id into token cache: "..token['kbase_sessionid'])
token_cache:set(token['kbase_sessionid'], token['token'])
session_id = profile.username
token_lock:unlock()
else
ngx.log(ngx.ERR, "Error: token username DOES NOT match cookie identity: "..profile.username)
end
else
ngx.log(ngx.ERR, "Error during token validation: "..status.." "..body)
end
end
token_lock:unlock() -- make sure its unlcoked
else
if cheader then
ngx.log(ngx.ERR, "Error: invalid token / auth format: "..cheader)
else
ngx.log(ngx.ERR, "Error: missing 'cookie' header")
end
end
return session_id
end
--
-- Check docker_map and update session_map if missing
-- this for-loop makes me wish lua had a continue statement
-- currently not using this function
--
sync_sessions = function()
ngx.log(ngx.INFO, "Updating session_map from docker_map")
-- add any assigned notebooks we don't know about
local ids = docker_map:get_keys()
local docker_lock = locklib:new(M.lock_name, lock_opts)
local session_lock = locklib:new(M.lock_name, lock_opts)
for num = 1, #ids do
id = ids[num]
-- lock memory map before access
elapsed, err = docker_lock:lock(id)
if elapsed then -- lock worked
local val = docker_map:get(id) -- make sure its still there
if val then
-- info = { state, ip:port, session, last_time, last_ip }
local info = notemgr:split(val)
-- this is assigned to a session
if info[1] ~= "queued" then
local target = session_map:get(info[3])
if target == nil then -- not in session_map
-- lock session_map before update
elapsed, err = session_lock:lock(info[3])
if elapsed then -- lock worked
target = session_map:get(info[3])
if target == nil then -- its still missing after lock
ngx.log(ngx.WARN, "session_map is stale, missing "..info[3]..", "..id)
local success,err,forcible = session_map:set(info[3], table.concat({info[2], id}, " "))
if not success then
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.log(ngx.ERR, "Error setting session_map: "..err)
end
end
session_lock:unlock() -- unlock if it worked
end
end
end
end
docker_lock:unlock() -- unlock if it worked
end
end
end
-- function to sync docker state with docker memory map
-- remove any containers that don't exist in both
sync_containers = function()
ngx.log(ngx.INFO, "Syncing docker memory map with docker container state")
local portmap = notemgr:get_notebooks()
local ids = docker_map:get_keys()
local dock_lock = locklib:new(M.lock_name, lock_opts)
local session_lock = locklib:new(M.lock_name, lock_opts)
-- delete from memory if not a container
for num = 1, #ids do
id = ids[num]
-- lock memory map before delete
elapsed, err = dock_lock:lock(id)
if elapsed then
val = docker_map:get(id) -- make sure its still there
if val and not portmap[id] then
-- info = { state, ip:port, session, last_time, last_ip }
local info = notemgr:split(val)
ngx.log(ngx.WARN, "memory maps are stale, deleting "..info[3]..", "..id)
docker_map:delete(id)
-- delete from session map if deleting from docker_map
elapsed, err = session_lock:lock(info[3])
if elapsed then
target = session_map:get(info[3])
if target then
session_map:delete(info[3])
end
session_lock:unlock() -- unlock if it worked
end
end
dock_lock:unlock() -- unlock if it worked
end
end
-- delete from docker if not in memory
-- we don't know if it was given a session or not
for id, _ in pairs(portmap) do
local mem_id = docker_map:get(id)
-- its missing, kill / remove
if mem_id == nil then
local ok, err = pcall(notemgr.remove_notebook, id)
if not ok then
ngx.log(ngx.ERR, "Error: "..err)
end
end
end
end
--
-- Spin up a new container, add to docker_map
-- id = container uuid
-- info = { state, ip:port, session, last_time, last_ip }
-- true if success, fasle if failed
--
new_container = function()
ngx.log(ngx.INFO, "Creating container for queue")
local id, info = notemgr:launch_notebook()
if id == nil then
ngx.log(ngx.ERR, "Failed to launch new instance : "..p.write(info))
return nil
end
-- lock key before writing it
local dock_lock = locklib:new(M.lock_name, lock_opts)
elapsed, err = dock_lock:lock(id)
if elapsed == nil then
ngx.log(ngx.ERR, "Error: failed to update docker cache: "..err)
return nil
end
docker_map:set(id, table.concat(info, " "))
dock_lock:unlock()
return id
end
--
-- Assign session to oldest qeueued container
-- edits docker_map and session_map
-- session_id is already locked when this function called
-- returns session info, nil if error
--
assign_container = function(session_id, client_ip)
-- sync maps with existing containers
sync_containers()
ngx.log(ngx.INFO, "Assigning container from queue")
-- get list of queued ids, oldest to newest
local ordered = {}
local ids = docker_map:get_keys()
for num = 1, #ids do
local id = ids[num]
local val = docker_map:get(id)
if val then
local info = notemgr:split(val)
table.insert(ordered, {id, tonumber(info[4])})
end
end
-- sort by time
table.sort(ordered, function(a,b) return a[2] < b[2] end)
-- process queued containers: oldest first / lock each in turn
local dock_lock = locklib:new(M.lock_name, lock_opts)
for num = 1, #ordered do
local id = ordered[num][1]
elapsed, err = dock_lock:lock(id)
if elapsed then
local val = docker_map:get(id)
-- make sure its still there
if val then
local info = notemgr:split(val)
if info[1] == "queued" then
if info[3] == "*" then -- found one
session_val = table.concat({info[2], id}, " ")
session_map:set(session_id, session_val)
docker_map:set(id, table.concat({"active", info[2], session_id, os.time(), client_ip}, " "))
dock_lock:unlock()
return session_val
else -- bad state, session with queued
info[1] = "idle"
docker_map:set(id, table.concat(info, " "))
end
end
end
dock_lock:unlock() -- unlock if it worked
end
end
return nil
end
--
-- Route to the appropriate proxy
--
use_proxy = function(self)
local target = nil
local new_flag = false
-- ngx.log( ngx.INFO, "In /narrative/ handler")
local client_ip = ngx.var.remote_addr
-- get the provisioning / reaper functions into the run queue if not already
-- the workers sometimes crash and having it here guarentees it will be running
check_provisioner()
check_marker()
-- get session
-- unauthorized if no session
local session_key = get_session()
if not session_key then
ngx.log(ngx.WARN, "No session_key found, bad auth")
return(ngx.exit(ngx.HTTP_UNAUTHORIZED))
end
-- get proxy target
target = session_map:get(session_key)
-- didn't find in session_map, lock and try again
if target == nil then
session_lock = locklib:new(M.lock_name, lock_opts)
elapsed, err = session_lock:lock(session_key)
if elasped then
target = session_map:get(session_key)
end
-- still missing, assign comtainer to session
if target == nil then
-- session_key still locked in called function
-- this updates docker_map with session info
target = assign_container(session_key, client_ip)
-- if assignment fails, launch new container and try again
if target == nil then
ngx.log(ngx.WARN, "No queued containers to assign, launching new")
res = new_container()
if res then
target = assign_container(session_key, client_ip)
end
end
-- can not assign a new one / bad state
if target == nil then
ngx.log(ngx.ERR, "No available docker containers!")
return(ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE))
end
-- if a queued container is assigned, enqueue another
new_container()
-- assign comtainer to session
local scheme = ngx.var.src_scheme and ngx.var.src_scheme or 'http'
local returnurl = string.format("%s://%s%s", scheme, ngx.var.host, ngx.var.request_uri)
return ngx.redirect(string.format(M.load_redirect, ngx.escape_uri(returnurl)))
end
session_lock.unlock()
end
-- proxy target already in session
if target ~= nil then
-- session = { IP:port, docker_id }
local session = notemgr:split(target)
ngx.var.target = session[1]
-- update docker_map session info, lock first
local dock_lock = locklib:new(M.lock_name, lock_opts)
elapsed, err = dock_lock:lock(session[2])
if elapsed == nil then
ngx.log(ngx.ERR, "Error: failed to lock docker cache: "..err)
end
success,err,forcible = docker_map:set(session[2], table.concat({"active", session[1], session_key, os.time(), client_ip}, " "))
if not success then
ngx.log(ngx.WARN, "Error: failed to update docker cache: "..err)
end
dock_lock:unlock()
elseif M.auth_redirect then
local scheme = ngx.var.src_scheme and ngx.var.src_scheme or 'http'
local returnurl = string.format("%s://%s/%s", scheme,ngx.var.host,ngx.var.request_uri)
return ngx.redirect(string.format(M.auth_redirect, ngx.escape_uri(returnurl)))
else
return(ngx.exit(ngx.HTTP_NOT_FOUND))
end
end
M.check_marker = check_marker
M.check_provisioner = check_provisioner
M.set_proxy = set_proxy
M.use_proxy = use_proxy
M.initialize = initialize
M.narrative_shutdown = narrative_shutdown
return M
| mit |
UnfortunateFruit/darkstar | scripts/globals/items/serving_of_zaru_soba.lua | 35 | 1312 | -----------------------------------------
-- ID: 5727
-- Item: serving_of_zaru_soba
-- Food Effect: 30Min?, All Races
-----------------------------------------
-- Agility 3
-- HP % 12 (cap 180)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5727);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 3);
target:addMod(MOD_FOOD_HPP, 12);
target:addMod(MOD_FOOD_HP_CAP, 180);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 3);
target:delMod(MOD_FOOD_HPP, 12);
target:delMod(MOD_FOOD_HP_CAP, 180);
end;
| gpl-3.0 |
Cyumus/NutScript | gamemode/config/sh_config.lua | 3 | 4689 | -- You can change the default language here:
nut.config.language = "english"
--[[
DO NOT CHANGE ANYTHING BELOW THIS.
This is the NutScript main configuration file.
This file DOES NOT set any configurations, instead it just prepares them.
To set the configuration, there is a "Config" tab in the F1 menu for super admins and above.
Use the menu to change the variables, not this file.
--]]
nut.config.add("maxChars", 5, "The maximum number of characters a player can have.", nil, {
data = {min = 1, max = 50},
category = "characters"
})
nut.config.add("color", Color(75, 119, 190), "The main color theme for the framework.", nil, {category = "appearance"})
nut.config.add("font", "Impact", "The font used to display titles.", function(oldValue, newValue)
if (CLIENT) then
hook.Run("LoadFonts", newValue)
end
end, {category = "appearance"})
nut.config.add("maxAttribs", 30, "The total maximum amount of attribute points allowed.", nil, {
data = {min = 1, max = 250},
category = "characters"
})
nut.config.add("chatRange", 280, "The maximum distance a person's IC chat message goes to.", nil, {
form = "Float",
data = {min = 10, max = 5000},
category = "chat"
})
nut.config.add("chatColor", Color(255, 239, 150), "The default color for IC chat.", nil, {category = "chat"})
nut.config.add("chatListenColor", Color(168, 240, 170), "The color for IC chat if you are looking at the speaker.", nil, {category = "chat"})
nut.config.add("oocDelay", 10, "The delay before a player can use OOC chat again in seconds.", nil, {
data = {min = 0, max = 10000},
category = "chat"
})
nut.config.add("loocDelay", 0, "The delay before a player can use LOOC chat again in seconds.", nil, {
data = {min = 0, max = 10000},
category = "chat"
})
nut.config.add("spawnTime", 5, "The time it takes to respawn.", nil, {
data = {min = 0, max = 10000},
category = "characters"
})
nut.config.add("invW", 6, "How many slots in a row there is in a default inventory.", nil, {
data = {min = 0, max = 20},
category = "characters"
})
nut.config.add("invH", 4, "How many slots in a column there is in a default inventory.", nil, {
data = {min = 0, max = 20},
category = "characters"
})
nut.config.add("minDescLen", 16, "The minimum number of characters in a description.", nil, {
data = {min = 0, max = 300},
category = "characters"
})
nut.config.add("saveInterval", 300, "How often characters save in seconds.", nil, {
data = {min = 60, max = 3600},
category = "characters"
})
nut.config.add("walkSpeed", 130, "How fast a player normally walks.", function(oldValue, newValue)
for k, v in ipairs(player.GetAll()) do
v:SetWalkSpeed(newValue)
end
end, {
data = {min = 75, max = 500},
category = "characters"
})
nut.config.add("runSpeed", 235, "How fast a player normally runs.", function(oldValue, newValue)
for k, v in ipairs(player.GetAll()) do
v:SetRunSpeed(newValue)
end
end, {
data = {min = 75, max = 500},
category = "characters"
})
nut.config.add("walkRatio", 0.5, "How fast one goes when holding ALT.", nil, {
form = "Float",
data = {min = 0, max = 1},
category = "characters"
})
nut.config.add("punchStamina", 10, "How much stamina punches use up.", nil, {
data = {min = 0, max = 100},
category = "characters"
})
nut.config.add("music", "music/hl2_song2.mp3", "The default music played in the character menu.", nil, {
category = "appearance"
})
nut.config.add("logo", "http://nutscript.rocks/nutscript.png", "The icon shown on the character menu. Max size is 86x86", nil, {
category = "appearance"
})
nut.config.add("logoURL", "http://nutscript.rocks/", "The URL opened when the icon is clicked.", nil, {
category = "appearance"
})
nut.config.add("sbRecog", false, "Whether or not recognition is used in the scoreboard.", nil, {
category = "characters"
})
nut.config.add("defMoney", 0, "The amount of money that players start with.", nil, {
category = "characters",
data = {min = 0, max = 1000}
})
nut.config.add("allowVoice", false, "Whether or not voice chat is allowed.", nil, {
category = "server"
})
nut.config.add("sbWidth", 0.325, "Scoreboard's width within percent of screen width.", function(oldValue, newValue)
if (CLIENT and IsValid(nut.gui.score)) then
nut.gui.score:Remove()
end
end, {
form = "Float",
category = "visual",
data = {min = 0.2, max = 1}
})
nut.config.add("sbHeight", 0.825, "Scoreboard's height within percent of screen height.", function(oldValue, newValue)
if (CLIENT and IsValid(nut.gui.score)) then
nut.gui.score:Remove()
end
end, {
form = "Float",
category = "visual",
data = {min = 0.3, max = 1}
})
nut.config.add("wepAlwaysRaised", false, "Whether or not weapons are always raised.", nil, {
category = "server"
}) | mit |
UnfortunateFruit/darkstar | scripts/zones/Selbina/npcs/Isacio.lua | 17 | 2906 | -----------------------------------
-- Area: Selbina
-- NPC: Isacio
-- Finishes Quest: Elder Memories
-- @pos -54 -1 -44 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local questStatus = player:getQuestStatus(OTHER_AREAS,ELDER_MEMORIES);
if(questStatus == QUEST_ACCEPTED and trade:getItemCount() == 1) then
local IsacioElderMemVar = player:getVar("IsacioElderMemVar");
if(IsacioElderMemVar == 1 and trade:hasItemQty(538,1)) then
player:startEvent(0x0073,537);
elseif(IsacioElderMemVar == 2 and trade:hasItemQty(537,1)) then
player:startEvent(0x0074,539);
elseif(IsacioElderMemVar == 3 and trade:hasItemQty(539,1)) then
player:startEvent(0x0075);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local questStatus = player:getQuestStatus(OTHER_AREAS, ELDER_MEMORIES);
if(player:getQuestStatus(OTHER_AREAS, THE_OLD_LADY) ~= QUEST_AVAILABLE) then
player:startEvent(0x0063);
elseif(questStatus == QUEST_COMPLETED) then
player:startEvent(0x0076);
elseif(questStatus == QUEST_ACCEPTED) then
IsacioElderMemVar = player:getVar("IsacioElderMemVar");
if(IsacioElderMemVar == 1) then
player:startEvent(0x0072,538);
elseif(IsacioElderMemVar == 2) then
player:startEvent(0x0072,537);
elseif(IsacioElderMemVar == 3) then
player:startEvent(0x0072,539);
end
else
if(player:getMainLvl() >= SUBJOB_QUEST_LEVEL) then
player:startEvent(0x006f,538);
else
player:startEvent(0x0077);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x006f and option == 40) then
player:addQuest(OTHER_AREAS, ELDER_MEMORIES);
player:setVar("IsacioElderMemVar", 1);
elseif(csid == 0x0073) then
player:tradeComplete();
player:setVar("IsacioElderMemVar", 2);
elseif(csid == 0x0074) then
player:tradeComplete();
player:setVar("IsacioElderMemVar", 3);
elseif(csid == 0x0075) then
player:tradeComplete();
player:unlockJob(0);
player:setVar("IsacioElderMemVar", 0);
player:messageSpecial(SUBJOB_UNLOCKED);
player:completeQuest(OTHER_AREAS, ELDER_MEMORIES);
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Lebros_Cavern/Zone.lua | 32 | 1419 | -----------------------------------
--
-- Zone: Lebros_Cavern
--
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Lebros_Cavern/IDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
local pos = player:getPos();
if (pos.x == 0 and pos.y == 0 and pos.z == 0) then
player:setPos(player:getInstance():getEntryPos());
end
player:addTempItem(5345);
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 == 0x66) then
player:setPos(0,0,0,0,61);
end
end;
-----------------------------------
-- onInstanceFailure
-----------------------------------
function onInstanceLoadFailed()
return 61;
end; | gpl-3.0 |
vonflynee/opencomputersserver | world/opencomputers/4f2775bd-9dcb-42e6-8318-1837ede27e76/bin/dmesg.lua | 15 | 1193 | local event = require "event"
local component = require "component"
local keyboard = require "keyboard"
local args = {...}
local interactive = io.output() == io.stdout
local color, isPal, evt
if interactive then
color, isPal = component.gpu.getForeground()
end
io.write("Press 'Ctrl-C' to exit\n")
pcall(function()
repeat
if #args > 0 then
evt = table.pack(event.pullMultiple("interrupted", table.unpack(args)))
else
evt = table.pack(event.pull())
end
if interactive then component.gpu.setForeground(0xCC2200) end
io.write("[" .. os.date("%T") .. "] ")
if interactive then component.gpu.setForeground(0x44CC00) end
io.write(tostring(evt[1]) .. string.rep(" ", math.max(10 - #tostring(evt[1]), 0) + 1))
if interactive then component.gpu.setForeground(0xB0B00F) end
io.write(tostring(evt[2]) .. string.rep(" ", 37 - #tostring(evt[2])))
if interactive then component.gpu.setForeground(0xFFFFFF) end
if evt.n > 2 then
for i = 3, evt.n do
io.write(" " .. tostring(evt[i]))
end
end
io.write("\n")
until evt[1] == "interrupted"
end)
if interactive then
component.gpu.setForeground(color, isPal)
end
| mit |
dpino/snabbswitch | src/program/ptree/ptree.lua | 9 | 2870 | -- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local engine = require("core.app")
local app_graph = require("core.config")
local lib = require("core.lib")
local cpuset = require("lib.cpuset")
local yang = require("lib.yang.yang")
local ptree = require("lib.ptree.ptree")
local function fatal (msg, ...)
print(string.format(msg, ...))
main.exit(1)
end
local function show_usage (exit_code)
print(require("program.ptree.README_inc"))
if exit_code then main.exit(exit_code) end
end
function parse_args (args)
local opts = { verbosity = 1, cpuset = cpuset.new() }
local scheduling = { ingress_drop_monitor = 'flush' }
local handlers = {}
function handlers.n (arg) opts.name = assert(arg) end
function handlers.v () opts.verbosity = opts.verbosity + 1 end
function handlers.t (arg) opts.trace = assert(arg) end
function handlers.D (arg)
opts.duration = assert(tonumber(arg), "duration must be a number")
assert(opts.duration >= 0, "duration can't be negative")
end
function handlers.cpu (arg)
opts.cpuset:add_from_string(arg)
end
handlers['real-time'] = function (arg)
scheduling.real_time = true
end
handlers["on-ingress-drop"] = function (arg)
if arg == 'flush' or arg == 'warn' then
scheduling.ingress_drop_monitor = arg
elseif arg == 'off' then
scheduling.ingress_drop_monitor = false
else
fatal("invalid --on-ingress-drop argument: %s (valid values: %s)",
arg, "flush, warn, off")
end
end
function handlers.j (arg) scheduling.j = arg end
function handlers.h () show_usage(0) end
args = lib.dogetopt(args, handlers, "vD:hn:j:t:",
{ verbose = "v", duration = "D", help = "h", cpu = 1, trace = "t",
["real-time"] = 0, ["on-ingress-drop"] = 1,
name="n" })
if #args ~= 3 then show_usage(1) end
return opts, scheduling, unpack(args)
end
function run (args)
local opts, scheduling, schema_file, setup_file, conf_file = parse_args(args)
local schema_name = yang.add_schema_file(schema_file)
local setup_thunk = loadfile(setup_file)
local conf = yang.load_configuration(conf_file, {schema_name=schema_name})
local setup_fn = setup_thunk()
if not type(setup_fn) then
fatal("Expected %s to evaluate to a function, instead got %s",
setup_file, tostring(setup_fn))
end
local manager = ptree.new_manager {
name = opts.name,
setup_fn = setup_fn,
cpuset = opts.cpuset,
initial_configuration = conf,
schema_name = schema_name,
worker_default_scheduling = scheduling,
log_level = ({"WARN","INFO","DEBUG"})[opts.verbosity or 1] or "DEBUG",
rpc_trace_file = opts.trace,
}
manager:main(opts.duration)
manager:stop()
end
| apache-2.0 |
NezzKryptic/Wire-Extras | lua/entities/gmod_wire_microphone/init.lua | 4 | 2799 |
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
ENT.WireDebugName = "Microphone"
local MODEL = Model("models/jaanus/wiretool/wiretool_range.mdl")
function ENT:Initialize()
self:SetModel( MODEL )
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self, { "On" })
self.Outputs = Wire_CreateOutputs(self, { "Level" })
self.Range = 512
self.Sensitivity = 1
self.Level = 0
self.IsOn = true
self:SetName("wiremicrophone"..tostring(self))
self:ShowOutput()
end
function ENT:AcceptInput(input, activator, caller, value)
if input=="OnSoundLevelChanged" then
self.Level = value
Wire_TriggerOutput(self, "Level", self.Level)
self:ShowOutput()
return true
end
return false
end
function ENT:TriggerInput(iname, value)
if iname=="On" then
self.IsOn = (value~=0)
if self.IsOn then
self.Microphone:Fire("Enable","",0)
else
self.Microphone:Fire("Disable","",0)
self.Level = 0
Wire_TriggerOutput(self, "Level", 0)
self:ShowOutput()
end
end
end
function ENT:OnRemove()
if self.Microphone and self.Microphone:IsValid() then
self.Microphone:Fire("Disable","",0)
self.Microphone:Remove()
end
Wire_Remove(self)
end
function ENT:Setup(range, sen, on, hearcombat, hearworld, hearplayer, hearbullet, hearexplo)
if range<0 then range=0 end
if sen<0 then sen=0 end
if sen>10 then sen=10 end
if on==2 then
on = self.IsOn
end
self.Range = range
self.Sensitivity = sen
-- If it has already a microphone, delete it
if self.Microphone and self.Microphone:IsValid() then
self.Microphone:Fire("Disable","",0)
self.Microphone:Remove()
end
-- Create teh microphone
self.Microphone = ents.Create("env_microphone")
self.Microphone:SetPos(self:GetPos())
self.Microphone:SetKeyValue("target","wiremicrophone"..tostring(self))
self.Microphone:SetKeyValue("Sensitivity",sen)
self.Microphone:SetKeyValue("MaxRange",range)
self.Microphone:SetKeyValue("spawnflags",hearcombat + 2*hearworld + 4*hearplayer + 8*hearbullet + 32*hearexplo)
self.Microphone:Spawn()
self.Microphone:Activate()
if on then
self.Microphone:Fire("Enable","",0)
else
self.Microphone:Fire("Disable","",0)
end
self.IsOn = on
self.Microphone:Fire("addoutput","SoundLevel wiremicrophone"..tostring(self)..",OnSoundLevelChanged",0)
self.Microphone:SetParent(self)
end
function ENT:Think()
self.BaseClass.Think(self)
end
function ENT:ShowOutput()
local txt = "Sound level: "..self.Level
if not self.IsOn then txt = txt.." (disabled)" end
self:SetOverlayText( txt )
end
function ENT:OnRestore()
Wire_Restored(self)
end
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Port_Jeuno/npcs/HomePoint#2.lua | 12 | 1238 | -----------------------------------
-- Area: Port Jeuno
-- NPC: HomePoint#2
-- @pos -155 -1 -4 246
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Port_Jeuno/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fd, 38);
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 == 0x21fd) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Port_Windurst/npcs/Puo_Rhen.lua | 38 | 1037 | -----------------------------------
-- Area: Port Windurst
-- NPC: Puo Rhen
-- Type: Mission Starter
-- @zone: 240
-- @pos -227.964 -9 187.087
--
-- Auto-Script: Requires Verification (Verfied By Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0048);
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 |
dmccuskey/lua-bytearray | dmc_lua/lua_error.lua | 46 | 3628 | --====================================================================--
-- lua_error.lua
--
-- Documentation:
-- * http://github.com/dmccuskey/lua-error
--====================================================================--
--[[
The MIT License (MIT)
Copyright (C) 2014-2015 David McCuskey. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--====================================================================--
--== DMC Lua Library : Lua Error
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.3.0"
--====================================================================--
--== Imports
local Class = require 'lua_class'
-- Check imports
-- TODO: work on this
assert( Class, "lua_error: requires lua_class" )
if checkModule then checkModule( Class, '1.1.2' ) end
--====================================================================--
--== Setup, Constants
-- none
--====================================================================--
--== Support Functions
-- based on https://gist.github.com/cwarden/1207556
local function try( funcs )
local try_f, catch_f, finally_f = funcs[1], funcs[2], funcs[3]
assert( try_f, "lua-error: missing function for try()" )
--==--
local status, result = pcall(try_f)
if not status and catch_f then
catch_f(result)
end
if finally_f then finally_f() end
return result
end
local function catch(f)
return f[1]
end
local function finally(f)
return f[1]
end
--====================================================================--
--== Error Base Class
--====================================================================--
local Error = newClass( nil, { name="Error Instance" } )
--== Class Constants ==--
Error.__version = VERSION
Error.DEFAULT_PREFIX = "ERROR: "
Error.DEFAULT_MESSAGE = "There was an error"
function Error:__new__( message, params )
message = message or self.DEFAULT_MESSAGE
params = params or {}
params.prefix = params.prefix or self.DEFAULT_PREFIX
--==--
-- guard subclasses
if self.is_class then return end
-- save args
self.prefix = params.prefix
self.message = message
self.traceback = debug.traceback()
end
-- must return a string
--
function Error:__tostring__( id )
return table.concat( { self.prefix, self.message, "\n", self.traceback } )
end
--====================================================================--
--== Error API Setup
--====================================================================--
-- globals
_G.try = try
_G.catch = catch
_G.finally = finally
return Error
| mit |
vonflynee/opencomputersserver | world/opencomputers/05fe03dc-84c6-416b-a304-6f79787f6411/lib/serialization.lua | 15 | 3764 | local serialization = {}
-- Important: pretty formatting will allow presenting non-serializable values
-- but may generate output that cannot be unserialized back.
function serialization.serialize(value, pretty)
local kw = {["and"]=true, ["break"]=true, ["do"]=true, ["else"]=true,
["elseif"]=true, ["end"]=true, ["false"]=true, ["for"]=true,
["function"]=true, ["goto"]=true, ["if"]=true, ["in"]=true,
["local"]=true, ["nil"]=true, ["not"]=true, ["or"]=true,
["repeat"]=true, ["return"]=true, ["then"]=true, ["true"]=true,
["until"]=true, ["while"]=true}
local id = "^[%a_][%w_]*$"
local ts = {}
local function s(v, l)
local t = type(v)
if t == "nil" then
return "nil"
elseif t == "boolean" then
return v and "true" or "false"
elseif t == "number" then
if v ~= v then
return "0/0"
elseif v == math.huge then
return "math.huge"
elseif v == -math.huge then
return "-math.huge"
else
return tostring(v)
end
elseif t == "string" then
return string.format("%q", v):gsub("\\\n","\\n")
elseif t == "table" and pretty and getmetatable(v) and getmetatable(v).__tostring then
return tostring(v)
elseif t == "table" then
if ts[v] then
if pretty then
return "recursion"
else
error("tables with cycles are not supported")
end
end
ts[v] = true
local i, r = 1, nil
local f
if pretty then
local ks, sks, oks = {}, {}, {}
for k in pairs(v) do
if type(k) == "number" then
table.insert(ks, k)
elseif type(k) == "string" then
table.insert(sks, k)
else
table.insert(oks, k)
end
end
table.sort(ks)
table.sort(sks)
for _, k in ipairs(sks) do
table.insert(ks, k)
end
for _, k in ipairs(oks) do
table.insert(ks, k)
end
local n = 0
f = table.pack(function()
n = n + 1
local k = ks[n]
if k ~= nil then
return k, v[k]
else
return nil
end
end)
else
f = table.pack(pairs(v))
end
for k, v in table.unpack(f) do
if r then
r = r .. "," .. (pretty and ("\n" .. string.rep(" ", l)) or "")
else
r = "{"
end
local tk = type(k)
if tk == "number" and k == i then
i = i + 1
r = r .. s(v, l + 1)
else
if tk == "string" and not kw[k] and string.match(k, id) then
r = r .. k
else
r = r .. "[" .. s(k, l + 1) .. "]"
end
r = r .. "=" .. s(v, l + 1)
end
end
ts[v] = nil -- allow writing same table more than once
return (r or "{") .. "}"
else
if pretty then
return tostring(t)
else
error("unsupported type: " .. t)
end
end
end
local result = s(value, 1)
local limit = type(pretty) == "number" and pretty or 10
if pretty then
local truncate = 0
while limit > 0 and truncate do
truncate = string.find(result, "\n", truncate + 1, true)
limit = limit - 1
end
if truncate then
return result:sub(1, truncate) .. "..."
end
end
return result
end
function serialization.unserialize(data)
checkArg(1, data, "string")
local result, reason = load("return " .. data, "=data", _, {math={huge=math.huge}})
if not result then
return nil, reason
end
local ok, output = pcall(result)
if not ok then
return nil, output
end
return output
end
return serialization
| mit |
Phyllostachys/junkcode | games/LuaPong/main.lua | 1 | 2981 | function love.load()
-- setup paddle size based on window
paddleWidth = love.graphics.getWidth() / 20
paddleHeight = love.graphics.getHeight() / 5
ballRadius = love.graphics.getWidth() / 100
paddle1Pos = {love.graphics.getWidth() / 15, love.graphics.getHeight() / 3}
paddle2Pos = { love.graphics.getWidth() - love.graphics.getWidth() / 15 - paddleWidth,
love.graphics.getHeight() / 3}
ballPos = {love.graphics.getWidth() / 2 - (2 * ballRadius), love.graphics.getHeight() / 2 - (2 * ballRadius)}
ballVel = {math.random(500), math.random(250)}
end
function love.draw()
love.graphics.clear()
love.graphics.polygon( 'fill',
paddle1Pos[1], paddle1Pos[2],
paddle1Pos[1] + paddleWidth, paddle1Pos[2],
paddle1Pos[1] + paddleWidth, paddle1Pos[2] + paddleHeight,
paddle1Pos[1], paddle1Pos[2] + paddleHeight)
love.graphics.polygon( 'fill',
paddle2Pos[1], paddle2Pos[2],
paddle2Pos[1] + paddleWidth, paddle2Pos[2],
paddle2Pos[1] + paddleWidth, paddle2Pos[2] + paddleHeight,
paddle2Pos[1], paddle2Pos[2] + paddleHeight)
love.graphics.circle('fill', ballPos[1], ballPos[2], ballRadius, 12)
local windowStr = "Width: ".. love.graphics.getWidth() .. ", Height: " .. love.graphics.getHeight()
local paddle1Str = "X: " .. paddle1Pos[1] .. ", Y:" .. paddle1Pos[2]
local paddle2Str = "X: " .. paddle2Pos[1] .. ", Y:" .. paddle2Pos[2]
local ballStr = "X: " .. ballPos[1] .. ", Y:" .. ballPos[2]
love.graphics.print(windowStr, 0, 0)
love.graphics.print(paddle1Str, 0, 11)
love.graphics.print(paddle2Str, 0, 22)
love.graphics.print(ballStr, 0, 33)
end
rate = 200 -- change to change the rate at which the var is changed
function love.update(dt)
-- update paddle 1
if love.keyboard.isDown("a") then -- reduce the value
paddle1Pos[2] = paddle1Pos[2] - (dt * rate)
end
if love.keyboard.isDown("s") then -- increase the value
paddle1Pos[2] = paddle1Pos[2] + (dt * rate)
end
if paddle1Pos[2] < 0 then paddle1Pos[2] = 0 end
if paddle1Pos[2] + paddleHeight > love.graphics.getHeight() then
paddle1Pos[2] = love.graphics.getHeight() - paddleHeight
end
-- update paddle 2
if love.keyboard.isDown("k") then -- reduce the value
paddle2Pos[2] = paddle2Pos[2] - (dt * rate)
end
if love.keyboard.isDown("l") then -- increase the value
paddle2Pos[2] = paddle2Pos[2] + (dt * rate)
end
if paddle2Pos[2] < 0 then paddle2Pos[2] = 0 end
if paddle2Pos[2] + paddleHeight > love.graphics.getHeight() then
paddle2Pos[2] = love.graphics.getHeight() - paddleHeight
end
ballPos = {ballPos[1] + (ballVel[1] * dt), ballPos[2] + (ballVel[2] * dt)}
if ballPos[1] > love.graphics.getWidth() or ballPos[1] < 0 then
ballVel[1] = ballVel[1] * -1
end
if ballPos[2] > love.graphics.getHeight() or ballPos[2] < 0 then
ballVel[2] = ballVel[2] * -1
end
end | mit |
jj918160/cocos2d-x-samples | samples/FantasyWarrior3D/src/cocos/cocos2d/extern.lua | 39 | 2506 |
function clone(object)
local lookup_table = {}
local function _copy(object)
if type(object) ~= "table" then
return object
elseif lookup_table[object] then
return lookup_table[object]
end
local new_table = {}
lookup_table[object] = new_table
for key, value in pairs(object) do
new_table[_copy(key)] = _copy(value)
end
return setmetatable(new_table, getmetatable(object))
end
return _copy(object)
end
--Create an class.
function class(classname, super)
local superType = type(super)
local cls
if superType ~= "function" and superType ~= "table" then
superType = nil
super = nil
end
if superType == "function" or (super and super.__ctype == 1) then
-- inherited from native C++ Object
cls = {}
if superType == "table" then
-- copy fields from super
for k,v in pairs(super) do cls[k] = v end
cls.__create = super.__create
cls.super = super
else
cls.__create = super
end
cls.ctor = function() end
cls.__cname = classname
cls.__ctype = 1
function cls.new(...)
local instance = cls.__create(...)
-- copy fields from class to native object
for k,v in pairs(cls) do instance[k] = v end
instance.class = cls
instance:ctor(...)
return instance
end
else
-- inherited from Lua Object
if super then
cls = clone(super)
cls.super = super
else
cls = {ctor = function() end}
end
cls.__cname = classname
cls.__ctype = 2 -- lua
cls.__index = cls
function cls.new(...)
local instance = setmetatable({}, cls)
instance.class = cls
instance:ctor(...)
return instance
end
end
return cls
end
function schedule(node, callback, delay)
local delay = cc.DelayTime:create(delay)
local sequence = cc.Sequence:create(delay, cc.CallFunc:create(callback))
local action = cc.RepeatForever:create(sequence)
node:runAction(action)
return action
end
function performWithDelay(node, callback, delay)
local delay = cc.DelayTime:create(delay)
local sequence = cc.Sequence:create(delay, cc.CallFunc:create(callback))
node:runAction(sequence)
return sequence
end
| mit |
UnfortunateFruit/darkstar | scripts/zones/Upper_Jeuno/npcs/Zekobi-Morokobi.lua | 38 | 1038 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Zekobi-Morokobi
-- Type: Standard NPC
-- @zone: 244
-- @pos 41.258 -5.999 -74.105
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0057);
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 |
UnfortunateFruit/darkstar | scripts/zones/Dangruf_Wadi/npcs/Grounds_Tome.lua | 34 | 1133 | -----------------------------------
-- Area: Dangruf Wadi
-- NPC: Grounds Tome
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/groundsofvalor");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
startGov(GOV_EVENT_DANGRUF_WADI,player);
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
updateGov(player,csid,option,639,640,641,642,643,644,645,646,0,0);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
finishGov(player,csid,option,639,640,641,642,643,644,645,646,0,0,GOV_MSG_DANGRUF_WADI);
end;
| gpl-3.0 |
dpino/snabbswitch | src/program/lwaftr/setup.lua | 3 | 23899 | module(..., package.seeall)
local config = require("core.config")
local manager = require("lib.ptree.ptree")
local PcapFilter = require("apps.packet_filter.pcap_filter").PcapFilter
local V4V6 = require("apps.lwaftr.V4V6").V4V6
local VirtioNet = require("apps.virtio_net.virtio_net").VirtioNet
local lwaftr = require("apps.lwaftr.lwaftr")
local lwutil = require("apps.lwaftr.lwutil")
local basic_apps = require("apps.basic.basic_apps")
local pcap = require("apps.pcap.pcap")
local ipv4_echo = require("apps.ipv4.echo")
local ipv4_fragment = require("apps.ipv4.fragment")
local ipv4_reassemble = require("apps.ipv4.reassemble")
local arp = require("apps.ipv4.arp")
local ipv6_echo = require("apps.ipv6.echo")
local ipv6_fragment = require("apps.ipv6.fragment")
local ipv6_reassemble = require("apps.ipv6.reassemble")
local ndp = require("apps.lwaftr.ndp")
local vlan = require("apps.vlan.vlan")
local pci = require("lib.hardware.pci")
local cltable = require("lib.cltable")
local ipv4 = require("lib.protocol.ipv4")
local ethernet = require("lib.protocol.ethernet")
local ipv4_ntop = require("lib.yang.util").ipv4_ntop
local binary = require("lib.yang.binary")
local S = require("syscall")
local engine = require("core.app")
local lib = require("core.lib")
local shm = require("core.shm")
local yang = require("lib.yang.yang")
local alarms = require("lib.yang.alarms")
local alarm_notification = false
local capabilities = {
['ietf-softwire-br']={feature={'binding'}},
['ietf-alarms']={feature={'operator-actions', 'alarm-shelving', 'alarm-history'}},
}
require('lib.yang.schema').set_default_capabilities(capabilities)
function read_config(filename)
return yang.load_configuration(filename,
{schema_name=lwaftr.LwAftr.yang_schema})
end
local function convert_ipv4(addr)
if addr ~= nil then return ipv4:pton(ipv4_ntop(addr)) end
end
-- Checks the existence of PCI devices.
local function validate_pci_devices(devices)
for _, address in pairs(devices) do
assert(lwutil.nic_exists(address),
("Could not locate PCI device '%s'"):format(address))
end
end
function lwaftr_app(c, conf)
assert(type(conf) == 'table')
local function append(t, elem) table.insert(t, elem) end
local function prepend(t, elem) table.insert(t, 1, elem) end
local device, id, queue = lwutil.parse_instance(conf)
-- Global interfaces
local gexternal_interface = conf.softwire_config.external_interface
local ginternal_interface = conf.softwire_config.internal_interface
-- Instance specific interfaces
local iexternal_interface = queue.external_interface
local iinternal_interface = queue.internal_interface
config.app(c, "reassemblerv4", ipv4_reassemble.Reassembler,
{ max_concurrent_reassemblies =
gexternal_interface.reassembly.max_packets,
max_fragments_per_reassembly =
gexternal_interface.reassembly.max_fragments_per_packet })
config.app(c, "reassemblerv6", ipv6_reassemble.Reassembler,
{ max_concurrent_reassemblies =
ginternal_interface.reassembly.max_packets,
max_fragments_per_reassembly =
ginternal_interface.reassembly.max_fragments_per_packet })
config.app(c, "icmpechov4", ipv4_echo.ICMPEcho,
{ address = convert_ipv4(iexternal_interface.ip) })
config.app(c, "icmpechov6", ipv6_echo.ICMPEcho,
{ address = iinternal_interface.ip })
config.app(c, "lwaftr", lwaftr.LwAftr, conf)
config.app(c, "fragmenterv4", ipv4_fragment.Fragmenter,
{ mtu=gexternal_interface.mtu })
config.app(c, "fragmenterv6", ipv6_fragment.Fragmenter,
{ mtu=ginternal_interface.mtu })
config.app(c, "ndp", ndp.NDP,
{ self_ip = iinternal_interface.ip,
self_mac = iinternal_interface.mac,
next_mac = iinternal_interface.next_hop.mac,
shared_next_mac_key = "group/"..device.."-ipv6-next-mac",
next_ip = iinternal_interface.next_hop.ip,
alarm_notification = conf.alarm_notification })
config.app(c, "arp", arp.ARP,
{ self_ip = convert_ipv4(iexternal_interface.ip),
self_mac = iexternal_interface.mac,
next_mac = iexternal_interface.next_hop.mac,
shared_next_mac_key = "group/"..device.."-ipv4-next-mac",
next_ip = convert_ipv4(iexternal_interface.next_hop.ip),
alarm_notification = conf.alarm_notification })
if conf.alarm_notification then
local lwaftr = require('program.lwaftr.alarms')
alarms.default_alarms(lwaftr.alarms)
end
local preprocessing_apps_v4 = { "reassemblerv4" }
local preprocessing_apps_v6 = { "reassemblerv6" }
local postprocessing_apps_v4 = { "fragmenterv4" }
local postprocessing_apps_v6 = { "fragmenterv6" }
if gexternal_interface.ingress_filter then
config.app(c, "ingress_filterv4", PcapFilter,
{ filter = gexternal_interface.ingress_filter,
alarm_type_qualifier='ingress-v4'})
append(preprocessing_apps_v4, "ingress_filterv4")
end
if ginternal_interface.ingress_filter then
config.app(c, "ingress_filterv6", PcapFilter,
{ filter = ginternal_interface.ingress_filter,
alarm_type_qualifier='ingress-v6'})
append(preprocessing_apps_v6, "ingress_filterv6")
end
if gexternal_interface.egress_filter then
config.app(c, "egress_filterv4", PcapFilter,
{ filter = gexternal_interface.egress_filter,
alarm_type_qualifier='egress-v4'})
prepend(postprocessing_apps_v4, "egress_filterv4")
end
if ginternal_interface.egress_filter then
config.app(c, "egress_filterv6", PcapFilter,
{ filter = ginternal_interface.egress_filter,
alarm_type_qualifier='egress-v6'})
prepend(postprocessing_apps_v6, "egress_filterv6")
end
-- Add a special hairpinning queue to the lwaftr app.
config.link(c, "lwaftr.hairpin_out -> lwaftr.hairpin_in")
append(preprocessing_apps_v4, { name = "arp", input = "south", output = "north" })
append(preprocessing_apps_v4, { name = "icmpechov4", input = "south", output = "north" })
prepend(postprocessing_apps_v4, { name = "icmpechov4", input = "north", output = "south" })
prepend(postprocessing_apps_v4, { name = "arp", input = "north", output = "south" })
append(preprocessing_apps_v6, { name = "ndp", input = "south", output = "north" })
append(preprocessing_apps_v6, { name = "icmpechov6", input = "south", output = "north" })
prepend(postprocessing_apps_v6, { name = "icmpechov6", input = "north", output = "south" })
prepend(postprocessing_apps_v6, { name = "ndp", input = "north", output = "south" })
set_preprocessors(c, preprocessing_apps_v4, "lwaftr.v4")
set_preprocessors(c, preprocessing_apps_v6, "lwaftr.v6")
set_postprocessors(c, "lwaftr.v6", postprocessing_apps_v6)
set_postprocessors(c, "lwaftr.v4", postprocessing_apps_v4)
end
local function link_apps(c, apps)
for i=1, #apps - 1 do
local output, input = "output", "input"
local src, dst = apps[i], apps[i+1]
if type(src) == "table" then
src, output = src["name"], src["output"]
end
if type(dst) == "table" then
dst, input = dst["name"], dst["input"]
end
config.link(c, ("%s.%s -> %s.%s"):format(src, output, dst, input))
end
end
function set_preprocessors(c, apps, dst)
assert(type(apps) == "table")
link_apps(c, apps)
local last_app, output = apps[#apps], "output"
if type(last_app) == "table" then
last_app, output = last_app.name, last_app.output
end
config.link(c, ("%s.%s -> %s"):format(last_app, output, dst))
end
function set_postprocessors(c, src, apps)
assert(type(apps) == "table")
local first_app, input = apps[1], "input"
if type(first_app) == "table" then
first_app, input = first_app.name, first_app.input
end
config.link(c, ("%s -> %s.%s"):format(src, first_app, input))
link_apps(c, apps)
end
local function link_source(c, v4_in, v6_in)
config.link(c, v4_in..' -> reassemblerv4.input')
config.link(c, v6_in..' -> reassemblerv6.input')
end
local function link_sink(c, v4_out, v6_out)
config.link(c, 'fragmenterv4.output -> '..v4_out)
config.link(c, 'fragmenterv6.output -> '..v6_out)
end
function load_phy(c, conf, v4_nic_name, v6_nic_name, ring_buffer_size)
local v4_pci, id, queue = lwutil.parse_instance(conf)
local v6_pci = queue.external_interface.device
local v4_info = pci.device_info(v4_pci)
local v6_info = pci.device_info(v6_pci)
validate_pci_devices({v4_pci, v6_pci})
lwaftr_app(c, conf, v4_pci)
config.app(c, v4_nic_name, require(v4_info.driver).driver, {
pciaddr=v4_pci,
vmdq=true, -- Needed to enable MAC filtering/stamping.
rxq=id,
txq=id,
poolnum=0,
vlan=queue.external_interface.vlan_tag,
rxcounter=1,
ring_buffer_size=ring_buffer_size,
macaddr=ethernet:ntop(queue.external_interface.mac)})
config.app(c, v6_nic_name, require(v6_info.driver).driver, {
pciaddr=v6_pci,
vmdq=true, -- Needed to enable MAC filtering/stamping.
rxq=id,
txq=id,
poolnum=0,
vlan=queue.internal_interface.vlan_tag,
rxcounter=1,
ring_buffer_size=ring_buffer_size,
macaddr = ethernet:ntop(queue.internal_interface.mac)})
link_source(c, v4_nic_name..'.'..v4_info.tx, v6_nic_name..'.'..v6_info.tx)
link_sink(c, v4_nic_name..'.'..v4_info.rx, v6_nic_name..'.'..v6_info.rx)
end
function load_on_a_stick(c, conf, args)
local pciaddr, id, queue = lwutil.parse_instance(conf)
local device = pci.device_info(pciaddr)
local driver = require(device.driver).driver
validate_pci_devices({pciaddr})
lwaftr_app(c, conf, pciaddr)
local v4_nic_name, v6_nic_name, v4v6, mirror = args.v4_nic_name,
args.v6_nic_name, args.v4v6, args.mirror
if v4v6 then
assert(queue.external_interface.vlan_tag == queue.internal_interface.vlan_tag)
config.app(c, 'nic', driver, {
pciaddr = pciaddr,
vmdq=true, -- Needed to enable MAC filtering/stamping.
rxq=id,
txq=id,
poolnum=0,
vlan=queue.external_interface.vlan_tag,
ring_buffer_size=args.ring_buffer_size,
macaddr = ethernet:ntop(queue.external_interface.mac)})
if mirror then
local Tap = require("apps.tap.tap").Tap
local ifname = mirror
config.app(c, 'tap', Tap, ifname)
config.app(c, v4v6, V4V6, {
mirror = true
})
config.link(c, v4v6..'.mirror -> tap.input')
else
config.app(c, v4v6, V4V6)
end
config.link(c, 'nic.'..device.tx..' -> '..v4v6..'.input')
config.link(c, v4v6..'.output -> nic.'..device.rx)
link_source(c, v4v6..'.v4', v4v6..'.v6')
link_sink(c, v4v6..'.v4', v4v6..'.v6')
else
config.app(c, v4_nic_name, driver, {
pciaddr = pciaddr,
vmdq=true, -- Needed to enable MAC filtering/stamping.
rxq=id,
txq=id,
poolnum=0,
vlan=queue.external_interface.vlan_tag,
ring_buffer_size=args.ring_buffer_size,
macaddr = ethernet:ntop(queue.external_interface.mac)})
config.app(c, v6_nic_name, driver, {
pciaddr = pciaddr,
vmdq=true, -- Needed to enable MAC filtering/stamping.
rxq=id,
txq=id,
poolnum=1,
vlan=queue.internal_interface.vlan_tag,
ring_buffer_size=args.ring_buffer_size,
macaddr = ethernet:ntop(queue.internal_interface.mac)})
link_source(c, v4_nic_name..'.'..device.tx, v6_nic_name..'.'..device.tx)
link_sink(c, v4_nic_name..'.'..device.rx, v6_nic_name..'.'..device.rx)
end
end
function load_virt(c, conf, v4_nic_name, v6_nic_name)
local v4_pci, id, queue = lwutil.parse_instance(conf)
local v6_pci = queue.external_device.device
lwaftr_app(c, conf, device)
validate_pci_devices({v4_pci, v6_pci})
config.app(c, v4_nic_name, VirtioNet, {
pciaddr=v4_pci,
vlan=queue.external_interface.vlan_tag,
macaddr=ethernet:ntop(queue.external_interface.mac)})
config.app(c, v6_nic_name, VirtioNet, {
pciaddr=v6_pci,
vlan=queue.internal_interface.vlan_tag,
macaddr = ethernet:ntop(queue.internal_interface.mac)})
link_source(c, v4_nic_name..'.tx', v6_nic_name..'.tx')
link_sink(c, v4_nic_name..'.rx', v6_nic_name..'.rx')
end
function load_bench(c, conf, v4_pcap, v6_pcap, v4_sink, v6_sink)
local device, id, queue = lwutil.parse_instance(conf)
lwaftr_app(c, conf, device)
config.app(c, "capturev4", pcap.PcapReader, v4_pcap)
config.app(c, "capturev6", pcap.PcapReader, v6_pcap)
config.app(c, "repeaterv4", basic_apps.Repeater)
config.app(c, "repeaterv6", basic_apps.Repeater)
if queue.external_interface.vlan_tag then
config.app(c, "untagv4", vlan.Untagger,
{ tag=queue.external_interface.vlan_tag })
end
if queue.internal_interface.vlan_tag then
config.app(c, "untagv6", vlan.Untagger,
{ tag=queue.internal_interface.vlan_tag })
end
config.app(c, v4_sink, basic_apps.Sink)
config.app(c, v6_sink, basic_apps.Sink)
config.link(c, "capturev4.output -> repeaterv4.input")
config.link(c, "capturev6.output -> repeaterv6.input")
local v4_src, v6_src = 'repeaterv4.output', 'repeaterv6.output'
if queue.external_interface.vlan_tag then
config.link(c, v4_src.." -> untagv4.input")
v4_src = "untagv4.output"
end
if queue.internal_interface.vlan_tag then
config.link(c, v6_src.." -> untagv6.input")
v6_src = "untagv6.output"
end
link_source(c, v4_src, v6_src)
link_sink(c, v4_sink..'.input', v6_sink..'.input')
end
function load_check_on_a_stick (c, conf, inv4_pcap, inv6_pcap, outv4_pcap, outv6_pcap)
local device, id, queue = lwutil.parse_instance(conf)
lwaftr_app(c, conf, device)
config.app(c, "capturev4", pcap.PcapReader, inv4_pcap)
config.app(c, "capturev6", pcap.PcapReader, inv6_pcap)
config.app(c, "output_filev4", pcap.PcapWriter, outv4_pcap)
config.app(c, "output_filev6", pcap.PcapWriter, outv6_pcap)
if queue.external_interface.vlan_tag then
config.app(c, "untagv4", vlan.Untagger,
{ tag=queue.external_interface.vlan_tag })
config.app(c, "tagv4", vlan.Tagger,
{ tag=queue.external_interface.vlan_tag })
end
if queue.internal_interface.vlan_tag then
config.app(c, "untagv6", vlan.Untagger,
{ tag=queue.internal_interface.vlan_tag })
config.app(c, "tagv6", vlan.Tagger,
{ tag=queue.internal_interface.vlan_tag })
end
config.app(c, 'v4v6', V4V6)
config.app(c, 'splitter', V4V6)
config.app(c, 'join', basic_apps.Join)
local sources = { "v4v6.v4", "v4v6.v6" }
local sinks = { "v4v6.v4", "v4v6.v6" }
if queue.external_interface.vlan_tag then
config.link(c, "capturev4.output -> untagv4.input")
config.link(c, "capturev6.output -> untagv6.input")
config.link(c, "untagv4.output -> join.in1")
config.link(c, "untagv6.output -> join.in2")
config.link(c, "join.output -> v4v6.input")
config.link(c, "v4v6.output -> splitter.input")
config.link(c, "splitter.v4 -> tagv4.input")
config.link(c, "splitter.v6 -> tagv6.input")
config.link(c, "tagv4.output -> output_filev4.input")
config.link(c, "tagv6.output -> output_filev6.input")
else
config.link(c, "capturev4.output -> join.in1")
config.link(c, "capturev6.output -> join.in2")
config.link(c, "join.output -> v4v6.input")
config.link(c, "v4v6.output -> splitter.input")
config.link(c, "splitter.v4 -> output_filev4.input")
config.link(c, "splitter.v6 -> output_filev6.input")
end
link_source(c, unpack(sources))
link_sink(c, unpack(sinks))
end
function load_check(c, conf, inv4_pcap, inv6_pcap, outv4_pcap, outv6_pcap)
local device, id, queue = lwutil.parse_instance(conf)
lwaftr_app(c, conf, device)
config.app(c, "capturev4", pcap.PcapReader, inv4_pcap)
config.app(c, "capturev6", pcap.PcapReader, inv6_pcap)
config.app(c, "output_filev4", pcap.PcapWriter, outv4_pcap)
config.app(c, "output_filev6", pcap.PcapWriter, outv6_pcap)
if queue.external_interface.vlan_tag then
config.app(c, "untagv4", vlan.Untagger,
{ tag=queue.external_interface.vlan_tag })
config.app(c, "tagv4", vlan.Tagger,
{ tag=queue.external_interface.vlan_tag })
end
if queue.internal_interface.vlan_tag then
config.app(c, "untagv6", vlan.Untagger,
{ tag=queue.internal_interface.vlan_tag })
config.app(c, "tagv6", vlan.Tagger,
{ tag=queue.internal_interface.vlan_tag })
end
local sources = { "capturev4.output", "capturev6.output" }
local sinks = { "output_filev4.input", "output_filev6.input" }
if queue.external_interface.vlan_tag then
sources = { "untagv4.output", "untagv6.output" }
sinks = { "tagv4.input", "tagv6.input" }
config.link(c, "capturev4.output -> untagv4.input")
config.link(c, "capturev6.output -> untagv6.input")
config.link(c, "tagv4.output -> output_filev4.input")
config.link(c, "tagv6.output -> output_filev6.input")
end
link_source(c, unpack(sources))
link_sink(c, unpack(sinks))
end
function load_soak_test(c, conf, inv4_pcap, inv6_pcap)
local device, id, queue = lwutil.parse_instance(conf)
lwaftr_app(c, conf, device)
config.app(c, "capturev4", pcap.PcapReader, inv4_pcap)
config.app(c, "capturev6", pcap.PcapReader, inv6_pcap)
config.app(c, "loop_v4", basic_apps.Repeater)
config.app(c, "loop_v6", basic_apps.Repeater)
config.app(c, "sink", basic_apps.Sink)
if queue.external_interface.vlan_tag then
config.app(c, "untagv4", vlan.Untagger,
{ tag=queue.external_interface.vlan_tag })
config.app(c, "tagv4", vlan.Tagger,
{ tag=queue.external_interface.vlan_tag })
end
if queue.internal_interface.vlan_tag then
config.app(c, "untagv6", vlan.Untagger,
{ tag=queue.internal_interface.vlan_tag })
config.app(c, "tagv6", vlan.Tagger,
{ tag=queue.internal_interface.vlan_tag })
end
local sources = { "loop_v4.output", "loop_v6.output" }
local sinks = { "sink.v4", "sink.v6" }
config.link(c, "capturev4.output -> loop_v4.input")
config.link(c, "capturev6.output -> loop_v6.input")
if queue.external_interface.vlan_tag then
sources = { "untagv4.output", "untagv6.output" }
sinks = { "tagv4.input", "tagv6.input" }
config.link(c, "loop_v4.output -> untagv4.input")
config.link(c, "loop_v6.output -> untagv6.input")
config.link(c, "tagv4.output -> sink.v4")
config.link(c, "tagv6.output -> sink.v6")
end
link_source(c, unpack(sources))
link_sink(c, unpack(sinks))
end
function load_soak_test_on_a_stick (c, conf, inv4_pcap, inv6_pcap)
local device, id, queue = lwutil.parse_instance(conf)
lwaftr_app(c, conf, device)
config.app(c, "capturev4", pcap.PcapReader, inv4_pcap)
config.app(c, "capturev6", pcap.PcapReader, inv6_pcap)
config.app(c, "loop_v4", basic_apps.Repeater)
config.app(c, "loop_v6", basic_apps.Repeater)
config.app(c, "sink", basic_apps.Sink)
if queue.external_interface.vlan_tag then
config.app(c, "untagv4", vlan.Untagger,
{ tag=queue.external_interface.vlan_tag })
config.app(c, "tagv4", vlan.Tagger,
{ tag=queue.external_interface.vlan_tag })
end
if queue.internal_interface.vlan_tag then
config.app(c, "untagv6", vlan.Untagger,
{ tag=queue.internal_interface.vlan_tag })
config.app(c, "tagv6", vlan.Tagger,
{ tag=queue.internal_interface.vlan_tag })
end
config.app(c, 'v4v6', V4V6)
config.app(c, 'splitter', V4V6)
config.app(c, 'join', basic_apps.Join)
local sources = { "v4v6.v4", "v4v6.v6" }
local sinks = { "v4v6.v4", "v4v6.v6" }
config.link(c, "capturev4.output -> loop_v4.input")
config.link(c, "capturev6.output -> loop_v6.input")
if queue.external_interface.vlan_tag then
config.link(c, "loop_v4.output -> untagv4.input")
config.link(c, "loop_v6.output -> untagv6.input")
config.link(c, "untagv4.output -> join.in1")
config.link(c, "untagv6.output -> join.in2")
config.link(c, "join.output -> v4v6.input")
config.link(c, "v4v6.output -> splitter.input")
config.link(c, "splitter.v4 -> tagv4.input")
config.link(c, "splitter.v6 -> tagv6.input")
config.link(c, "tagv4.output -> sink.in1")
config.link(c, "tagv6.output -> sink.in2")
else
config.link(c, "loop_v4.output -> join.in1")
config.link(c, "loop_v6.output -> join.in2")
config.link(c, "join.output -> v4v6.input")
config.link(c, "v4v6.output -> splitter.input")
config.link(c, "splitter.v4 -> sink.in1")
config.link(c, "splitter.v6 -> sink.in2")
end
link_source(c, unpack(sources))
link_sink(c, unpack(sinks))
end
-- Produces configuration for each worker. Each queue on each device
-- will get its own worker process.
local function compute_worker_configs(conf)
local ret = {}
local copier = binary.config_copier_for_schema_by_name('snabb-softwire-v2')
local make_copy = copier(conf)
for device, queues in pairs(conf.softwire_config.instance) do
for k, _ in cltable.pairs(queues.queue) do
local worker_id = string.format('%s/%s', device, k.id)
local worker_config = make_copy()
local instance = worker_config.softwire_config.instance
for other_device, queues in pairs(conf.softwire_config.instance) do
if other_device ~= device then
instance[other_device] = nil
else
for other_k, _ in cltable.pairs(queues.queue) do
if other_k.id ~= k.id then
instance[device].queue[other_k] = nil
end
end
end
end
ret[worker_id] = worker_config
end
end
return ret
end
function ptree_manager(f, conf, manager_opts)
-- Claim the name if one is defined.
local function switch_names(config)
local currentname = engine.program_name
local name = config.softwire_config.name
-- Don't do anything if the name isn't set.
if name == nil then
return
end
local success, err = pcall(engine.claim_name, name)
if success == false then
-- Restore the previous name.
config.softwire_config.name = currentname
assert(success, err)
end
end
local function setup_fn(conf)
switch_names(conf)
local worker_app_graphs = {}
for worker_id, worker_config in pairs(compute_worker_configs(conf)) do
local app_graph = config.new()
worker_config.alarm_notification = true
f(app_graph, worker_config)
worker_app_graphs[worker_id] = app_graph
end
return worker_app_graphs
end
local initargs = {
setup_fn = setup_fn,
initial_configuration = conf,
schema_name = 'snabb-softwire-v2',
default_schema = 'ietf-softwire-br',
-- log_level="DEBUG"
}
for k, v in pairs(manager_opts or {}) do
assert(not initargs[k])
initargs[k] = v
end
return manager.new_manager(initargs)
end
| apache-2.0 |
FailcoderAddons/supervillain-ui | SVUI_Skins/components/blizzard/friends.lua | 1 | 10811 | --[[
##############################################################################
S V U I By: Failcoder
##############################################################################
--]]
--[[ GLOBALS ]]--
local _G = _G;
local unpack = _G.unpack;
local select = _G.select;
local ipairs = _G.ipairs;
local pairs = _G.pairs;
--[[ ADDON ]]--
local SV = _G['SVUI'];
local L = SV.L;
local MOD = SV.Skins;
local Schema = MOD.Schema;
--[[
##########################################################
HELPERS
##########################################################
]]--
local FrameSuffix = {
"LeftDisabled",
"MiddleDisabled",
"RightDisabled",
"Left",
"Middle",
"Right"
};
local FriendsFrameList1 = {
"ScrollOfResurrectionSelectionFrame",
"ScrollOfResurrectionSelectionFrameList",
"FriendsListFrame",
"FriendsTabHeader",
"FriendsFrameFriendsScrollFrameScrollBar",
"WhoFrameColumnHeader1",
"WhoFrameColumnHeader2",
"WhoFrameColumnHeader3",
"WhoFrameColumnHeader4",
"ChannelListScrollFrameScrollBar",
"ChannelRoster",
"FriendsFramePendingButton1",
"FriendsFramePendingButton2",
"FriendsFramePendingButton3",
"FriendsFramePendingButton4",
"ChannelFrameDaughterFrame",
"AddFriendFrame",
"AddFriendNoteFrame",
"QuickJoinFrame",
"QuickJoinScrollFrame",
"QuickJoinRoleSelectionFrame"
};
local FriendsFrameButtons = {
"FriendsFrameAddFriendButton",
"FriendsFrameSendMessageButton",
"WhoFrameWhoButton",
"WhoFrameAddFriendButton",
"WhoFrameGroupInviteButton",
"ChannelFrameNewButton",
"FriendsFrameIgnorePlayerButton",
"FriendsFrameUnsquelchButton",
"FriendsFramePendingButton1AcceptButton",
"FriendsFramePendingButton1DeclineButton",
"FriendsFramePendingButton2AcceptButton",
"FriendsFramePendingButton2DeclineButton",
"FriendsFramePendingButton3AcceptButton",
"FriendsFramePendingButton3DeclineButton",
"FriendsFramePendingButton4AcceptButton",
"FriendsFramePendingButton4DeclineButton",
"ChannelFrameDaughterFrameOkayButton",
"ChannelFrameDaughterFrameCancelButton",
"AddFriendEntryFrameAcceptButton",
"AddFriendEntryFrameCancelButton",
"AddFriendInfoFrameContinueButton",
"ScrollOfResurrectionSelectionFrameAcceptButton",
"ScrollOfResurrectionSelectionFrameCancelButton"
};
local function TabCustomHelper(this)
if not this then return end
for _,prop in pairs(FrameSuffix) do
local frame = _G[this:GetName()..prop]
frame:SetTexture("")
end
this:GetHighlightTexture():SetTexture("")
this.backdrop = CreateFrame("Frame", nil, this)
this.backdrop:SetStyle("!_Frame", "Default")
this.backdrop:SetFrameLevel(this:GetFrameLevel()-1)
this.backdrop:SetPoint("TOPLEFT", 3, -8)
this.backdrop:SetPoint("BOTTOMRIGHT", -6, 0)
end
local function ChannelList_OnUpdate()
for i = 1, MAX_DISPLAY_CHANNEL_BUTTONS do
local btn = _G["ChannelButton"..i]
if btn then
btn:RemoveTextures()
btn:SetHighlightTexture("Interface\\PaperDollInfoFrame\\UI-Character-Tab-Highlight")
_G["ChannelButton"..i.."Text"]:SetFontObject(SVUI_Font_Default)
end
end
end
--[[
##########################################################
FRIENDSFRAME MODR
##########################################################
]]--FriendsFrameBattlenetFrameScrollFrame
local function FriendsFrameStyle()
--print('test FriendsFrameStyle')
if SV.db.Skins.blizzard.enable ~= true or SV.db.Skins.blizzard.friends ~= true then
return
end
SV.API:Set("Window", FriendsFrame)
FriendsFrameInset:RemoveTextures()
WhoFrameListInset:RemoveTextures()
WhoFrameEditBoxInset:RemoveTextures()
SV.API:Set("EditBox", WhoFrameEditBoxInset)
--ChannelFrameRightInset:RemoveTextures()
--ChannelFrameLeftInset:RemoveTextures()
--ChannelFrameRightInset:SetStyle("!_Frame", "Model")
--ChannelFrameLeftInset:SetStyle("!_Frame", "Model")
LFRQueueFrameListInset:RemoveTextures()
LFRQueueFrameRoleInset:RemoveTextures()
LFRQueueFrameCommentInset:RemoveTextures()
LFRQueueFrameListInset:SetStyle("!_Frame", "Model")
FriendsFrameInset:SetStyle("!_Frame", "Model")
--FriendsFrameFriendsScrollFrameScrollBar:SetStyle("!_Frame", "Model")
WhoFrameListInset:SetStyle("!_Frame", "Model")
--RaidFrame:SetStyle("!_Frame", "Model")
for _, frame in pairs(FriendsFrameButtons)do
if(_G[frame]) then
_G[frame]:SetStyle("Button")
end
end
-- for c, texture in pairs(FriendsFrameList2)do
-- _G[texture]:Die()
-- end
for _, frame in pairs(FriendsFrameList1) do
if(_G[frame]) then
_G[frame]:RemoveTextures(true)
end
end
for i = 1, FriendsFrame:GetNumRegions()do
local a1 = select(i, FriendsFrame:GetRegions())
if a1:GetObjectType() == "Texture"then
a1:SetTexture("")
a1:SetAlpha(0)
end
end
FriendsFrameFriendsScrollFrame:DisableDrawLayer("BACKGROUND")
SV.API:Set("ScrollBar", FriendsFrameFriendsScrollFrame, 5)
SV.API:Set("ScrollBar", WhoListScrollFrame, 5)
SV.API:Set("ScrollBar", ChannelFrame.ChannelRoster.ScrollFrame, 5)
SV.API:Set("ScrollBar", QuickJoinScrollFrame, 5)
FriendsFrameStatusDropDown:SetPoint('TOPLEFT', FriendsTabHeader, 'TOPLEFT', 0, -27)
SV.API:Set("DropDown", FriendsFrameStatusDropDown, 70)
FriendsFrameBattlenetFrame:RemoveTextures()
FriendsFrameBattlenetFrame:SetHeight(22)
FriendsFrameBattlenetFrame:SetPoint('TOPLEFT', FriendsFrameStatusDropDown, 'TOPRIGHT', 0, -1)
FriendsFrameBattlenetFrame:SetStyle("!_Frame", "Inset")
FriendsFrameBattlenetFrame:SetBackdropColor(0,0,0,0.8)
-- FriendsFrameBattlenetFrame.BroadcastButton:GetNormalTexture():SetTexCoord(.28, .72, .28, .72)
-- FriendsFrameBattlenetFrame.BroadcastButton:GetPushedTexture():SetTexCoord(.28, .72, .28, .72)
-- FriendsFrameBattlenetFrame.BroadcastButton:GetHighlightTexture():SetTexCoord(.28, .72, .28, .72)
FriendsFrameBattlenetFrame.BroadcastButton:RemoveTextures()
FriendsFrameBattlenetFrame.BroadcastButton:SetSize(22,22)
FriendsFrameBattlenetFrame.BroadcastButton:SetPoint('TOPLEFT', FriendsFrameBattlenetFrame, 'TOPRIGHT', 8, 0)
FriendsFrameBattlenetFrame.BroadcastButton:SetStyle("Button")
FriendsFrameBattlenetFrame.BroadcastButton:SetBackdropColor(0.4,0.4,0.4)
FriendsFrameBattlenetFrame.BroadcastButton:SetNormalTexture([[Interface\FriendsFrame\UI-Toast-BroadcastIcon]])
FriendsFrameBattlenetFrame.BroadcastButton:SetPushedTexture([[Interface\FriendsFrame\UI-Toast-BroadcastIcon]])
FriendsFrameBattlenetFrame.BroadcastButton:SetScript('OnClick', function()
SV:StaticPopup_Show("SET_BN_BROADCAST")
end)
QuickJoinFrame.JoinQueueButton:RemoveTextures();
QuickJoinFrame.JoinQueueButton:SetStyle("Button");
QuickJoinFrame.JoinQueueButton:ClearAllPoints();
QuickJoinFrame.JoinQueueButton:SetPoint("BOTTOMRIGHT", QuickJoinFrame, "BOTTOMRIGHT", -6, 2);
FriendsFrameBattlenetFrame.Tag:SetFontObject(SVUI_Font_Narrator)
AddFriendNameEditBox:SetStyle("Editbox")
AddFriendFrame:SetStyle("!_Frame", "Transparent", true)
ScrollOfResurrectionSelectionFrame:SetStyle("!_Frame", 'Transparent')
ScrollOfResurrectionSelectionFrameList:SetStyle("!_Frame", 'Default')
SV.API:Set("ScrollBar", ScrollOfResurrectionSelectionFrameListScrollFrame, 4)
ScrollOfResurrectionSelectionFrameTargetEditBox:SetStyle("Editbox")
FriendsFrameBroadcastInput:SetStyle("Frame", "Default")
--ChannelFrameDaughterFrameChannelName:SetStyle("Frame", "Default")
--ChannelFrameDaughterFrameChannelPassword:SetStyle("Frame", "Default")
ChannelFrame:HookScript("OnShow", function()
ChannelFrame.ChannelRoster.ScrollFrame.scrollBar:RemoveTextures()
end)
hooksecurefunc("FriendsFrame_OnEvent", function()
ChannelFrame.ChannelRoster.ScrollFrame.scrollBar:RemoveTextures()
end)
WhoFrame:HookScript("OnShow", function()
ChannelFrame.ChannelRoster.ScrollFrame.scrollBar:RemoveTextures()
end)
hooksecurefunc("FriendsFrame_OnEvent", function()
WhoListScrollFrameScrollBar:RemoveTextures()
end)
--ChannelFrameDaughterFrame:SetStyle("Frame", 'Inset')
--SV.API:Set("CloseButton", ChannelFrameDaughterFrameDetailCloseButton, ChannelFrameDaughterFrame)
SV.API:Set("CloseButton", FriendsFrameCloseButton, FriendsFrame.Panel)
SV.API:Set("DropDown", WhoFrameDropDown, 150)
for i = 1, 4 do
SV.API:Set("Tab", _G["FriendsFrameTab"..i])
end
for i = 1, 3 do
TabCustomHelper(_G["FriendsTabHeaderTab"..i])
end
--hooksecurefunc("ChannelList_Update", ChannelList_OnUpdate)
FriendsFriendsFrame:SetStyle("Frame", 'Inset')
_G["FriendsFriendsFrame"]:RemoveTextures()
_G["FriendsFriendsList"]:RemoveTextures()
--_G["FriendsFriendsNoteFrame"]:RemoveTextures()
_G["FriendsFriendsSendRequestButton"]:SetStyle("Button")
_G["FriendsFriendsCloseButton"]:SetStyle("Button")
FriendsFriendsList:SetStyle("Editbox")
--FriendsFriendsNoteFrame:SetStyle("Editbox")
SV.API:Set("DropDown", FriendsFriendsFrameDropDown, 150)
--BNConversationInviteDialog:RemoveTextures()
--BNConversationInviteDialog:SetStyle("Frame", 'Transparent')
--BNConversationInviteDialogList:RemoveTextures()
--BNConversationInviteDialogList:SetStyle("!_Frame", 'Default')
--BNConversationInviteDialogInviteButton:SetStyle("Button")
--BNConversationInviteDialogCancelButton:SetStyle("Button")
--for i = 1, BN_CONVERSATION_INVITE_NUM_DISPLAYED do
-- _G["BNConversationInviteDialogListFriend"..i].checkButton:SetStyle("CheckButton")
--end
FriendsTabHeaderSoRButton:SetStyle("!_Frame", 'Default')
FriendsTabHeaderSoRButton:SetStyle("Button")
FriendsTabHeaderSoRButtonIcon:SetDrawLayer('OVERLAY')
FriendsTabHeaderSoRButtonIcon:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
FriendsTabHeaderSoRButtonIcon:InsetPoints()
FriendsTabHeaderSoRButton:SetPoint('TOPRIGHT', FriendsTabHeader, 'TOPRIGHT', -8, -56)
FriendsTabHeaderRecruitAFriendButton:SetStyle("!_Frame", 'Default')
FriendsTabHeaderRecruitAFriendButton:SetStyle("Button")
FriendsTabHeaderRecruitAFriendButtonIcon:SetDrawLayer('OVERLAY')
FriendsTabHeaderRecruitAFriendButtonIcon:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
FriendsTabHeaderRecruitAFriendButtonIcon:InsetPoints()
FriendsFrameIgnoreScrollFrameScrollBar:SetStyle("!_Frame", "Model")
SV.API:Set("ScrollBar", FriendsFrameIgnoreScrollFrame, 4)
IgnoreListFrame:RemoveTextures()
ScrollOfResurrectionFrame:RemoveTextures()
ScrollOfResurrectionFrameAcceptButton:SetStyle("Button")
ScrollOfResurrectionFrameCancelButton:SetStyle("Button")
ScrollOfResurrectionFrameTargetEditBoxLeft:SetTexture("")
ScrollOfResurrectionFrameTargetEditBoxMiddle:SetTexture("")
ScrollOfResurrectionFrameTargetEditBoxRight:SetTexture("")
ScrollOfResurrectionFrameNoteFrame:RemoveTextures()
ScrollOfResurrectionFrameNoteFrame:SetStyle("!_Frame")
ScrollOfResurrectionFrameTargetEditBox:SetStyle("!_Frame")
ScrollOfResurrectionFrame:SetStyle("!_Frame", 'Transparent')
end
--[[
##########################################################
MOD LOADING
##########################################################
]]--
MOD:SaveCustomStyle("FRIENDS", FriendsFrameStyle)
| mit |
nesstea/darkstar | scripts/globals/spells/lightning_carol.lua | 27 | 1547 | -----------------------------------------
-- Spell: Lightning Carol
-- Increases lightning resistance for party members within the area of effect.
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
local power = 20;
if (sLvl+iLvl > 200) then
power = power + math.floor((sLvl+iLvl-200) / 10);
end
if (power >= 40) then
power = 40;
end
local iBoost = caster:getMod(MOD_CAROL_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
power = power + iBoost*5;
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_CAROL,power,0,duration,caster:getID(), ELE_LIGHTNING, 1)) then
spell:setMsg(75);
end
return EFFECT_CAROL;
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Port_Bastok/npcs/Corann.lua | 29 | 2129 | -----------------------------------
-- Area: Port Bastok
-- NPC: Corann
-- Start & Finishes Quest: The Quadav's Curse
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
TheQuadav = player:getQuestStatus(BASTOK,THE_QUADAV_S_CURSE);
if (TheQuadav == QUEST_ACCEPTED) then
count = trade:getItemCount();
QuadavBack = trade:hasItemQty(596,1);
if (count == 1 and QuadavBack == true) then
player:startEvent(0x0051);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
TheQuadav = player:getQuestStatus(BASTOK,THE_QUADAV_S_CURSE);
OutOfOneShell = player:getQuestStatus(BASTOK,OUT_OF_ONE_S_SHELL);
if (OutOfOneShell == QUEST_COMPLETED) then
player:startEvent(0x0058);
elseif (TheQuadav == QUEST_COMPLETED) then
player:startEvent(0x0057);
elseif (TheQuadav == QUEST_AVAILABLE) then
player:startEvent(0x0050);
else
player:startEvent(0x0026);
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 == 0x0050) then
player:addQuest(BASTOK,THE_QUADAV_S_CURSE);
elseif (csid == 0x0051) then
player:tradeComplete();
player:completeQuest(BASTOK,THE_QUADAV_S_CURSE);
player:addFame(BASTOK,120);
player:addItem(12832);
player:messageSpecial(ITEM_OBTAINED,12832);
end
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Ifrits_Cauldron/npcs/Altar_of_Ashes.lua | 17 | 1977 | ----------------------------------
-- Area: Ifrit's Cauldron
-- NPC: Altar of Ashes
-- Involved in Quest: Greetings to the Guardian
-- @pos 16 .1 -58 205
-----------------------------------
require("scripts/zones/Ifrits_Cauldron/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local Guardian = player:getQuestStatus(OUTLANDS,GREETINGS_TO_THE_GUARDIAN);
if(Guardian == QUEST_ACCEPTED and trade:hasItemQty(4596,1)) then
player:messageSpecial(ALTAR_OFFERING,0,4596);
player:setVar("PamamaVar",1); --Set variable to reflect first completion of quest
player:tradeComplete();
elseif(Guardian == QUEST_COMPLETED and trade:hasItemQty(4596,1)) then
player:messageSpecial(ALTAR_OFFERING,0,4596);
player:setVar("PamamaVar",2); --Set variable to reflect repeat of quest, not first time
player:tradeComplete();
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Guardian = player:getQuestStatus(OUTLANDS,GREETINGS_TO_THE_GUARDIAN);
if(Guardian == QUEST_ACCEPTED and player:getVar("PamamaVar") == 1 or player:getVar("PamamaVar") == 2) then
player:messageSpecial(ALTAR_COMPLETED);
elseif(Guardian == QUEST_ACCEPTED and player:getVar("PamamaVar") == 0) then
player:messageSpecial(ALTAR_INSPECT);
else
player:messageSpecial(ALTAR_STANDARD);
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 |
nesstea/darkstar | scripts/globals/weaponskills/power_slash.lua | 11 | 1698 | -----------------------------------
-- Power Slash
-- Great Sword weapon skill
-- Skill level: 30
-- Delivers a single-hit attack. params.crit varies with TP.
-- Modifiers: STR:60% ; VIT:60%
-- 100%TP 200%TP 300%TP
-- 1.0 1.0 1.0
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.numHits = 1;
-- ftp damage mods (for Damage Varies with TP; lines are calculated in the function
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
-- wscs are in % so 0.2=20%
params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.2; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
-- critical mods, again in % (ONLY USE FOR CRITICAL HIT VARIES WITH TP)
params.crit100 = 0.2; params.crit200=0.4; params.crit300=0.6;
params.canCrit = true;
-- accuracy mods (ONLY USE FOR ACCURACY VARIES WITH TP) , should be the acc at those %s NOT the penalty values. Leave 0 if acc doesnt vary with tp.
params.acc100 = 0; params.acc200=0; params.acc300=0;
-- attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default.
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.6; params.vit_wsc = 0.6;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/items/anchovy_pizza.lua | 35 | 1225 | -----------------------------------------
-- ID: 5699
-- Item: anchovy_pizza
-- Food Effect: 3hours, All Races
-----------------------------------------
-- Dexterity 1
-- Attack 20%
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5699);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 1);
target:addMod(MOD_FOOD_ATTP, 20);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 1);
target:delMod(MOD_FOOD_ATTP, 20);
end;
| gpl-3.0 |
LuaDist2/servicekit-posix | servicekit.lua | 2 | 3180 | #!/usr/bin/env lua
---
-- Servicekit: a platform-agnostic daemonization API
--
-- These are the routines that the ServiceKit user calls directly.
--
-- @module servicekit
--
local _servicekit = {}
local _events = require "servicekit.events"
local posix = require 'posix'
---
-- Contains the version number of this ServiceKit instance
--
_servicekit.version = "1.0 2012.1109"
---
-- Contains the platform this ServiceKit instance runs on
--
_servicekit.platform = "posix"
--
-- Detach from our controlling terminal.
--
local function detach()
--
-- Fork. Parent dies. Negative pids equal an error.
--
local pid = posix.fork()
if pid < 0 then
err, errno = posix.errno()
error("Fork failed, errno " .. tostring(err))
end
-- We're the parent.
if pid > 0 then
os.exit(0)
end
--
-- Become process group leader. This causes a full disconnect
-- from the controlling terminal.
--
-- Minimal error handling. This failing is rare.
--
assert(posix.setpid('s'), 'Cannot start new session')
--
-- Set working directory to '/', so filesystem mounting/unmounting
-- isn't a bear.
--
-- We will let people who want a chroot() do that later.
--
-- No error message? Sorry. We're detached now.
--
assert(posix.chdir('/'))
--
-- Disconnect stdin/out/err and replace with /dev/null. This
-- prevents a stray print() command or io.read/write from molesting
-- a hapless network socket.
--
local devnull, err = posix.open("/dev/null", posix.O_RDONLY)
assert(devnull, "Couldn't open /dev/null: " .. tostring(err))
assert(posix.dup2(devnull, 0), "Cannot dup stdin")
assert(posix.dup2(devnull, 1), "Cannot dup stdout")
assert(posix.dup2(devnull, 2), "Cannot dup stderr")
end
---
-- Handle a sigterm or sigint
--
local function term_handler()
_events.beginstop()
end
---
-- Handle a sighup
--
local function reload_handler()
_events.reload()
end
---
-- Setup signal handling.
--
local function setsignals()
posix.signal(posix.SIGINT, term_handler)
posix.signal(posix.SIGTERM, term_handler)
posix.signal(posix.SIGHUP, reload_handler)
end
---
-- Setup a new service. MUST be called before anything else.
--
-- @param events A table of event handler callbacks that implement your
-- service. The minimal set of events consists of just
-- run() and beginstop().
--
-- @see events
--
function _servicekit.setup( events )
assert(type(events) == 'table')
for k, v in pairs(events) do
assert(_events[k], 'Unknown event: ' .. k)
_events[k] = v
end
_events.ready = true
end
---
-- Runs the service.
--
-- @param detached If true, the program detaches into the background.
-- Set to false to keep the program in the foreground
-- instead. If omitted, defaults to true.
--
function _servicekit.run( detached )
assert(_events.ready, "Service is undefined: call setup() first")
if detached == nil then detached = true end
if detached then detach() end
setsignals()
_events.start()
_events.run()
_events.stop()
end
---
-- Returns the process ID, or some other valid identifier on other
-- platforms.
--
function _servicekit.pid()
return posix.getpid('pid')
end
return _servicekit
| mit |
nesstea/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Count_Zaebos.lua | 2 | 1595 | -----------------------------------
-- Area: Dynamis Xarcabard
-- MOB: Count Zaebos
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Xarcabard/TextIDs");
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger");
if (mob:isInBattlefieldList() == false) then
mob:addInBattlefieldList();
Animate_Trigger = Animate_Trigger + 128;
SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger);
if (Animate_Trigger == 32767) then
SpawnMob(17330911); -- 142
SpawnMob(17330912); -- 143
SpawnMob(17330177); -- Dynamis Lord
GetMobByID(17330183):setSpawn(-364,-35.661,17.254); -- Set Ying and Yang's spawn points to their initial spawn point.
GetMobByID(17330184):setSpawn(-364,-35.974,24.254);
SpawnMob(17330183);
SpawnMob(17330184);
activateAnimatedWeapon(); -- Change subanim of all animated weapon
end
end
if (Animate_Trigger == 32767) then
ally:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE);
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/items/bowl_of_nashmau_stew.lua | 36 | 1975 | -----------------------------------------
-- ID: 5595
-- Item: Bowl of Nashmau Stew
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- MP -100
-- Vitality -10
-- Agility -10
-- Intelligence -10
-- Mind -10
-- Charisma -10
-- Accuracy +15% Cap 25
-- Attack +18% Cap 60
-- Defense -100
-- Evasion -100
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5595);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, -100);
target:addMod(MOD_VIT, -10);
target:addMod(MOD_AGI, -10);
target:addMod(MOD_INT, -10);
target:addMod(MOD_MND, -10);
target:addMod(MOD_CHR, -10);
target:addMod(MOD_FOOD_ACCP, 18);
target:addMod(MOD_FOOD_ACC_CAP, 25);
target:addMod(MOD_FOOD_ATTP, 15);
target:addMod(MOD_FOOD_ATT_CAP, 60);
target:addMod(MOD_DEF, -100);
target:addMod(MOD_EVA, -100);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, -100);
target:delMod(MOD_VIT, -10);
target:delMod(MOD_AGI, -10);
target:delMod(MOD_INT, -10);
target:delMod(MOD_MND, -10);
target:delMod(MOD_CHR, -10);
target:delMod(MOD_FOOD_ACCP, 18);
target:delMod(MOD_FOOD_ACC_CAP, 25);
target:delMod(MOD_FOOD_ATTP, 15);
target:delMod(MOD_FOOD_ATT_CAP, 60);
target:delMod(MOD_DEF, -100);
target:delMod(MOD_EVA, -100);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/globals/abilities/pets/geocrush.lua | 28 | 1448 | ---------------------------------------------------
-- Geocrush
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/globals/magic");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill)
local dINT = math.floor(pet:getStat(MOD_INT) - target:getStat(MOD_INT));
local tp = skill:getTP() / 10;
local master = pet:getMaster();
local merits = 0;
if (master ~= nil and master:isPC()) then
merits = master:getMerit(MERIT_GEOCRUSH);
end
tp = tp + (merits - 40);
if (tp > 300) then
tp = 300;
end
--note: this formula is only accurate for level 75 - 76+ may have a different intercept and/or slope
local damage = math.floor(512 + 1.72*(tp+1));
damage = damage + (dINT * 1.5);
damage = MobMagicalMove(pet,target,skill,damage,ELE_EARTH,1,TP_NO_EFFECT,0);
damage = mobAddBonuses(pet, nil, target, damage.dmg, ELE_EARTH);
damage = AvatarFinalAdjustments(damage,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_NONE,1);
target:delHP(damage);
target:updateEnmityFromDamage(pet,damage);
if (target:hasStatusEffect(EFFECT_STUN) == false) then
target:addStatusEffect(EFFECT_STUN,3,3,3);
end
return damage;
end | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Windurst_Waters/npcs/Ohbiru-Dohbiru.lua | 19 | 9351 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Ohbiru-Dohbiru
-- Involved in quest: Food For Thought
-- Starts and finishes quest: Toraimarai Turmoil
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local turmoil = player:getQuestStatus(WINDURST,TORAIMARAI_TURMOIL);
local count = trade:getItemCount();
if(player:getQuestStatus(WINDURST,WATER_WAY_TO_GO) == QUEST_ACCEPTED) then
if(trade:hasItemQty(4351,1) and count == 1) then
player:startEvent(0x0163,900);
end
elseif (player:getQuestStatus(WINDURST,FOOD_FOR_THOUGHT) == QUEST_ACCEPTED) then
local OhbiruFood = player:getVar("Ohbiru_Food_var");
if (trade:hasItemQty(4493,1) == true and trade:hasItemQty(4408,1) == true and trade:hasItemQty(624,1) == true and count == 3 and OhbiruFood ~= 2) then -- Traded all 3 items & Didn't ask for order
rand = math.random(1,2);
if (rand == 1) then
player:startEvent(0x0145,440);
else
player:startEvent(0x0146);
end
elseif (trade:hasItemQty(4493,1) == true and trade:hasItemQty(4408,1) == true and trade:hasItemQty(624,1) == true and count == 3 and OhbiruFood == 2) then -- Traded all 3 items after receiving order
player:startEvent(0x0142,440);
end
elseif(turmoil == QUEST_ACCEPTED) then
if(count == 3 and trade:getGil() == 0 and trade:hasItemQty(906,3) == true) then --Check that all 3 items have been traded
player:startEvent(0x0317);
else
player:startEvent(0x0312,4500,267,906); -- Reminder of needed items
end
elseif(turmoil == QUEST_COMPLETED) then
if(count == 3 and trade:getGil () == 0 and trade:hasItemQty(906,3) == true) then --Check that all 3 items have been traded
player:startEvent(0x0317);
else
player:startEvent(0x031b,4500,0,906); -- Reminder of needed items for repeated quest
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Check for Missions first (priority?)
-- If the player has started the mission or not
local pfame = player:getFameLevel(WINDURST);
local turmoil = player:getQuestStatus(WINDURST,TORAIMARAI_TURMOIL);
local FoodForThought = player:getQuestStatus(WINDURST,FOOD_FOR_THOUGHT);
local needToZone = player:needToZone();
local OhbiruFood = player:getVar("Ohbiru_Food_var"); -- Variable to track progress of Ohbiru-Dohbiru in Food for Thought
local waterWayToGo = player:getQuestStatus(WINDURST,WATER_WAY_TO_GO);
local overnightDelivery = player:getQuestStatus(WINDURST,OVERNIGHT_DELIVERY);
if(player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("MEMORIES_OF_A_MAIDEN_Status")==2)then
player:startEvent(0x0368);
elseif(player:getCurrentMission(WINDURST) == THE_PRICE_OF_PEACE) then
if(player:getVar("ohbiru_dohbiru_talk") == 1) then
player:startEvent(0x8f);
else
player:startEvent(0x90);
end
elseif(waterWayToGo == QUEST_COMPLETED and needToZone) then
player:startEvent(0x0164,0,4351);
elseif(waterWayToGo == QUEST_ACCEPTED) then
if(player:hasItem(504) == false and player:hasItem(4351) == false) then
player:startEvent(0x0162);
else
player:startEvent(0x0161);
end
elseif(waterWayToGo == QUEST_AVAILABLE and overnightDelivery == QUEST_COMPLETED and pfame >= 3) then
player:startEvent(0x0160,0,4351);
elseif(FoodForThought == QUEST_AVAILABLE and OhbiruFood == 0) then
player:startEvent(0x0134); -- Hungry; mentions the experiment. First step in quest for this NPC.
player:setVar("Ohbiru_Food_var",1);
elseif(FoodForThought == QUEST_AVAILABLE and OhbiruFood == 1) then
player:startEvent(0x0135); -- Hungry. The NPC complains of being hungry before the quest is active.
elseif(FoodForThought == QUEST_ACCEPTED and OhbiruFood < 2) then
player:startEvent(0x013c,0,4493,624,4408); -- Gives Order
player:setVar("Ohbiru_Food_var",2);
elseif(FoodForThought == QUEST_ACCEPTED and OhbiruFood == 2) then
player:startEvent(0x013d,0,4493,624,4408); -- Repeats Order
elseif(FoodForThought == QUEST_ACCEPTED and OhbiruFood == 3) then
player:startEvent(0x0144); -- Reminds player to check on friends if he has been given his food.
elseif(FoodForThought == QUEST_COMPLETED and needToZone == true) then
player:startEvent(0x0158); -- Post Food for Thought Dialogue
elseif(overnightDelivery == QUEST_COMPLETED and pfame < 6) then
player:startEvent(0x015f); -- Post Overnight Delivery Dialogue
--
-- Begin Toraimarai Turmoil Section
--
elseif(turmoil == QUEST_AVAILABLE and pfame >= 6 and needToZone == false) then
player:startEvent(0x0311,4500,267,906);
elseif(turmoil == QUEST_ACCEPTED) then
player:startEvent(0x0312,4500,267,906); -- Reminder of needed items
elseif(turmoil == QUEST_COMPLETED) then
player:startEvent(0x031b,4500,0,906); -- Allows player to initiate repeat of Toraimarai Turmoil
else
player:startEvent(0x0158);
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);
-- Check Missions first (priority?)
turmoil = player:getQuestStatus(WINDURST,TORAIMARAI_TURMOIL);
if(csid == 0x8f) then
player:setVar("ohbiru_dohbiru_talk",2);
elseif (csid == 0x0142 or csid == 0x0145) then
if(player:getVar("Kerutoto_Food_var") == 3 and player:getVar("Kenapa_Food_var") == 4 and player:getVar("Ohbiru_Food_var") == 2) then -- If this is the last NPC to be fed
player:tradeComplete();
player:completeQuest(WINDURST,FOOD_FOR_THOUGHT);
player:addTitle(FAST_FOOD_DELIVERER);
player:addGil(GIL_RATE*440);
player:setVar("Kerutoto_Food_var",0); -- ------------------------------------------
player:setVar("Kenapa_Food_var",0); -- Erase all the variables used in this quest
player:setVar("Ohbiru_Food_var",0); -- ------------------------------------------
player:addFame(WINDURST,WIN_FAME*100);
player:needToZone(true);
else
player:tradeComplete();
player:addGil(GIL_RATE*440);
player:setVar("Ohbiru_Food_var",3); -- If this is NOT the last NPC given food, flag this NPC as completed.
end
elseif(csid == 0x0146) then
if(player:getVar("Kerutoto_Food_var") == 3 and player:getVar("Kenapa_Food_var") == 4 and player:getVar("Ohbiru_Food_var") == 2) then -- If this is the last NPC to be fed
player:tradeComplete();
player:completeQuest(WINDURST,FOOD_FOR_THOUGHT);
player:addTitle(FAST_FOOD_DELIVERER);
player:addGil(GIL_RATE*440);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*440);
player:setVar("Kerutoto_Food_var",0); -- ------------------------------------------
player:setVar("Kenapa_Food_var",0); -- Erase all the variables used in this quest
player:setVar("Ohbiru_Food_var",0); -- ------------------------------------------
player:addFame(WINDURST,WIN_FAME*100);
player:needToZone(true);
else
player:tradeComplete();
player:addGil(GIL_RATE*440);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*440);
player:setVar("Ohbiru_Food_var",3); -- If this is NOT the last NPC given food, flag this NPC as completed.
end
elseif(csid == 0x0311 and option == 1) then -- Adds Toraimarai turmoil
player:addQuest(WINDURST,TORAIMARAI_TURMOIL);
player:messageSpecial(KEYITEM_OBTAINED,267);
player:addKeyItem(267); -- Rhinostery Certificate
elseif(csid == 0x0317 and turmoil == QUEST_ACCEPTED) then -- Completes Toraimarai turmoil - first time
player:addGil(GIL_RATE*4500);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*4500);
player:completeQuest(WINDURST,TORAIMARAI_TURMOIL);
player:addFame(WINDURST,WIN_FAME*100);
player:addTitle(CERTIFIED_RHINOSTERY_VENTURER);
player:tradeComplete();
elseif(csid == 0x0317 and turmoil == 2) then -- Completes Toraimarai turmoil - repeats
player:addGil(GIL_RATE*4500);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*4500);
player:addFame(WINDURST,WIN_FAME*50);
player:tradeComplete();
elseif(csid == 0x0160 and option == 0 or csid == 0x0162) then
if(player:getFreeSlotsCount() >= 1) then
if(player:getQuestStatus(WINDURST,WATER_WAY_TO_GO) == QUEST_AVAILABLE) then
player:addQuest(WINDURST,WATER_WAY_TO_GO);
end
player:addItem(504);
player:messageSpecial(ITEM_OBTAINED,504);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,504);
end
elseif(csid == 0x0163) then
player:addGil(GIL_RATE*900);
player:completeQuest(WINDURST,WATER_WAY_TO_GO);
player:addFame(WINDURST,WIN_FAME*40);
player:tradeComplete();
player:needToZone(true);
elseif(csid == 0x0368) then
player:setVar("MEMORIES_OF_A_MAIDEN_Status",3);
end
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Bibiki_Bay/npcs/Mep_Nhapopoluko.lua | 27 | 1182 | -----------------------------------
-- Area: Bibiki Bay
-- NPC: Mep Nhapopoluko
-- Type: Guild Merchant NPC (Fishing Guild)
-- @pos 464.350 -6 752.731 4
-----------------------------------
package.loaded["scripts/zones/Bibiki_Bay/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Bibiki_Bay/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(519,1,18,5)) then
player:showText(npc, MEP_NHAPOPOLUKO_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.