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
zwhfly/openwrt-luci
applications/luci-statistics/luasrc/statistics/rrdtool/definitions/iptables.lua
86
1131
--[[ Luci statistics - iptables plugin diagram definition (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: ipt_bytes.lua 2276 2008-06-03 23:18:37Z jow $ ]]-- module("luci.statistics.rrdtool.definitions.iptables", package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) return { { title = "%H: Firewall: Processed bytes in %pi", vlabel = "Bytes/s", number_format = "%5.0lf%sB/s", totals_format = "%5.0lf%sB", data = { types = { "ipt_bytes" }, options = { ipt_bytes = { total = true, title = "%di" } } } }, { title = "%H: Firewall: Processed packets in %pi", vlabel = "Packets/s", number_format = "%5.1lf P/s", totals_format = "%5.0lf%s", data = { types = { "ipt_packets" }, options = { ipt_packets = { total = true, title = "%di" } } } } } end
apache-2.0
freifunk-gluon/luci
applications/luci-asterisk/luasrc/model/cbi/asterisk/phone_sip.lua
80
3813
--[[ LuCI - Lua Configuration Interface Copyright 2008 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local ast = require("luci.asterisk") local function find_outgoing_contexts(uci) local c = { } local h = { } uci:foreach("asterisk", "dialplan", function(s) if not h[s['.name']] then c[#c+1] = { s['.name'], "Dialplan: %s" % s['.name'] } h[s['.name']] = true end end) return c end local function find_incoming_contexts(uci) local c = { } local h = { } uci:foreach("asterisk", "sip", function(s) if s.context and not h[s.context] and uci:get_bool("asterisk", s['.name'], "provider") then c[#c+1] = { s.context, "Incoming: %s" % s['.name'] or s.context } h[s.context] = true end end) return c end -- -- SIP phone info -- if arg[2] == "info" then form = SimpleForm("asterisk", "SIP Phone Information") form.reset = false form.submit = "Back to overview" local info, keys = ast.sip.peer(arg[1]) local data = { } for _, key in ipairs(keys) do data[#data+1] = { key = key, val = type(info[key]) == "boolean" and ( info[key] and "yes" or "no" ) or ( info[key] == nil or #info[key] == 0 ) and "(none)" or tostring(info[key]) } end itbl = form:section(Table, data, "SIP Phone %q" % arg[1]) itbl:option(DummyValue, "key", "Key") itbl:option(DummyValue, "val", "Value") function itbl.parse(...) luci.http.redirect( luci.dispatcher.build_url("admin", "asterisk", "phones") ) end return form -- -- SIP phone configuration -- elseif arg[1] then cbimap = Map("asterisk", "Edit SIP Client") peer = cbimap:section(NamedSection, arg[1]) peer.hidden = { type = "friend", qualify = "yes", host = "dynamic", nat = "no", canreinvite = "no" } back = peer:option(DummyValue, "_overview", "Back to phone overview") back.value = "" back.titleref = luci.dispatcher.build_url("admin", "asterisk", "phones") active = peer:option(Flag, "disable", "Account enabled") active.enabled = "yes" active.disabled = "no" function active.cfgvalue(...) return AbstractValue.cfgvalue(...) or "yes" end exten = peer:option(Value, "extension", "Extension Number") cbimap.uci:foreach("asterisk", "dialplanexten", function(s) exten:value( s.extension, "%s (via %s/%s)" %{ s.extension, s.type:upper(), s.target } ) end) display = peer:option(Value, "callerid", "Display Name") username = peer:option(Value, "username", "Authorization ID") password = peer:option(Value, "secret", "Authorization Password") password.password = true regtimeout = peer:option(Value, "registertimeout", "Registration Time Value") function regtimeout.cfgvalue(...) return AbstractValue.cfgvalue(...) or "60" end sipport = peer:option(Value, "port", "SIP Port") function sipport.cfgvalue(...) return AbstractValue.cfgvalue(...) or "5060" end linekey = peer:option(ListValue, "_linekey", "Linekey Mode (broken)") linekey:value("", "Off") linekey:value("trunk", "Trunk Appearance") linekey:value("call", "Call Appearance") dialplan = peer:option(ListValue, "context", "Assign Dialplan") dialplan.titleref = luci.dispatcher.build_url("admin", "asterisk", "dialplans") for _, v in ipairs(find_outgoing_contexts(cbimap.uci)) do dialplan:value(unpack(v)) end incoming = peer:option(StaticList, "incoming", "Receive incoming calls from") for _, v in ipairs(find_incoming_contexts(cbimap.uci)) do incoming:value(unpack(v)) end --function incoming.cfgvalue(...) --error(table.concat(MultiValue.cfgvalue(...),".")) --end return cbimap end
apache-2.0
anshkumar/yugioh-glaze
assets/script/c86100785.lua
3
1261
--ゾーン・イーター function c86100785.initial_effect(c) local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(86100785,0)) e1:SetCategory(CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e1:SetCode(EVENT_DAMAGE_STEP_END) e1:SetCondition(c86100785.condition) e1:SetOperation(c86100785.operation) c:RegisterEffect(e1) end function c86100785.condition(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local bc=c:GetBattleTarget() return c==Duel.GetAttacker() and bc and bc:IsRelateToBattle() and bc:IsFaceup() end function c86100785.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local bc=c:GetBattleTarget() if bc:IsRelateToBattle() then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetCountLimit(1) e1:SetRange(LOCATION_MZONE) e1:SetReset(RESET_EVENT+0x1fe0000) e1:SetOperation(c86100785.desop) e1:SetLabel(0) e1:SetOwnerPlayer(tp) bc:RegisterEffect(e1) end end function c86100785.desop(e,tp,eg,ep,ev,re,r,rp) local ct=e:GetLabel() ct=ct+1 e:SetLabel(ct) e:GetOwner():SetTurnCounter(ct) if ct==5 then Duel.Destroy(e:GetHandler(),REASON_EFFECT) end end
gpl-2.0
dwing4g/jane
port/lua/test.lua
1
3875
-- UTF-8 without BOM local print = print local error = error local require = require local setmetatable = setmetatable local floor = math.floor local format = string.format local util = require "util" local bean = require "bean" local Stream = require "stream" local Queue = require "queue" local Rc4 = require "rc4" local class = util.class local clone = util.clone do local ClassA = class -- 定义类ClassA { a = 1, b = 2, __new = function(self) -- 定义构造函数 print("new ClassA", self) end, } local ClassB = class -- 定义类ClassB { __base = ClassA, -- 指定基类ClassA c = 3, __new = function(self, t) -- 定义构造函数 ClassA.__new(self) -- 基类构造函数参数不确定,所以只能手动调用,也可以写成self.__base.__new(self) print("new ClassB", self) return setmetatable(clone(t), self.__class) -- 使用t表的克隆代替当前的self作为对象 end, } local a = ClassA() -- 创建ClassA的实例 local b = ClassB { c = 333 } -- 创建ClassB的实例,{c=333}会被传到构造函数,如果没有构造函数,则成为对象初始值 print(a.a, 1) -- 访问成员变量,如不存在,则自动取类中定义的默认值,如果是表类型,则会自动从类中默认值深拷贝一个,并赋值成员变量 print(a.c, nil) a.a = 11 -- 设置成员变量,下次读取则因为有此变量而不会再从类中取默认值 a.c = 33 print(a.a, 11) print(a.b, 2) print(a.c, 33) print(b.a, 1) print(b.c, 333) b.a = 11 b.c = 33 print(b.a, 11) print(b.b, 2) print(b.c, 33) end print "----------------------------------------" do local b = bean.TestType { v1 = true, v2 = 2 } print(b.v1, b.v2, b.v3) print(b.v19) print(b.v19.value1) b.v19.value2 = 3 print(b.v19.value2) print(b.v19) print(b.__name) print(b.__type) print(b.__base[17].name) print(b.__base.v18.id) end print "----------------------------------------" do local s = Stream() local b = bean.TestType() print(b.v16.__map) b.v1 = 1 b.v2 = 2 b.v3 = 3 b.v4 = 4 b.v5 = 5 b.v6 = 6 b.v7 = 7 b.v8 = "abc" b.v9 = "def" b.v10[1] = true b.v11[1] = 11 b.v12[1] = 12 b.v13[1] = 13 b.v14[1] = 14 b.v15[1] = 15 b.v16[3] = "xyz" b.v17[bean.TestBean{value1=1,value2=2}] = true b.v18.name = bean.TestBean{value1=3,value2=4} b.v19.value1 = 5 print(b) s:clear() s:marshal(b) s:flush() print(s) s:unmarshal(b.__class) print(s) print(b) end print "----------------------------------------" do local function testInt(x) local s = Stream() s:marshalInt(x) s:flush() local y = s:unmarshalInt() if x ~= y then error(format("unmarshal wrong value: %.0f -> %.0f dump: %s", x, y, s)) end if s:pos() ~= s:limit() then error(format("unmarshal wrong position: %.0f dump: %s", x, s)) end end local function testUInt(x) local s = Stream() s:marshalUInt(x) s:flush() local y = s:unmarshalUInt() if x ~= y then error(format("unmarshal wrong value: %.0f -> %.0f dump: %s", x, y, s)) end if s:pos() ~= s:limit() then error(format("unmarshal wrong position: %.0f dump: %s", x, s)) end end local function testAll(x) if x > 0xfffffffffffff then x = 0xfffffffffffff end testInt(x) testInt(-x) testUInt((x > 0 and x or -x) % 0x100000000) end local x = 1 for _ = 0, 52 do testAll(x) testAll(x - 2) testAll(x - 1) testAll(x + 1) testAll(x + 2) testAll(x + floor(x / 2) + 1) testAll(x + floor(x / 4) + 2) testAll(x + floor(x / 4) + 3) testAll(x + x - 1) x = x + x end print "testInt OK!" end print "----------------------------------------" do local q = Queue() q:push(1) print(q) print(q:pop(), 1) print(q) end print "----------------------------------------" do local r = Rc4() r:setOutputKey "abc" local m = r:updateOutput "qwer" r = Rc4() r:setInputKey "abc" print(r:updateInput(m), "qwer") end print "========================================"
lgpl-3.0
RockySeven3161/Merbot-test
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
sjznxd/lc-20130302
applications/luci-openvpn/luasrc/model/cbi/openvpn-basic.lua
71
3274
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.ip") require("luci.model.uci") local basicParams = { -- -- Widget, Name, Default(s), Description -- { ListValue, "verb", { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, translate("Set output verbosity") }, { Value, "nice",0, translate("Change process priority") }, { Value,"port",1194, translate("TCP/UDP port # for both local and remote") }, { ListValue,"dev_type",{ "tun", "tap" }, translate("Type of used device") }, { Flag,"tun_ipv6",0, translate("Make tun device IPv6 capable") }, { Value,"ifconfig","10.200.200.3 10.200.200.1", translate("Set tun/tap adapter parameters") }, { Value,"server","10.200.200.0 255.255.255.0", translate("Configure server mode") }, { Value,"server_bridge","192.168.1.1 255.255.255.0 192.168.1.128 192.168.1.254", translate("Configure server bridge") }, { Flag,"nobind",0, translate("Do not bind to local address and port") }, { Flag,"comp_lzo",0, translate("Use fast LZO compression") }, { Value,"keepalive","10 60", translate("Helper directive to simplify the expression of --ping and --ping-restart in server mode configurations") }, { ListValue,"proto",{ "udp", "tcp" }, translate("Use protocol") }, { Flag,"client",0, translate("Configure client mode") }, { Flag,"client_to_client",0, translate("Allow client-to-client traffic") }, { DynamicList,"remote","vpnserver.example.org", translate("Remote host name or ip address") }, { FileUpload,"secret","/etc/openvpn/secret.key 1", translate("Enable Static Key encryption mode (non-TLS)") }, { FileUpload,"pkcs12","/etc/easy-rsa/keys/some-client.pk12", translate("PKCS#12 file containing keys") }, { FileUpload,"ca","/etc/easy-rsa/keys/ca.crt", translate("Certificate authority") }, { FileUpload,"dh","/etc/easy-rsa/keys/dh1024.pem", translate("Diffie Hellman parameters") }, { FileUpload,"cert","/etc/easy-rsa/keys/some-client.crt", translate("Local certificate") }, { FileUpload,"key","/etc/easy-rsa/keys/some-client.key", translate("Local private key") }, } local m = Map("openvpn") local p = m:section( SimpleSection ) p.template = "openvpn/pageswitch" p.mode = "basic" p.instance = arg[1] local s = m:section( NamedSection, arg[1], "openvpn" ) for _, option in ipairs(basicParams) do local o = s:option( option[1], option[2], option[2], option[4] ) o.optional = true if option[1] == DummyValue then o.value = option[3] else if option[1] == DynamicList then o.cast = nil function o.cfgvalue(...) local val = AbstractValue.cfgvalue(...) return ( val and type(val) ~= "table" ) and { val } or val end end if type(option[3]) == "table" then if o.optional then o:value("", "-- remove --") end for _, v in ipairs(option[3]) do v = tostring(v) o:value(v) end o.default = tostring(option[3][1]) else o.default = tostring(option[3]) end end for i=5,#option do if type(option[i]) == "table" then o:depends(option[i]) end end end return m
apache-2.0
anshkumar/yugioh-glaze
assets/script/c40884383.lua
3
1302
--凶悪犯-チョップマン function c40884383.initial_effect(c) --equip local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(40884383,0)) e1:SetCategory(CATEGORY_EQUIP) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCode(EVENT_FLIP_SUMMON_SUCCESS) e1:SetTarget(c40884383.eqtg) e1:SetOperation(c40884383.eqop) c:RegisterEffect(e1) end function c40884383.filter(c,ec) return c:IsType(TYPE_EQUIP) and c:CheckEquipTarget(ec) end function c40884383.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c40884383.filter(chkc,e:GetHandler()) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0 and Duel.IsExistingTarget(c40884383.filter,tp,LOCATION_GRAVE,0,1,nil,e:GetHandler()) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP) local g=Duel.SelectTarget(tp,c40884383.filter,tp,LOCATION_GRAVE,0,1,1,nil,e:GetHandler()) Duel.SetOperationInfo(0,CATEGORY_EQUIP,g,1,0,0) end function c40884383.eqop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 then return end local c=e:GetHandler() local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and c:IsFaceup() and c:IsRelateToEffect(e) then Duel.Equip(tp,tc,c) end end
gpl-2.0
anshkumar/yugioh-glaze
assets/script/c94454495.lua
3
2669
--Kozmo Sliprider function c94454495.initial_effect(c) --destroy local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e1:SetTarget(c94454495.destg) e1:SetOperation(c94454495.desop) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e2) --spsummon local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_SPECIAL_SUMMON) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_TO_GRAVE) e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e3:SetCondition(c94454495.spcon) e3:SetCost(c94454495.spcost) e3:SetTarget(c94454495.sptg) e3:SetOperation(c94454495.spop) c:RegisterEffect(e3) end function c94454495.desfilter(c) return c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsDestructable() end function c94454495.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() and c94454495.desfilter(chkc) end if chk==0 then return Duel.IsExistingTarget(c94454495.desfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,c94454495.desfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) end function c94454495.desop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.Destroy(tc,REASON_EFFECT) end end function c94454495.spcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:IsReason(REASON_DESTROY) and c:IsReason(REASON_BATTLE+REASON_EFFECT) end function c94454495.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() and e:GetHandler():IsLocation(LOCATION_GRAVE) end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST) end function c94454495.spfilter(c,e,tp) return c:IsSetCard(0xd2) and c:IsLevelBelow(4) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c94454495.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c94454495.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end function c94454495.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c94454495.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
Scavenge/darkstar
scripts/zones/Port_San_dOria/npcs/Nogelle.lua
16
2431
----------------------------------- -- Area: Port San d'Oria -- NPC: Nogelle -- Starts Lufet's Lake Salt ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/titles"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end if (player:getQuestStatus(SANDORIA,LUFET_S_LAKE_SALT) == QUEST_ACCEPTED) then local count = trade:getItemCount(); LufetSalt = trade:hasItemQty(1019,3); if (LufetSalt == true and count == 3) then player:tradeComplete(); player:addFame(SANDORIA,30); player:addGil(GIL_RATE*600); player:addTitle(BEAN_CUISINE_SALTER); player:completeQuest(SANDORIA,LUFET_S_LAKE_SALT); player:startEvent(0x000b); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local LufetsLakeSalt = player:getQuestStatus(SANDORIA,LUFET_S_LAKE_SALT); if (LufetsLakeSalt == 0) then player:startEvent(0x000c); elseif (LufetsLakeSalt == 1) then player:startEvent(0x000a); elseif (LufetsLakeSalt == 2) then player:startEvent(0x020a); 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 == 0x000c and option == 1) then player:addQuest(SANDORIA,LUFET_S_LAKE_SALT); elseif (csid == 0x000b) then player:messageSpecial(GIL_OBTAINED,GIL_RATE*600); end end;
gpl-3.0
3203317/g
assets/redis/group_users_ready_channel.lua
1
1051
-- huangxin <3203317@qq.com> local db = KEYS[1]; local server_id = KEYS[2]; local channel_id = KEYS[3]; -- redis.call('SELECT', db); local user_id = redis.call('GET', server_id ..'::'.. channel_id); if (false == user_id) then return 'invalid_user_id'; end; -- 不在任何群组 local group_id = redis.call('HGET', 'prop::'.. user_id, 'group_id'); if (false == group_id) then return 'invalid_group_id'; end; -- 获取群组的类型 redis.call('SELECT', 1 + db); local group_type = redis.call('HGET', 'prop::group::'.. group_id, 'type'); if (false == group_type) then return 'invalid_group_id'; end; local group_pos = redis.call('HGETALL', 'pos::group::'.. group_type ..'::'.. group_id); -- redis.call('SELECT', db); local result = {}; for i=2, #group_pos, 2 do local u, hand = string.match(group_pos[i], '(.*)::(.*)'); if ('1' == hand) then table.insert(result, redis.call('HGET', 'prop::'.. u, 'server_id')); table.insert(result, redis.call('HGET', 'prop::'.. u, 'channel_id')); end; end; return result;
mit
Scavenge/darkstar
scripts/zones/Cloister_of_Flames/mobs/Ifrit_Prime.lua
23
1783
----------------------------------------------------- -- Area: Cloister of Flames -- MOB: Ifrit Prime -- Involved in Quest: Trial by Fire -- Involved in Mission: ASA-4 Sugar Coated Directive ----------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/status"); ----------------------------------- -- OnMobFight Action ----------------------------------- function onMobFight(mob, target) local mobId = mob:getID(); -- ASA-4: Astral Flow Behavior - Guaranteed to Use At Least 5 times before killable, at specified intervals. if (mob:getBattlefield():getBcnmID() == 547 and GetMobAction(mobId) == ACTION_ATTACK) then local astralFlows = mob:getLocalVar("astralflows"); if ((astralFlows == 0 and mob:getHPP() <= 80) or (astralFlows == 1 and mob:getHPP() <= 60) or (astralFlows == 2 and mob:getHPP() <= 40) or (astralFlows == 3 and mob:getHPP() <= 20) or (astralFlows == 4 and mob:getHPP() <= 1)) then mob:setLocalVar("astralflows",astralFlows + 1); mob:useMobAbility(848); if (astralFlows >= 5) then mob:setUnkillable(false); end end end end; ----------------------------------- -- OnMobSpawn Action ----------------------------------- function onMobSpawn(mob) -- ASA-4: Avatar is Unkillable Until Its Used Astral Flow At Least 5 times At Specified Intervals if (mob:getBattlefield():getBcnmID() == 547) then mob:setLocalVar("astralflows","0"); mob:setUnkillable(true); end end; ----------------------------------- -- OnMobDeath Action ----------------------------------- function onMobDeath(mob, player, isKiller) end;
gpl-3.0
angking0802wu/UniLua
Assets/StreamingAssets/LuaRoot/test/big.lua
9
2059
if _soft then return 'a' end print "testing large tables" local debug = require"debug" local lim = 2^18 + 1000 local prog = { "local y = {0" } for i = 1, lim do prog[#prog + 1] = i end prog[#prog + 1] = "}\n" prog[#prog + 1] = "X = y\n" prog[#prog + 1] = ("assert(X[%d] == %d)"):format(lim - 1, lim - 2) prog[#prog + 1] = "return 0" prog = table.concat(prog, ";") local env = {string = string, assert = assert} local f = assert(load(prog, nil, nil, env)) f() assert(env.X[lim] == lim - 1 and env.X[lim + 1] == lim) for k in pairs(env) do env[k] = nil end -- yields during accesses larger than K (in RK) setmetatable(env, { __index = function (t, n) coroutine.yield('g'); return _G[n] end, __newindex = function (t, n, v) coroutine.yield('s'); _G[n] = v end, }) X = nil co = coroutine.wrap(f) assert(co() == 's') assert(co() == 'g') assert(co() == 'g') assert(co() == 0) assert(X[lim] == lim - 1 and X[lim + 1] == lim) -- errors in accesses larger than K (in RK) getmetatable(env).__index = function () end getmetatable(env).__newindex = function () end local e, m = pcall(f) assert(not e and m:find("global 'X'")) -- errors in metamethods getmetatable(env).__newindex = function () error("hi") end local e, m = xpcall(f, debug.traceback) assert(not e and m:find("'__newindex'")) f, X = nil coroutine.yield'b' if not _no32 then -- { print "testing string length overflow" local repstrings = 192 -- number of strings to be concatenated local ssize = math.ceil(2^32 / repstrings) + 1 -- size of each string assert(repstrings * ssize > 2^32) -- this should be larger than maximum size_t local longs = string.rep("\0", ssize) -- create one long string -- create function to concatentate 'repstrings' copies of its argument local rep = assert(load( "local a = ...; return " .. string.rep("a", repstrings, ".."))) local a, b = pcall(rep, longs) -- call that function -- it should fail without creating string (result would be too large) assert(not a and string.find(b, "overflow")) end -- } print'OK' return 'a'
mit
Scavenge/darkstar
scripts/zones/Gustav_Tunnel/npcs/qm2.lua
16
2311
----------------------------------- -- Area: Gustav tunnel -- NPC: qm2 (???) -- Missions: Bastok 9-1 -- @pos -130 1.256 252.696 212 ----------------------------------- package.loaded["scripts/zones/Gustav_Tunnel/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Gustav_Tunnel/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ---------------------------------- function onTrade(player,npc,trade) end; ---------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(BASTOK) == THE_SALT_OF_THE_EARTH) then if (GetMobAction(17645794) == 0 and GetMobAction(17645795) == 0 and GetMobAction(17645796) == 0 and GetMobAction(17645797) == 0 and GetMobAction(17645798) == 0 and GetMobAction(17645799) == 0 and GetMobAction(17645800) == 0 and GetMobAction(17645801) == 0 and GetMobAction(17645802) == 0 and GetMobAction(17645803) == 0 and GetMobAction(17645804) == 0 and GetMobAction(17645805) == 0 and GetMobAction(17645806) == 0 and GetMobAction(17645807) == 0 and GetMobAction(17645808) == 0) then if (player:getVar("BASTOK91") == 3) then if not(player:hasKeyItem(MIRACLESALT)) then player:addKeyItem(MIRACLESALT); player:messageSpecial(KEYITEM_OBTAINED,MIRACLESALT); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end elseif (player:getVar("BASTOK91") == 2) then SpawnMob(17645794):updateClaim(player); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Kyklas/luci-proto-hso
libs/nixio/axTLS/samples/lua/axssl.lua
176
19286
#!/usr/local/bin/lua -- -- Copyright (c) 2007, Cameron Rich -- -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the axTLS project nor the names of its -- contributors may be used to endorse or promote products derived -- from this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -- CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY -- OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- Demonstrate the use of the axTLS library in Lua with a set of -- command-line parameters similar to openssl. In fact, openssl clients -- should be able to communicate with axTLS servers and visa-versa. -- -- This code has various bits enabled depending on the configuration. To enable -- the most interesting version, compile with the 'full mode' enabled. -- -- To see what options you have, run the following: -- > [lua] axssl s_server -? -- > [lua] axssl s_client -? -- -- The axtls/axtlsl shared libraries must be in the same directory or be found -- by the OS. -- -- require "bit" require("axtlsl") local socket = require("socket") -- print version? if #arg == 1 and arg[1] == "version" then print("axssl.lua "..axtlsl.ssl_version()) os.exit(1) end -- -- We've had some sort of command-line error. Print out the basic options. -- function print_options(option) print("axssl: Error: '"..option.."' is an invalid command.") print("usage: axssl [s_server|s_client|version] [args ...]") os.exit(1) end -- -- We've had some sort of command-line error. Print out the server options. -- function print_server_options(build_mode, option) local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET) local ca_cert_size = axtlsl.ssl_get_config( axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET) print("unknown option "..option) print("usage: s_server [args ...]") print(" -accept\t- port to accept on (default is 4433)") print(" -quiet\t\t- No server output") if build_mode >= axtlsl.SSL_BUILD_SERVER_ONLY then print(" -cert arg\t- certificate file to add (in addition to ".. "default) to chain -") print("\t\t Can repeat up to "..cert_size.." times") print(" -key arg\t- Private key file to use - default DER format") print(" -pass\t\t- private key file pass phrase source") end if build_mode >= axtlsl.SSL_BUILD_ENABLE_VERIFICATION then print(" -verify\t- turn on peer certificate verification") print(" -CAfile arg\t- Certificate authority - default DER format") print("\t\t Can repeat up to "..ca_cert_size.." times") end if build_mode == axtlsl.SSL_BUILD_FULL_MODE then print(" -debug\t\t- Print more output") print(" -state\t\t- Show state messages") print(" -show-rsa\t- Show RSA state") end os.exit(1) end -- -- We've had some sort of command-line error. Print out the client options. -- function print_client_options(build_mode, option) local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET) local ca_cert_size = axtlsl.ssl_get_config( axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET) print("unknown option "..option) if build_mode >= axtlsl.SSL_BUILD_ENABLE_CLIENT then print("usage: s_client [args ...]") print(" -connect host:port - who to connect to (default ".. "is localhost:4433)") print(" -verify\t- turn on peer certificate verification") print(" -cert arg\t- certificate file to use - default DER format") print(" -key arg\t- Private key file to use - default DER format") print("\t\t Can repeat up to "..cert_size.." times") print(" -CAfile arg\t- Certificate authority - default DER format") print("\t\t Can repeat up to "..ca_cert_size.."times") print(" -quiet\t\t- No client output") print(" -pass\t\t- private key file pass phrase source") print(" -reconnect\t- Drop and re-make the connection ".. "with the same Session-ID") if build_mode == axtlsl.SSL_BUILD_FULL_MODE then print(" -debug\t\t- Print more output") print(" -state\t\t- Show state messages") print(" -show-rsa\t- Show RSA state") end else print("Change configuration to allow this feature") end os.exit(1) end -- Implement the SSL server logic. function do_server(build_mode) local i = 2 local v local port = 4433 local options = axtlsl.SSL_DISPLAY_CERTS local quiet = false local password = "" local private_key_file = nil local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET) local ca_cert_size = axtlsl. ssl_get_config(axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET) local cert = {} local ca_cert = {} while i <= #arg do if arg[i] == "-accept" then if i >= #arg then print_server_options(build_mode, arg[i]) end i = i + 1 port = arg[i] elseif arg[i] == "-quiet" then quiet = true options = bit.band(options, bit.bnot(axtlsl.SSL_DISPLAY_CERTS)) elseif build_mode >= axtlsl.SSL_BUILD_SERVER_ONLY then if arg[i] == "-cert" then if i >= #arg or #cert >= cert_size then print_server_options(build_mode, arg[i]) end i = i + 1 table.insert(cert, arg[i]) elseif arg[i] == "-key" then if i >= #arg then print_server_options(build_mode, arg[i]) end i = i + 1 private_key_file = arg[i] options = bit.bor(options, axtlsl.SSL_NO_DEFAULT_KEY) elseif arg[i] == "-pass" then if i >= #arg then print_server_options(build_mode, arg[i]) end i = i + 1 password = arg[i] elseif build_mode >= axtlsl.SSL_BUILD_ENABLE_VERIFICATION then if arg[i] == "-verify" then options = bit.bor(options, axtlsl.SSL_CLIENT_AUTHENTICATION) elseif arg[i] == "-CAfile" then if i >= #arg or #ca_cert >= ca_cert_size then print_server_options(build_mode, arg[i]) end i = i + 1 table.insert(ca_cert, arg[i]) elseif build_mode == axtlsl.SSL_BUILD_FULL_MODE then if arg[i] == "-debug" then options = bit.bor(options, axtlsl.SSL_DISPLAY_BYTES) elseif arg[i] == "-state" then options = bit.bor(options, axtlsl.SSL_DISPLAY_STATES) elseif arg[i] == "-show-rsa" then options = bit.bor(options, axtlsl.SSL_DISPLAY_RSA) else print_server_options(build_mode, arg[i]) end else print_server_options(build_mode, arg[i]) end else print_server_options(build_mode, arg[i]) end else print_server_options(build_mode, arg[i]) end i = i + 1 end -- Create socket for incoming connections local server_sock = socket.try(socket.bind("*", port)) --------------------------------------------------------------------------- -- This is where the interesting stuff happens. Up until now we've -- just been setting up sockets etc. Now we do the SSL handshake. --------------------------------------------------------------------------- local ssl_ctx = axtlsl.ssl_ctx_new(options, axtlsl.SSL_DEFAULT_SVR_SESS) if ssl_ctx == nil then error("Error: Server context is invalid") end if private_key_file ~= nil then local obj_type = axtlsl.SSL_OBJ_RSA_KEY if string.find(private_key_file, ".p8") then obj_type = axtlsl.SSL_OBJ_PKCS8 end if string.find(private_key_file, ".p12") then obj_type = axtlsl.SSL_OBJ_PKCS12 end if axtlsl.ssl_obj_load(ssl_ctx, obj_type, private_key_file, password) ~= axtlsl.SSL_OK then error("Private key '" .. private_key_file .. "' is undefined.") end end for _, v in ipairs(cert) do if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CERT, v, "") ~= axtlsl.SSL_OK then error("Certificate '"..v .. "' is undefined.") end end for _, v in ipairs(ca_cert) do if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CACERT, v, "") ~= axtlsl.SSL_OK then error("Certificate '"..v .."' is undefined.") end end while true do if not quiet then print("ACCEPT") end local client_sock = server_sock:accept(); local ssl = axtlsl.ssl_server_new(ssl_ctx, client_sock:getfd()) -- do the actual SSL handshake local connected = false local res local buf while true do socket.select({client_sock}, nil) res, buf = axtlsl.ssl_read(ssl) if res == axtlsl.SSL_OK then -- connection established and ok if axtlsl.ssl_handshake_status(ssl) == axtlsl.SSL_OK then if not quiet and not connected then display_session_id(ssl) display_cipher(ssl) end connected = true end end if res > axtlsl.SSL_OK then for _, v in ipairs(buf) do io.write(string.format("%c", v)) end elseif res < axtlsl.SSL_OK then if not quiet then axtlsl.ssl_display_error(res) end break end end -- client was disconnected or the handshake failed. print("CONNECTION CLOSED") axtlsl.ssl_free(ssl) client_sock:close() end axtlsl.ssl_ctx_free(ssl_ctx) end -- -- Implement the SSL client logic. -- function do_client(build_mode) local i = 2 local v local port = 4433 local options = bit.bor(axtlsl.SSL_SERVER_VERIFY_LATER, axtlsl.SSL_DISPLAY_CERTS) local private_key_file = nil local reconnect = 0 local quiet = false local password = "" local session_id = {} local host = "127.0.0.1" local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET) local ca_cert_size = axtlsl. ssl_get_config(axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET) local cert = {} local ca_cert = {} while i <= #arg do if arg[i] == "-connect" then if i >= #arg then print_client_options(build_mode, arg[i]) end i = i + 1 local t = string.find(arg[i], ":") host = string.sub(arg[i], 1, t-1) port = string.sub(arg[i], t+1) elseif arg[i] == "-cert" then if i >= #arg or #cert >= cert_size then print_client_options(build_mode, arg[i]) end i = i + 1 table.insert(cert, arg[i]) elseif arg[i] == "-key" then if i >= #arg then print_client_options(build_mode, arg[i]) end i = i + 1 private_key_file = arg[i] options = bit.bor(options, axtlsl.SSL_NO_DEFAULT_KEY) elseif arg[i] == "-CAfile" then if i >= #arg or #ca_cert >= ca_cert_size then print_client_options(build_mode, arg[i]) end i = i + 1 table.insert(ca_cert, arg[i]) elseif arg[i] == "-verify" then options = bit.band(options, bit.bnot(axtlsl.SSL_SERVER_VERIFY_LATER)) elseif arg[i] == "-reconnect" then reconnect = 4 elseif arg[i] == "-quiet" then quiet = true options = bit.band(options, bnot(axtlsl.SSL_DISPLAY_CERTS)) elseif arg[i] == "-pass" then if i >= #arg then print_server_options(build_mode, arg[i]) end i = i + 1 password = arg[i] elseif build_mode == axtlsl.SSL_BUILD_FULL_MODE then if arg[i] == "-debug" then options = bit.bor(options, axtlsl.SSL_DISPLAY_BYTES) elseif arg[i] == "-state" then options = bit.bor(axtlsl.SSL_DISPLAY_STATES) elseif arg[i] == "-show-rsa" then options = bit.bor(axtlsl.SSL_DISPLAY_RSA) else -- don't know what this is print_client_options(build_mode, arg[i]) end else -- don't know what this is print_client_options(build_mode, arg[i]) end i = i + 1 end local client_sock = socket.try(socket.connect(host, port)) local ssl local res if not quiet then print("CONNECTED") end --------------------------------------------------------------------------- -- This is where the interesting stuff happens. Up until now we've -- just been setting up sockets etc. Now we do the SSL handshake. --------------------------------------------------------------------------- local ssl_ctx = axtlsl.ssl_ctx_new(options, axtlsl.SSL_DEFAULT_CLNT_SESS) if ssl_ctx == nil then error("Error: Client context is invalid") end if private_key_file ~= nil then local obj_type = axtlsl.SSL_OBJ_RSA_KEY if string.find(private_key_file, ".p8") then obj_type = axtlsl.SSL_OBJ_PKCS8 end if string.find(private_key_file, ".p12") then obj_type = axtlsl.SSL_OBJ_PKCS12 end if axtlsl.ssl_obj_load(ssl_ctx, obj_type, private_key_file, password) ~= axtlsl.SSL_OK then error("Private key '"..private_key_file.."' is undefined.") end end for _, v in ipairs(cert) do if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CERT, v, "") ~= axtlsl.SSL_OK then error("Certificate '"..v .. "' is undefined.") end end for _, v in ipairs(ca_cert) do if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CACERT, v, "") ~= axtlsl.SSL_OK then error("Certificate '"..v .."' is undefined.") end end -- Try session resumption? if reconnect ~= 0 then local session_id = nil local sess_id_size = 0 while reconnect > 0 do reconnect = reconnect - 1 ssl = axtlsl.ssl_client_new(ssl_ctx, client_sock:getfd(), session_id, sess_id_size) res = axtlsl.ssl_handshake_status(ssl) if res ~= axtlsl.SSL_OK then if not quiet then axtlsl.ssl_display_error(res) end axtlsl.ssl_free(ssl) os.exit(1) end display_session_id(ssl) session_id = axtlsl.ssl_get_session_id(ssl) sess_id_size = axtlsl.ssl_get_session_id_size(ssl) if reconnect > 0 then axtlsl.ssl_free(ssl) client_sock:close() client_sock = socket.try(socket.connect(host, port)) end end else ssl = axtlsl.ssl_client_new(ssl_ctx, client_sock:getfd(), nil, 0) end -- check the return status res = axtlsl.ssl_handshake_status(ssl) if res ~= axtlsl.SSL_OK then if not quiet then axtlsl.ssl_display_error(res) end os.exit(1) end if not quiet then local common_name = axtlsl.ssl_get_cert_dn(ssl, axtlsl.SSL_X509_CERT_COMMON_NAME) if common_name ~= nil then print("Common Name:\t\t\t"..common_name) end display_session_id(ssl) display_cipher(ssl) end while true do local line = io.read() if line == nil then break end local bytes = {} for i = 1, #line do bytes[i] = line.byte(line, i) end bytes[#line+1] = 10 -- add carriage return, null bytes[#line+2] = 0 res = axtlsl.ssl_write(ssl, bytes, #bytes) if res < axtlsl.SSL_OK then if not quiet then axtlsl.ssl_display_error(res) end break end end axtlsl.ssl_ctx_free(ssl_ctx) client_sock:close() end -- -- Display what cipher we are using -- function display_cipher(ssl) io.write("CIPHER is ") local cipher_id = axtlsl.ssl_get_cipher_id(ssl) if cipher_id == axtlsl.SSL_AES128_SHA then print("AES128-SHA") elseif cipher_id == axtlsl.SSL_AES256_SHA then print("AES256-SHA") elseif axtlsl.SSL_RC4_128_SHA then print("RC4-SHA") elseif axtlsl.SSL_RC4_128_MD5 then print("RC4-MD5") else print("Unknown - "..cipher_id) end end -- -- Display what session id we have. -- function display_session_id(ssl) local session_id = axtlsl.ssl_get_session_id(ssl) local v if #session_id > 0 then print("-----BEGIN SSL SESSION PARAMETERS-----") for _, v in ipairs(session_id) do io.write(string.format("%02x", v)) end print("\n-----END SSL SESSION PARAMETERS-----") end end -- -- Main entry point. Doesn't do much except works out whether we are a client -- or a server. -- if #arg == 0 or (arg[1] ~= "s_server" and arg[1] ~= "s_client") then print_options(#arg > 0 and arg[1] or "") end local build_mode = axtlsl.ssl_get_config(axtlsl.SSL_BUILD_MODE) _ = arg[1] == "s_server" and do_server(build_mode) or do_client(build_mode) os.exit(0)
apache-2.0
Scavenge/darkstar
scripts/zones/Riverne-Site_A01/npcs/_0u2.lua
17
1368
----------------------------------- -- Area: Riverne Site #A01 -- NPC: Unstable Displacement ----------------------------------- package.loaded["scripts/zones/Riverne-Site_A01/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Riverne-Site_A01/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1691,1) and trade:getItemCount() == 1) then -- Trade Giant Scale player:tradeComplete(); npc:openDoor(RIVERNE_PORTERS); player:messageSpecial(SD_HAS_GROWN); end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 8) then player:startEvent(0x11); else player:messageSpecial(SD_VERY_SMALL); end; return 1; 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
Scavenge/darkstar
scripts/zones/West_Ronfaure/mobs/Forest_Hare.lua
14
1059
----------------------------------- -- Area: West Ronfaure -- MOB: Forest Hare ----------------------------------- require("scripts/globals/fieldsofvalor"); require("scripts/zones/West_Ronfaure/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) checkRegime(player,mob,2,1); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local mobID = mob:getID(); if (Jaggedy_Eared_Jack_PH[mobID] ~= nil) then local ToD = GetServerVariable("[POP]Jaggedy_Eared_Jack"); if (ToD <= os.time(t) and GetMobAction(Jaggedy_Eared_Jack) == 0) then if (math.random(1,20) == 5) then UpdateNMSpawnPoint(Jaggedy_Eared_Jack); GetMobByID(Jaggedy_Eared_Jack):setRespawnTime(GetMobRespawnTime(mobID)); SetServerVariable("[PH]Jaggedy_Eared_Jack", mobID); DeterMob(mobID, true); end end end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Windurst_Waters/npcs/Clais.lua
14
1723
----------------------------------- -- Area: Windurst Waters -- NPC: Clais -- Involved In Quest: Hat in Hand -- @zone = 238 -- @pos = -31 -3 11 ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Windurst_Walls/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) function testflag(set,flag) return (set % (2*flag) >= flag) end hatstatus = player:getQuestStatus(WINDURST,HAT_IN_HAND); if ((hatstatus == 1 or player:getVar("QuestHatInHand_var2") == 1) and testflag(tonumber(player:getVar("QuestHatInHand_var")),8) == false) then player:startEvent(0x0039); -- Show Off Hat else player:startEvent(0x025a); -- Standard Conversation 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 == 0x0039) then -- Show Off Hat player:setVar("QuestHatInHand_var",player:getVar("QuestHatInHand_var")+8); player:setVar("QuestHatInHand_count",player:getVar("QuestHatInHand_count")+1); end end;
gpl-3.0
Scavenge/darkstar
scripts/globals/items/hobgoblin_pie.lua
12
1617
----------------------------------------- -- ID: 4325 -- Item: hobgoblin_pie -- Food Effect: 60Min, All Races ----------------------------------------- -- Health 15 -- Magic 15 -- Agility 4 -- Charisma -7 -- Health Regen While Healing 2 -- Defense % 12 (cap 60) ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,4325); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 15); target:addMod(MOD_MP, 15); target:addMod(MOD_AGI, 4); target:addMod(MOD_CHR, -7); target:addMod(MOD_HPHEAL, 2); target:addMod(MOD_FOOD_DEFP, 12); target:addMod(MOD_FOOD_DEF_CAP, 60); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 15); target:delMod(MOD_MP, 15); target:delMod(MOD_AGI, 4); target:delMod(MOD_CHR, -7); target:delMod(MOD_HPHEAL, 2); target:delMod(MOD_FOOD_DEFP, 12); target:delMod(MOD_FOOD_DEF_CAP, 60); end;
gpl-3.0
PicoleDeLimao/Ninpou2
game/dota_addons/ninpou2/scripts/vscripts/libraries/modifiers/modifier_animation.lua
24
10825
modifier_animation = class({}) local _CODE_TO_ANIMATION_TRANSLATE = { [0]= "loadout", [1]= "split_shot", [2]= "chemical_rage", [3]= "agedspirit", [4]= "aggressive", [5]= "injured", [6]= "ancient_armor", [7]= "anvil", [8]= "arcana", [9]= "techies_arcana", [10]= "fast", [11]= "faster", [12]= "fastest", [13]= "abysm", [14]= "dualwield", [15]= "forcestaff_friendly", [16]= "phantom_attack", [17]= "snowangel", [18]= "suicide_squad", [19]= "taunt_fullbody", [20]= "armaments_set", [21]= "instagib", [22]= "tidehunter_boat", [23]= "shinobi_tail", [24]= "tidebringer", [25]= "masquerade", [26]= "pyre", [27]= "shinobi", [28]= "immortal", [29]= "cauldron", [30]= "red_moon", [31]= "when_nature_attacks", [32]= "odachi", [33]= "wraith_spin", [34]= "eyeoffetizu", [35]= "berserkers_blood", [36]= "flying", [37]= "frost_arrow", [38]= "manta", [39]= "come_get_it", [40]= "good_day_sir", [41]= "backstab", [42]= "offhand_basher", [43]= "batter_up", [44]= "black", [45]= "haste", [46]= "with_item", [47]= "bot", [48]= "web", [49]= "fountain", [50]= "broodmother_spin", [51]= "burrowed", [52]= "sandking_rubyspire_burrowstrike", [53]= "moth", [54]= "frostivus", [55]= "desolation", [56]= "sm_head", [57]= "chasm", [58]= "greevil_black_hole", [59]= "greevil_blade_fury", [60]= "greevil_bloodlust", [61]= "greevil_cold_snap", [62]= "greevil_decrepify", [63]= "greevil_diabolic_edict", [64]= "greevil_echo_slam", [65]= "greevil_fatal_bonds", [66]= "greevil_ice_wall", [67]= "ancestral_scepter", [68]= "greevil_laguna_blade", [69]= "greevil_leech_seed", [70]= "greevil_magic_missile", [71]= "greevil_maledict", [72]= "greevil_miniboss_black_brain_sap", [73]= "greevil_miniboss_black_nightmare", [74]= "greevil_miniboss_blue_cold_feet", [75]= "greevil_miniboss_blue_ice_vortex", [76]= "greevil_miniboss_green_living_armor", [77]= "greevil_miniboss_green_overgrowth", [78]= "greevil_miniboss_orange_dragon_slave", [79]= "greevil_miniboss_orange_lightstrike_array", [80]= "greevil_miniboss_purple_plague_ward", [81]= "greevil_miniboss_purple_venomous_gale", [82]= "greevil_miniboss_red_earthshock", [83]= "greevil_miniboss_red_overpower", [84]= "greevil_miniboss_white_purification", [85]= "greevil_miniboss_yellow_ion_shell", [86]= "greevil_miniboss_yellow_surge", [87]= "greevil_natures_attendants", [88]= "greevil_phantom_strike", [89]= "greevil_poison_nova", [90]= "greevil_purification", [91]= "greevil_shadow_strike", [92]= "greevil_shadow_wave", [93]= "stalker_exo", [94]= "death_protest", [95]= "nihility", [96]= "deadwinter_soul", [97]= "charge", [98]= "charge_attack", [99]= "iron_surge", [100]= "impatient_maiden", [101]= "glacier", [102]= "snowball", [103]= "corpse_dresstop", [104]= "corpse_dress", [105]= "corpse_scarf", [106]= "unbroken", [107]= "dc_sb_charge", [108]= "dc_sb_charge_attack", [109]= "dc_sb_charge_finish", [110]= "dc_sb_ultimate", [111]= "faces_hakama", [112]= "faces_wraps", [113]= "faces_mask", [114]= "lodestar", [115]= "reincarnate", [116]= "demon_drain", [117]= "divine_sorrow", [118]= "divine_sorrow_loadout", [119]= "divine_sorrow_loadout_spawn", [120]= "divine_sorrow_sunstrike", [121]= "duel_kill", [122]= "forcestaff_enemy", [123]= "fish_slap", [124]= "focusfire", [125]= "fear", [126]= "ftp_dendi_back", [127]= "triumphant_timelord", [128]= "ground_pound", [129]= "harlequin", [130]= "injured_aggressive", [131]= "f2p_doom", [132]= "obsidian_helmet", [133]= "item_style_2", [134]= "blood_chaser", [135]= "manias_mask", [136]= "punch", [137]= "thirst", [138]= "impetus", [139]= "taunt_killtaunt", [140]= "level_1", [141]= "level_2", [142]= "level_3", [143]= "dagger_twirl", [144]= "ancestors_edge", [145]= "ancestors_pauldron", [146]= "ancestors_vambrace", [147]= "bladebiter", [148]= "burning_fiend", [149]= "fiery_soul", [150]= "frostiron_raider", [151]= "obeisance_of_the_keeper", [152]= "salvaged_sword", [153]= "serene_honor", [154]= "shinobi_mask", [155]= "swordonshoulder", [156]= "whalehook", [157]= "winterblight", [158]= "lucentyr", [159]= "lyreleis_breeze", [160]= "mace", [161]= "tinker_rollermaw", [162]= "meld", [163]= "agrressive", [164]= "miniboss", [165]= "moonfall", [166]= "moon_griffon", [167]= "overpower1", [168]= "overpower2", [169]= "overpower3", [170]= "overpower4", [171]= "overpower5", [172]= "overpower6", [173]= "loda", [174]= "dark_wraith", [175]= "pinfold", [176]= "digger", [177]= "portrait_fogheart", [178]= "silent_ripper", [179]= "shake_moneymaker", [180]= "belly_flop", [181]= "roshan", [182]= "am_blink", [183]= "mana_void", [184]= "culling_blade", [185]= "brain_sap", [186]= "fiends_grip", [187]= "roar", [188]= "axes", [189]= "stolen_firefly", [190]= "firefly", [191]= "freezing_field", [192]= "frostbite", [193]= "crystal_nova", [194]= "black_hole", [195]= "fissure", [196]= "slam", [197]= "totem", [198]= "omnislash", [199]= "spin", [200]= "finger", [201]= "impale", [202]= "laguna", [203]= "lsa", [204]= "mana_drain", [205]= "wave", [206]= "leap", [207]= "requiem", [208]= "shadowraze", [209]= "sprout", [210]= "summon", [211]= "teleport", [212]= "wrath", [213]= "darkness", [214]= "void", [215]= "guardian_angel", [216]= "purification", [217]= "repel", [218]= "dismember", [219]= "life_drain", [220]= "hook", [221]= "qop_blink", [222]= "scream", [223]= "shadow_strike", [224]= "sonic_wave", [225]= "ravage", [226]= "snipe", [227]= "stolen_charge", [228]= "strike", [229]= "burrow", [230]= "shrapnel", [231]= "ball_lightning", [232]= "remnant", [233]= "bolt", [234]= "vortex", [235]= "earthshock", [236]= "gale", [237]= "plague_ward", [238]= "poison_nova", [239]= "viper_strike", [240]= "wall", [241]= "ward", [242]= "powershot", [243]= "end", [244]= "windrun", [245]= "windy", [246]= "chase", [247]= "injured rare", [248]= "pegleg", [249]= "start", [250]= "sb_helmet", [251]= "sb_bracers", [252]= "sb_shoulder", [253]= "sb_spear", [254]= "dominator", [255]= "iron", [256]= "sven_shield", [257]= "sven_warcry", [258]= "chicken_gesture", [259]= "emp", [260]= "slasher_weapon", [261]= "slasher_offhand", [262]= "slasher_chest", [263]= "slasher_mask", [264]= "sm_armor", [265]= "sm_shoulder", [266]= "wolfhound", [267]= "great_safari", [268]= "taunt_quickdraw_gesture", [269]= "sparrowhawk_bow", [270]= "sparrowhawk_cape", [271]= "sparrowhawk_quiver", [272]= "sparrowhawk_hood", [273]= "sparrowhawk_shoulder", [274]= "twister", [275]= "sprint", [276]= "sugarrush", [277]= "trickortreat", [278]= "transition", [279]= "torment", [280]= "stinger", [281]= "whats_that", [282]= "witchdoctor_jig", [283]= "backstroke_gesture", [284]= "bazooka", [285]= "cat_dancer_gesture", [286]= "face_me", [287]= "swag_gesture", [288]= "get_burned", [289]= "giddy_up_gesture", [290]= "guitar", [291]= "hang_loose_gesture", [292]= "horn", [293]= "happy_dance", [294]= "jump_gesture", [295]= "loser", [296]= "lute", [297]= "magic_ends_here", [298]= "mag_power_gesture", [299]= "mask_lord", [300]= "poundnpoint", [301]= "robot_gesture", [302]= "taunt_roll_gesture", [303]= "sharp_blade", [304]= "staff_swing", [305]= "groove_gesture", [306]= "telebolt", [307]= "admirals_prow", [308]= "turbulent_teleport", [309]= "timelord_head", [310]= "tree", [311]= "dryad_tree", [312]= "tidehunter_toss_fish", [313]= "enchant_totem", [314]= "trapper", [315]= "twinblade_attack", [316]= "twinblade_attack_b", [317]= "twinblade_attack_c", [318]= "twinblade_attack_d", [319]= "twinblade_attack_injured", [320]= "twinblade_death", [321]= "twinblade_idle", [322]= "twinblade_idle_injured", [323]= "twinblade_idle_rare", [324]= "twinblade_injured_attack_b", [325]= "twinblade_jinada", [326]= "twinblade_jinada_injured", [327]= "twinblade_shuriken_toss", [328]= "twinblade_shuriken_toss_injured", [329]= "twinblade_spawn", [330]= "twinblade_stun", [331]= "twinblade_track", [332]= "twinblade_track_injured", [333]= "twinblade_victory", [334]= "melee", [335]= "backward", [336]= "forward", [337]= "vendetta", [338]= "viridi_set", [339]= "fishstick", [340]= "dogofduty", [341]= "cryAnimationExportNode", [342]= "dog_of_duty", [343]= "dizzying_punch", [344]= "wardstaff", [345]= "glory", [346]= "white", [347]= "tidehunter_yippy", [348]= "rampant", [349]= "overload", [350]="surge", [351]="es_prosperity", [352]="Espada_pistola", [353]="overload_injured", [354]="ss_fortune", [355]="liquid_fire", [356]="jakiro_icemelt", [357]="jakiro_roar", [358]="chakram", [359]="doppelwalk", [360]="enrage", [361]="fast_run", [362]="overpower", [363]="overwhelmingodds", [364]="pregame", [365]="shadow_dance", [366]="shukuchi", [367]="strength", [368]="twinblade_run", [369]="twinblade_run_injured", [370]="windwalk", } function modifier_animation:OnCreated(keys) self.keys = keys if not IsServer() then local stack = keys.stack_count local activity = bit.band(stack, 0x07FF) local rate = bit.rshift(bit.band(stack, 0x7F800), 11) local rest = bit.rshift(bit.band(stack, 0xFFF80000), 19) self.activity = activity self.rate = rate / 20 self.rest = rest --print(self.activity) --print(self.rate) --print(self.rest) self.translate = _CODE_TO_ANIMATION_TRANSLATE[self.rest] else self.translate = keys.translate end end function modifier_animation:GetAttributes() return MODIFIER_ATTRIBUTE_PERMANENT + MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE --+ MODIFIER_ATTRIBUTE_MULTIPLE end function modifier_animation:IsHidden() return true end function modifier_animation:IsDebuff() return false end function modifier_animation:IsPurgable() return false end function modifier_animation:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_OVERRIDE_ANIMATION, MODIFIER_PROPERTY_OVERRIDE_ANIMATION_RATE, MODIFIER_PROPERTY_OVERRIDE_ANIMATION_WEIGHT, MODIFIER_PROPERTY_TRANSLATE_ACTIVITY_MODIFIERS, } return funcs end function modifier_animation:GetOverrideAnimation(...) return self.activity end function modifier_animation:GetOverrideAnimationRate(...) return self.rate end function modifier_animation:GetOverrideAnimationWeight(...) return 1 end function modifier_animation:GetActivityTranslationModifiers(...) --print('MA: ', self.translate, IsServer()) return self.translate or 0 end
apache-2.0
Zero-K-Experiments/Zero-K-Experiments
gamedata/modularcomms/weapons/flamethrower.lua
4
1508
local name = "commweapon_flamethrower" local weaponDef = { name = [[Flame Thrower]], areaOfEffect = 64, avoidGround = false, avoidFeature = false, cegTag = [[flamer]], collideFeature = false, collideGround = false, craterBoost = 0, craterMult = 0, customParams = { slot = [[5]], muzzleEffectFire = [[custom:RAIDMUZZLE]], flamethrower = [[1]], setunitsonfire = "1", burntime = [[450]], light_camera_height = 2800, light_color = [[0.6 0.39 0.18]], light_radius = 260, light_fade_time = 10, light_beam_mult_frames = 5, light_beam_mult = 5, }, damage = { default = 10, subs = 0.1, }, explosionGenerator = [[custom:SMOKE]], fallOffRate = 1, fireStarter = 100, heightMod = 1, impulseBoost = 0, impulseFactor = 0, interceptedByShieldType = 1, noExplode = true, noSelfDamage = true, --predictBoost = 1, range = 270, reloadtime = 5/30, rgbColor = [[1 1 1]], soundStart = [[weapon/flamethrower]], soundTrigger = true, texture1 = [[flame]], thickness = 0, tolerance = 5000, turret = true, weaponType = [[LaserCannon]], weaponVelocity = 800, } return name, weaponDef
gpl-2.0
Zero-K-Experiments/Zero-K-Experiments
EngineOptions.lua
15
6020
-- $Id$ -- Custom Options Definition Table format -- NOTES: -- - using an enumerated table lets you specify the options order -- -- These keywords must be lowercase for LuaParser to read them. -- -- key: the string used in the script.txt -- name: the displayed name -- desc: the description (could be used as a tooltip) -- type: the option type -- def: the default value -- min: minimum value for number options -- max: maximum value for number options -- step: quantization step, aligned to the def value -- maxlen: the maximum string length for string options -- items: array of item strings for list options -- scope: 'all', 'player', 'team', 'allyteam' <<< not supported yet >>> -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Example EngineOptions.lua -- local options = { { key = 'startconds', name = 'Starting Conditions', desc = 'Set the starting conditions.', type = 'section', }, { key = 'modifiers', name = 'In-Game Conditions', desc = 'Set up ingame conditions.', type = 'section', }, --[[ { key = 'GameMode', name = 'Game end condition', desc = 'Determines what condition triggers the defeat of a player', type = 'list', section= 'modifiers', def = '0', items = { { key = '0', name = 'Kill everything', desc = 'The player will lose when all his units have died', }, { key = '1', name = 'Commander ends', desc = 'The player will lose when his commander dies', }, { key = '2', name = 'Commander lineage ends', desc = 'This is a stricter form of commander ends\nevery unit will inherit the lineage from the player whom built it\neven if shared, when the commander dies the unit will still die', }, }, }, { key = 'StartMetal', name = 'Starting metal', desc = 'Determines amount of metal and metal storage that each player will start with', type = 'number', section= 'startconds', def = 1000, min = 0, max = 10000, step = 10, -- quantization is aligned to the def value -- (step <= 0) means that there is no quantization }, { key = 'StartEnergy', name = 'Starting energy', desc = 'Determines amount of metal and metal storage that each player will start with', type = 'number', section= 'StartingResources', def = 1000, min = 0, max = 10000, step = 10, -- quantization is aligned to the def value -- (step <= 0) means that there is no quantization }, --]] { key = 'MaxUnits', name = 'Max units', desc = 'Determines the ceiling of how many units and buildings a player is allowed to own at the same time (limited by spring to 10000 / (#commanders + 1))', type = 'number', section= 'modifiers', def = 1500, min = 10, max = 3000, step = 10, -- quantization is aligned to the def value -- (step <= 0) means that there is no quantization }, --[[ { key = 'LimitDgun', name = 'Limit D-Gun range', desc = "The commander's D-Gun weapon will be usable only close to the player's starting location", type = 'bool', section = 'modifiers', def = false, },]]-- --[[ { key = 'GhostedBuildings', name = 'Ghosted buildings', desc = "Once an enemy building will be spotted\n a ghost trail will be placed to memorize location even after the loss of the line of sight", type = 'bool', def = true, }, --]] { key = 'diplomacy', name = 'Diplomacy Settings', desc = 'Configure diplomacy settings.', type = 'section', }, { key = 'FixedAllies', name = 'Fixed ingame alliances', desc = 'Disables the use of the /ally command for ingame ceasefires. \nkey: fixedallies', type = 'bool', section = 'diplomacy', def = false, }, { key = 'MinSpeed', name = 'Minimum game speed', desc = 'Sets the minimum speed that the players will be allowed to change to', type = 'number', section= 'modifiers', def = 0.5, min = 0.1, max = 10, step = 0.1, -- quantization is aligned to the def value -- (step <= 0) means that there is no quantization }, { key = 'MaxSpeed', name = 'Maximum game speed', desc = 'Sets the maximum speed that the players will be allowed to change to', type = 'number', section= 'modifiers', def = 2, min = 0.1, max = 10, step = 0.1, -- quantization is aligned to the def value -- (step <= 0) means that there is no quantization }, { key = 'mapsettings', name = 'Map Related Settings', desc = 'Configure map related settings.', type = 'section', }, { key = 'DisableMapDamage', name = 'Disable Map Deformations', desc = 'Prevents the map shape from being changed by weapons and terraforming', type = 'bool', section= 'mapsettings', def = false, }, --[[ -- the following options can create problems and were never used by interface programs, thus are commented out for the moment { key = 'LuaGaia', name = 'Enables gaia', desc = 'Enables gaia player', type = 'bool', def = true, }, { key = 'NoHelperAIs', name = 'Disable helper AIs', desc = 'Disables luaui and group ai usage for all players', type = 'bool', def = false, }, { key = 'LuaRules', name = 'Enable LuaRules', desc = 'Enable mod usage of LuaRules', type = 'bool', def = true, }, --]] } return options
gpl-2.0
taxler/radish
packaging/extensions/platform_win32/lua/exports/mswindows/shell/init.lua
1
14229
local ffi = require 'ffi' local mswin = require 'exports.mswindows' local guids = require 'exports.guids' local com = require 'exports.mswindows.com' local automation = require 'exports.mswindows.automation' ffi.cdef [[ typedef enum FDE_SHAREVIOLATION_RESPONSE { FDESVR_DEFAULT = 0, FDESVR_ACCEPT = 1, FDESVR_REFUSE = 2 } FDE_SHAREVIOLATION_RESPONSE; typedef enum FDE_OVERWRITE_RESPONSE { FDEOR_DEFAULT = 0, FDEOR_ACCEPT = 1, FDEOR_REFUSE = 2 } FDE_OVERWRITE_RESPONSE; enum { FOS_OVERWRITEPROMPT = 0x00000002, // (on by default in the save dialog) FOS_STRICTFILETYPES = 0x00000004, // In the save dialog, only allow the user to choose a file that has // one of the file extensions provided in SetFileTypes. FOS_NOCHANGEDIR = 0x00000008, // Don't change the current working directory FOS_PICKFOLDERS = 0x00000020, // Invoke the open dialog in folder picking mode. FOS_FORCEFILESYSTEM = 0x00000040, // Ensure that items returned are filesystem items. FOS_ALLNONSTORAGEITEMS = 0x00000080, // Allow choosing items that have no storage. FOS_NOVALIDATE = 0x00000100, FOS_ALLOWMULTISELECT = 0x00000200, FOS_PATHMUSTEXIST = 0x00000800, // (on by default) FOS_FILEMUSTEXIST = 0x00001000, // (on by default in the open dialog and folder picker) FOS_CREATEPROMPT = 0x00002000, FOS_SHAREAWARE = 0x00004000, FOS_NOREADONLYRETURN = 0x00008000, // (on by default in the save dialog) FOS_NOTESTFILECREATE = 0x00010000, // Avoid testing the creation of the chosen file in the save dialog // (specifying this flag will circumvent some useful error handling, such as access denied) FOS_HIDEMRUPLACES = 0x00020000, // (not used in Win7) FOS_HIDEPINNEDPLACES = 0x00040000, // Don't display the standard namespace locations in the navigation pane. // (generally used along with AddPlace) FOS_NODEREFERENCELINKS = 0x00100000, // Don't treat shortcuts as their target files. FOS_DONTADDTORECENT = 0x02000000, // Don't add the chosen file to the recent documents list (SHAddToRecentDocs) FOS_FORCESHOWHIDDEN = 0x10000000, // Show all files including system and hidden files. FOS_DEFAULTNOMINIMODE = 0x20000000, // (not used in Win7) FOS_FORCEPREVIEWPANEON = 0x40000000 }; typedef enum FDAP { FDAP_BOTTOM = 0, FDAP_TOP = 1 } FDAP; typedef struct COMDLG_FILTERSPEC { const wchar_t* pszName; const wchar_t* pszSpec; } COMDLG_FILTERSPEC; typedef enum SIGDN { // lower word (& with 0xFFFF) SIGDN_NORMALDISPLAY = 0x00000000, // SHGDN_NORMAL SIGDN_PARENTRELATIVEPARSING = (int) 0x80018001, // SHGDN_INFOLDER | SHGDN_FORPARSING SIGDN_DESKTOPABSOLUTEPARSING = (int) 0x80028000, // SHGDN_FORPARSING SIGDN_PARENTRELATIVEEDITING = (int) 0x80031001, // SHGDN_INFOLDER | SHGDN_FOREDITING SIGDN_DESKTOPABSOLUTEEDITING = (int) 0x8004c000, // SHGDN_FORPARSING | SHGDN_FORADDRESSBAR SIGDN_FILESYSPATH = (int) 0x80058000, // SHGDN_FORPARSING SIGDN_URL = (int) 0x80068000, // SHGDN_FORPARSING SIGDN_PARENTRELATIVEFORADDRESSBAR = (int) 0x8007c001, // SHGDN_INFOLDER | SHGDN_FORPARSING | SHGDN_FORADDRESSBAR SIGDN_PARENTRELATIVE = (int) 0x80080001 // SHGDN_INFOLDER } SIGDN; typedef enum SIATTRIBFLAGS { SIATTRIBFLAGS_AND = 0x00000001, SIATTRIBFLAGS_OR = 0x00000002, SIATTRIBFLAGS_APPCOMPAT = 0x00000003, SIATTRIBFLAGS_MASK = 0x00000003, SIATTRIBFLAGS_ALLITEMS = 0x00004000 } SIATTRIBFLAGS; typedef enum CDCONTROLSTATEF { CDCS_INACTIVE = 0x00000000, CDCS_ENABLED = 0x00000001, CDCS_VISIBLE = 0x00000002, CDCS_ENABLEDVISIBLE = 0x00000003, } CDCONTROLSTATEF; ]] com.def { {'IShellItem'; methods = { {'BindToHandler', 'IBindCtx*, GUID* bhid, GUID* iid, void** out_value'}; {'GetParent', 'IShellItem** out_parent'}; {'GetDisplayName', 'SIGDN, wchar_t** out_name'}; {'GetAttributes', 'uint32_t sfgao_mask, uint32_t* out_sfgao_attribs'}; {'Compare', 'IShellItem*, uint32_t sichint, int* out_order'}; }; iid = '43826d1e-e718-42ee-bc55-a1e261c37bfe'; }; {'IShellItemArray'; methods = { {'BindToHandler', 'IBindCtx*, GUID* bhid, GUID* iid, void** out_obj'}; {'GetPropertyStore', 'GETPROPERTYSTOREFLAGS flags, GUID* iidof_store, void** out_store'}; {'GetPropertyDescriptionList', 'PROPERTYKEY* keyType, GUID* iidof_list, void** out_list'}; {'GetAttributes', 'SIATTRIBFLAGS attrib_flags, uint32_t sfgao_mask, uint32_t* out_sfgao_attribs'}; {'GetCount', 'uint32_t* out_count'}; {'GetItemAt', 'uint32_t index, IShellItem** out_item'}; {'EnumItems', 'IEnumShellItems** out_enum'}; }; iid = 'b63ea76d-1f85-456f-a19c-48159efa858b'; }; automation.enumdef { 'IEnumShellItems'; ctype = 'IShellItem*'; iid = '70629033-e363-4a28-a567-0db78006e6d7'; }; {'IShellItemFilter'; methods = { {'IncludeItem', 'IShellItem*'}; {'GetEnumFlagsForItem', 'IShellItem*, uint32_t* out_shcont_flags'}; }; iid = '2659B475-EEB8-48b7-8F07-B378810F48CF'; }; {'IModalWindow'; methods = { {'Show', 'void* owner_hwnd'}; }; iid = 'b4db1657-70d7-485e-8e3e-6fcb5a5c1802'; }; {'IFileDialogEvents'; methods = { {'OnFileOk', 'IFileDialog*'}; {'OnFolderChanging', 'IFileDialog*, IShellItem*'}; {'OnFolderChange', 'IFileDialog*'}; {'OnSelectionChange', 'IFileDialog*'}; {'OnShareViolation', 'IFileDialog*, IShellItem*, FDE_SHAREVIOLATION_RESPONSE* out_response'}; {'OnTypeChange', 'IFileDialog*'}; {'OnOverwrite', 'IFileDialog*, IShellItem*, FDE_OVERWRITE_RESPONSE* out_response'}; }; iid = '973510db-7d7f-452b-8975-74a85828d354'; }; {'IFileDialog', inherits='IModalWindow'; methods = { {'SetFileTypes', 'uint32_t specs_count, COMDLG_FILTERSPEC* specs'}; {'SetFileTypeIndex', 'uint32_t'}; {'GetFileTypeIndex', 'uint32_t*'}; {'Advise', 'IFileDialogEvents*, uint32_t* out_cookie'}; {'Unadvise', 'uint32_t cookie'}; {'SetOptions', 'uint32_t options'}; {'GetOptions', 'uint32_t* out_options'}; {'SetDefaultFolder', 'IShellItem*'}; {'SetFolder', 'IShellItem*'}; {'GetFolder', 'IShellItem** out_folder'}; {'GetCurrentSelection', 'IShellItem** out_selection'}; {'SetFileName', 'const wchar_t*'}; {'GetFileName', 'wchar_t* out_name'}; {'SetTitle', 'const wchar_t*'}; {'SetOkButtonLabel', 'const wchar_t*'}; {'SetFileNameLabel', 'const wchar_t*'}; {'GetResult', 'IShellItem** out_result'}; {'AddPlace', 'IShellItem*, FDAP'}; {'SetDefaultExtension', 'const wchar_t*'}; {'Close', 'int32_t hresult'}; {'SetClientGuid', 'GUID*'}; {'ClearClientData'}; {'SetFilter', 'IShellItemFilter*'}; }; iid = '42f85136-db7e-439c-85f1-e4075d135fc8'; }; {'IFileOpenDialog', inherits='IFileDialog'; methods = { {'GetResults', 'IShellItemArray** out_results'}; {'GetSelectedItems', 'IShellItemArray** out_items'}; }; iid = 'd57c7288-d4ad-4768-be02-9d969532d960'; }; {'IFileSaveDialog', inherits='IFileDialog'; methods = { {'SetSaveAsItem', 'IShellItem*'}; {'SetProperties', 'IPropertyStore*'}; {'SetCollectedProperties', 'IPropertyDescriptionList*, bool32 append_default'}; {'GetProperties', 'IPropertyStore** out_properties'}; {'ApplyProperties', 'IShellItem*, IPropertyStore*, void* hwnd, IFileOperationProgressSink*'} }; iid = '84bccd23-5fde-4cdb-aea4-af64b83d78ab'; }; {'IFileDialogCustomize'; methods = { {'EnableOpenDropDown', 'uint32_t id'}; {'AddMenu', 'uint32_t id, const wchar_t* label'}; {'AddPushButton', 'uint32_t id, const wchar_t* label'}; {'AddComboBox', 'uint32_t id'}; {'AddRadioButtonList', 'uint32_t id'}; {'AddCheckButton', 'uint32_t id, const wchar_t* label, bool32 checked'}; {'AddEditBox', 'uint32_t id, const wchar_t* text'}; {'AddSeparator', 'uint32_t id'}; {'AddText', 'uint32_t id, const wchar_t*'}; {'SetControlLabel', 'uint32_t id, const wchar_t*'}; {'GetControlState', 'uint32_t id, CDCONTROLSTATEF* out_state'}; {'SetControlState', 'uint32_t id, CDCONTROLSTATEF'}; {'GetEditBoxText', 'uint32_t id, wchar_t** out_text'}; {'SetEditBoxText', 'uint32_t id, const wchar_t* text'}; {'GetCheckButtonState', 'uint32_t id, bool32* out_checked'}; {'SetCheckButtonState', 'uint32_t id, bool32 checked'}; {'AddControlItem', 'uint32_t control_id, uint32_t item_id, const wchar_t* label'}; {'RemoveControlItem', 'uint32_t control_id, uint32_t item_id'}; {'RemoteAllControlItems', 'uint32_t id'}; {'GetControlItemState', 'uint32_t control_id, uint32_t item_id, CDCONTROLSTATEF* out_state'}; {'SetControlItemState', 'uint32_t control_id, uint32_t item_id, CDCONTROLSTATEF state'}; {'GetSelectedControlItem', 'uint32_t control_id, uint32_t* out_item_id'}; {'SetSelectedControlItem', 'uint32_t control_id, uint32_t item_id'}; {'StartVisualGroup', 'uint32_t id, const wchar_t* label'}; {'EndVisualGroup'}; {'MakeProminent', 'uint32_t id'}; -- one control only {'SetControlItemText', 'uint32_t control_id, uint32_t item_id, const wchar_t*'}; }; iid = 'e6fdd21a-163f-4975-9c8c-a69f1ba37034'; }; {'IFileOperationProgressSink'; methods = { {'StartOperations'}; {'FinishOperations', 'int32_t hresult'}; {'PreRenameItem', 'uint32_t flags, IShellItem*, const wchar_t* new_name'}; {'PostRenameItem', [[ uint32_t flags, IShellItem*, const wchar_t* new_name, int32_t rename_hresult, IShellItem* newly_created]]}; {'PreMoveItem', 'uint32_t flags, IShellItem*, IShellItem* dest_folder, const wchar_t* new_name'}; {'PostMoveItem', [[ uint32_t flags, IShellItem*, IShellItem* dest_folder, const wchar_t* new_name, int32_t move_hresult, IShellItem* newly_created]]}; {'PreCopyItem', 'uint32_t flags, IShellItem*, IShellItem* dest_folder, const wchar_t* new_name'}; {'PostCopyItem', [[ uint32_t flags, IShellItem*, IShellItem* dest_folder, const wchar_t* new_name, int32_t copy_hresult, IShellItem* newly_created]]}; {'PreDeleteItem', 'uint32_t flags, IShellItem*'}; {'PostDeleteItem', 'uint32_t flags, IShellItem*, int32_t delete_hresult, IShellItem* newly_created'}; {'PreNewItem', 'uint32_t flags, IShellItem* dest_folder, const wchar_t* new_name'}; {'PostNewItem', [[ uint32_t flags, IShellItem* dest_folder, const wchar_t* new_name, const wchar_t* template_name, uint32_t file_attributes, int32_t file_attributes, int32_t new_hresult, IShellItem* new_item]]}; {'UpdateProgress', 'uint32_t total_work, uint32_t so_far'}; {'ResetTimer'}; {'PauseTimer'}; {'ResumeTimer'}; }; iid = '04b0f1a7-9490-44bc-96e1-4296a31252e2'; }; {"ITaskbarList"; methods = { {'HrInit'}; {'AddTab', 'void* hwnd'}; {'DeleteTab', 'void* hwnd'}; {'ActivateTab', 'void* hwnd'}; {'SetActiveAlt', 'void* hwnd'}; }; iid = '56FDF344-FD6D-11d0-958A006097C9A090'; }; {"ITaskbarList2", inherits='ITaskbarList'; methods = { {'MarkFullscreenWindow', 'void* hwnd, bool32'}; }; iid = '602D4995-B13A-429b-A66E1935E44F4317'; }; {"ITaskbarList3", inherits='ITaskbarList2'; methods = { {'SetProgressValue', 'void* hwnd, uint64_t done, uint64_t total'}; {'SetProgressState', 'void* hwnd, uint32_t tbpfFlags'}; {'RegisterTab', 'void* hwndTab, void* hwndMDI'}; {'UnregisterTab', 'void* hwndTab'}; {'SetTabOrder', 'void* hwndTab, void* hwndInsertBefore'}; {'SetTabActive', 'void* hwndTab, void* hwndMDI, uint32_t tbatFlags'}; {'ThumbBarAddButtons', 'void* hwnd, uint32_t buttons, void* button'}; {'ThumbBarUpdateButtons', 'void* hwnd, uint32_t buttons, void* button'}; {'ThumbBarSetImageList', 'void* hwnd, void* himagelist'}; {'SetOverlayIcon', 'void* hwnd, void* hicon, const wchar_t* description'}; {'SetThumbnailTooltip', 'void* hwnd, const wchar_t* toolTip'}; {'SetThumbnailClip', 'void* hwnd, RECT* clip'}; }; iid = 'EA1AFB91-9E28-4B86-90E99E9F8A5EEFAF'; }; } ffi.cdef [[ enum { WM_DROPFILES = 0x0233 }; void DragAcceptFiles(void* hwnd, bool32); uint32_t DragQueryFileA(void* hdrop, uint32_t index, char* buffer, uint32_t bufferSize); uint32_t DragQueryFileW(void* hdrop, uint32_t index, wchar_t* buffer, uint32_t bufferSize); bool32 DragQueryPoint(void* hdrop, POINT*); void DragFinish(void* hdrop); void* ExtractIconW(void* hInstance, const wchar_t* path, uint32_t index); int32_t ShellExecuteW( void* hwnd, const wchar_t* operation, const wchar_t* file, const wchar_t* parameters, const wchar_t* directory, int32_t show); enum { NIM_ADD = 0, NIM_MODIFY = 1, NIM_DELETE = 2, NIM_SETFOCUS = 3, NIM_SETVERSION = 4, NIF_MESSAGE = 1, NIF_ICON = 2, NIF_TIP = 4, NIF_STATE = 8, NIF_INFO = 0x10, NIF_GUID = 0x20, NIF_REALTIME = 0x40, NIF_SHOWTIP = 0x80, NIIF_NONE = 0, NIIF_INFO = 1, NIIF_WARNING = 2, NIIF_ERROR = 3, NIIF_USER = 4, NIIF_ICON_MASK = 0xF, NIIF_NOSOUND = 0x10, NIIF_LARGE_ICON = 0x20, NIIF_RESPECT_QUIET_TIME = 0x80, NOTIFYICON_VERSION_4 = 4, NIN_SELECT = WM_USER + 0, NINF_KEY = 0x1, NIN_KEYSELECT = NIN_SELECT | NINF_KEY, NIN_BALLOONSHOW = WM_USER + 2, NIN_BALLOONHIDE = WM_USER + 3, NIN_BALLOONTIMEOUT = WM_USER + 4, NIN_BALLOONUSERCLICK = WM_USER + 5, NIN_POPUPOPEN = WM_USER + 6, NIN_POPUPCLOSE = WM_USER + 7 }; typedef struct NOTIFYICONDATAW { uint32_t cbSize; void* hWnd; uint32_t uID, uFlags, uCallbackMessage; void* hIcon; wchar_t szTip[128]; uint32_t dwState, dwStateMask; wchar_t szInfo[256]; union { uint32_t uTimeout; uint32_t uVersion; }; wchar_t szInfoTitle[64]; uint32_t dwInfoFlags; GUID guidItem; void* hBalloonIcon; } NOTIFYICONDATAW; bool32 Shell_NotifyIconW(uint32_t nim, NOTIFYICONDATAW*); ]] return ffi.load 'shell32'
mit
Scavenge/darkstar
scripts/globals/limbus.lua
21
37011
-------------------------------------- require("scripts/globals/keyitems") -------------------------------------- APPOLLYON_SE_NE = 1 -- out 557 -1 441 128 APPOLLYON_NW_SW = 2 -- out -561 0 443 242 TEMENOS = 3 -- WHITE_CARD = 349 -- RED_CARD = 350 -- BLACK_CARD = 351 -- COSMOCLEANSE = 734 -- REGION NW_Apollyon = 1 SW_Apollyon = 2 NE_Apollyon = 3 SE_Apollyon = 4 CS_Apollyon = 5 Central_Apollyon = 6 Temenos_Western_Tower = 1 Temenos_Northern_Tower = 2 Temenos_Eastern_Tower = 3 Central_Temenos_Basement = 4 Central_Temenos_1st_Floor = 5 Central_Temenos_2nd_Floor = 6 Central_Temenos_3rd_Floor = 7 Central_Temenos_4th_Floor = 8 APPOLLYON_SE_NE_BCNM_LIST = { -- instanceID, white, red, black, bitmap, bit, instanceRegion 1292, {false, false, true, 8, NE_Apollyon}, -- 'NE_Apollyon' region 3 438 0 -89 1293, {false, false, true, 4, SE_Apollyon}, -- 'SE_Apollyon' 468 0 -625 1294, {false, false, false, 32, CS_Apollyon}, -- 'CS_Apollyon' 0 0 -210 1295, {false, false, false, 64, CS_Apollyon}, -- 'CS_Apollyon_II' 0 0 -133 1296, {false, false, false, 16, Central_Apollyon}, -- 'Central_Apollyon' 0 0 210 1297, {false, false, false, 128, Central_Apollyon} -- 'Central_Apollyon_II' 0 0 210 } APPOLLYON_NW_SW_BCNM_LIST = { 1290, {false, true, false, 2, NW_Apollyon}, -- 'NW_Apollyon' -439 0 -89 1291, {false, true, false, 1, SW_Apollyon}, -- 'SW_Apollyon' -468 0 -626 1294, {false, false, false, 32, CS_Apollyon}, -- 'CS_Apollyon' 0 0 -210 1295, {false, false, false, 64, CS_Apollyon}, -- 'CS_Apollyon_II' 0 0 -133 1296, {false, false, false, 16, Central_Apollyon}, -- 'Central_Apollyon' 0 0 210 1297, {false, false, false, 128, Central_Apollyon} -- 'Central_Apollyon_II' 0 0 210 } TEMENOS_LIST = { 1298, {true, false, false, 4, Temenos_Western_Tower}, -- 'Temenos_Western_Tower' 380 71 -184 1299, {true, false, false, 1, Temenos_Northern_Tower}, -- 'Temenos_Northern_Tower' 380 71 375 1300, {true, false, false, 2, Temenos_Eastern_Tower}, -- 'Temenos_Eastern_Tower' 380 -2 96 1301, {false, false, false, 128, Central_Temenos_Basement}, -- 'Central_Temenos_Basement' 580 -2 -544 1302, {false, false, false, 256, Central_Temenos_Basement}, -- 'Central_Temenos_Basement_II' 540 -2 -544 1303, {false, false, false, 64, Central_Temenos_1st_Floor}, -- 'Central_Temenos_1st_Floor' 260 -162 -504 1304, {false, false, false, 32, Central_Temenos_2nd_Floor}, -- 'Central_Temenos_2nd_Floor' 20 -2 -544 1305, {false, false, false, 16, Central_Temenos_3rd_Floor}, -- 'Central_Temenos_3rd_Floor' -296 -162 -500 1306, {false, false, false, 8, Central_Temenos_4th_Floor}, -- 'Central_Temenos_4th_Floor' -540 -2 -584 1307, {false, false, false, 512, Central_Temenos_4th_Floor} -- 'Central_Temenos_4th_Floor_II' -540 -2 -584 } MIMICPOSITION = { 1, {-363, 0, -282}; 2, {-359, 0, -277}; 3, {-326, 0, -301}; 4, {-331, 0, -330}; 5, {-340, 0, -330}; 6, {-345, 0, -311}; 7, {-339, 0, -300}; 8, {-335, 0, -281}; } STATUS_NORMAL = 0 STATUS_DISAPPEAR = 2 cTIME = 1 cITEM = 2 cRESTORE = 3 cMIMIC = 4 ARMOURY_CRATES_LIST_APPOLLYON = { -- armoryID, (type, regionID, time, despawnothercoffer, mimicID, lootID) 1, {cTIME, SE_Apollyon, 5, false, 0, 0}, -- time SE_Appollyon floor 1 2, {cITEM, SE_Apollyon, 0, false, 0, 110}, -- items SE_Appollyon floor 1 3, {cRESTORE, SE_Apollyon, 0, false, 0, 0}, -- restore SE_Appollyon floor 1 14, {cTIME, SW_Apollyon, 10, false, 0, 0}, -- time SW_Appollyon floor 1 15, {cITEM, SW_Apollyon, 0, false, 0, 119}, -- items SW_Appollyon floor 1 16, {cRESTORE, SW_Apollyon, 0, false, 0, 0}, -- restore SW_Appollyon floor 1 -- 32, {}, -- mimic -- 33, {}, -- mimic -- 34, {}, -- mimic -- 35, {}, -- mimic -- 36, {}, -- mimic -- 37, {}, -- mimic -- 38, {}, -- mimic 39, {cITEM, Central_Apollyon, 0, false, 0, 128}, -- omega 40, {cTIME, NW_Apollyon, 5, false, 0, 0}, -- time NW_Appollyon floor 1 T1 41, {cTIME, NW_Apollyon, 5, false, 0, 0}, -- time NW_Appollyon floor 1 T2 42, {cTIME, NW_Apollyon, 5, false, 0, 0}, -- time NW_Appollyon floor 1 T3 43, {cTIME, NW_Apollyon, 5, false, 0, 0}, -- time NW_Appollyon floor 2 T1 44, {cTIME, NW_Apollyon, 5, false, 0, 0}, -- time NW_Appollyon floor 2 T2 45, {cTIME, NW_Apollyon, 5, false, 0, 0}, -- time NW_Appollyon floor 2 T3 70, {cTIME, SW_Apollyon, 10, true, 0, 0}, -- time SW_Appollyon floor 2 71, {cITEM, SW_Apollyon, 0, true, 0, 120}, -- items SW_Appollyon floor 2 72, {cRESTORE, SW_Apollyon, 0, true, 0, 0}, -- restore SW_Appollyon floor 2 81, {cTIME, NE_Apollyon, 5, false, 0, 0}, -- time NE_Appollyon floor 1 T2 82, {cTIME, NE_Apollyon, 5, false, 0, 0}, -- time NE_Appollyon floor 1 T3 83, {cTIME, NE_Apollyon, 5, false, 0, 0}, -- time NE_Appollyon floor 2 T2 84, {cTIME, NE_Apollyon, 5, false, 0, 0}, -- time NE_Appollyon floor 2 T3 85, {cTIME, NE_Apollyon, 5, false, 0, 0}, -- time NE_Appollyon floor 3 T2 94, {cTIME, NE_Apollyon, 5, false, 0, 0}, -- time NE_Appollyon floor 3 T3 95, {cTIME, NE_Apollyon, 5, false, 0, 0}, -- time NE_Appollyon floor 4 T2 96, {cTIME, NE_Apollyon, 5, false, 0, 0}, -- time NE_Appollyon floor 4 T3 97, {cTIME, NW_Apollyon, 5, false, 0, 0}, -- time NW_Appollyon floor 4 T2 98, {cTIME, NW_Apollyon, 5, false, 0, 0}, -- time NW_Appollyon floor 4 T3 107, {cITEM, NW_Apollyon, 0, false, 0, 123}, -- item NW_Appollyon floor 1 108, {cITEM, NW_Apollyon, 0, false, 0, 124}, -- item NW_Appollyon floor 2 109, {cITEM, NW_Apollyon, 0, false, 0, 125}, -- item NW_Appollyon floor 3 110, {cITEM, NW_Apollyon, 0, false, 0, 126}, -- item NW_Appollyon floor 4 111, {cITEM, NW_Apollyon, 0, false, 0, 127}, -- item NW_Appollyon floor 5 118, {cTIME, NE_Apollyon, 5, false, 0, 0}, -- time NE_Appollyon floor 1 T1 119, {cITEM, NE_Apollyon, 0, false, 0, 114}, -- items NE_Appollyon floor 1 120, {cRESTORE, NE_Apollyon, 0, false, 0, 0}, -- restore NE_Appollyon floor 1 125, {cTIME, NE_Apollyon, 5, false, 0, 10}, -- time NE_Appollyon floor 2 T1 126, {cITEM, NE_Apollyon, 0, false, 0, 115}, -- items NE_Appollyon floor 2 127, {cRESTORE, NE_Apollyon, 0, false, 0, 0}, -- restore NE_Appollyon floor 2 139, {cTIME, NE_Apollyon, 5, false, 0, 0}, -- time NE_Appollyon floor 3 T1 140, {cITEM, NE_Apollyon, 0, false, 0, 116}, -- items NE_Appollyon floor 3 141, {cRESTORE, NE_Apollyon, 0, false, 0, 0}, -- restore NE_Appollyon floor 3 153, {cTIME, NE_Apollyon, 5, false, 0, 0}, -- time NE_Appollyon floor 4 T1 154, {cITEM, NE_Apollyon, 0, false, 0, 117}, -- items NE_Appollyon floor 4 155, {cRESTORE, NE_Apollyon, 0, false, 0, 0}, -- restore NE_Appollyon floor 4 177, {cTIME, NW_Apollyon, 5, false, 0, 0}, -- time NW_Apollyon floor 3 T1 178, {cITEM, NE_Apollyon, 0, false, 0, 118}, -- items NE_Appollyon floor 5 179, {cRESTORE, NW_Apollyon, 0, false, 0, 0}, -- restore NW_Apollyon floor 4 189, {cTIME, NW_Apollyon, 5, false, 0, 0}, -- time NW_Appollyon floor 3 T2 190, {cTIME, NW_Apollyon, 5, false, 0, 0}, -- time NW_Appollyon floor 3 T3 195, {cTIME, SW_Apollyon, 10, false, 0, 0}, -- time SW_Appollyon floor 3 196, {cITEM, SW_Apollyon, 5, false, 0, 121}, -- items SW_Appollyon floor 3 197, {cRESTORE, SW_Apollyon, 0, false, 0, 0}, -- restore SW_Appollyon floor 3 210, {cMIMIC, SW_Apollyon, 0, false, 0, 0}, -- PH for mimic 211, {cMIMIC, SW_Apollyon, 0, false, 0, 0}, -- PH for mimic 212, {cMIMIC, SW_Apollyon, 0, false, 0, 0}, -- PH for mimic 213, {cMIMIC, SW_Apollyon, 0, false, 0, 0}, -- PH for mimic 214, {cMIMIC, SW_Apollyon, 0, false, 0, 0}, -- PH for mimic 215, {cMIMIC, SW_Apollyon, 0, false, 0, 0}, -- PH for mimic 216, {cMIMIC, SW_Apollyon, 0, false, 0, 0}, -- PH for mimic 232, {cTIME, SE_Apollyon, 5, false, 0, 0}, -- time SE_Appollyon floor 2 233, {cITEM, SE_Apollyon, 0, false, 0, 111}, -- items SE_Appollyon floor 2 234, {cRESTORE, SE_Apollyon, 0, false, 0, 0}, -- restore SE_Appollyon floor 2 246, {cTIME, SE_Apollyon, 10, false, 0, 0}, -- time SE_Appollyon floor 3 247, {cITEM, SE_Apollyon, 0, false, 0, 112}, -- items SE_Appollyon floor 3 248, {cRESTORE, SE_Apollyon, 0, false, 0, 0}, -- restore SE_Appollyon floor 3 259, {cITEM, Central_Apollyon, 0, false, 0, 129}, -- Pod 262, {cTIME, NW_Apollyon, 5, false, 0, 0}, -- time NW_Appollyon floor 4 T1 263, {cITEM, SE_Apollyon, 0, false, 0, 113}, -- items SE_Appollyon floor 4 264, {cRESTORE, NW_Apollyon, 0, false, 0, 0}, -- restore NW_Apollyon floor 1 289, {cRESTORE, NW_Apollyon, 0, false, 0, 0}, -- restore NW_Apollyon floor 2 313, {cITEM, SW_Apollyon, 0, false, 0, 122}, -- items SW_Appollyon floor 4 327, {cRESTORE, NW_Apollyon, 0, false, 0, 0}, -- restore NW_Apollyon floor 3 } ARMOURY_CRATES_LIST_TEMENOS = { -- armoryID, (type, regionID, time, despawnothercoffer, mimicID, lootID) 1, {cITEM, Temenos_Western_Tower, 0, false, 0, 137}, 2, {cITEM, Temenos_Western_Tower, 0, false, 0, 138}, 3, {cITEM, Temenos_Western_Tower, 0, false, 0, 139}, 10, {cITEM, Temenos_Western_Tower, 0, false, 0, 140}, 11, {cITEM, Temenos_Western_Tower, 0, false, 0, 141}, 12, {cITEM, Temenos_Western_Tower, 0, false, 0, 142}, 17, {cITEM, Temenos_Western_Tower, 0, false, 0, 143}, 18, {cITEM, Temenos_Northern_Tower, 0, true, 0, 130}, -- F1 19, {cITEM, Temenos_Northern_Tower, 0, true, 0, 131}, -- F2 26, {cITEM, Temenos_Northern_Tower, 0, true, 0, 132}, -- F3 27, {cITEM, Temenos_Northern_Tower, 0, true, 0, 133}, -- F4 28, {cITEM, Temenos_Northern_Tower, 0, true, 0, 134}, -- F5 38, {cITEM, Temenos_Northern_Tower, 0, true, 0, 135}, -- F6 39, {cITEM, Temenos_Northern_Tower, 0, false, 0, 136}, -- F7 40, {cITEM, Temenos_Eastern_Tower, 0, true, 0, 144}, 45, {cITEM, Temenos_Eastern_Tower, 0, true, 0, 145}, 46, {cITEM, Temenos_Eastern_Tower, 0, true, 0, 146}, 47, {cITEM, Temenos_Eastern_Tower, 0, true, 0, 147}, 68, {cITEM, Temenos_Eastern_Tower, 0, true, 0, 148}, 69, {cITEM, Temenos_Eastern_Tower, 0, true, 0, 149}, 70, {cITEM, Temenos_Eastern_Tower, 0, true, 0, 150}, 71, {cITEM, Central_Temenos_1st_Floor, 0, false, 0, 151}, 77, {cITEM, Central_Temenos_2nd_Floor, 0, false, 0, 152}, 78, {cITEM, Central_Temenos_3rd_Floor, 0, false, 0, 153}, -- central 4eme floor ------------------------------- 79, {cITEM, Central_Temenos_4th_Floor, 0, false, 0, 154}, -- 80, {cITEM, Central_Temenos_4th_Floor, 0, false, 1, 155}, 86, {cITEM, Central_Temenos_4th_Floor, 0, false, 1, 155}, 87, {cITEM, Central_Temenos_4th_Floor, 0, false, 1, 155}, 88, {cITEM, Central_Temenos_4th_Floor, 0, false, 1, 155}, 89, {cITEM, Central_Temenos_4th_Floor, 0, false, 2, 155}, 95, {cITEM, Central_Temenos_4th_Floor, 0, false, 2, 155}, 96, {cITEM, Central_Temenos_4th_Floor, 0, false, 2, 155}, 97, {cITEM, Central_Temenos_4th_Floor, 0, false, 2, 155}, 98, {cITEM, Central_Temenos_4th_Floor, 0, false, 3, 155}, 104, {cITEM, Central_Temenos_4th_Floor, 0, false, 3, 155}, 105, {cITEM, Central_Temenos_4th_Floor, 0, false, 3, 155}, 106, {cITEM, Central_Temenos_4th_Floor, 0, false, 3, 155}, 107, {cITEM, Central_Temenos_4th_Floor, 0, false, 4, 155}, 113, {cITEM, Central_Temenos_4th_Floor, 0, false, 4, 155}, 114, {cITEM, Central_Temenos_4th_Floor, 0, false, 4, 155}, 115, {cITEM, Central_Temenos_4th_Floor, 0, false, 5, 155}, 116, {cITEM, Central_Temenos_4th_Floor, 0, false, 5, 155}, 122, {cITEM, Central_Temenos_4th_Floor, 0, false, 5, 155}, -- 123, {cMIMIC, Temenos_Eastern_Tower, 0, true, 0, 0}, 127, {cMIMIC, Temenos_Eastern_Tower, 0, true, 0, 0}, ------------------------------------------- 128, {cTIME, Temenos_Western_Tower, 15, false, 0, 0}, 129, {cTIME, Temenos_Western_Tower, 15, false, 0, 0}, 139, {cTIME, Temenos_Western_Tower, 15, false, 0, 0}, 140, {cTIME, Temenos_Western_Tower, 15, false, 0, 0}, 141, {cTIME, Temenos_Western_Tower, 15, false, 0, 0}, 151, {cTIME, Temenos_Western_Tower, 15, false, 0, 0}, 152, {cTIME, Temenos_Northern_Tower, 15, true, 0, 0}, -- F1 153, {cTIME, Temenos_Northern_Tower, 15, true, 0, 0}, -- F2 160, {cTIME, Temenos_Northern_Tower, 15, true, 0, 0}, -- F3 161, {cTIME, Temenos_Northern_Tower, 15, true, 0, 0}, -- F4 162, {cTIME, Temenos_Northern_Tower, 15, true, 0, 0}, -- F5 172, {cTIME, Temenos_Northern_Tower, 15, true, 0, 0}, -- F6 173, {cTIME, Temenos_Eastern_Tower, 15, true, 0, 0}, 174, {cTIME, Temenos_Eastern_Tower, 15, true, 0, 0}, 181, {cTIME, Temenos_Eastern_Tower, 15, true, 0, 0}, 182, {cTIME, Temenos_Eastern_Tower, 15, true, 0, 0}, 183, {cTIME, Temenos_Eastern_Tower, 15, true, 0, 0}, 190, {cTIME, Temenos_Eastern_Tower, 15, true, 0, 0}, 197, {cTIME, Central_Temenos_Basement, 5, false, 0, 0}, 199, {cTIME, Central_Temenos_Basement, 5, false, 0, 0}, 200, {cTIME, Central_Temenos_Basement, 5, false, 0, 0}, 201, {cTIME, Central_Temenos_Basement, 5, false, 0, 0}, 202, {cTIME, Central_Temenos_Basement, 5, false, 0, 0}, 203, {cRESTORE, Temenos_Western_Tower, 0, false, 0, 0}, 204, {cRESTORE, Temenos_Western_Tower, 0, false, 0, 0}, 205, {cRESTORE, Temenos_Western_Tower, 0, false, 0, 0}, 206, {cRESTORE, Temenos_Western_Tower, 0, false, 0, 0}, 207, {cRESTORE, Temenos_Western_Tower, 0, false, 0, 0}, 208, {cRESTORE, Temenos_Western_Tower, 0, false, 0, 0}, 209, {cRESTORE, Temenos_Northern_Tower, 0, true, 0, 0}, -- F1 210, {cRESTORE, Temenos_Northern_Tower, 0, true, 0, 0}, -- F2 211, {cRESTORE, Temenos_Northern_Tower, 0, true, 0, 0}, -- F3 212, {cRESTORE, Temenos_Northern_Tower, 0, true, 0, 0}, -- F4 213, {cRESTORE, Temenos_Northern_Tower, 0, true, 0, 0}, -- F5 214, {cRESTORE, Temenos_Northern_Tower, 0, true, 0, 0}, -- F6 215, {cRESTORE, Temenos_Eastern_Tower, 0, true, 0, 0}, 216, {cRESTORE, Temenos_Eastern_Tower, 0, true, 0, 0}, 217, {cRESTORE, Temenos_Eastern_Tower, 0, true, 0, 0}, 236, {cRESTORE, Temenos_Eastern_Tower, 0, true, 0, 0}, 261, {cRESTORE, Temenos_Eastern_Tower, 0, true, 0, 0}, 277, {cRESTORE, Temenos_Eastern_Tower, 0, true, 0, 0}, 284, {cMIMIC, Temenos_Eastern_Tower, 0, true, 0, 0}, 321, {cMIMIC, Temenos_Eastern_Tower, 0, true, 0, 0}, 348, {cMIMIC, Temenos_Eastern_Tower, 0, true, 0, 0}, 360, {cMIMIC, Temenos_Eastern_Tower, 0, true, 0, 0}, 393, {cMIMIC, Temenos_Eastern_Tower, 0, true, 0, 0} } function LimbusEntrance(player, entrance) switch (entrance): caseof { [1] = function (x) player:setPos(643, 0.1, -600, 124, 0x26) -- instance entrer 600 1 -600 end, -- sortiezone 637, -4, -642, 642, 4, -637 [2] = function (x) player:setPos(-668, 0.1, -666, 209, 0x26) -- instance entrer -599 0 -600 end, -- sortiezone -642, -4, -642, -637, 4, -637 } end function ResetPlayerLimbusVariable(player) player:setVar("characterLimbusKey", 0) player:setVar("LimbusID", 0) end function GenerateLimbusKey() local Key = math.random(1, 1000000) while (IsKeyExist(Key) == true) do Key = math.random(1, 1000000) end return Key end function HideArmouryCrates(Region, Zone) if (Zone == APPOLLYON_SE_NE or Zone == APPOLLYON_NW_SW) then for X = 1, #ARMOURY_CRATES_LIST_APPOLLYON, 2 do if (ARMOURY_CRATES_LIST_APPOLLYON[X+1][2] == Region) then GetNPCByID((ARMOURY_CRATES_LIST_APPOLLYON[X])+16932864):setStatus(STATUS_DISAPPEAR) end end elseif (Zone == TEMENOS) then for X = 1, #ARMOURY_CRATES_LIST_TEMENOS, 2 do if (ARMOURY_CRATES_LIST_TEMENOS[X+1][2] == Region) then GetNPCByID((ARMOURY_CRATES_LIST_TEMENOS[X])+16928768):setStatus(STATUS_DISAPPEAR) end end end end function HideTemenosDoor(Region) if (Region == Temenos_Northern_Tower) then GetNPCByID((450)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((451)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((452)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((453)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((454)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((455)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((456)+16928770):setStatus(STATUS_DISAPPEAR) elseif (Region == Temenos_Eastern_Tower) then GetNPCByID((457)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((458)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((459)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((460)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((461)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((462)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((463)+16928770):setStatus(STATUS_DISAPPEAR) elseif (Region == Temenos_Western_Tower) then GetNPCByID((464)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((465)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((466)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((467)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((468)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((469)+16928770):setStatus(STATUS_DISAPPEAR) GetNPCByID((470)+16928770):setStatus(STATUS_DISAPPEAR) elseif (Region == Central_Temenos_1st_Floor) then GetNPCByID((471)+16928770):setStatus(STATUS_DISAPPEAR) elseif (Region == Central_Temenos_2nd_Floor) then GetNPCByID((472)+16928770):setStatus(STATUS_DISAPPEAR) elseif (Region == Central_Temenos_3rd_Floor) then GetNPCByID((473)+16928770):setStatus(STATUS_DISAPPEAR) elseif (Region == Central_Temenos_4th_Floor) then GetNPCByID((474)+16928770):setStatus(STATUS_DISAPPEAR) elseif (Region == Central_Temenos_Basement) then GetNPCByID((475)+16928770):setStatus(STATUS_DISAPPEAR) end end function IselementalDayAreDead() local day = GetServerVariable("[SW_Apollyon]ElementalTrigger") - 1 local daykill=false if (day == 0) then -- fire if (IsMobDead(16932913) == true and IsMobDead(16932921) == true and IsMobDead(16932929) == true) then daykill = true end elseif (day == 1) then -- earth if (IsMobDead(16932912) == true and IsMobDead(16932920) == true and IsMobDead(16932928) == true) then daykill = true end elseif (day == 2) then -- water if (IsMobDead(16932916) == true and IsMobDead(16932924) == true and IsMobDead(16932932) == true) then daykill = true end elseif (day == 3) then -- wind if (IsMobDead(16932910) == true and IsMobDead(16932918) == true and IsMobDead(16932926) == true) then daykill = true end elseif (day == 4) then -- ice if (IsMobDead(16932914) == true and IsMobDead(16932922) == true and IsMobDead(16932930) == true) then daykill = true end elseif (day == 5) then -- lightning if (IsMobDead(16932917) == true and IsMobDead(16932925) == true and IsMobDead(16932933) == true) then daykill = true end elseif (day == 6) then -- ligth if (IsMobDead(16932931) == true and IsMobDead(16932915) == true and IsMobDead(16932923) == true) then daykill = true end elseif (day == 7) then -- dark if (IsMobDead(16932911) == true and IsMobDead(16932919) == true and IsMobDead(16932927) == true) then daykill = true end end return daykill end -------------------------------------------------- -- alreadyReceived -- I use this function for TE and Boss Trigger -------------------------------------------------- function alreadyReceived(player, number, region) local LimbusVar = 0 local bit = {} local pZone = player:getZoneID() if (pZone == 37) then -- WHY? Why is there even HERE? elseif (pZone == 38) then LimbusVar = GetServerVariable("[CS_Apollyon]Already_Received") end for i = 12, 0, -1 do local twop = 2^i if (LimbusVar >= twop) then bit[i+1] = 1 LimbusVar = LimbusVar - twop else bit[i+1] = 0 end end -- printf("received %u", bit[number]) if (bit[number] == 0) then return false else return true end end function addLimbusList(player, number, Region) local pZone = player:getZoneID() if (pZone == 37) then -- The hell? elseif (pZone == 38) then SetServerVariable("[CS_Apollyon]Already_Received", GetServerVariable("[CS_Apollyon]Already_Received") + number) end end function IsKeyExist(Key) -- return true if Key already exist for another linbus local H = false local KeyAlreadyExist = { GetServerVariable("[NW_Apollyon]UniqueID"), GetServerVariable("[SW_Apollyon]UniqueID"), GetServerVariable("[NE_Apollyon]UniqueID"), GetServerVariable("[SE_Apollyon]UniqueID"), GetServerVariable("[CS_Apollyon]UniqueID"), GetServerVariable("[CS_Apollyon_II]UniqueID"), GetServerVariable("[Central_Apollyon]UniqueID"), GetServerVariable("[Central_Apollyon_II]UniqueID"), GetServerVariable("[Temenos_W_Tower]UniqueID"), GetServerVariable("[Temenos_N_Tower"), GetServerVariable("[Temenos_E_Tower]UniqueID"), GetServerVariable("[C_Temenos_Base]UniqueID"), GetServerVariable("[C_Temenos_Base_II]UniqueID"), GetServerVariable("[C_Temenos_1st]UniqueID"), GetServerVariable("[C_Temenos_2nd]UniqueID"), GetServerVariable("[C_Temenos_3rd]UniqueID"), GetServerVariable("[C_Temenos_4th]UniqueID"), GetServerVariable("[C_Temenos_4th_II]UniqueID"), } for nl = 1, #KeyAlreadyExist, 1 do if (KeyAlreadyExist[nl] == Key) then H = true break end end return H end function GetLimbusKeyFromInstance(instanceID) local Instancekey = 0 switch (instanceID): caseof { [1290] = function (x) Instancekey = GetServerVariable("[NW_Apollyon]UniqueID") end, [1291] = function (x) Instancekey = GetServerVariable("[SW_Apollyon]UniqueID") end, [1292] = function (x) Instancekey = GetServerVariable("[NE_Apollyon]UniqueID") end, [1293] = function (x) Instancekey = GetServerVariable("[SE_Apollyon]UniqueID") end, [1294] = function (x) Instancekey = GetServerVariable("[CS_Apollyon]UniqueID") end, [1295] = function (x) Instancekey = GetServerVariable("[CS_Apollyon_II]UniqueID") end, [1296] = function (x) Instancekey = GetServerVariable("[Central_Apollyon]UniqueID") end, [1297] = function (x) Instancekey = GetServerVariable("[Central_Apollyon_II]UniqueID") end, [1298] = function (x) Instancekey = GetServerVariable("[Temenos_W_Tower]UniqueID") end, [1299] = function (x) Instancekey = GetServerVariable("[Temenos_N_Tower") end, [1300] = function (x) Instancekey = GetServerVariable("[Temenos_E_Tower]UniqueID") end, [1301] = function (x) Instancekey = GetServerVariable("[C_Temenos_Base]UniqueID") end, [1302] = function (x) Instancekey = GetServerVariable("[C_Temenos_Base_II]UniqueID") end, [1303] = function (x) Instancekey = GetServerVariable("[C_Temenos_1st]UniqueID") end, [1304] = function (x) Instancekey = GetServerVariable("[C_Temenos_2nd]UniqueID") end, [1305] = function (x) Instancekey = GetServerVariable("[C_Temenos_3rd]UniqueID") end, [1306] = function (x) Instancekey = GetServerVariable("[C_Temenos_4th]UniqueID") end, [1307] = function (x) Instancekey = GetServerVariable("[C_Temenos_4th_II]UniqueID") end, } -- print("Server__instanceID "..instanceID.." Serverkey "..Instancekey) return Instancekey end function IsMobDead(mobID) local ActionValue = GetMobAction(mobID) -- Todo: replace this if (ActionValue == 0 or ActionValue == 21 or ActionValue == 22 or ActionValue == 23) then return true else return false end end function despawnLimbusCS() for n = 16933130, 16933136, 1 do if (IsMobDead(n) == false) then DespawnMob(n) end end for n = 16933138, 16933143, 1 do if (IsMobDead(n) == false) then DespawnMob(n) end end for n = 16933145, 16933152, 1 do if (IsMobDead(n) == false) then DespawnMob(n) end end end function SpawnCofferSWfloor3() -- print("spawn_coffer") GetNPCByID(16932864+210):setPos(MIMICPOSITION[2][1], MIMICPOSITION[2][2], MIMICPOSITION[2][3]) GetNPCByID(16932864+210):setStatus(STATUS_NORMAL) GetNPCByID(16932864+211):setPos(MIMICPOSITION[4][1], MIMICPOSITION[4][2], MIMICPOSITION[4][3]) GetNPCByID(16932864+211):setStatus(STATUS_NORMAL) GetNPCByID(16932864+212):setPos(MIMICPOSITION[6][1], MIMICPOSITION[6][2], MIMICPOSITION[6][3]) GetNPCByID(16932864+212):setStatus(STATUS_NORMAL) GetNPCByID(16932864+213):setPos(MIMICPOSITION[8][1], MIMICPOSITION[8][2], MIMICPOSITION[8][3]) GetNPCByID(16932864+213):setStatus(STATUS_NORMAL) GetNPCByID(16932864+214):setPos(MIMICPOSITION[10][1], MIMICPOSITION[10][2], MIMICPOSITION[10][3]) GetNPCByID(16932864+214):setStatus(STATUS_NORMAL) GetNPCByID(16932864+215):setPos(MIMICPOSITION[12][1], MIMICPOSITION[12][2], MIMICPOSITION[12][3]) GetNPCByID(16932864+215):setStatus(STATUS_NORMAL) GetNPCByID(16932864+216):setPos(MIMICPOSITION[14][1], MIMICPOSITION[14][2], MIMICPOSITION[14][3]) GetNPCByID(16932864+216):setStatus(STATUS_NORMAL) SetServerVariable("[SW_Apollyon]MimicTrigger", 1) end function SpawnCofferTemenosCFloor4() -- print("spawn_coffer") GetNPCByID(16928768+80):setPos(-560, -6, -459) GetNPCByID(16928768+80):setStatus(STATUS_NORMAL) GetNPCByID(16928768+86):setPos(-540, -6, -459) GetNPCByID(16928768+86):setStatus(STATUS_NORMAL) GetNPCByID(16928768+87):setPos(-576, -6, -459) GetNPCByID(16928768+87):setStatus(STATUS_NORMAL) GetNPCByID(16928768+88):setPos(-528, -6, -459) GetNPCByID(16928768+88):setStatus(STATUS_NORMAL) GetNPCByID(16928768+89):setPos(-592, -6, -487) GetNPCByID(16928768+89):setStatus(STATUS_NORMAL) GetNPCByID(16928768+95):setPos(-566, -6, -486) GetNPCByID(16928768+95):setStatus(STATUS_NORMAL) GetNPCByID(16928768+96):setPos(-566, -6, -513) GetNPCByID(16928768+96):setStatus(STATUS_NORMAL) GetNPCByID(16928768+97):setPos(-592, -6, -513) GetNPCByID(16928768+97):setStatus(STATUS_NORMAL) GetNPCByID(16928768+98):setPos(-531, -0.5, -501) GetNPCByID(16928768+98):setStatus(STATUS_NORMAL) GetNPCByID(16928768+104):setPos(-527, -6, -512) GetNPCByID(16928768+104):setStatus(STATUS_NORMAL) GetNPCByID(16928768+105):setPos(-552, -6, -512) GetNPCByID(16928768+105):setStatus(STATUS_NORMAL) GetNPCByID(16928768+106):setPos(-552, -6, -488) GetNPCByID(16928768+106):setStatus(STATUS_NORMAL) GetNPCByID(16928768+107):setPos(-488, 2, -510) GetNPCByID(16928768+107):setStatus(STATUS_NORMAL) GetNPCByID(16928768+113):setPos(-486, 2, -491) GetNPCByID(16928768+113):setStatus(STATUS_NORMAL) GetNPCByID(16928768+114):setPos(-508, 2, -513) GetNPCByID(16928768+114):setStatus(STATUS_NORMAL) GetNPCByID(16928768+115):setPos(-488, 2, -408) GetNPCByID(16928768+115):setStatus(STATUS_NORMAL) GetNPCByID(16928768+116):setPos(-485, 2, -423) GetNPCByID(16928768+116):setStatus(STATUS_NORMAL) GetNPCByID(16928768+122):setPos(-506, 2, -406) GetNPCByID(16928768+122):setStatus(STATUS_NORMAL) end function Randomcoffer(Floor, region) local cofferID = 0 local cofferType = 0 local spawnchance=math.random(0, 100) if (spawnchance < 31) then if (spawnchance < 15) then cofferType=cITEM elseif (spawnchance < 25) then cofferType=cRESTORE elseif (spawnchance < 30) then cofferType=cTIME end else -- print("nothing_spawn") end if (region == Temenos_Western_Tower and cofferType == cITEM) then switch (Floor): caseof { [1] = function (x) cofferID = 1 end, [2] = function (x) cofferID = 2 end, [3] = function (x) cofferID = 3 end, [4] = function (x) cofferID = 10 end, [5] = function (x) cofferID = 11 end, [6] = function (x) cofferID = 12 end, } elseif (region == Temenos_Western_Tower and cofferType == cRESTORE) then switch (Floor): caseof { [1] = function (x) cofferID = 203 end, [2] = function (x) cofferID = 204 end, [3] = function (x) cofferID = 205 end, [4] = function (x) cofferID = 206 end, [5] = function (x) cofferID = 207 end, [6] = function (x) cofferID = 208 end, } elseif (region == Temenos_Western_Tower and cofferType == cTIME) then switch (Floor): caseof { [1] = function (x) cofferID = 128 end, [2] = function (x) cofferID = 129 end, [3] = function (x) cofferID = 139 end, [4] = function (x) cofferID = 140 end, [5] = function (x) cofferID = 141 end, [6] = function (x) cofferID = 151 end, } end -- print("cofferID" ..cofferID) return cofferID end function ResetKeyForEmptyLimbus(player, instanceID) local instancestatus = player:isSpecialBattlefieldEmpty(GetInstanceRegion(instanceID)) -- print("instancestatus"..instancestatus) if (instancestatus == 0) then switch (instanceID): caseof { [1290] = function (x) SetServerVariable("[NW_Apollyon]UniqueID", 0) print("[NW_Apollyon]KeyDelete") end, [1291] = function (x) SetServerVariable("[SW_Apollyon]UniqueID", 0) print("[SW_Apollyon]KeyDelete") end, [1292] = function (x) SetServerVariable("[NE_Apollyon]UniqueID", 0) print("[NE_Apollyon]KeyDelete") end, [1293] = function (x) SetServerVariable("[SE_Apollyon]UniqueID", 0) print("[SE_Apollyon]KeyDelete") end, [1294] = function (x) SetServerVariable("[CS_Apollyon]UniqueID", 0) print("[CS_Apollyon]KeyDelete") end, [1295] = function (x) SetServerVariable("[CS_Apollyon_II]UniqueID", 0) print("[CS_Apollyon_II]KeyDelete") end, [1296] = function (x) SetServerVariable("[Central_Apollyon]UniqueID", 0) print("[Central_Apollyon]KeyDelete") end, [1297] = function (x) SetServerVariable("[Central_Apollyon_II]UniqueID", 0) print("[Central_Apollyon_II]KeyDelete") end, [1298] = function (x) SetServerVariable("[Temenos_W_Tower]UniqueID", 0) print("[Temenos_W_Tower]KeyDelete") end, [1299] = function (x) SetServerVariable("[Temenos_N_Tower]UniqueID", 0) print("[Temenos_N_Tower]KeyDelete") end, [1300] = function (x) SetServerVariable("[Temenos_E_Tower]UniqueID", 0) print("[Temenos_E_Tower]KeyDelete") end, [1301] = function (x) SetServerVariable("[C_Temenos_Base]UniqueID", 0) print("[C_Temenos_Base]KeyDelete") end, [1302] = function (x) SetServerVariable("[C_Temenos_Base_II]UniqueID", 0) print("[C_Temenos_Base_II]KeyDelete") end, [1303] = function (x) SetServerVariable("[C_Temenos_1st]UniqueID", 0) print("[C_Temenos_1st]KeyDelete") end, [1304] = function (x) SetServerVariable("[C_Temenos_2nd]UniqueID", 0) print("[C_Temenos_2nd]KeyDelete") end, [1305] = function (x) SetServerVariable("[C_Temenos_3rd]UniqueID", 0) print("[C_Temenos_3rd]KeyDelete") end, [1306] = function (x) SetServerVariable("[C_Temenos_4th]UniqueID", 0) print("[C_Temenos_4th]KeyDelete") end, [1307] = function (x) SetServerVariable("[C_Temenos_4th_II]UniqueID", 0) print("[C_Temenos_4th_II]KeyDelete") end, } end end function GetInstanceRegion(instanceID) local region = 0 for K = 1, #APPOLLYON_SE_NE_BCNM_LIST, 2 do if (APPOLLYON_SE_NE_BCNM_LIST[K] == instanceID) then region =APPOLLYON_SE_NE_BCNM_LIST[K+1][5] end end for L = 1, #APPOLLYON_NW_SW_BCNM_LIST, 2 do if (APPOLLYON_NW_SW_BCNM_LIST[L] == instanceID) then region =APPOLLYON_NW_SW_BCNM_LIST[L+1][5] end end for M = 1, #TEMENOS_LIST, 2 do if (TEMENOS_LIST[M] == instanceID) then region = TEMENOS_LIST[M+1][5] end end return region end function RegisterLimbusInstance(player, instanceID) local playerLimbusKeyID = player:getVar("characterLimbusKey") local playerLimbusID = player:getVar("LimbusID") local inst = 0 ResetKeyForEmptyLimbus(player, instanceID) -- instancekey will be reset if this instance is empty if (playerLimbusID == 0) then playerLimbusID = instanceID end -- print("Player_:_instanceID_"..playerLimbusID.." Playerkey "..playerLimbusKeyID) if (playerLimbusID ~= 0) then if (GetLimbusKeyFromInstance(playerLimbusID) == 0 and playerLimbusKeyID == 0) then inst = player:bcnmRegister(playerLimbusID) -- Build Limbus printf("Regionfound: %u", inst) if (inst == GetInstanceRegion(playerLimbusID)) then player:bcnmEnter(playerLimbusID) printf("BCNM_CREATE_WITH_REGION: %u", inst) else if (playerLimbusID == 1290 or playerLimbusID == 1291 or playerLimbusID == 1294 or playerLimbusID == 1295 or playerLimbusID == 1296 or playerLimbusID == 1297) then player:setPos(-668, 0.1, -666) else player:setPos(643, 0.1, -600) end player:messageSpecial(7006) ResetPlayerLimbusVariable(player) print("BCNM_cant_be _created") end end end end function TryTobackOnCurrentLimbus(player) local currentlimbus = 0 local playerLimbusID = player:getVar("LimbusID") local playerLimbusKeyID = player:getVar("characterLimbusKey") -- print("Player_:_instanceID_"..playerLimbusID.." Playerkey "..playerLimbusKeyID) if (GetLimbusKeyFromInstance(playerLimbusID) == playerLimbusKeyID and player:isSpecialBattlefieldEmpty(GetInstanceRegion(playerLimbusID)) == 1) then -- player deco and back currentlimbus = playerLimbusID print("trying_to_add_player_on_the_current_bcnm") local registration = player:addPlayerToSpecialBattlefield(playerLimbusID) if (registration ~= 1) then currentlimbus = 0 end else currentlimbus = 0 end return currentlimbus end
gpl-3.0
Joker-Developer/jokersuper
plugins/anti-spam.lua
4
5321
--[[ # For More Information ....! # Developer : Aziz < @devss_bot > #Dev # our channel: @help_tele ]] kicktable = {} do local TIME_CHECK = 2 -- seconds -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then return msg end if msg.from.id == our_id then return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Save stats on Redis if msg.to.type == 'channel' then -- User is on channel local hash = 'channel:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end if msg.to.type == 'user' then -- User is on chat local hash = 'PM:'..msg.from.id redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) --Load moderation data local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then --Check if flood is on or off if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then return msg end end -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) local data = load_data(_config.moderation.data) local NUM_MSG_MAX = 5 if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])--Obtain group flood sensitivity end end local max_msg = NUM_MSG_MAX * 1 if msgs > max_msg then local user = msg.from.id local chat = msg.to.id local whitelist = "whitelist" local is_whitelisted = redis:sismember(whitelist, user) -- Ignore mods,owner and admins if is_momod(msg) then return msg end if is_whitelisted == true then return msg end local receiver = get_receiver(msg) if msg.to.type == 'user' then local max_msg = 7 * 1 print(msgs) if msgs >= max_msg then print("Pass2") send_large_msg("user#id"..msg.from.id, "User ["..msg.from.id.."] blocked for spam.") savelog(msg.from.id.." PM", "User ["..msg.from.id.."] blocked for spam.") block_user("user#id"..msg.from.id,ok_cb,false)--Block user if spammed in private end end if kicktable[user] == true then return end delete_msg(msg.id, ok_cb, false) kick_user(user, chat) local username = msg.from.username local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", "") if msg.to.type == 'chat' or msg.to.type == 'channel' then if username then savelog(msg.to.id, name_log.." @"..username.." ["..msg.from.id.."] kicked for #spam") send_large_msg(receiver , "Flooding is not allowed here\n@"..username.."["..msg.from.id.."]\nStatus: User kicked") else savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked for #spam") send_large_msg(receiver , "Flooding is not allowed here\nName:"..name_log.."["..msg.from.id.."]\nStatus: User kicked") end end -- incr it on redis local gbanspam = 'gban:spam'..msg.from.id redis:incr(gbanspam) local gbanspam = 'gban:spam'..msg.from.id local gbanspamonredis = redis:get(gbanspam) --Check if user has spammed is group more than 4 times if gbanspamonredis then if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then --Global ban that user banall_user(msg.from.id) local gbanspam = 'gban:spam'..msg.from.id --reset the counter redis:set(gbanspam, 0) if msg.from.username ~= nil then username = msg.from.username else username = "---" end local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") --Send this to that chat send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)") send_large_msg("channel#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)") local GBan_log = 'GBan_log' local GBan_log = data[tostring(GBan_log)] for k,v in pairs(GBan_log) do log_SuperGroup = v gban_text = "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)" --send it to log group/channel send_large_msg(log_SuperGroup, gban_text) end end end kicktable[user] = true msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function cron() --clear that table on the top of the plugins kicktable = {} end return { patterns = {}, cron = cron, pre_process = pre_process } end
gpl-2.0
Scavenge/darkstar
scripts/zones/Bhaflau_Thickets/npcs/Daswil.lua
6
2734
----------------------------------- -- Area: Bhaflau Thickets -- NPC: Daswil -- Type: Assault -- @pos -208.720 -12.889 -779.713 52 ----------------------------------- package.loaded["scripts/zones/Bhaflau_Thickets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/Bhaflau_Thickets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local toauMission = player:getCurrentMission(TOAU); local beginnings = player:getQuestStatus(AHT_URHGAN,BEGINNINGS); -- IMMORTAL SENTRIES if (toauMission == IMMORTAL_SENTRIES) then if (player:hasKeyItem(SUPPLIES_PACKAGE)) then player:startEvent(5); elseif (player:getVar("AhtUrganStatus") == 1) then player:startEvent(6); end; -- BEGINNINGS elseif (beginnings == QUEST_ACCEPTED) then if (not player:hasKeyItem(BRAND_OF_THE_SKYSERPENT)) then player:startEvent(8); -- brands you else player:startEvent(9); -- mortals were meant to seek power end; -- ASSAULT elseif (toauMission >= PRESIDENT_SALAHEEM) then local IPpoint = player:getCurrency("imperial_standing"); if (player:hasKeyItem(MAMOOL_JA_ASSAULT_ORDERS) and player:hasKeyItem(ASSAULT_ARMBAND) == false) then player:startEvent(512,50,IPpoint); else player:startEvent(7); -- player:delKeyItem(ASSAULT_ARMBAND); end; -- DEFAULT DIALOG else player:startEvent(4); end; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- IMMORTAL SENTRIES if (csid == 5 and option == 1) then player:delKeyItem(SUPPLIES_PACKAGE); player:setVar("AhtUrganStatus",1); -- BEGINNINGS elseif (csid == 8) then player:addKeyItem(BRAND_OF_THE_SKYSERPENT); player:messageSpecial(KEYITEM_OBTAINED,BRAND_OF_THE_SKYSERPENT); -- ASSAULT elseif (csid == 512 and option == 1) then player:delCurrency("imperial_standing", 50); player:addKeyItem(ASSAULT_ARMBAND); player:messageSpecial(KEYITEM_OBTAINED,ASSAULT_ARMBAND); end; end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Bastok_Mines/npcs/Trail_Markings.lua
7
3061
----------------------------------- -- Area: Bastok Mines -- NPC: Trail Markings -- Dynamis-Bastok Enter -- @pos 99 1 -67 234 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/dynamis"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if bit.band(player:getVar("Dynamis_Status"),1) == 1 then player:startEvent(0x00CB); -- cs with Cornelia elseif (player:getVar("DynaBastok_Win") == 1) then player:startEvent(0x00d7,HYDRA_CORPS_EYEGLASS); -- Win CS elseif (player:hasKeyItem(VIAL_OF_SHROUDED_SAND)) then local firstDyna = 0; local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); local dynaUniqueID = GetServerVariable("[DynaBastok]UniqueID"); if (checkFirstDyna(player,2)) then -- First Dyna-Bastok => CS firstDyna = 1; end if (player:getMainLvl() < DYNA_LEVEL_MIN) then player:messageSpecial(PLAYERS_HAVE_NOT_REACHED_LEVEL,DYNA_LEVEL_MIN); elseif ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or (player:getVar("DynamisID") == dynaUniqueID and dynaUniqueID > 0)) then player:startEvent(0x00c9,2,firstDyna,0,BETWEEN_2DYNA_WAIT_TIME,64,VIAL_OF_SHROUDED_SAND,4236,4237); else dayRemaining = math.floor(((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) - realDay)/3456); player:messageSpecial(YOU_CANNOT_ENTER_DYNAMIS,dayRemaining,2); end else player:messageSpecial(UNUSUAL_ARRANGEMENT_PEBBLES); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("updateRESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("finishRESULT: %u",option); if (csid == 0x00CB) then player:addKeyItem(VIAL_OF_SHROUDED_SAND); player:messageSpecial(KEYITEM_OBTAINED,VIAL_OF_SHROUDED_SAND); player:setVar("Dynamis_Status",bit.band(player:getVar("Dynamis_Status"),bit.bnot(1))); elseif (csid == 0x00d7) then player:setVar("DynaBastok_Win",0); elseif (csid == 0x00c9 and option == 0) then if (checkFirstDyna(player,2)) then player:setVar("Dynamis_Status",bit.bor(player:getVar("Dynamis_Status"),4)); end player:setVar("enteringDynamis",1); player:setPos(116.482,0.994,-72.121,128,0xba); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Port_Bastok/npcs/Ilita.lua
14
1224
----------------------------------- -- Area: Port Bastok -- NPC: Ilita -- Linkshell merchant -- @pos -142 -1 -25 236 -- Confirmed shop stock, August 2013 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:showText(npc,ILITA_SHOP_DIALOG,513); stock = { 0x0200, 8000, --Linkshell 0x3F9D, 375 --Pendant Compass } 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
Zero-K-Experiments/Zero-K-Experiments
units/tacnuke.lua
3
3979
unitDef = { unitname = [[tacnuke]], name = [[Eos]], description = [[Tactical Nuke]], buildCostEnergy = 600, buildCostMetal = 600, builder = false, buildingGroundDecalDecaySpeed = 30, buildingGroundDecalSizeX = 3, buildingGroundDecalSizeY = 3, buildingGroundDecalType = [[tacnuke_aoplane.dds]], buildPic = [[tacnuke.png]], buildTime = 600, canAttack = true, category = [[SINK UNARMED]], collisionVolumeOffsets = [[0 25 0]], collisionVolumeScales = [[20 60 20]], collisionVolumeType = [[CylY]], customParams = { description_fr = [[Lance Missile Nucléaire Tactique]], description_de = [[Taktische Rakete]], helptext = [[A long-range precision strike weapon. The Eos' blast radius is small, but lethal.]], helptext_fr = [[Le Eos est un lance missile nucléaire tactique. Les tetes nucléaires ne sont pas aussi lourdes que celles du Silencer et la portée moindre. Mais bien placé, il peut faire des ravages, et présente un rapport cout/efficacité plus qu'interressant.]], helptext_de = [[Eine weitreichende, präzise Waffe. Die Druckwelle ist zwar klein, aber tödlich.]], mobilebuilding = [[1]], }, explodeAs = [[WEAPON]], footprintX = 1, footprintZ = 1, iconType = [[cruisemissilesmall]], idleAutoHeal = 5, idleTime = 1800, maxDamage = 1000, maxSlope = 18, minCloakDistance = 150, objectName = [[wep_tacnuke.s3o]], script = [[cruisemissile.lua]], seismicSignature = 4, selfDestructAs = [[WEAPON]], sfxtypes = { explosiongenerators = { [[custom:RAIDMUZZLE]], }, }, sightDistance = 0, useBuildingGroundDecal = false, yardMap = [[o]], weapons = { { def = [[WEAPON]], badTargetCategory = [[SWIM LAND SHIP HOVER]], onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP]], }, }, weaponDefs = { WEAPON = { name = [[Tactical Nuke]], areaOfEffect = 192, avoidFriendly = false, cegTag = [[tactrail]], collideFriendly = false, craterBoost = 4, craterMult = 3.5, customParams = { lups_explodelife = 1.5, stats_hide_dps = 1, -- meaningless stats_hide_reload = 1, light_color = [[1.35 0.8 0.36]], light_radius = 400, }, damage = { default = 3502.5, subs = 175, }, edgeEffectiveness = 0.4, explosionGenerator = [[custom:NUKE_150]], fireStarter = 0, flightTime = 20, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, model = [[wep_tacnuke.s3o]], range = 3500, reloadtime = 10, smokeTrail = false, soundHit = [[explosion/mini_nuke]], soundStart = [[weapon/missile/tacnuke_launch]], tolerance = 4000, turnrate = 18000, weaponAcceleration = 180, weaponTimer = 3, weaponType = [[StarburstLauncher]], weaponVelocity = 1200, }, }, featureDefs = { }, } return lowerkeys({ tacnuke = unitDef })
gpl-2.0
Scavenge/darkstar
scripts/zones/Cape_Teriggan/mobs/Greater_Manticore.lua
14
1046
----------------------------------- -- Area: Cape Teriggan -- MOB: Greater Manticore -- Note: Place Holder for Frostmane ----------------------------------- require("scripts/zones/Cape_Teriggan/MobIDs"); require("scripts/globals/fieldsofvalor"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) checkRegime(player,mob,108,2); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local mobID = mob:getID(); if (Frostmane_PH[mobID] ~= nil) then local ToD = GetServerVariable("[POP]Frostmane"); if (ToD <= os.time(t) and GetMobAction(Frostmane) == 0) then if (math.random(1,20) == 5) then UpdateNMSpawnPoint(Frostmane); GetMobByID(Frostmane):setRespawnTime(GetMobRespawnTime(mobID)); SetServerVariable("[PH]Frostmane", mobID); DeterMob(mobID, true); end end end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Mount_Zhayolm/npcs/Mining_Point.lua
17
1080
----------------------------------- -- Area: Mount Zhayolm -- NPC: Mining Point ----------------------------------- package.loaded["scripts/zones/Mount_Zhayolm/TextIDs"] = nil; ------------------------------------- require("scripts/globals/mining"); require("scripts/zones/Mount_Zhayolm/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startMining(player,player:getZoneID(),npc,trade,0x0099); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(MINING_IS_POSSIBLE_HERE,605); 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
Kyklas/luci-proto-hso
contrib/luadoc/lua/luadoc/lp.lua
175
4389
---------------------------------------------------------------------------- -- Lua Pages Template Preprocessor. -- -- @release $Id: lp.lua,v 1.7 2007/04/18 14:28:39 tomas Exp $ ---------------------------------------------------------------------------- local assert, error, getfenv, loadstring, setfenv = assert, error, getfenv, loadstring, setfenv local find, format, gsub, strsub = string.find, string.format, string.gsub, string.sub local concat, tinsert = table.concat, table.insert local open = io.open module (...) ---------------------------------------------------------------------------- -- function to do output local outfunc = "io.write" -- accepts the old expression field: `$| <Lua expression> |$' local compatmode = true -- -- Builds a piece of Lua code which outputs the (part of the) given string. -- @param s String. -- @param i Number with the initial position in the string. -- @param f Number with the final position in the string (default == -1). -- @return String with the correspondent Lua code which outputs the part of the string. -- local function out (s, i, f) s = strsub(s, i, f or -1) if s == "" then return s end -- we could use `%q' here, but this way we have better control s = gsub(s, "([\\\n\'])", "\\%1") -- substitute '\r' by '\'+'r' and let `loadstring' reconstruct it s = gsub(s, "\r", "\\r") return format(" %s('%s'); ", outfunc, s) end ---------------------------------------------------------------------------- -- Translate the template to Lua code. -- @param s String to translate. -- @return String with translated code. ---------------------------------------------------------------------------- function translate (s) if compatmode then s = gsub(s, "$|(.-)|%$", "<?lua = %1 ?>") s = gsub(s, "<!%-%-$$(.-)$$%-%->", "<?lua %1 ?>") end s = gsub(s, "<%%(.-)%%>", "<?lua %1 ?>") local res = {} local start = 1 -- start of untranslated part in `s' while true do local ip, fp, target, exp, code = find(s, "<%?(%w*)[ \t]*(=?)(.-)%?>", start) if not ip then break end tinsert(res, out(s, start, ip-1)) if target ~= "" and target ~= "lua" then -- not for Lua; pass whole instruction to the output tinsert(res, out(s, ip, fp)) else if exp == "=" then -- expression? tinsert(res, format(" %s(%s);", outfunc, code)) else -- command tinsert(res, format(" %s ", code)) end end start = fp + 1 end tinsert(res, out(s, start)) return concat(res) end ---------------------------------------------------------------------------- -- Defines the name of the output function. -- @param f String with the name of the function which produces output. function setoutfunc (f) outfunc = f end ---------------------------------------------------------------------------- -- Turns on or off the compatibility with old CGILua 3.X behavior. -- @param c Boolean indicating if the compatibility mode should be used. function setcompatmode (c) compatmode = c end ---------------------------------------------------------------------------- -- Internal compilation cache. local cache = {} ---------------------------------------------------------------------------- -- Translates a template into a Lua function. -- Does NOT execute the resulting function. -- Uses a cache of templates. -- @param string String with the template to be translated. -- @param chunkname String with the name of the chunk, for debugging purposes. -- @return Function with the resulting translation. function compile (string, chunkname) local f, err = cache[string] if f then return f end f, err = loadstring (translate (string), chunkname) if not f then error (err, 3) end cache[string] = f return f end ---------------------------------------------------------------------------- -- Translates and executes a template in a given file. -- The translation creates a Lua function which will be executed in an -- optionally given environment. -- @param filename String with the name of the file containing the template. -- @param env Table with the environment to run the resulting function. function include (filename, env) -- read the whole contents of the file local fh = assert (open (filename)) local src = fh:read("*a") fh:close() -- translates the file into a function local prog = compile (src, '@'..filename) local _env if env then _env = getfenv (prog) setfenv (prog, env) end prog () end
apache-2.0
Scavenge/darkstar
scripts/zones/Buburimu_Peninsula/npcs/Lobho_Ukipturi.lua
14
1789
----------------------------------- -- Area: Buburimu Peninsula -- NPC: Lobho Ukipturi -- @pos -485 -31 50 118 ----------------------------------- package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); require("scripts/zones/Buburimu_Peninsula/TextIDs"); local region = KOLSHUSHU; local csid = 0x7ff4; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local owner = GetRegionOwner(region); local arg1 = getArg1(owner,player); if (owner == player:getNation()) then nation = 1; elseif (arg1 < 1792) then nation = 2; else nation = 0; end player:startEvent(csid,nation,OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP(),0,0,0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then ShowOPVendorShop(player); elseif (option == 2) then if (player:delGil(OP_TeleFee(player,region))) then toHomeNation(player); end elseif (option == 6) then player:delCP(OP_TeleFee(player,region)); toHomeNation(player); end end;
gpl-3.0
ramindel0761/tele_ir
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-3.0
nmacs/lm3s-uclinux
lib/liblua/LuaTwitter-0.9.2/test.lua
1
1662
#!/usr/bin/env lua -- Example usage of the LuaTwitter :) -- loading module local twitter = require("twitter") local APP_KEY = "YourAppConsumerKey" local APP_SECRET = "YourAppConsumerSecret" -- if you already have access token and it's secret - pass them :) -- but if you don't have an access token, then you sholud get it. here is example for obtaining access token local ACCESS_TOKEN = nil local ACCESS_TOKEN_SECRET = nil -- creating client instance me = twitter.Client( ACCESS_TOKEN, ACCESS_TOKEN_SECRET, APP_KEY, APP_SECRET ) print(me:Version()) -- consumer is the OAuth consumer instance local r = me.consumer.getRequestToken() print( string.format("Please visit %s to get the PIN", r.getAuthUrl()) ) print( "Enter the PIN:" ) local PIN = io.stdin:read'*l' local a = me.consumer.getAccessTokenByPin( PIN, r.getToken() ) me:SetAccessToken( a.getToken(), a.getTokenSecret() ) -- verifying given credentials ret = me:VerifyCredentials() if not me:isError(ret) then print(string.format("Hello %s!", ret.screen_name)) end -- comment this line to see result's details if true then return end ret = me:HomeTimeline() print( "Result type: ", type(ret) ) -- printing Twitter result print( "Result: ") if type(ret) == "table" then for k,v in pairs(ret) do if type(v) ~= "table" then print(tostring(k) .. " => " .. tostring(v)) else print(k) for k2,v2 in pairs(v) do if type(v2) ~= "table" then print("\t"..tostring(k2) .. " => " .. tostring(v2)) else print("\t"..k2) for k3,v3 in pairs(v2) do print("\t\t"..tostring(k3) .. " => " .. tostring(v3)) end end end end end else print(ret) end
gpl-2.0
Scavenge/darkstar
scripts/globals/spells/bluemagic/wild_carrot.lua
27
1735
----------------------------------------- -- Spell: Wild Carrot -- Restores HP for the target party member -- Spell cost: 37 MP -- Monster Type: Beasts -- Spell Type: Magical (Light) -- Blue Magic Points: 3 -- Stat Bonus: HP+5 -- Level: 30 -- Casting Time: 2.5 seconds -- Recast Time: 6 seconds -- -- Combos: Resist Sleep ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local minCure = 120; local divisor = 1; local constant = 60; local power = getCurePowerOld(caster); if (power > 299) then divisor = 15.6666; constant = 170.43; elseif (power > 179) then divisor = 2; constant = 105; end local final = getCureFinal(caster,spell,getBaseCureOld(power,divisor,constant),minCure,true); final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then --Applying server mods.... final = final * CURE_POWER; end local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:addHP(final); target:wakeUp(); caster:updateEnmityFromCure(target,final); spell:setMsg(7); return final; end;
gpl-3.0
ShayanHaddadian/Tele-OvEr
plugins/banhammer.lua
1085
11557
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
Scavenge/darkstar
scripts/zones/Beadeaux/npcs/Treasure_Coffer.lua
13
4750
----------------------------------- -- Area: Beadeaux -- NPC: Treasure Coffer -- @zone 147 -- @pos 215 40 69 ----------------------------------- package.loaded["scripts/zones/Beadeaux/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Beadeaux/TextIDs"); local TreasureType = "Coffer"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1043,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1043,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); -- IMPORTANT ITEM: AF Keyitems, AF Items, & Map ----------- local mJob = player:getMainJob(); local AFHandsActivated = player:getVar("BorghertzAlreadyActiveWithJob"); local oldGauntlets = player:hasKeyItem(OLD_GAUNTLETS); local listAF = getAFbyZone(zone); if (AFHandsActivated == 3 and oldGauntlets == false) then questItemNeeded = 1; else for nb = 1,#listAF,3 do local QHANDS = player:getQuestStatus(JEUNO,listAF[nb + 1]); if (QHANDS ~= QUEST_AVAILABLE and mJob == listAF[nb] and player:hasItem(listAF[nb + 2]) == false) then questItemNeeded = 2; break end end end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 1) then player:addKeyItem(OLD_GAUNTLETS); player:messageSpecial(KEYITEM_OBTAINED,OLD_GAUNTLETS); -- Old Gauntlets (KI) elseif (questItemNeeded == 2) then for nb = 1,#listAF,3 do if (mJob == listAF[nb]) then player:addItem(listAF[nb + 2]); player:messageSpecial(ITEM_OBTAINED,listAF[nb + 2]); break end end else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = cofferLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); else player:messageSpecial(CHEST_MIMIC); spawnMimic(zone,npc,player); UpdateTreasureSpawnPoint(npc:getID(), true); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1043); 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
Scavenge/darkstar
scripts/globals/items/piece_of_bubble_chocolate.lua
12
1154
----------------------------------------- -- ID: 4496 -- Item: piece_of_bubble_chocolate -- Food Effect: 30Min, All Races ----------------------------------------- -- Magic Regen While Healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4496); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
omid1212/spam
plugins/greeter.lua
18
4399
--[[ Sends a custom message when a user enters or leave a chat. !welcome group The custom message will send to the group. Recommended way. !welcome pm The custom message will send to private chat newly joins member. Not recommended as a privacy concern and the possibility of user reporting the bot. !welcome disable Disable welcome service. Also, you can just disable greeter plugin. --]] do local function is_banned(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id local banned = redis:get(hash) return banned or false end local function is_super_banned(user_id) local hash = 'superbanned:'..user_id local superbanned = redis:get(hash) return superbanned or false end local function welcome_message(msg, new_member) local data = load_data(_config.moderation.data) local welcome_stat = data[tostring(msg.to.id)]['settings']['welcome'] if data[tostring(msg.to.id)] then local about = '' local rules = '' if data[tostring(msg.to.id)]['description'] then about = data[tostring(msg.to.id)]['description'] about = "\nDescription :\n"..about.."\n" end if data[tostring(msg.to.id)]['rules'] then rules = data[tostring(msg.to.id)]['rules'] rules = "\nRules :\n"..rules.."\n" end local welcomes = "Welcome "..new_member..".\nYou are in group '"..string.gsub(msg.to.print_name, "_", " ").."'\n" if welcome_stat == 'group' then receiver = get_receiver(msg) elseif welcome_stat == 'private' then receiver = 'user#id'..msg.from.id end send_large_msg(receiver, welcomes..about..rules.."\n", ok_cb, false) end end local function run(msg, matches) local data = load_data(_config.moderation.data) local welcome_stat = data[tostring(msg.to.id)]['settings']['welcome'] if matches[1] == 'welcome' then if matches[2] == 'group' then if welcome_stat ~= 'group' then data[tostring(msg.to.id)]['settings']['welcome'] = 'group' save_data(_config.moderation.data, data) end return 'Welcome service already enabled.\nWelcome message will shown in group.' end if matches[2] == 'pm' then if welcome_stat ~= 'private' then data[tostring(msg.to.id)]['settings']['welcome'] = 'private' save_data(_config.moderation.data, data) end return 'Welcome service already enabled.\nWelcome message will send as private message to new member.' end if matches[2] == 'disable' then if welcome_stat == 'no' then return 'Welcome service is not enabled.' else data[tostring(msg.to.id)]['settings']['welcome'] = 'no' save_data(_config.moderation.data, data) return 'Welcome service has been disabled.' end end end if welcome_stat ~= 'no' and msg.action and msg.action.type then -- do not greet (super)banned users or API bots. local action = msg.action.type if action == 'chat_add_user' or action == 'chat_add_user_link' or action == "chat_del_user" then if msg.action.link_issuer then user_id = msg.from.id new_member = (msg.from.first_name or '')..' '..(msg.from.last_name or '') user_flags = msg.flags else user_id = msg.action.user.id new_member = (msg.action.user.first_name or '')..' '..(msg.action.user.last_name or '') user_flags = msg.action.user.flags end local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, msg.to.id) if superbanned or banned then print 'Ignored. User is banned!' return nil end if user_flags == 4352 then print "Ignored. It's an API bot." return nil end end if matches[1] == "chat_add_user" then welcome_message(msg, new_member) elseif matches[1] == "chat_add_user_link" then welcome_message(msg, new_member) elseif matches[1] == "chat_del_user" then return 'Bye '..new_member..'!' end end end return { description = 'Sends a custom message when a user enters or leave a chat.', usage = { moderator = { '!welcome group : Welcome message will shows in group.', '!welcome pm : Welcome message will send to new member via PM.', '!welcome disable : Disable welcome message.' }, }, patterns = { "^!!tgservice (.+)$", "^!(welcome) (.*)$" }, run = run, moderated = true } end
gpl-2.0
Zero-K-Experiments/Zero-K-Experiments
effects/tess.lua
25
7232
-- tess return { ["tess"] = { air = true, count = 10, ground = true, water = true, debris1 = { air = true, class = [[CSimpleParticleSystem]], count = 20, ground = true, water = true, properties = { airdrag = 0.98, colormap = [[0.22 0.18 0.15 1 0.22 0.18 0.15 1 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 90, emitvector = [[0, 1, 0]], gravity = [[0, -0.2, 0]], numparticles = 5, particlelife = [[50 i-0.5]], particlelifespread = 0, particlesize = [[10 r10]], particlesizespread = 0, particlespeed = 3, particlespeedspread = 1, pos = [[0, 0, 0]], sizegrowth = [[-0.1 i0.015]], sizemod = 1.0, texture = [[debris2]], }, }, debris2 = { air = true, class = [[CSimpleParticleSystem]], count = 20, ground = true, water = true, properties = { airdrag = 0.98, colormap = [[0.22 0.18 0.15 1 0.22 0.18 0.15 1 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 20, emitvector = [[0, 1, 0]], gravity = [[0, -0.2, 0]], numparticles = 5, particlelife = 150, particlelifespread = 0, particlesize = [[1 r10]], particlesizespread = 0, particlespeed = 5, particlespeedspread = 8, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[debris2]], }, }, dirt1 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.8, colormap = [[1 0.5 0.3 0.3 0.45 0.37 0.3 1 0.45 0.37 0.3 1 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 25, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 30, particlelife = 18.5, particlelifespread = 5, particlesize = 1.5, particlesizespread = 3, particlespeed = 0, particlespeedspread = 19, pos = [[0, 2, 0]], sizegrowth = 3, sizemod = 1.0, texture = [[dirtplosion2]], }, }, dirt2 = { air = true, class = [[CSimpleParticleSystem]], count = 0, ground = true, water = true, properties = { airdrag = 0.8, colormap = [[1 0.5 0.3 0.3 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 25, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 30, particlelife = 8.5, particlelifespread = 5, particlesize = 1.5, particlesizespread = 3, particlespeed = 0, particlespeedspread = 19, pos = [[0, 2, 0]], sizegrowth = 3, sizemod = 1.0, texture = [[dirtplosion2]], }, }, dirt3 = { air = true, class = [[CSimpleParticleSystem]], count = 10, ground = true, water = true, properties = { airdrag = 0.8, colormap = [[0 0 0 0.01 0.22 0.18 0.15 1 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 25, emitvector = [[0, 1, 0]], gravity = [[0, -0.2, 0]], numparticles = 1, particlelife = 80, particlelifespread = 5, particlesize = 1.5, particlesizespread = 3, particlespeed = 5, particlespeedspread = 24, pos = [[0, 2, 0]], sizegrowth = 1, sizemod = 1.0, texture = [[kfoam]], }, }, fanny = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 60, explosiongenerator = [[custom:FANNY]], pos = [[0, 0, 0]], }, }, glow = { air = true, class = [[CSimpleParticleSystem]], count = 10, ground = true, water = true, properties = { airdrag = 1, colormap = [[0 0 0 0.01 1 1 0.8 0.9 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 180, emitvector = [[-0, 1, 0]], gravity = [[0, 0.00, 0]], numparticles = 1, particlelife = 5, particlelifespread = 0, particlesize = 60, particlesizespread = 10, particlespeed = 1, particlespeedspread = 0, pos = [[0, 2, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[diamondstar]], }, }, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.99, flashsize = 150, ttl = 5, color = { [1] = 1, [2] = 1, [3] = 0.80000001192093, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 0, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 0 0.01 1 0.7 0.5 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 40, particlelife = 30, particlelifespread = 0, particlesize = 2, particlesizespread = 7, particlespeed = 2, particlespeedspread = 16, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, }
gpl-2.0
Scavenge/darkstar
scripts/globals/weaponskills/smash_axe.lua
18
1569
----------------------------------- -- Smash Axe -- Axe weapon skill -- Skill level: 40 -- Stuns enemy. Duration of stun varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Snow Gorget & Aqua Gorget. -- Aligned with the Snow Belt & Aqua Belt. -- Element: None -- Modifiers: STR:100% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; 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.str_wsc = 1.0; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); if (damage > 0) then local duration = (tp/500); if (target:hasStatusEffect(EFFECT_STUN) == false) then target:addStatusEffect(EFFECT_STUN, 1, 0, duration); end end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
PaulBatchelor/Soundpipe
modules/data/nsmp.lua
3
2591
sptbl["nsmp"] = { files = { module = "nsmp.c", header = "nsmp.h", example = "ex_nsmp.c", }, func = { create = "sp_nsmp_create", destroy = "sp_nsmp_destroy", init = "sp_nsmp_init", compute = "sp_nsmp_compute", other = { sp_nsmp_print_index = { description = "Prints the index and their corresponding keyword", args = { } } } }, params = { mandatory = { { name = "ft", type = "sp_ftbl*", description = "ftbl of the audio file. It should be mono.", default = "N/A" }, { name = "sr", type = "int", description = "samplerate.", default = "N/A" }, { name = "init", type = "const char*", description = "ini file.", default = "N/A" } }, optional = { { name = "index", type = "uint32_t", description = "This is an optional parameter. These values are always set to a value by default, and can be set after the init function has been called.", default = 0 }, } }, modtype = "module", description = [[Nanosamp: a tiny sampler built for Soundpipe A nanosamp file is comprised of a mono audio file and an ini file. Nanosamp is geared towards percussive and found sound sample players, and is intended to be combined with soundpipe modules. The ini file contains mappings that correspond to the audio file. Such an entry would look like this: [keyword] pos = 2.3 size = 3 </pre> In this instance, an entry called "keyword" has been made, starting at 2.3 seconds in the audio file, with a length of 3 seconds. An example file oneart.ini has been created in the examples folder. The SoundPipe implementation of nanosamp will automatically index the entries in the order they appear in the INI file and must be selected this way by changing the index parameter. Soundpipe will only select the new entry when the trigger input is a non-zero value. ]], ninputs = 1, noutputs = 1, inputs = { { name = "trigger", description = "Trigger input." }, }, outputs = { { name = "signal out", description = "Signal output." }, } }
mit
Scavenge/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/HomePoint#1.lua
27
1300
----------------------------------- -- Area: Southern_San_dOria_[S] -- NPC: HomePoint#1 -- @pos -85.468 1.000 -66.454 80 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 68); 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
Scavenge/darkstar
scripts/zones/Port_San_dOria/npcs/Perdiouvilet.lua
14
1750
----------------------------------- -- Area: Port San d'Oria -- NPC: Perdiouvilet -- Involved in Quest: Lure of the Wildcat (San d'Oria) -- @pos -59 -5 -29 232 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatSandy = player:getVar("WildcatSandy"); if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,10) == false) then player:startEvent(0x02ee); else player:startEvent(0x02fa); 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 == 0x02ee) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",10,true); end end;
gpl-3.0
mymedia2/GroupButler
plugins/configure.lua
8
3170
local config = require 'config' local u = require 'utilities' local api = require 'methods' local plugin = {} local function cache_chat_title(chat_id, title) print('caching title...') local key = 'chat:'..chat_id..':title' db:set(key, title) db:expire(key, config.bot_settings.cache_time.chat_titles) return title end local function get_chat_title(chat_id) local cached_title = db:get('chat:'..chat_id..':title') if not cached_title then local chat_object = api.getChat(chat_id) if chat_object then return cache_chat_title(chat_id, chat_object.result.title) end else return cached_title end end local function do_keyboard_config(chat_id, user_id, is_admin) local keyboard = { inline_keyboard = { {{text = _("🛠 Menu"), callback_data = 'config:menu:'..chat_id}}, {{text = _("⚡️ Antiflood"), callback_data = 'config:antiflood:'..chat_id}}, {{text = _("🌈 Media"), callback_data = 'config:media:'..chat_id}}, {{text = _("🚫 Antispam"), callback_data = 'config:antispam:'..chat_id}}, {{text = _("📥 Log channel"), callback_data = 'config:logchannel:'..chat_id}} } } local show_mod_button = db:hget('chat:'..chat_id..':modsettings', 'promdem') or config.chat_settings['modsettings']['promdem'] if u.is_owner(chat_id, user_id) or (show_mod_button == 'yes' and is_admin) then table.insert(keyboard.inline_keyboard, {{text = _("👔 Moderators"), callback_data = 'config:mods:'..chat_id}}) end return keyboard end function plugin.onTextMessage(msg, blocks) if msg.chat.type ~= 'private' then if u.is_allowed('config', msg.chat.id, msg.from) then local chat_id = msg.chat.id local keyboard = do_keyboard_config(chat_id, msg.from.id) if not db:get('chat:'..chat_id..':title') then cache_chat_title(chat_id, msg.chat.title) end local res = api.sendMessage(msg.from.id, _("<b>%s</b>\n<i>Change the settings of your group</i>"):format(msg.chat.title:escape_html()), 'html', keyboard) if not u.is_silentmode_on(msg.chat.id) then --send the responde in the group only if the silent mode is off if res then api.sendMessage(msg.chat.id, _("_I've sent you the keyboard via private message_"), true) else u.sendStartMe(msg) end end end end end function plugin.onCallbackQuery(msg, blocks) local chat_id = msg.target_id local keyboard = do_keyboard_config(chat_id, msg.from.id, msg.from.admin) local text = _("<i>Change the settings of your group</i>") local chat_title = get_chat_title(chat_id) if chat_title then text = ("<b>%s</b>\n"):format(chat_title:escape_html())..text end api.editMessageText(msg.chat.id, msg.message_id, text, 'html', keyboard) end plugin.triggers = { onTextMessage = { config.cmd..'config$', config.cmd..'settings$', }, onCallbackQuery = { '^###cb:config:back:' } } return plugin
gpl-2.0
endlessm/chromium-browser
third_party/skia/resources/lua/slides_content.lua
78
1789
Skia Overview 2014 < transition =slide> One API -- many backends - Raster [8888, 565, A8] - GPU [opengl] - PDF - XPS - Picture - Pipe <transition= fade> One Team -- many clients - Chrome - ChromeOS - Clank - Android Framework - 3rd parties (e.g. FireFox) <transition= rotate> <blockstyle = code> Optimize for CPU variety - x86 - 32bit (SSE, SSE2, ...), 64bit - Arm - thumb, arm, NEON, ... 64bit? - MIPS (just starting) <transition= zoom> Optimize for GPU variety - Nvidia - Qualcom - Imagination - ... - ES2 -vs- ES3 -vs- Desktop profiles Lots of testing and measuring - build-bots -- unittests, micro-benchmarks, image-regressions -- http://108.170.217.252:10117/console - webpage archives (in progress) -- "map-reduce" server for saerching/historgrams -- macro-benchmarks, image-reressions -- gpu : cpu fuzzy compares Skia Roadmap [Fall '13] Roadmap in a nutshell - GPU performance - Pictures - Images - Fonts - PDF Roadmap : GPU Performance - Clipping changes are expensive - Texture cache optimizations - Better batching / reordering - Rely more on multi-sampling - ES3/desktop features (e.g. path-rendering) - ... continuo ad absurdum Roadmap : Pictures - Playback performance -- improve culling -- multi-core support - Record performance -- improve hash/cache -- improve measuring/bbox computation - Feedback to clients -- annotations -- heat-map for time spent drawing -- peep-hole optimizations Roadmap : Images - HQ filtering and mipmaps - Unpremul support - sRGB support (future) - Improve cache / lazy-decoding Roadmap : Fonts - Color emoji - DirectWrite on windows -- subpixel positioning! - new FontMgr -- extended styles Roadmap : PDF - Android -- perspective, color-filters - New Viewer project -- print-preview and more -- can output picture / gpu directly
bsd-3-clause
endlessm/chromium-browser
third_party/spirv-headers/src/include/spirv/1.0/spirv.lua
59
25964
-- Copyright (c) 2014-2018 The Khronos Group Inc. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and/or associated documentation files (the "Materials"), -- to deal in the Materials without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Materials, and to permit persons to whom the -- Materials are 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 Materials. -- -- MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS -- STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND -- HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ -- -- THE MATERIALS ARE 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 MATERIALS OR THE USE OR OTHER DEALINGS -- IN THE MATERIALS. -- This header is automatically generated by the same tool that creates -- the Binary Section of the SPIR-V specification. -- Enumeration tokens for SPIR-V, in various styles: -- C, C++, C++11, JSON, Lua, Python -- -- - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL -- - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL -- - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL -- - Lua will use tables, e.g.: spv.SourceLanguage.GLSL -- - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL'] -- -- Some tokens act like mask values, which can be OR'd together, -- while others are mutually exclusive. The mask-like ones have -- "Mask" in their name, and a parallel enum that has the shift -- amount (1 << x) for each corresponding enumerant. spv = { MagicNumber = 0x07230203, Version = 0x00010000, Revision = 12, OpCodeMask = 0xffff, WordCountShift = 16, SourceLanguage = { Unknown = 0, ESSL = 1, GLSL = 2, OpenCL_C = 3, OpenCL_CPP = 4, HLSL = 5, }, ExecutionModel = { Vertex = 0, TessellationControl = 1, TessellationEvaluation = 2, Geometry = 3, Fragment = 4, GLCompute = 5, Kernel = 6, }, AddressingModel = { Logical = 0, Physical32 = 1, Physical64 = 2, }, MemoryModel = { Simple = 0, GLSL450 = 1, OpenCL = 2, }, ExecutionMode = { Invocations = 0, SpacingEqual = 1, SpacingFractionalEven = 2, SpacingFractionalOdd = 3, VertexOrderCw = 4, VertexOrderCcw = 5, PixelCenterInteger = 6, OriginUpperLeft = 7, OriginLowerLeft = 8, EarlyFragmentTests = 9, PointMode = 10, Xfb = 11, DepthReplacing = 12, DepthGreater = 14, DepthLess = 15, DepthUnchanged = 16, LocalSize = 17, LocalSizeHint = 18, InputPoints = 19, InputLines = 20, InputLinesAdjacency = 21, Triangles = 22, InputTrianglesAdjacency = 23, Quads = 24, Isolines = 25, OutputVertices = 26, OutputPoints = 27, OutputLineStrip = 28, OutputTriangleStrip = 29, VecTypeHint = 30, ContractionOff = 31, PostDepthCoverage = 4446, StencilRefReplacingEXT = 5027, }, StorageClass = { UniformConstant = 0, Input = 1, Uniform = 2, Output = 3, Workgroup = 4, CrossWorkgroup = 5, Private = 6, Function = 7, Generic = 8, PushConstant = 9, AtomicCounter = 10, Image = 11, StorageBuffer = 12, }, Dim = { Dim1D = 0, Dim2D = 1, Dim3D = 2, Cube = 3, Rect = 4, Buffer = 5, SubpassData = 6, }, SamplerAddressingMode = { None = 0, ClampToEdge = 1, Clamp = 2, Repeat = 3, RepeatMirrored = 4, }, SamplerFilterMode = { Nearest = 0, Linear = 1, }, ImageFormat = { Unknown = 0, Rgba32f = 1, Rgba16f = 2, R32f = 3, Rgba8 = 4, Rgba8Snorm = 5, Rg32f = 6, Rg16f = 7, R11fG11fB10f = 8, R16f = 9, Rgba16 = 10, Rgb10A2 = 11, Rg16 = 12, Rg8 = 13, R16 = 14, R8 = 15, Rgba16Snorm = 16, Rg16Snorm = 17, Rg8Snorm = 18, R16Snorm = 19, R8Snorm = 20, Rgba32i = 21, Rgba16i = 22, Rgba8i = 23, R32i = 24, Rg32i = 25, Rg16i = 26, Rg8i = 27, R16i = 28, R8i = 29, Rgba32ui = 30, Rgba16ui = 31, Rgba8ui = 32, R32ui = 33, Rgb10a2ui = 34, Rg32ui = 35, Rg16ui = 36, Rg8ui = 37, R16ui = 38, R8ui = 39, }, ImageChannelOrder = { R = 0, A = 1, RG = 2, RA = 3, RGB = 4, RGBA = 5, BGRA = 6, ARGB = 7, Intensity = 8, Luminance = 9, Rx = 10, RGx = 11, RGBx = 12, Depth = 13, DepthStencil = 14, sRGB = 15, sRGBx = 16, sRGBA = 17, sBGRA = 18, ABGR = 19, }, ImageChannelDataType = { SnormInt8 = 0, SnormInt16 = 1, UnormInt8 = 2, UnormInt16 = 3, UnormShort565 = 4, UnormShort555 = 5, UnormInt101010 = 6, SignedInt8 = 7, SignedInt16 = 8, SignedInt32 = 9, UnsignedInt8 = 10, UnsignedInt16 = 11, UnsignedInt32 = 12, HalfFloat = 13, Float = 14, UnormInt24 = 15, UnormInt101010_2 = 16, }, ImageOperandsShift = { Bias = 0, Lod = 1, Grad = 2, ConstOffset = 3, Offset = 4, ConstOffsets = 5, Sample = 6, MinLod = 7, }, ImageOperandsMask = { MaskNone = 0, Bias = 0x00000001, Lod = 0x00000002, Grad = 0x00000004, ConstOffset = 0x00000008, Offset = 0x00000010, ConstOffsets = 0x00000020, Sample = 0x00000040, MinLod = 0x00000080, }, FPFastMathModeShift = { NotNaN = 0, NotInf = 1, NSZ = 2, AllowRecip = 3, Fast = 4, }, FPFastMathModeMask = { MaskNone = 0, NotNaN = 0x00000001, NotInf = 0x00000002, NSZ = 0x00000004, AllowRecip = 0x00000008, Fast = 0x00000010, }, FPRoundingMode = { RTE = 0, RTZ = 1, RTP = 2, RTN = 3, }, LinkageType = { Export = 0, Import = 1, }, AccessQualifier = { ReadOnly = 0, WriteOnly = 1, ReadWrite = 2, }, FunctionParameterAttribute = { Zext = 0, Sext = 1, ByVal = 2, Sret = 3, NoAlias = 4, NoCapture = 5, NoWrite = 6, NoReadWrite = 7, }, Decoration = { RelaxedPrecision = 0, SpecId = 1, Block = 2, BufferBlock = 3, RowMajor = 4, ColMajor = 5, ArrayStride = 6, MatrixStride = 7, GLSLShared = 8, GLSLPacked = 9, CPacked = 10, BuiltIn = 11, NoPerspective = 13, Flat = 14, Patch = 15, Centroid = 16, Sample = 17, Invariant = 18, Restrict = 19, Aliased = 20, Volatile = 21, Constant = 22, Coherent = 23, NonWritable = 24, NonReadable = 25, Uniform = 26, SaturatedConversion = 28, Stream = 29, Location = 30, Component = 31, Index = 32, Binding = 33, DescriptorSet = 34, Offset = 35, XfbBuffer = 36, XfbStride = 37, FuncParamAttr = 38, FPRoundingMode = 39, FPFastMathMode = 40, LinkageAttributes = 41, NoContraction = 42, InputAttachmentIndex = 43, Alignment = 44, ExplicitInterpAMD = 4999, OverrideCoverageNV = 5248, PassthroughNV = 5250, ViewportRelativeNV = 5252, SecondaryViewportRelativeNV = 5256, HlslCounterBufferGOOGLE = 5634, HlslSemanticGOOGLE = 5635, }, BuiltIn = { Position = 0, PointSize = 1, ClipDistance = 3, CullDistance = 4, VertexId = 5, InstanceId = 6, PrimitiveId = 7, InvocationId = 8, Layer = 9, ViewportIndex = 10, TessLevelOuter = 11, TessLevelInner = 12, TessCoord = 13, PatchVertices = 14, FragCoord = 15, PointCoord = 16, FrontFacing = 17, SampleId = 18, SamplePosition = 19, SampleMask = 20, FragDepth = 22, HelperInvocation = 23, NumWorkgroups = 24, WorkgroupSize = 25, WorkgroupId = 26, LocalInvocationId = 27, GlobalInvocationId = 28, LocalInvocationIndex = 29, WorkDim = 30, GlobalSize = 31, EnqueuedWorkgroupSize = 32, GlobalOffset = 33, GlobalLinearId = 34, SubgroupSize = 36, SubgroupMaxSize = 37, NumSubgroups = 38, NumEnqueuedSubgroups = 39, SubgroupId = 40, SubgroupLocalInvocationId = 41, VertexIndex = 42, InstanceIndex = 43, SubgroupEqMaskKHR = 4416, SubgroupGeMaskKHR = 4417, SubgroupGtMaskKHR = 4418, SubgroupLeMaskKHR = 4419, SubgroupLtMaskKHR = 4420, BaseVertex = 4424, BaseInstance = 4425, DrawIndex = 4426, DeviceIndex = 4438, ViewIndex = 4440, BaryCoordNoPerspAMD = 4992, BaryCoordNoPerspCentroidAMD = 4993, BaryCoordNoPerspSampleAMD = 4994, BaryCoordSmoothAMD = 4995, BaryCoordSmoothCentroidAMD = 4996, BaryCoordSmoothSampleAMD = 4997, BaryCoordPullModelAMD = 4998, FragStencilRefEXT = 5014, ViewportMaskNV = 5253, SecondaryPositionNV = 5257, SecondaryViewportMaskNV = 5258, PositionPerViewNV = 5261, ViewportMaskPerViewNV = 5262, }, SelectionControlShift = { Flatten = 0, DontFlatten = 1, }, SelectionControlMask = { MaskNone = 0, Flatten = 0x00000001, DontFlatten = 0x00000002, }, LoopControlShift = { Unroll = 0, DontUnroll = 1, }, LoopControlMask = { MaskNone = 0, Unroll = 0x00000001, DontUnroll = 0x00000002, }, FunctionControlShift = { Inline = 0, DontInline = 1, Pure = 2, Const = 3, }, FunctionControlMask = { MaskNone = 0, Inline = 0x00000001, DontInline = 0x00000002, Pure = 0x00000004, Const = 0x00000008, }, MemorySemanticsShift = { Acquire = 1, Release = 2, AcquireRelease = 3, SequentiallyConsistent = 4, UniformMemory = 6, SubgroupMemory = 7, WorkgroupMemory = 8, CrossWorkgroupMemory = 9, AtomicCounterMemory = 10, ImageMemory = 11, }, MemorySemanticsMask = { MaskNone = 0, Acquire = 0x00000002, Release = 0x00000004, AcquireRelease = 0x00000008, SequentiallyConsistent = 0x00000010, UniformMemory = 0x00000040, SubgroupMemory = 0x00000080, WorkgroupMemory = 0x00000100, CrossWorkgroupMemory = 0x00000200, AtomicCounterMemory = 0x00000400, ImageMemory = 0x00000800, }, MemoryAccessShift = { Volatile = 0, Aligned = 1, Nontemporal = 2, }, MemoryAccessMask = { MaskNone = 0, Volatile = 0x00000001, Aligned = 0x00000002, Nontemporal = 0x00000004, }, Scope = { CrossDevice = 0, Device = 1, Workgroup = 2, Subgroup = 3, Invocation = 4, }, GroupOperation = { Reduce = 0, InclusiveScan = 1, ExclusiveScan = 2, }, KernelEnqueueFlags = { NoWait = 0, WaitKernel = 1, WaitWorkGroup = 2, }, KernelProfilingInfoShift = { CmdExecTime = 0, }, KernelProfilingInfoMask = { MaskNone = 0, CmdExecTime = 0x00000001, }, Capability = { Matrix = 0, Shader = 1, Geometry = 2, Tessellation = 3, Addresses = 4, Linkage = 5, Kernel = 6, Vector16 = 7, Float16Buffer = 8, Float16 = 9, Float64 = 10, Int64 = 11, Int64Atomics = 12, ImageBasic = 13, ImageReadWrite = 14, ImageMipmap = 15, Pipes = 17, Groups = 18, DeviceEnqueue = 19, LiteralSampler = 20, AtomicStorage = 21, Int16 = 22, TessellationPointSize = 23, GeometryPointSize = 24, ImageGatherExtended = 25, StorageImageMultisample = 27, UniformBufferArrayDynamicIndexing = 28, SampledImageArrayDynamicIndexing = 29, StorageBufferArrayDynamicIndexing = 30, StorageImageArrayDynamicIndexing = 31, ClipDistance = 32, CullDistance = 33, ImageCubeArray = 34, SampleRateShading = 35, ImageRect = 36, SampledRect = 37, GenericPointer = 38, Int8 = 39, InputAttachment = 40, SparseResidency = 41, MinLod = 42, Sampled1D = 43, Image1D = 44, SampledCubeArray = 45, SampledBuffer = 46, ImageBuffer = 47, ImageMSArray = 48, StorageImageExtendedFormats = 49, ImageQuery = 50, DerivativeControl = 51, InterpolationFunction = 52, TransformFeedback = 53, GeometryStreams = 54, StorageImageReadWithoutFormat = 55, StorageImageWriteWithoutFormat = 56, MultiViewport = 57, SubgroupBallotKHR = 4423, DrawParameters = 4427, SubgroupVoteKHR = 4431, StorageBuffer16BitAccess = 4433, StorageUniformBufferBlock16 = 4433, StorageUniform16 = 4434, UniformAndStorageBuffer16BitAccess = 4434, StoragePushConstant16 = 4435, StorageInputOutput16 = 4436, DeviceGroup = 4437, MultiView = 4439, VariablePointersStorageBuffer = 4441, VariablePointers = 4442, AtomicStorageOps = 4445, SampleMaskPostDepthCoverage = 4447, ImageGatherBiasLodAMD = 5009, FragmentMaskAMD = 5010, StencilExportEXT = 5013, ImageReadWriteLodAMD = 5015, SampleMaskOverrideCoverageNV = 5249, GeometryShaderPassthroughNV = 5251, ShaderViewportIndexLayerEXT = 5254, ShaderViewportIndexLayerNV = 5254, ShaderViewportMaskNV = 5255, ShaderStereoViewNV = 5259, PerViewAttributesNV = 5260, SubgroupShuffleINTEL = 5568, SubgroupBufferBlockIOINTEL = 5569, SubgroupImageBlockIOINTEL = 5570, }, Op = { OpNop = 0, OpUndef = 1, OpSourceContinued = 2, OpSource = 3, OpSourceExtension = 4, OpName = 5, OpMemberName = 6, OpString = 7, OpLine = 8, OpExtension = 10, OpExtInstImport = 11, OpExtInst = 12, OpMemoryModel = 14, OpEntryPoint = 15, OpExecutionMode = 16, OpCapability = 17, OpTypeVoid = 19, OpTypeBool = 20, OpTypeInt = 21, OpTypeFloat = 22, OpTypeVector = 23, OpTypeMatrix = 24, OpTypeImage = 25, OpTypeSampler = 26, OpTypeSampledImage = 27, OpTypeArray = 28, OpTypeRuntimeArray = 29, OpTypeStruct = 30, OpTypeOpaque = 31, OpTypePointer = 32, OpTypeFunction = 33, OpTypeEvent = 34, OpTypeDeviceEvent = 35, OpTypeReserveId = 36, OpTypeQueue = 37, OpTypePipe = 38, OpTypeForwardPointer = 39, OpConstantTrue = 41, OpConstantFalse = 42, OpConstant = 43, OpConstantComposite = 44, OpConstantSampler = 45, OpConstantNull = 46, OpSpecConstantTrue = 48, OpSpecConstantFalse = 49, OpSpecConstant = 50, OpSpecConstantComposite = 51, OpSpecConstantOp = 52, OpFunction = 54, OpFunctionParameter = 55, OpFunctionEnd = 56, OpFunctionCall = 57, OpVariable = 59, OpImageTexelPointer = 60, OpLoad = 61, OpStore = 62, OpCopyMemory = 63, OpCopyMemorySized = 64, OpAccessChain = 65, OpInBoundsAccessChain = 66, OpPtrAccessChain = 67, OpArrayLength = 68, OpGenericPtrMemSemantics = 69, OpInBoundsPtrAccessChain = 70, OpDecorate = 71, OpMemberDecorate = 72, OpDecorationGroup = 73, OpGroupDecorate = 74, OpGroupMemberDecorate = 75, OpVectorExtractDynamic = 77, OpVectorInsertDynamic = 78, OpVectorShuffle = 79, OpCompositeConstruct = 80, OpCompositeExtract = 81, OpCompositeInsert = 82, OpCopyObject = 83, OpTranspose = 84, OpSampledImage = 86, OpImageSampleImplicitLod = 87, OpImageSampleExplicitLod = 88, OpImageSampleDrefImplicitLod = 89, OpImageSampleDrefExplicitLod = 90, OpImageSampleProjImplicitLod = 91, OpImageSampleProjExplicitLod = 92, OpImageSampleProjDrefImplicitLod = 93, OpImageSampleProjDrefExplicitLod = 94, OpImageFetch = 95, OpImageGather = 96, OpImageDrefGather = 97, OpImageRead = 98, OpImageWrite = 99, OpImage = 100, OpImageQueryFormat = 101, OpImageQueryOrder = 102, OpImageQuerySizeLod = 103, OpImageQuerySize = 104, OpImageQueryLod = 105, OpImageQueryLevels = 106, OpImageQuerySamples = 107, OpConvertFToU = 109, OpConvertFToS = 110, OpConvertSToF = 111, OpConvertUToF = 112, OpUConvert = 113, OpSConvert = 114, OpFConvert = 115, OpQuantizeToF16 = 116, OpConvertPtrToU = 117, OpSatConvertSToU = 118, OpSatConvertUToS = 119, OpConvertUToPtr = 120, OpPtrCastToGeneric = 121, OpGenericCastToPtr = 122, OpGenericCastToPtrExplicit = 123, OpBitcast = 124, OpSNegate = 126, OpFNegate = 127, OpIAdd = 128, OpFAdd = 129, OpISub = 130, OpFSub = 131, OpIMul = 132, OpFMul = 133, OpUDiv = 134, OpSDiv = 135, OpFDiv = 136, OpUMod = 137, OpSRem = 138, OpSMod = 139, OpFRem = 140, OpFMod = 141, OpVectorTimesScalar = 142, OpMatrixTimesScalar = 143, OpVectorTimesMatrix = 144, OpMatrixTimesVector = 145, OpMatrixTimesMatrix = 146, OpOuterProduct = 147, OpDot = 148, OpIAddCarry = 149, OpISubBorrow = 150, OpUMulExtended = 151, OpSMulExtended = 152, OpAny = 154, OpAll = 155, OpIsNan = 156, OpIsInf = 157, OpIsFinite = 158, OpIsNormal = 159, OpSignBitSet = 160, OpLessOrGreater = 161, OpOrdered = 162, OpUnordered = 163, OpLogicalEqual = 164, OpLogicalNotEqual = 165, OpLogicalOr = 166, OpLogicalAnd = 167, OpLogicalNot = 168, OpSelect = 169, OpIEqual = 170, OpINotEqual = 171, OpUGreaterThan = 172, OpSGreaterThan = 173, OpUGreaterThanEqual = 174, OpSGreaterThanEqual = 175, OpULessThan = 176, OpSLessThan = 177, OpULessThanEqual = 178, OpSLessThanEqual = 179, OpFOrdEqual = 180, OpFUnordEqual = 181, OpFOrdNotEqual = 182, OpFUnordNotEqual = 183, OpFOrdLessThan = 184, OpFUnordLessThan = 185, OpFOrdGreaterThan = 186, OpFUnordGreaterThan = 187, OpFOrdLessThanEqual = 188, OpFUnordLessThanEqual = 189, OpFOrdGreaterThanEqual = 190, OpFUnordGreaterThanEqual = 191, OpShiftRightLogical = 194, OpShiftRightArithmetic = 195, OpShiftLeftLogical = 196, OpBitwiseOr = 197, OpBitwiseXor = 198, OpBitwiseAnd = 199, OpNot = 200, OpBitFieldInsert = 201, OpBitFieldSExtract = 202, OpBitFieldUExtract = 203, OpBitReverse = 204, OpBitCount = 205, OpDPdx = 207, OpDPdy = 208, OpFwidth = 209, OpDPdxFine = 210, OpDPdyFine = 211, OpFwidthFine = 212, OpDPdxCoarse = 213, OpDPdyCoarse = 214, OpFwidthCoarse = 215, OpEmitVertex = 218, OpEndPrimitive = 219, OpEmitStreamVertex = 220, OpEndStreamPrimitive = 221, OpControlBarrier = 224, OpMemoryBarrier = 225, OpAtomicLoad = 227, OpAtomicStore = 228, OpAtomicExchange = 229, OpAtomicCompareExchange = 230, OpAtomicCompareExchangeWeak = 231, OpAtomicIIncrement = 232, OpAtomicIDecrement = 233, OpAtomicIAdd = 234, OpAtomicISub = 235, OpAtomicSMin = 236, OpAtomicUMin = 237, OpAtomicSMax = 238, OpAtomicUMax = 239, OpAtomicAnd = 240, OpAtomicOr = 241, OpAtomicXor = 242, OpPhi = 245, OpLoopMerge = 246, OpSelectionMerge = 247, OpLabel = 248, OpBranch = 249, OpBranchConditional = 250, OpSwitch = 251, OpKill = 252, OpReturn = 253, OpReturnValue = 254, OpUnreachable = 255, OpLifetimeStart = 256, OpLifetimeStop = 257, OpGroupAsyncCopy = 259, OpGroupWaitEvents = 260, OpGroupAll = 261, OpGroupAny = 262, OpGroupBroadcast = 263, OpGroupIAdd = 264, OpGroupFAdd = 265, OpGroupFMin = 266, OpGroupUMin = 267, OpGroupSMin = 268, OpGroupFMax = 269, OpGroupUMax = 270, OpGroupSMax = 271, OpReadPipe = 274, OpWritePipe = 275, OpReservedReadPipe = 276, OpReservedWritePipe = 277, OpReserveReadPipePackets = 278, OpReserveWritePipePackets = 279, OpCommitReadPipe = 280, OpCommitWritePipe = 281, OpIsValidReserveId = 282, OpGetNumPipePackets = 283, OpGetMaxPipePackets = 284, OpGroupReserveReadPipePackets = 285, OpGroupReserveWritePipePackets = 286, OpGroupCommitReadPipe = 287, OpGroupCommitWritePipe = 288, OpEnqueueMarker = 291, OpEnqueueKernel = 292, OpGetKernelNDrangeSubGroupCount = 293, OpGetKernelNDrangeMaxSubGroupSize = 294, OpGetKernelWorkGroupSize = 295, OpGetKernelPreferredWorkGroupSizeMultiple = 296, OpRetainEvent = 297, OpReleaseEvent = 298, OpCreateUserEvent = 299, OpIsValidEvent = 300, OpSetUserEventStatus = 301, OpCaptureEventProfilingInfo = 302, OpGetDefaultQueue = 303, OpBuildNDRange = 304, OpImageSparseSampleImplicitLod = 305, OpImageSparseSampleExplicitLod = 306, OpImageSparseSampleDrefImplicitLod = 307, OpImageSparseSampleDrefExplicitLod = 308, OpImageSparseSampleProjImplicitLod = 309, OpImageSparseSampleProjExplicitLod = 310, OpImageSparseSampleProjDrefImplicitLod = 311, OpImageSparseSampleProjDrefExplicitLod = 312, OpImageSparseFetch = 313, OpImageSparseGather = 314, OpImageSparseDrefGather = 315, OpImageSparseTexelsResident = 316, OpNoLine = 317, OpAtomicFlagTestAndSet = 318, OpAtomicFlagClear = 319, OpImageSparseRead = 320, OpDecorateId = 332, OpSubgroupBallotKHR = 4421, OpSubgroupFirstInvocationKHR = 4422, OpSubgroupAllKHR = 4428, OpSubgroupAnyKHR = 4429, OpSubgroupAllEqualKHR = 4430, OpSubgroupReadInvocationKHR = 4432, OpGroupIAddNonUniformAMD = 5000, OpGroupFAddNonUniformAMD = 5001, OpGroupFMinNonUniformAMD = 5002, OpGroupUMinNonUniformAMD = 5003, OpGroupSMinNonUniformAMD = 5004, OpGroupFMaxNonUniformAMD = 5005, OpGroupUMaxNonUniformAMD = 5006, OpGroupSMaxNonUniformAMD = 5007, OpFragmentMaskFetchAMD = 5011, OpFragmentFetchAMD = 5012, OpSubgroupShuffleINTEL = 5571, OpSubgroupShuffleDownINTEL = 5572, OpSubgroupShuffleUpINTEL = 5573, OpSubgroupShuffleXorINTEL = 5574, OpSubgroupBlockReadINTEL = 5575, OpSubgroupBlockWriteINTEL = 5576, OpSubgroupImageBlockReadINTEL = 5577, OpSubgroupImageBlockWriteINTEL = 5578, OpDecorateStringGOOGLE = 5632, OpMemberDecorateStringGOOGLE = 5633, }, }
bsd-3-clause
wjhandboy/Atlas
examples/tutorial-resultset.lua
40
3110
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] --[[ --]] -- init the query-counter if it isn't done yet if not proxy.global.query_counter then proxy.global.query_counter = 0 end local query_counter = 0 --- -- read_query() can return a resultset -- -- You can use read_query() to return a result-set. -- -- @param packet the mysql-packet sent by the client -- -- @return -- * nothing to pass on the packet as is, -- * proxy.PROXY_SEND_QUERY to send the queries from the proxy.queries queue -- * proxy.PROXY_SEND_RESULT to send your own result-set -- function read_query( packet ) -- a new query came in in this connection proxy.global.query_counter = proxy.global.query_counter + 1 query_counter = query_counter + 1 if string.byte(packet) == proxy.COM_QUERY then --[[ we use a simple string-match to split commands are word-boundaries mysql> show querycounter is split into command = "show" option = "querycounter" spaces are ignored, the case has to be as is. mysql> show myerror returns a error-packet --]] -- try to match the string up to the first non-alphanum local f_s, f_e, command = string.find(packet, "^%s*(%w+)", 2) local option if f_e then -- if that match, take the next sub-string as option f_s, f_e, option = string.find(packet, "^%s+(%w+)", f_e + 1) end -- we got our commands, execute it if string.lower(command) == "show" and string.lower(option) == "querycounter" then --- -- proxy.PROXY_SEND_RESULT requires -- -- proxy.response.type to be either -- * proxy.MYSQLD_PACKET_OK or -- * proxy.MYSQLD_PACKET_ERR -- -- for proxy.MYSQLD_PACKET_OK you need a resultset -- * fields -- * rows -- -- for proxy.MYSQLD_PACKET_ERR -- * errmsg proxy.response.type = proxy.MYSQLD_PACKET_OK proxy.response.resultset = { fields = { { type = proxy.MYSQL_TYPE_LONG, name = "global_query_counter", }, { type = proxy.MYSQL_TYPE_LONG, name = "query_counter", }, }, rows = { { proxy.global.query_counter, query_counter } } } -- we have our result, send it back return proxy.PROXY_SEND_RESULT elseif string.lower(command) == "show" and string.lower(option) == "myerror" then proxy.response.type = proxy.MYSQLD_PACKET_ERR proxy.response.errmsg = "my first error" return proxy.PROXY_SEND_RESULT end end end
gpl-2.0
ld-test/cwtest
cwtest.lua
3
8506
local has_strict = pcall(require, "pl.strict") local has_pretty, pretty = pcall(require, "pl.pretty") if not has_strict then print("WARNING: pl.strict not found, strictness not enforced.") end if not has_pretty then pretty = nil print("WARNING: pl.pretty not found, using alternate formatter.") end --- logic borrowed to Penlight local deepcompare deepcompare = function(t1, t2) local ty1 = type(t1) local ty2 = type(t2) if ty1 ~= ty2 then return false end -- non-table types can be directly compared if ty1 ~= "table" then return t1 == t2 end -- as well as tables which have the metamethod __eq local mt = getmetatable(t1) if mt and mt.__eq then return t1 == t2 end for k1 in pairs(t1) do if t2[k1] == nil then return false end end for k2 in pairs(t2) do if t1[k2] == nil then return false end end for k1,v1 in pairs(t1) do local v2 = t2[k1] if not deepcompare(v1, v2) then return false end end return true end local compare_no_order = function(t1, t2, cmp) cmp = cmp or deepcompare -- non-table types are considered *never* equal here if (type(t1) ~= "table") or (type(t2) ~= "table") then return false end if #t1 ~= #t2 then return false end local visited = {} for i = 1,#t1 do local val = t1[i] local gotcha for j = 1,#t2 do if not visited[j] then if cmp(val, t2[j]) then gotcha = j break end end end if not gotcha then return false end visited[gotcha] = true end return true end --- basic pretty.write fallback local less_pretty_write less_pretty_write = function(t) local quote = function(s) if type(s) == "string" then return string.format("%q", tostring(s)) else return tostring(s) end end if type(t) == "table" then local r = {"{"} for k,v in pairs(t) do if type(k) ~= "number" then k = quote(k) end r[#r+1] = "[" r[#r+1] = k r[#r+1] = "]=" r[#r+1] = less_pretty_write(v) r[#r+1] = "," end r[#r+1] = "}" return table.concat(r) else return quote(t) end end --- end of Penlight fallbacks local pretty_write if pretty then pretty_write = function(x) return pretty.write(x, "") end else pretty_write = less_pretty_write end local printf = function(p, ...) io.stdout:write(string.format(p, ...)); io.stdout:flush() end local eprintf = function(p, ...) io.stderr:write(string.format(p, ...)) end local log_success = function(self, tpl, ...) assert(type(tpl) == "string") local s = (select('#', ...) == 0) and tpl or string.format(tpl, ...) self.successes[#self.successes+1] = s if self.verbosity == 2 then self.printf("\n%s\n", s) else self.printf(".") end return true end local log_failure = function(self, tpl, ...) assert(type(tpl) == "string") local s = (select('#', ...) == 0) and tpl or string.format(tpl, ...) self.failures[#self.failures+1] = s if self.verbosity > 0 then self.eprintf("\n%s\n", s) else self.printf("x") end return true end local pass_tpl = function(self, tpl, ...) assert(type(tpl) == "string") local info = debug.getinfo(3) self:log_success( "[OK] %s line %d%s", info.short_src, info.currentline, (select('#', ...) == 0) and tpl or string.format(tpl, ...) ) return true end local fail_tpl = function(self, tpl, ...) assert(type(tpl) == "string") local info = debug.getinfo(3) self:log_failure( "[KO] %s line %d%s", info.short_src, info.currentline, (select('#', ...) == 0) and tpl or string.format(tpl, ...) ) return false end local pass_assertion = function(self) local info = debug.getinfo(3) self:log_success( "[OK] %s line %d (assertion)", info.short_src, info.currentline ) return true end local fail_assertion = function(self) local info = debug.getinfo(3) self:log_failure( "[KO] %s line %d (assertion)", info.short_src, info.currentline ) return false end local pass_eq = function(self, x, y) local info = debug.getinfo(3) self:log_success( "[OK] %s line %d\n expected: %s\n got: %s", info.short_src, info.currentline, pretty_write(y), pretty_write(x) ) return true end local fail_eq = function(self, x, y) local info = debug.getinfo(3) self:log_failure( "[KO] %s line %d\n expected: %s\n got: %s", info.short_src, info.currentline, pretty_write(y), pretty_write(x) ) return false end local start = function(self, s) assert((not (self.failures or self.successes)), "test already started") self.failures, self.successes = {}, {} if self.verbosity > 0 then self.printf("\n=== %s ===\n", s) else self.printf("%s ", s) end end local done = function(self) local f, s = self.failures, self.successes assert((f and s), "call start before done") local failed = (#f > 0) if failed then if self.verbosity > 0 then self.printf("\n=== FAILED ===\n") else self.printf(" FAILED\n") for i=1,#f do self.eprintf("\n%s\n", f[i]) end self.printf("\n") end else if self.verbosity > 0 then self.printf("\n=== OK ===\n") else self.printf(" OK\n") end end self.failures, self.successes = nil, nil if failed then self.tainted = true end return (not failed) end local eq = function(self, x, y) local ok = (x == y) or deepcompare(x, y) local r = (ok and pass_eq or fail_eq)(self, x, y) return r end local neq = function(self, x, y) local sx, sy = pretty_write(x), pretty_write(y) local r if deepcompare(x, y) then r = fail_tpl(self, " (%s == %s)", sx, sy) else r = pass_tpl(self, " (%s != %s)", sx, sy) end return r end local seq = function(self, x, y) -- list-sets local ok = compare_no_order(x, y) local r = (ok and pass_eq or fail_eq)(self, x, y) return r end local _assert_fun = function(x, ...) if (select('#', ...) == 0) then return (x and pass_assertion or fail_assertion) else return (x and pass_tpl or fail_tpl) end end local is_true = function(self, x, ...) local r = _assert_fun(x, ...)(self, ...) return r end local is_false = function(self, x, ...) local r = _assert_fun((not x), ...)(self, ...) return r end local err = function(self, f, e) local r = { pcall(f) } if e then if type(e) == "string" then if r[1] then table.remove(r, 1) r = fail_tpl( self, "\n expected error: %s\n got: %s", e, pretty_write(r, "") ) elseif r[2] ~= e then r = fail_tpl( self, "\n expected error: %s\n got error: %s", e, r[2] ) else r = pass_tpl(self, ": error [[%s]] caught", e) end elseif type(e) == "table" and type(e.matching) == "string" then local pattern = e.matching if r[1] then table.remove(r, 1) r = fail_tpl( self, "\n expected error, got: %s", e, pretty_write(r, "") ) elseif not r[2]:match(pattern) then r = fail_tpl( self, "\n expected error matching: %q\n got error: %s", pattern, r[2] ) else r = pass_tpl(self, ": error [[%s]] caught", e) end end else if r[1] then table.remove(r, 1) r = fail_tpl( self, ": expected error, got %s", pretty_write(r, "") ) else r = pass_tpl(self, ": error caught") end end return r end local exit = function(self) os.exit(self.tainted and 1 or 0) end local methods = { start = start, done = done, eq = eq, neq = neq, seq = seq, yes = is_true, no = is_false, err = err, exit = exit, -- below: only to build custom tests log_success = log_success, log_failure = log_failure, pass_eq = pass_eq, fail_eq = fail_eq, pass_assertion = pass_assertion, fail_assertion = fail_assertion, pass_tpl = pass_tpl, fail_tpl = fail_tpl, } local new = function(verbosity) if not verbosity then verbosity = 0 elseif type(verbosity) ~= "number" then verbosity = 1 end assert( (math.floor(verbosity) == verbosity) and (verbosity >= 0) and (verbosity < 3) ) local r = { verbosity = verbosity, printf = printf, eprintf = eprintf, tainted = false, } return setmetatable(r, {__index = methods}) end return { new = new, pretty_write = pretty_write, deepcompare = deepcompare, compare_no_order = compare_no_order, }
mit
Scavenge/darkstar
scripts/zones/Grauberg_[S]/npcs/qm5.lua
48
1159
----------------------------------- -- Area: Grauberg [S] -- NPC: ??? -- Quest - Fires of Discontent -- pos 258 33 516 ----------------------------------- package.loaded["scripts/zones/Grauberg_[S]/TextIDs"] = nil; ------------------------------------- require("scripts/globals/harvesting"); require("scripts/zones/Grauberg_[S]/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(CRYSTAL_WAR,FIRES_OF_DISCONTENT) == QUEST_ACCEPTED) then if (player:getVar("FiresOfDiscProg") == 3) then player:startEvent(0x000B); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid==0x000B) then player:setVar("FiresOfDiscProg",4); end end;
gpl-3.0
Brenin/PJ-3100
Working Launchers/Games/Stepmania/StepMania 5/Themes/_fallback/Scripts/00 init.lua
1
2650
-- This file is always executed first. -- Override Lua's upper and lower functions with our own, which is always UTF-8. if Uppercase then string.upper = Uppercase string.lower = Lowercase Uppercase = nil -- don't use directly Lowercase = nil -- don't use directly end Trace = lua.Trace Warn = lua.Warn print = Trace -- Use MersenneTwister in place of math.random and math.randomseed. if MersenneTwister then math.random = MersenneTwister.Random math.randomseed = MersenneTwister.Seed end PLAYER_1 = "PlayerNumber_P1" PLAYER_2 = "PlayerNumber_P2" NUM_PLAYERS = #PlayerNumber OtherPlayer = { [PLAYER_1] = PLAYER_2, [PLAYER_2] = PLAYER_1 } function string:find_last(text) local LastPos = 0 while true do local p = string.find(self, text, LastPos+1, true) if not p then return LastPos end LastPos = p end end -- Round to nearest integer. function math.round(n) if n > 0 then return math.floor(n+0.5) else return math.ceil(n-0.5) end end function split(delimiter, text) local list = {} local pos = 1 while 1 do local first,last = string.find(text, delimiter, pos) if first then table.insert(list, string.sub(text, pos, first-1)) pos = last+1 else table.insert(list, string.sub(text, pos)) break end end return list end function join(delimiter, list) return table.concat(list, delimiter) end -- (c) 2006 Glenn Maynard -- 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, and/or sell copies of the Software, and to permit persons to -- whom the Software is furnished to do so, provided that the above -- copyright notice(s) and this permission notice appear in all copies of -- the Software and that both the above copyright notice(s) and this -- permission notice appear in supporting documentation. -- -- 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 OF -- THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS -- INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT -- OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS -- OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -- PERFORMANCE OF THIS SOFTWARE.
mit
Scavenge/darkstar
scripts/globals/items/green_curry_bun.lua
12
1831
----------------------------------------- -- ID: 5756 -- Item: green_curry_bun -- Food Effect: 30 min, All Races ----------------------------------------- -- TODO: Group effects -- VIT +1 -- AGI +2 -- Ranged Accuracy +5% (cap 25) -- DEF +9% (cap 160) -- Resist Sleep +3 -- hHP +2 -- hMP +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,1800,5756); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_VIT, 1); target:addMod(MOD_AGI, 2); target:addMod(MOD_FOOD_RACCP, 5); target:addMod(MOD_FOOD_RACC_CAP, 25); target:addMod(MOD_FOOD_DEFP, 9); target:addMod(MOD_FOOD_DEF_CAP, 160); target:addMod(MOD_SLEEPRES, 3); target:addMod(MOD_HPHEAL, 2); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_VIT, 1); target:delMod(MOD_AGI, 2); target:delMod(MOD_FOOD_RACCP, 5); target:delMod(MOD_FOOD_RACC_CAP, 25); target:delMod(MOD_FOOD_DEFP, 9); target:delMod(MOD_FOOD_DEF_CAP, 160); target:delMod(MOD_SLEEPRES, 3); target:delMod(MOD_HPHEAL, 2); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Melleupaux.lua
17
1304
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Melleupaux -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; require("scripts/zones/Tavnazian_Safehold/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,MELLEUPAUX_SHOP_DIALOG); stock = {0x4042,1867, --Dagger 0x40b6,8478, --Longsword 0x43B7,8, --Rusty Bolt 0x47C7,93240, --Falx (COP Chapter 4 Needed; not implemented yet) 0x4726,51905} --Voulge (COP Chapter 4 Needed; not implemented yet) 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
Scavenge/darkstar
scripts/zones/Outer_Horutoto_Ruins/npcs/Treasure_Chest.lua
17
3006
----------------------------------- -- Area: Horutoto Ruins -- NPC: Treasure Chest -- @zone 194 ----------------------------------- package.loaded["scripts/zones/Outer_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/treasure"); require("scripts/zones/Outer_Horutoto_Ruins/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 43; local TreasureMinLvL = 33; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --trade:hasItemQty(1029,1); -- Treasure Key --trade:hasItemQty(1115,1); -- Skeleton Key --trade:hasItemQty(1023,1); -- Living Key --trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1029,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1029); 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
wkitty42/snort3
piglet/tests/interface/codec_data.lua
1
1218
plugin = { type = "piglet", name = "piglet::codec_data", test = function() -- Put the dofile here so that it doesn't get loaded twice dofile(SCRIPT_DIR .. "/common.lua") return run_all(tests) end } INIT_PROTO = 1 DEFAULT_VALUES = { next_prot_id = 0, lyr_len = 0, invalid_bytes = 0, proto_bits = 0, codec_flags = 0, ip_layer_cnt = 0, ip6_extension_count = 0, curr_ip6_extension = 0, ip6_csum_proto = 0 } VALUES = { next_prot_id = 1, lyr_len = 2, invalid_bytes = 3, proto_bits = 4, codec_flags = 5, ip_layer_cnt = 6, ip6_extension_count = 7, curr_ip6_extension = 8, ip6_csum_proto = 9 } tests = { initialize_default = function() local cd = CodecData.new() assert(cd) assert(cd:get().next_prot_id == 0) end, initialize_with_number = function() local cd = CodecData.new(INIT_PROTO) assert(cd:get().next_prot_id == INIT_PROTO) end, initialize_with_table = function() local cd = CodecData.new() assert_table_eq("get()", DEFAULT_VALUES, cd:get()) cd:set(VALUES) assert_table_eq("set()", VALUES, cd:get()) end }
gpl-2.0
kankaristo/premake-core
tests/actions/make/cpp/test_make_linking.lua
3
4230
-- -- tests/actions/make/cpp/test_make_linking.lua -- Validate the link step generation for makefiles. -- Copyright (c) 2010-2013 Jason Perkins and the Premake project -- local suite = test.declare("make_linking") local make = premake.make local project = premake.project -- -- Setup and teardown -- local wks, prj function suite.setup() _OS = "linux" wks, prj = test.createWorkspace() end local function prepare(calls) local cfg = test.getconfig(prj, "Debug") local toolset = premake.tools.gcc premake.callarray(make, calls, cfg, toolset) end -- -- Check link command for a shared C++ library. -- function suite.links_onCppSharedLib() kind "SharedLib" prepare { "ldFlags", "linkCmd" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s -shared LINKCMD = $(CXX) -o "$@" $(OBJECTS) $(RESOURCES) $(ALL_LDFLAGS) $(LIBS) ]] end -- -- Check link command for a shared C library. -- function suite.links_onCSharedLib() language "C" kind "SharedLib" prepare { "ldFlags", "linkCmd" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s -shared LINKCMD = $(CC) -o "$@" $(OBJECTS) $(RESOURCES) $(ALL_LDFLAGS) $(LIBS) ]] end -- -- Check link command for a static library. -- function suite.links_onStaticLib() kind "StaticLib" prepare { "ldFlags", "linkCmd" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s LINKCMD = $(AR) -rcs "$@" $(OBJECTS) ]] end -- -- Check link command for a Mac OS X universal static library. -- function suite.links_onMacUniversalStaticLib() architecture "universal" kind "StaticLib" prepare { "ldFlags", "linkCmd" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s LINKCMD = libtool -o "$@" $(OBJECTS) ]] end -- -- Check a linking to a sibling static library. -- function suite.links_onSiblingStaticLib() links "MyProject2" test.createproject(wks) kind "StaticLib" location "build" prepare { "ldFlags", "libs", "ldDeps" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s LIBS += build/bin/Debug/libMyProject2.a LDDEPS += build/bin/Debug/libMyProject2.a ]] end -- -- Check a linking to a sibling shared library. -- function suite.links_onSiblingSharedLib() links "MyProject2" test.createproject(wks) kind "SharedLib" location "build" prepare { "ldFlags", "libs", "ldDeps" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s LIBS += build/bin/Debug/libMyProject2.so LDDEPS += build/bin/Debug/libMyProject2.so ]] end -- -- Check a linking to a sibling shared library using -l and -L. -- function suite.links_onSiblingSharedLib() links "MyProject2" flags { "RelativeLinks" } test.createproject(wks) kind "SharedLib" location "build" prepare { "ldFlags", "libs", "ldDeps" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -Lbuild/bin/Debug -s LIBS += -lMyProject2 LDDEPS += build/bin/Debug/libMyProject2.so ]] end -- -- Check a linking multiple siblings. -- function suite.links_onSiblingStaticLib() links "MyProject2" links "MyProject3" test.createproject(wks) kind "StaticLib" location "build" test.createproject(wks) kind "StaticLib" location "build" prepare { "ldFlags", "libs", "ldDeps" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s LIBS += -Wl,--start-group build/bin/Debug/libMyProject2.a build/bin/Debug/libMyProject3.a -Wl,--end-group LDDEPS += build/bin/Debug/libMyProject2.a build/bin/Debug/libMyProject3.a ]] end -- -- When referencing an external library via a path, the directory -- should be added to the library search paths, and the library -- itself included via an -l flag. -- function suite.onExternalLibraryWithPath() location "MyProject" links { "libs/SomeLib" } prepare { "ldFlags", "libs" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -L../libs -s LIBS += -lSomeLib ]] end -- -- When referencing an external library with a period in the -- file name make sure it appears correctly in the LIBS -- directive. Currently the period and everything after it -- is stripped -- function suite.onExternalLibraryWithPath() location "MyProject" links { "libs/SomeLib-1.1" } prepare { "libs", } test.capture [[ LIBS += -lSomeLib-1.1 ]] end
bsd-3-clause
afonso360/lua-llvm
src/core/type.nobj.lua
1
6530
-- Copyright (C) 2017 Afonso Bordado -- -- Licensed under the MIT license <http://opensource.org/licenses/MIT>, -- This file may not be copied, modified, or distributed except according -- to the terms of that license. -- Missing -- Sequential types -- Structure types -- Function types object "Type" { c_source [[ typedef struct LLVMOpaqueType Type; ]], method "get_context" { c_method_call "Context *" "LLVMGetTypeContext" {}, }, method "is_sized" { c_method_call "bool" "LLVMTypeIsSized" {}, }, method "dump" { doc [[ Dumps a type to stderr ]], c_method_call "void" "LLVMDumpType" {}, }, constructor "void" { doc [[ Context is optional ]], var_in { "Context *", "ctx?" }, c_source [[ if (${ctx} == NULL) { ${this} = LLVMVoidType(); } else { ${this} = LLVMVoidTypeInContext(${ctx}); } ]], }, constructor "label" { doc [[ Context is optional ]], var_in { "Context *", "ctx?" }, c_source [[ if (${ctx} == NULL) { ${this} = LLVMLabelType(); } else { ${this} = LLVMLabelTypeInContext(${ctx}); } ]], }, constructor "x86mmx" { doc [[ Context is optional ]], var_in { "Context *", "ctx?" }, c_source [[ if (${ctx} == NULL) { ${this} = LLVMX86MMXType(); } else { ${this} = LLVMX86MMXTypeInContext(${ctx}); } ]], }, } object "FunctionType" { extends "Type", c_source [[ typedef Type FunctionType; ]], constructor "new" { var_in { "Type *", "return_type" }, var_in { "<any>", "parameters" }, var_in { "bool", "var_arg" }, c_source [[ size_t n; Type ** arr; n = lua_rawlen(L, 2); arr = calloc(n, sizeof(Type *)); for (int i=1; i<=n; i++) { lua_rawgeti(L, 2, i); arr[i-1] = obj_type_Type_check(L, -1); lua_pop(L, 1); } ${this} = LLVMFunctionType(${return_type}, arr, n, ${var_arg}); free(arr); ]], }, method "is_vararg" { c_method_call "bool" "LLVMIsFunctionVarArg" {} }, method "return_type" { c_method_call "Type *" "LLVMGetReturnType" {} }, method "count_param_types" { c_method_call "unsigned" "LLVMCountParamTypes" {} }, method "param_types" { var_out { "<any>", "parameters" }, c_source [[ size_t n = LLVMCountParamTypes(${this}); Type ** arr = calloc(n, sizeof(Type *)); lua_createtable(L, n, 0); LLVMGetParamTypes(${this}, arr); for (int i=0; i<n; i++) { Type * ty = arr[i]; obj_type_FunctionType_push(L, ty, 0); lua_rawseti(L, -2, i+1); } free(arr); ]], } } object "IntType" { extends "Type", c_source [[ typedef Type IntType; ]], constructor "int1" { doc [[ Context is optional ]], var_in { "Context *", "ctx?" }, c_source [[ if (${ctx} == NULL) { ${this} = LLVMInt1Type(); } else { ${this} = LLVMInt1TypeInContext(${ctx}); } ]], }, constructor "int8" { doc [[ Context is optional ]], var_in { "Context *", "ctx?" }, c_source [[ if (${ctx} == NULL) { ${this} = LLVMInt8Type(); } else { ${this} = LLVMInt8TypeInContext(${ctx}); } ]], }, constructor "int16" { doc [[ Context is optional ]], var_in { "Context *", "ctx?" }, c_source [[ if (${ctx} == NULL) { ${this} = LLVMInt16Type(); } else { ${this} = LLVMInt16TypeInContext(${ctx}); } ]], }, constructor "int32" { doc [[ Context is optional ]], var_in { "Context *", "ctx?" }, c_source [[ if (${ctx} == NULL) { ${this} = LLVMInt32Type(); } else { ${this} = LLVMInt32TypeInContext(${ctx}); } ]], }, constructor "int64" { doc [[ Context is optional ]], var_in { "Context *", "ctx?" }, c_source [[ if (${ctx} == NULL) { ${this} = LLVMInt64Type(); } else { ${this} = LLVMInt64TypeInContext(${ctx}); } ]], }, constructor "int128" { doc [[ Context is optional ]], var_in { "Context *", "ctx?" }, c_source [[ if (${ctx} == NULL) { ${this} = LLVMInt128Type(); } else { ${this} = LLVMInt128TypeInContext(${ctx}); } ]], }, constructor "int" { doc [[ Context is optional ]], doc [[ Bits: Size of the integer ]], var_in { "unsigned", "bits" }, var_in { "Context *", "ctx?" }, c_source [[ if (${ctx} == NULL) { ${this} = LLVMIntType(${bits}); } else { ${this} = LLVMIntTypeInContext(${ctx}, ${bits}); } ]], }, method "get_int_width" { c_method_call "unsigned" "LLVMGetIntTypeWidth" {} }, } object "FloatType" { extends "Type", c_source [[ typedef Type FloatType; ]], -- Floating Point constructor "half" { doc [[ Context is optional ]], var_in { "Context *", "ctx?" }, c_source [[ if (${ctx} == NULL) { ${this} = LLVMHalfType(); } else { ${this} = LLVMHalfTypeInContext(${ctx}); } ]], }, constructor "float" { doc [[ Context is optional ]], var_in { "Context *", "ctx?" }, c_source [[ if (${ctx} == NULL) { ${this} = LLVMFloatType(); } else { ${this} = LLVMFloatTypeInContext(${ctx}); } ]], }, constructor "double" { doc [[ Context is optional ]], var_in { "Context *", "ctx?" }, c_source [[ if (${ctx} == NULL) { ${this} = LLVMDoubleType(); } else { ${this} = LLVMDoubleTypeInContext(${ctx}); } ]], }, constructor "x86fp80" { doc [[ Context is optional ]], var_in { "Context *", "ctx?" }, c_source [[ if (${ctx} == NULL) { ${this} = LLVMX86FP80Type(); } else { ${this} = LLVMX86FP80TypeInContext(${ctx}); } ]], }, constructor "fp128" { doc [[ Context is optional ]], var_in { "Context *", "ctx?" }, c_source [[ if (${ctx} == NULL) { ${this} = LLVMFP128Type(); } else { ${this} = LLVMFP128TypeInContext(${ctx}); } ]], }, constructor "ppcfp128" { doc [[ Context is optional ]], var_in { "Context *", "ctx?" }, c_source [[ if (${ctx} == NULL) { ${this} = LLVMPPCFP128Type(); } else { ${this} = LLVMPPCFP128TypeInContext(${ctx}); } ]], }, }
mit
smanolache/kong
kong/plugins/runscope/log.lua
5
2874
local cjson = require "cjson" local url = require "socket.url" local _M = {} local HTTPS = "https" local ngx_log = ngx.log local ngx_log_ERR = ngx.ERR local ngx_timer_at = ngx.timer.at local string_format = string.format local string_len = string.len -- Generates http payload . -- @param `method` http method to be used to send data -- @param `parsed_url` contains the host details -- @param `message` Message to be logged -- @return `payload` http payload local function generate_post_payload(parsed_url, access_token, message) local body = cjson.encode(message) local payload = string_format( "%s %s HTTP/1.1\r\nHost: %s\r\nConnection: Keep-Alive\r\nAuthorization: Bearer %s\r\nContent-Type: application/json\r\nContent-Length: %s\r\n\r\n%s", "POST", parsed_url.path, parsed_url.host, access_token, string_len(body), body) return payload end -- Parse host url -- @param `url` host url -- @return `parsed_url` a table with host details like domain name, port, path etc local function parse_url(host_url) local parsed_url = url.parse(host_url) if not parsed_url.port then if parsed_url.scheme == "http" then parsed_url.port = 80 elseif parsed_url.scheme == HTTPS then parsed_url.port = 443 end end if not parsed_url.path then parsed_url.path = "/" end return parsed_url end -- Log to a Http end point. -- @param `premature` -- @param `conf` Configuration table, holds http endpoint details -- @param `message` Message to be logged local function log(premature, conf, message) if premature then return end local ok, err local parsed_url = parse_url(conf.api_endpoint.."/buckets/"..conf.bucket_key.."/messages") local access_token = conf.access_token local host = parsed_url.host local port = tonumber(parsed_url.port) local sock = ngx.socket.tcp() sock:settimeout(conf.timeout) ok, err = sock:connect(host, port) if not ok then ngx_log(ngx_log_ERR, "[runscope] failed to connect to "..host..":"..tostring(port)..": ", err) return end if parsed_url.scheme == HTTPS then local _, err = sock:sslhandshake(true, host, false) if err then ngx_log(ngx_log_ERR, "[runscope] failed to do SSL handshake with "..host..":"..tostring(port)..": ", err) end end ok, err = sock:send(generate_post_payload(parsed_url, access_token, message).."\r\n") if not ok then ngx_log(ngx_log_ERR, "[runscope] failed to send data to "..host..":"..tostring(port)..": ", err) end ok, err = sock:setkeepalive(conf.keepalive) if not ok then ngx_log(ngx_log_ERR, "[runscope] failed to keepalive to "..host..":"..tostring(port)..": ", err) return end end function _M.execute(conf, message) local ok, err = ngx_timer_at(0, log, conf, message) if not ok then ngx_log(ngx_log_ERR, "[runscope] failed to create timer: ", err) end end return _M
apache-2.0
Zero-K-Experiments/Zero-K-Experiments
LuaUI/Widgets/chili_new/skins/default/skin.lua
9
17179
--//============================================================================= --// default local skin = { info = { name = "default", version = "0.1", author = "jK", } } --//============================================================================= --// Render Helpers local function _DrawBorder(x,y,w,h,bt,color1,color2) gl.Color(color1) gl.Vertex(x, y+h) gl.Vertex(x+bt, y+h-bt) gl.Vertex(x, y) gl.Vertex(x+bt, y) gl.Vertex(x+bt, y) gl.Vertex(x+bt, y+bt) gl.Vertex(x+w, y) gl.Vertex(x+w-bt,y+bt) gl.Color(color2) gl.Vertex(x+w-bt,y+bt) gl.Vertex(x+w, y) gl.Vertex(x+w-bt,y+h) gl.Vertex(x+w, y+h) gl.Vertex(x+w-bt,y+h-bt) gl.Vertex(x+w-bt,y+h) gl.Vertex(x+bt, y+h-bt) gl.Vertex(x+bt, y+h) gl.Vertex(x, y+h) end local function _DrawCheck(rect) local x,y,w,h = rect[1],rect[2],rect[3],rect[4] gl.Vertex(x+w*0.25, y+h*0.5) gl.Vertex(x+w*0.125,y+h*0.625) gl.Vertex(x+w*0.375,y+h*0.625) gl.Vertex(x+w*0.375,y+h*0.875) gl.Vertex(x+w*0.75, y+h*0.25) gl.Vertex(x+w*0.875,y+h*0.375) end local function _DrawHLine(x,y,w,bt,color1,color2) gl.Color(color1) gl.Vertex(x, y) gl.Vertex(x, y+bt) gl.Vertex(x+w, y) gl.Vertex(x+w, y+bt) gl.Color(color2) gl.Vertex(x+w, y+bt) gl.Vertex(x+w, y+2*bt) gl.Vertex(x, y+bt) gl.Vertex(x, y+2*bt) end local function _DrawVLine(x,y,h,bt,color1,color2) gl.Color(color1) gl.Vertex(x, y) gl.Vertex(x+bt, y) gl.Vertex(x, y+h) gl.Vertex(x+bt, y+h) gl.Color(color2) gl.Vertex(x+bt, y+h) gl.Vertex(x+2*bt,y+h) gl.Vertex(x+bt, y) gl.Vertex(x+2*bt,y) end local function _DrawDragGrip(obj) local x = obj.borderThickness + 1 local y = obj.borderThickness + 1 local w = obj.dragGripSize[1] local h = obj.dragGripSize[2] gl.Color(0.8,0.8,0.8,0.9) gl.Vertex(x, y + h*0.5) gl.Vertex(x + w*0.5, y) gl.Vertex(x + w*0.5, y + h*0.5) gl.Color(0.3,0.3,0.3,0.9) gl.Vertex(x + w*0.5, y + h*0.5) gl.Vertex(x + w*0.5, y) gl.Vertex(x + w, y + h*0.5) gl.Vertex(x + w*0.5, y + h) gl.Vertex(x, y + h*0.5) gl.Vertex(x + w*0.5, y + h*0.5) gl.Color(0.1,0.1,0.1,0.9) gl.Vertex(x + w*0.5, y + h) gl.Vertex(x + w*0.5, y + h*0.5) gl.Vertex(x + w, y + h*0.5) end local function _DrawResizeGrip(obj) local resizable = obj.resizable if IsTweakMode() then resizable = resizable or obj.tweakResizable end if (resizable) then local x = obj.width - obj.padding[3] --obj.borderThickness - 1 local y = obj.height - obj.padding[4] --obj.borderThickness - 1 local w = obj.resizeGripSize[1] local h = obj.resizeGripSize[2] x = x-1 y = y-1 gl.Color(1,1,1,0.2) gl.Vertex(x - w, y) gl.Vertex(x, y - h) gl.Vertex(x - math.floor(w*0.66), y) gl.Vertex(x, y - math.floor(h*0.66)) gl.Vertex(x - math.floor(w*0.33), y) gl.Vertex(x, y - math.floor(h*0.33)) x = x+1 y = y+1 gl.Color(0.1, 0.1, 0.1, 0.9) gl.Vertex(x - w, y) gl.Vertex(x, y - h) gl.Vertex(x - math.floor(w*0.66), y) gl.Vertex(x, y - math.floor(h*0.66)) gl.Vertex(x - math.floor(w*0.33), y) gl.Vertex(x, y - math.floor(h*0.33)) end end --//============================================================================= --// function DrawBorder(obj,state) local x = 0 local y = 0 local w = obj.width local h = obj.height local bt = obj.borderThickness gl.Color((state.pressed and obj.borderColor2) or obj.borderColor) gl.Vertex(x, y+h) gl.Vertex(x+bt, y+h-bt) gl.Vertex(x, y) gl.Vertex(x+bt, y) gl.Vertex(x+bt, y) gl.Vertex(x+bt, y+bt) gl.Vertex(x+w, y) gl.Vertex(x+w-bt,y+bt) gl.Color((state.pressed and obj.borderColor) or obj.borderColor2) gl.Vertex(x+w-bt,y+bt) gl.Vertex(x+w, y) gl.Vertex(x+w-bt,y+h) gl.Vertex(x+w, y+h) gl.Vertex(x+w-bt,y+h-bt) gl.Vertex(x+w-bt,y+h) gl.Vertex(x+bt, y+h-bt) gl.Vertex(x+bt, y+h) gl.Vertex(x, y+h) end function DrawBackground(obj) gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawBackground, obj) end function _DrawScrollbar(obj, type, x,y,w,h, pos, visiblePercent, state) gl.Color(obj.backgroundColor) gl.Rect(x,y,x+w,y+h) if (type=='horizontal') then local gripx,gripw = x+w*pos, w*visiblePercent gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawBorder, gripx,y,gripw,h, 1, obj.borderColor, obj.borderColor2) else local gripy,griph = y+h*pos, h*visiblePercent gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawBorder, x,gripy,w,griph, 1, obj.borderColor, obj.borderColor2) end end function _DrawBackground(obj) local x = 0 local y = 0 local w = obj.width local h = obj.height gl.Color(obj.backgroundColor) gl.Vertex(x, y) gl.Vertex(x, y+h) gl.Vertex(x+w, y) gl.Vertex(x+w, y+h) end function _DrawTabBackground(obj) local x = 0 local y = 0 local w = obj.width local h = obj.height local bt= 2 gl.Color(obj.backgroundColor) gl.Vertex(x+bt, y+bt) gl.Vertex(x+bt, y+h) gl.Vertex(x+w-bt, y+bt) gl.Vertex(x+w-bt, y+h) end local function _DrawTabBorder(obj, state) local x = 0 local y = 0 local w = obj.width local h = obj.height local bt= 2 gl.Color(obj.borderColor) gl.Vertex(x, y+h) gl.Vertex(x+bt, y+h) gl.Vertex(x, y+bt) gl.Vertex(x+bt, y+bt) gl.Vertex(x+bt, y) gl.Vertex(x+w-bt, y+bt) gl.Vertex(x+w-bt, y) gl.Color(obj.borderColor2) gl.Vertex(x+w-bt, y) gl.Vertex(x+w-bt, y+bt) gl.Vertex(x+w, y+bt) gl.Vertex(x+w-bt, y+h) gl.Vertex(x+w, y+h) end --//============================================================================= --// Control Renderer function DrawWindow(obj) gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawBackground, obj, obj.state) gl.BeginEnd(GL.TRIANGLE_STRIP, DrawBorder, obj, obj.state) end function DrawButton(obj) gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawBackground, obj, obj.state) gl.BeginEnd(GL.TRIANGLE_STRIP, DrawBorder, obj, obj.state) if (obj.caption) then local w = obj.width local h = obj.height obj.font:Print(obj.caption, w*0.5, h*0.5, "center", "center") end end function _DrawTriangle(obj) local w = obj.width local x = 0 local y = 0 local w = obj.width local h = obj.height local bt = obj.borderThickness local tw = 10 gl.Color(obj.focusColor) gl.Vertex(x + w - tw*1.5, y + (h - tw) * 0.5) gl.Vertex(x + w - tw*0.5, y + (h - tw) * 0.5) gl.Vertex(x + w - tw, y + tw + (h - tw) * 0.5) end function DrawComboBox(obj) DrawButton(obj) --draw triangle that indicates this is a combobox gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTriangle, obj) end function DrawCursor(x, y, w, h) gl.Vertex(x, y) gl.Vertex(x, y + h) gl.Vertex(x + w, y) gl.Vertex(x + w, y + h) end function DrawEditBox(obj) gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawBackground, obj, obj.state) if obj.state.focused then gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawBorder, 0, 0, obj.width, obj.height, obj.borderThickness, obj.focusColor, obj.focusColor) else gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawBorder, 0, 0, obj.width, obj.height, obj.borderThickness, obj.borderColor2, obj.borderColor) end if (obj.text) then if (obj.offset > obj.cursor) then obj.offset = obj.cursor end local clientX,clientY,clientWidth,clientHeight = unpack4(obj.clientArea) --// make cursor pos always visible (when text is longer than editbox!) repeat local txt = obj.text:sub(obj.offset, obj.cursor) local wt = obj.font:GetTextWidth(txt) if (wt <= clientWidth) then break end if (obj.offset >= obj.cursor) then break end obj.offset = obj.offset + 1 until (false) local txt = obj.text:sub(obj.offset) --// strip part at the end that exceeds the editbox local lsize = math.max(0, obj.font:WrapText(txt, clientWidth, clientHeight):len() - 3) -- find a good start (3 dots at end if stripped) while (lsize <= txt:len()) do local wt = obj.font:GetTextWidth(txt:sub(1, lsize)) if (wt > clientWidth) then break end lsize = lsize + 1 end txt = txt:sub(1, lsize - 1) gl.Color(1,1,1,1) obj.font:DrawInBox(txt, clientX, clientY, clientWidth, clientHeight, obj.align, obj.valign) if obj.state.focused then local cursorTxt = obj.text:sub(obj.offset, obj.cursor - 1) local cursorX = obj.font:GetTextWidth(cursorTxt) local dt = Spring.DiffTimers(Spring.GetTimer(), obj._interactedTime) local as = math.sin(dt * 8); local ac = math.cos(dt * 8); if (as < 0) then as = 0 end if (ac < 0) then ac = 0 end local alpha = as + ac if (alpha > 1) then alpha = 1 end alpha = 0.8 * alpha local cc = obj.cursorColor gl.Color(cc[1], cc[2], cc[3], cc[4] * alpha) gl.BeginEnd(GL.TRIANGLE_STRIP, DrawCursor, cursorX + clientX - 1, clientY, 3, clientHeight) end end end function DrawPanel(obj) gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawBackground, obj, obj.state) gl.BeginEnd(GL.TRIANGLE_STRIP, DrawBorder, obj, obj.state) end function DrawItemBkGnd(obj,x,y,w,h,state) if (state=="selected") then gl.Color(0.15,0.15,0.9,1) else gl.Color({0.8, 0.8, 1, 0.45}) end gl.Rect(x,y,x+w,y+h) gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawBorder, x,y,w,h, 1, obj.borderColor, obj.borderColor2) end function DrawScrollPanel(obj) local clientX,clientY,clientWidth,clientHeight = unpack4(obj.clientArea) local contX,contY,contWidth,contHeight = unpack4(obj.contentArea) gl.PushMatrix() gl.Translate(clientX, clientY,0) if obj._vscrollbar and (contHeight > 0) then local height = (not obj._hscrollbar and obj.height) or (obj.height - obj.scrollbarSize) _DrawScrollbar(obj, 'vertical', obj.width - obj.scrollbarSize, 0, obj.scrollbarSize, height, obj.scrollPosY/contHeight, clientHeight/contHeight) end if obj._hscrollbar and (contWidth > 0) then local width = (not obj._vscrollbar and obj.width) or (obj.width - obj.scrollbarSize) _DrawScrollbar(obj, 'horizontal', 0, obj.height - obj.scrollbarSize, width, obj.scrollbarSize, obj.scrollPosX/contWidth, clientWidth/contWidth) end gl.PopMatrix() end function DrawTrackbar(obj) local percent = (obj.value-obj.min)/(obj.max-obj.min) local w = obj.width local h = obj.height gl.Color(0,0,0,1) gl.Rect(0,h*0.5,w,h*0.5+1) local vc = h*0.5 --//verticale center local pos = percent*w gl.Rect(pos-2,vc-h*0.5,pos+2,vc+h*0.5) end function DrawCheckbox(obj) local vc = obj.height*0.5 --//verticale center local tx = 0 local ty = vc gl.PushMatrix() gl.Translate(0,0,0) obj.font:Print(obj.caption, tx, ty, "left", "center") local box = obj.boxsize local rect = {obj.width-box,obj.height*0.5-box*0.5,box,box} gl.Color(obj.backgroundColor) gl.Rect(rect[1]+1,rect[2]+1,rect[1]+1+rect[3]-2,rect[2]+1+rect[4]-2) gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawBorder, rect[1],rect[2],rect[3],rect[4], 1, obj.borderColor, obj.borderColor2) if (obj.state.checked) then gl.BeginEnd(GL.TRIANGLE_STRIP,_DrawCheck,rect) end gl.PopMatrix() end function DrawColorbars(obj) gl.PushMatrix() gl.Translate(0,0,0) local barswidth = obj.width - (obj.height + 4) local color = obj.color local step = obj.height/7 --bars local rX1,rY1,rX2,rY2 = 0,0*step,color[1]*barswidth,1*step local gX1,gY1,gX2,gY2 = 0,2*step,color[2]*barswidth,3*step local bX1,bY1,bX2,bY2 = 0,4*step,color[3]*barswidth,5*step local aX1,aY1,aX2,aY2 = 0,6*step,(color[4] or 1)*barswidth,7*step gl.Color(1,0,0,1) gl.Rect(rX1,rY1,rX2,rY2) gl.Color(0,1,0,1) gl.Rect(gX1,gY1,gX2,gY2) gl.Color(0,0,1,1) gl.Rect(bX1,bY1,bX2,bY2) gl.Color(1,1,1,1) gl.Rect(aX1,aY1,aX2,aY2) gl.Color(color) gl.Rect(barswidth + 2,obj.height,obj.width - 2,0) gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawBorder, barswidth + 2,0,obj.width - barswidth - 4,obj.height, 1, obj.borderColor, obj.borderColor2) gl.PopMatrix() end function DrawLine(self) if (self.style:find("^v")) then gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawVLine, self.width * 0.5, 0, self.height, 1, self.borderColor, self.borderColor2) else gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawHLine, 0, self.height * 0.5, self.width, 1, self.borderColor, self.borderColor2) end end function DrawDragGrip(obj) gl.BeginEnd(GL.TRIANGLES, _DrawDragGrip, obj) end function DrawResizeGrip(obj) gl.BeginEnd(GL.LINES, _DrawResizeGrip, obj) end local darkBlue = {0.0,0.0,0.6,0.9} function DrawTreeviewNode(self) if CompareLinks(self.treeview.selected,self) then local x = self.clientArea[1] local y = 0 local w = self.children[1].width local h = self.clientArea[2] + self.children[1].height gl.Color(0.1,0.1,1,0.55) gl.Rect(0,0,w,h) gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawBorder, 0,0,w,h, 1, darkBlue, darkBlue) end end local function _DrawLineV(x, y1, y2, width, next_func, ...) gl.Vertex(x-width*0.5, y1) gl.Vertex(x+width*0.5, y1) gl.Vertex(x-width*0.5, y2) gl.Vertex(x+width*0.5, y1) gl.Vertex(x-width*0.5, y2) gl.Vertex(x+width*0.5, y2) if (next_func) then next_func(...) end end local function _DrawLineH(x1, x2, y, width, next_func, ...) gl.Vertex(x1, y-width*0.5) gl.Vertex(x1, y+width*0.5) gl.Vertex(x2, y-width*0.5) gl.Vertex(x1, y+width*0.5) gl.Vertex(x2, y-width*0.5) gl.Vertex(x2, y+width*0.5) if (next_func) then next_func(...) end end function DrawTreeviewNodeTree(self) local x1 = math.ceil(self.padding[1]*0.5) local x2 = self.padding[1] local y1 = 0 local y2 = self.height local y3 = self.padding[2] + math.ceil(self.children[1].height*0.5) if (self.parent)and(CompareLinks(self,self.parent.nodes[#self.parent.nodes])) then y2 = y3 end gl.Color(self.treeview.treeColor) gl.BeginEnd(GL.TRIANGLES, _DrawLineV, x1-0.5, y1, y2, 1, _DrawLineH, x1, x2, y3-0.5, 1) if (not self.nodes[1]) then return end gl.Color(1,1,1,1) local image = self.ImageExpanded or self.treeview.ImageExpanded if (not self.expanded) then image = self.ImageCollapsed or self.treeview.ImageCollapsed end TextureHandler.LoadTexture(0, image, self) local texInfo = gl.TextureInfo(image) or {xsize=1, ysize=1} local tw,th = texInfo.xsize, texInfo.ysize _DrawTextureAspect(0,0,math.ceil(self.padding[1]),math.ceil(self.children[1].height) ,tw,th) gl.Texture(0,false) end --//============================================================================= --// function DrawTabBarItem(self) gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTabBackground, self, self.state) gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTabBorder, self, self.state) if self.caption then local w = self.width local h = self.height local bt= 2 local oldColor = self.font.color if self.state.selected then self.font:SetColor(self.focusColor) end self.font:Print(self.caption, w*0.5, bt+h*0.5, "center", "center") if self.state.selected then self.font:SetColor(oldColor) end end end --//============================================================================= --// skin.general = { --font = "FreeSansBold.ttf", textColor = {0,0,0,1}, font = { outlineColor = {0,0,0,0.5}, outline = false, size = 13, }, --padding = {5, 5, 5, 5}, --// padding: left, top, right, bottom borderThickness = 1.5, borderColor = {1,1,1,0.6}, borderColor2 = {0,0,0,0.8}, backgroundColor = {0.8, 0.8, 1, 0.4}, } skin.colorbars = { DrawControl = DrawColorbars, } skin.icons = { imageplaceholder = ":cl:placeholder.png", } skin.image = { } skin.button = { DrawControl = DrawButton, } skin.checkbox = { DrawControl = DrawCheckbox, } skin.imagelistview = { imageFolder = "folder.png", imageFolderUp = "folder_up.png", DrawItemBackground = DrawItemBkGnd, } --[[ skin.imagelistviewitem = { padding = {12, 12, 12, 12}, DrawSelectionItemBkGnd = DrawSelectionItemBkGnd, } --]] skin.panel = { DrawControl = DrawPanel, } skin.scrollpanel = { DrawControl = DrawScrollPanel, } skin.trackbar = { DrawControl = DrawTrackbar, } skin.treeview = { ImageExpanded = ":cl:treeview_node_expanded.png", ImageCollapsed = ":cl:treeview_node_collapsed.png", treeColor = {0,0,0,0.6}, minItemHeight = 16, DrawNode = DrawTreeviewNode, DrawNodeTree = DrawTreeviewNodeTree, } skin.window = { DrawControl = DrawWindow, DrawDragGrip = DrawDragGrip, DrawResizeGrip = DrawResizeGrip, hitpadding = {4, 4, 4, 4}, boxes = { resize = {-21, -21, -10, -10}, drag = {0, 0, "100%", 10}, }, NCHitTest = NCHitTestWithPadding, NCMouseDown = WindowNCMouseDown, NCMouseDownPostChildren = WindowNCMouseDownPostChildren, } skin.editbox = { DrawControl = DrawEditBox, backgroundColor = {1, 1, 1, 0.9}, } skin.combobox = { DrawControl = DrawComboBox, } skin.line = { DrawControl = DrawLine, } skin.tabbaritem = { borderColor = {1.0, 1.0, 1.0, 0.8}, borderColor2 = {0.0, 0.0, 0.0, 0.8}, backgroundColor = {0.8, 0.8, 1.0, 0.7}, textColor = {0.1, 0.1, 0.1, 1.0}, DrawControl = DrawTabBarItem, } skin.control = skin.general --//============================================================================= --// return skin
gpl-2.0
Scavenge/darkstar
scripts/globals/spells/sleep.lua
27
1086
----------------------------------------- -- Spell: Sleep I ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local duration = 60; if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then duration = duration * 2; end caster:delStatusEffect(EFFECT_SABOTEUR); local pINT = caster:getStat(MOD_INT); local mINT = target:getStat(MOD_INT); local dINT = (pINT - mINT); local resm = applyResistanceEffect(caster,spell,target,dINT,ENFEEBLING_MAGIC_SKILL,0,EFFECT_SLEEP_I); if (resm < 0.5) then spell:setMsg(85);--resist message return EFFECT_SLEEP_I; end duration = duration * resm; if (target:addStatusEffect(EFFECT_SLEEP_I,1,0,duration)) then spell:setMsg(236); else spell:setMsg(75); end return EFFECT_SLEEP_I; end;
gpl-3.0
Brenin/PJ-3100
Working Launchers/Games/Stepmania/StepMania 5/Themes/_fallback/Scripts/02 StageMods.lua
1
3876
function AreStagePlayerModsForced() return GAMESTATE:IsAnExtraStage() or (GAMESTATE:GetPlayMode() == "PlayMode_Oni") end function AreStageSongModsForced() local pm = GAMESTATE:GetPlayMode() local bOni = pm == "PlayMode_Oni" local bBattle = pm == "PlayMode_Battle" local bRave = pm == "PlayMode_Rave" return GAMESTATE:IsAnExtraStage() or bOni or bBattle or bRave end function ScreenSelectMusic:setupmusicstagemods() Trace( "setupmusicstagemods" ) local pm = GAMESTATE:GetPlayMode() if pm == "PlayMode_Battle" or pm == "PlayMode_Rave" then local so = GAMESTATE:GetDefaultSongOptions() GAMESTATE:SetSongOptions( "ModsLevel_Stage", so ) MESSAGEMAN:Broadcast( "SongOptionsChanged" ) elseif GAMESTATE:IsAnExtraStage() then if GAMESTATE:GetPreferredSongGroup() == "---Group All---" then local song = GAMESTATE:GetCurrentSong() GAMESTATE:SetPreferredSongGroup( song:GetGroupName() ) end local bExtra2 = GAMESTATE:IsExtraStage2() local style = GAMESTATE:GetCurrentStyle() local song, steps = SONGMAN:GetExtraStageInfo( bExtra2, style ) local po, so if bExtra2 then po = THEME:GetMetric("SongManager","OMESPlayerModifiers") so = THEME:GetMetric("SongManager","OMESStageModifiers") else po = THEME:GetMetric("SongManager","ExtraStagePlayerModifiers") so = THEME:GetMetric("SongManager","ExtraStageStageModifiers") end local difficulty = steps:GetDifficulty() local Reverse = PlayerNumber:Reverse() GAMESTATE:SetCurrentSong( song ) GAMESTATE:SetPreferredSong( song ) for pn in ivalues(GAMESTATE:GetHumanPlayers()) do GAMESTATE:SetCurrentSteps( pn, steps ) GAMESTATE:GetPlayerState(pn):SetPlayerOptions( "ModsLevel_Stage", po ) GAMESTATE:SetPreferredDifficulty( pn, difficulty ) MESSAGEMAN:Broadcast( "PlayerOptionsChanged", {PlayerNumber = pn} ) end GAMESTATE:SetSongOptions( "ModsLevel_Stage", so ) MESSAGEMAN:Broadcast( "SongOptionsChanged" ) end return self end function ScreenSelectMusic:setupcoursestagemods() local mode = GAMESTATE:GetPlayMode() if mode == "PlayMode_Oni" then local po = "clearall,default" -- Let SSMusic set battery. -- local so = "failimmediate,battery" local so = "failimmediate" local Reverse = PlayerNumber:Reverse() for pn in ivalues(GAMESTATE:GetHumanPlayers()) do GAMESTATE:GetPlayerState(pn):SetPlayerOptions( "ModsLevel_Stage", po ) MESSAGEMAN:Broadcast( "PlayerOptionsChanged", {PlayerNumber = pn} ) end GAMESTATE:SetSongOptions( "ModsLevel_Stage", so ) MESSAGEMAN:Broadcast( "SongOptionsChanged" ) end return self end -- (c) 2006-2007 Steve Checkoway -- 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, and/or sell copies of the Software, and to permit persons to -- whom the Software is furnished to do so, provided that the above -- copyright notice(s) and this permission notice appear in all copies of -- the Software and that both the above copyright notice(s) and this -- permission notice appear in supporting documentation. -- -- 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 OF -- THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS -- INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT -- OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS -- OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -- PERFORMANCE OF THIS SOFTWARE.
mit
zozaiq/DEV_ZOZO
libs/XMLElement.lua
569
4025
-- Copyright 2009 Leo Ponomarev. Distributed under the BSD Licence. -- updated for module-free world of lua 5.3 on April 2 2015 -- Not documented at all, but not interesting enough to warrant documentation anyway. local setmetatable, pairs, ipairs, type, getmetatable, tostring, error = setmetatable, pairs, ipairs, type, getmetatable, tostring, error local table, string = table, string local XMLElement={} local mt XMLElement.new = function(lom) return setmetatable({lom=lom or {}}, mt) end local function filter(filtery_thing, lom) filtery_thing=filtery_thing or '*' for i, thing in ipairs(type(filtery_thing)=='table' and filtery_thing or {filtery_thing}) do if thing == "text()" then if type(lom)=='string' then return true end elseif thing == '*' then if type(lom)=='table' then return true end else if type(lom)=='table' and string.lower(lom.tag)==string.lower(thing) then return true end end end return nil end mt ={ __index = { getAttr = function(self, attribute) if type(attribute) ~= "string" then return nil, "attribute name must be a string." end return self.lom.attr[attribute] end, setAttr = function(self, attribute, value) if type(attribute) ~= "string" then return nil, "attribute name must be a string." end if value == nil then return self:removeAttr(attribute) end self.lom.attr[attribute]=tostring(value) return self end, removeAttr = function(self, attribute) local lom = self.lom if type(attribute) ~= "string" then return nil, "attribute name must be a string." end if not lom.attr[attribute] then return self end for i,v in ipairs(lom.attr) do if v == attribute then table.remove(lom.attr, i) break end end lom.attr[attribute]=nil end, removeAllAttributes = function(self) local attr = self.lom.attr for i, v in pairs(self.lom.attr) do attr[i]=nil end return self end, getAttributes = function(self) local attr = {} for i, v in ipairs(self.lom.attr) do table.insert(attr,v) end return attr end, getXML = function(self) local function getXML(lom) local attr, inner = {}, {} for i, attribute in ipairs(lom.attr) do table.insert(attr, string.format('%s=%q', attribute, lom.attr[attribute])) end for i, v in ipairs(lom) do local t = type(v) if t == "string" then table.insert(inner, v) elseif t == "table" then table.insert(inner, getXML(v)) else error("oh shit") end end local tagcontents = table.concat(inner) local attrstring = #attr>0 and (" " .. table.concat(attr, " ")) or "" if #tagcontents>0 then return string.format("<%s%s>%s</%s>", lom.tag, attrstring, tagcontents, lom.tag) else return string.format("<%s%s />", lom.tag, attrstring) end end return getXML(self.lom) end, getText = function(self) local function getText(lom) local inner = {} for i, v in ipairs(lom) do local t = type(v) if t == "string" then table.insert(inner, v) elseif t == "table" then table.insert(inner, getText(v)) end end return table.concat(inner) end return getText(self.lom) end, getChildren = function(self, filter_thing) local res = {} for i, node in ipairs(self.lom) do if filter(filter_thing, node) then table.insert(res, type(node)=='table' and XMLElement.new(node) or node) end end return res end, getDescendants = function(self, filter_thing) local res = {} local function descendants(lom) for i, child in ipairs(lom) do if filter(filter_thing, child) then table.insert(res, type(child)=='table' and XMLElement.new(child) or child) if type(child)=='table' then descendants(child) end end end end descendants(self.lom) return res end, getChild = function(self, filter_thing) for i, node in ipairs(self.lom) do if filter(filter_thing, node) then return type(node)=='table' and XMLElement.new(node) or node end end end, getTag = function(self) return self.lom.tag end }} return XMLElement
gpl-2.0
Scavenge/darkstar
scripts/globals/items/cluster_of_paprika.lua
12
1278
----------------------------------------- -- ID: 5740 -- Item: Cluster of Paprika -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility 1 -- Vitality -3 -- Defense -1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5740); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, -3); target:addMod(MOD_DEF, -1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, -3); target:delMod(MOD_DEF, -1); end;
gpl-3.0
Kyklas/luci-proto-hso
modules/admin-full/luasrc/model/cbi/admin_status/processes.lua
85
1448
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- f = SimpleForm("processes", translate("Processes"), translate("This list gives an overview over currently running system processes and their status.")) f.reset = false f.submit = false t = f:section(Table, luci.sys.process.list()) t:option(DummyValue, "PID", translate("PID")) t:option(DummyValue, "USER", translate("Owner")) t:option(DummyValue, "COMMAND", translate("Command")) t:option(DummyValue, "%CPU", translate("CPU usage (%)")) t:option(DummyValue, "%MEM", translate("Memory usage (%)")) hup = t:option(Button, "_hup", translate("Hang Up")) hup.inputstyle = "reload" function hup.write(self, section) null, self.tag_error[section] = luci.sys.process.signal(section, 1) end term = t:option(Button, "_term", translate("Terminate")) term.inputstyle = "remove" function term.write(self, section) null, self.tag_error[section] = luci.sys.process.signal(section, 15) end kill = t:option(Button, "_kill", translate("Kill")) kill.inputstyle = "reset" function kill.write(self, section) null, self.tag_error[section] = luci.sys.process.signal(section, 9) end return f
apache-2.0
Scavenge/darkstar
scripts/zones/Sauromugue_Champaign/npcs/qm4.lua
14
2471
----------------------------------- -- Area: Sauromugue Champaign -- NPC: qm4 (???) (Tower 4) -- Involved in Quest: THF AF "As Thick As Thieves" -- @pos 129.587 -0.600 -235.525 120 ----------------------------------- package.loaded["scripts/zones/Sauromugue_Champaign/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Sauromugue_Champaign/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local thickAsThievesGrapplingCS = player:getVar("thickAsThievesGrapplingCS"); if (thickAsThievesGrapplingCS >= 2 and thickAsThievesGrapplingCS <= 7) then if (trade:hasItemQty(17474,1) and trade:getItemCount() == 1) then -- Trade grapel player:messageSpecial(THF_AF_WALL_OFFSET+3,0,17474); -- You cannot get a decent grip on the wall using the [Grapnel]. end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local thickAsThieves = player:getQuestStatus(WINDURST,AS_THICK_AS_THIEVES); local thickAsThievesGrapplingCS = player:getVar("thickAsThievesGrapplingCS"); if (thickAsThieves == QUEST_ACCEPTED) then if (thickAsThievesGrapplingCS == 4) then player:messageSpecial(THF_AF_MOB); GetMobByID(17269107):setSpawn(122,0,-230); SpawnMob(17269107):updateClaim(player); -- Climbpix Highrise elseif (thickAsThievesGrapplingCS == 0 or thickAsThievesGrapplingCS == 1 or thickAsThievesGrapplingCS == 2 or thickAsThievesGrapplingCS == 3 or thickAsThievesGrapplingCS == 5 or thickAsThievesGrapplingCS == 6 or thickAsThievesGrapplingCS == 7) then player:messageSpecial(THF_AF_WALL_OFFSET); end 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
Scavenge/darkstar
scripts/zones/Port_Bastok/npcs/Qiji.lua
29
2077
----------------------------------- -- Area: Port Bastok -- NPC: Qiji -- Starts & Ends Quest: Forever to Hold ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(12497,1) and trade:getItemCount() == 1) then -- Trade Brass Hairpin if (player:getVar("ForevertoHold_Event") == 1) then player:startEvent(0x7c); player:setVar("ForevertoHold_Event",2); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) ForevertoHold = player:getQuestStatus(BASTOK,FOREVER_TO_HOLD); if (player:getFameLevel(BASTOK) >= 2 and ForevertoHold == QUEST_AVAILABLE) then player:startEvent(0x7B); elseif (ForevertoHold == QUEST_ACCEPTED and player:getVar("ForevertoHold_Event") == 3) then player:startEvent(0x7e); else player:startEvent(0x21); 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 == 0x7b) then player:addQuest(BASTOK,FOREVER_TO_HOLD); player:setVar("ForevertoHold_Event",1); elseif (csid == 0x7e) then player:addTitle(QIJIS_FRIEND); player:addGil(GIL_RATE*300); player:messageSpecial(GIL_OBTAINED,GIL_RATE*300); player:addFame(BASTOK,80); player:completeQuest(BASTOK,FOREVER_TO_HOLD); end end;
gpl-3.0
BlockMen/minetest_next
mods/beds/spawns.lua
10
1365
local world_path = minetest.get_worldpath() local org_file = world_path .. "/beds_spawns" local file = world_path .. "/beds_spawns" local bkwd = false -- check for PA's beds mod spawns local cf = io.open(world_path .. "/beds_player_spawns", "r") if cf ~= nil then io.close(cf) file = world_path .. "/beds_player_spawns" bkwd = true end function beds.read_spawns() local spawns = beds.spawn local input = io.open(file, "r") if input and not bkwd then repeat local x = input:read("*n") if x == nil then break end local y = input:read("*n") local z = input:read("*n") local name = input:read("*l") spawns[name:sub(2)] = {x = x, y = y, z = z} until input:read(0) == nil io.close(input) elseif input and bkwd then beds.spawn = minetest.deserialize(input:read("*all")) input:close() beds.save_spawns() os.rename(file, file .. ".backup") file = org_file else spawns = {} end end function beds.save_spawns() if not beds.spawn then return end local output = io.open(org_file, "w") for i, v in pairs(beds.spawn) do output:write(v.x.." "..v.y.." "..v.z.." "..i.."\n") end io.close(output) end function beds.set_spawns() for name,_ in pairs(beds.player) do local player = minetest.get_player_by_name(name) local p = player:getpos() beds.spawn[name] = p end beds.save_spawns() end
gpl-3.0
Zero-K-Experiments/Zero-K-Experiments
LuaRules/Gadgets/unit_nanoframe_death.lua
2
4743
-- $Id: unit_terraform.lua 3299 2008-11-25 07:25:57Z google frog $ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Nano Frame Death Handeling", desc = "Makes nanoframes explode if above X% completetion and makes dying nanoframes leave wrecks.", author = "Google Frog", date = "Mar 29, 2009", license = "GNU GPL, v2 or later", layer = -10, enabled = true } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if (not gadgetHandler:IsSyncedCode()) then return false -- no unsynced code end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Speedups local spSetUnitHealth = Spring.SetUnitHealth local spGetUnitHealth = Spring.GetUnitHealth local spGetUnitPosition = Spring.GetUnitPosition local spGetUnitBuildFacing = Spring.GetUnitBuildFacing local spCreateUnit = Spring.CreateUnit local spDestroyUnit = Spring.DestroyUnit local spGetUnitSelfDTime = Spring.GetUnitSelfDTime local spSetFeatureResurrect = Spring.SetFeatureResurrect local spSetFeatureHealth = Spring.SetFeatureHealth local spSetFeatureReclaim = Spring.SetFeatureReclaim local spGetGroundHeight = Spring.GetGroundHeight local spCreateFeature = Spring.CreateFeature local spValidUnitID = Spring.ValidUnitID -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local unitFromFactory = {} local isAFactory = {} function gadget:UnitCreated(unitID,unitDefID,_,builderID) local ud = UnitDefs[unitDefID] if ud and ud.isFactory then isAFactory[unitID] = true end if builderID and isAFactory[builderID] then unitFromFactory[unitID] = true end end local function ScrapUnit(unitID, unitDefID, team, progress, face) if (unitDefID and UnitDefs[unitDefID] and UnitDefs[unitDefID].wreckName and FeatureDefNames[UnitDefs[unitDefID].wreckName]) then local wreck = FeatureDefNames[UnitDefs[unitDefID].wreckName].id if (wreck and FeatureDefs[wreck]) then local nextWreck = FeatureDefs[wreck].deathFeatureID if nextWreck and FeatureDefs[nextWreck] then wreck = FeatureDefs[wreck].deathFeatureID if progress < 0.5 then nextWreck = FeatureDefs[wreck].deathFeatureID if nextWreck and FeatureDefs[nextWreck] then wreck = FeatureDefs[wreck].deathFeatureID progress = progress * 2 end end end local x, _, z = spGetUnitPosition(unitID) local y = spGetGroundHeight(x, z) if (progress == 0) then progress = 0.001 end local allyTeam = select(6, Spring.GetTeamInfo(team)) local featureID = spCreateFeature(wreck, x, y, z, face, allyTeam) if featureID then Spring.TransferFeature(featureID, team) local maxHealth = FeatureDefs[wreck].maxHealth spSetFeatureReclaim(featureID, progress) --spSetFeatureResurrect(featureID, UnitDefs[unitDefID].name, face) spSetFeatureHealth(featureID, progress*maxHealth) else Spring.Echo("No featureID", wreck) end end end end function gadget:UnitDestroyed(unitID, unitDefID, unitTeam) local health, _,_,_,progress = spGetUnitHealth(unitID) if (progress == 1) or (health > 0 and unitFromFactory[unitID]) or GG.wasMorphedTo[unitID] then isAFactory[unitID] = nil unitFromFactory[unitID] = nil return end local ud = UnitDefs[unitDefID] local face = (spGetUnitBuildFacing(unitID) or 1) if (progress > 0.8) then local explodeAs = ud.deathExplosion if explodeAs then local wd = WeaponDefNames[explodeAs] if wd then local _,_,_,x,y,z = spGetUnitPosition(unitID, true) local projId = Spring.SpawnProjectile(wd.id, { pos = {x,y,z}, ttl = 1, }) --Spring.SetProjectileCollision(projId) <- in case ttl = 1 does not work end end end if (progress > 0.05 and not Spring.GetUnitRulesParam(unitID, "noWreck")) then ScrapUnit(unitID, unitDefID, unitTeam, progress, face) end isAFactory[unitID] = nil unitFromFactory[unitID] = nil end function gadget:Initialize() for _, unitID in ipairs(Spring.GetAllUnits()) do local unitDefID = Spring.GetUnitDefID(unitID) local team = Spring.GetUnitTeam(unitID) gadget:UnitCreated(unitID, unitDefID, team) end GG.wasMorphedTo = GG.wasMorphedTo or {} end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
Scavenge/darkstar
scripts/globals/mobskills/Head_Snatch.lua
37
1058
--------------------------------------------- -- Head Snatch -- -- Description: Grabs a single target's head. -- Type: Physical -- Utsusemi/Blink absorb: Ignores shadows -- Range: Melee -- Notes: Only used by Gurfurlur the Menacing. Reduces HP to 10%. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if(mob:getFamily() == 316) then local mobSkin = mob:getModelId(); if (mobSkin == 1867) then return 0; else return 1; end end return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
Scavenge/darkstar
scripts/zones/The_Garden_of_RuHmet/npcs/HomePoint#1.lua
14
1284
----------------------------------- -- Area: The_Garden_of_RuHmet -- NPC: HomePoint#1 -- @pos -426 0 368 35 ----------------------------------- package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/The_Garden_of_RuHmet/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 89); 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
jchuang1977/openwrt
package/lean/luci-app-nfs/luasrc/model/cbi/nfs.lua
3
1768
local fs = require "nixio.fs" m = Map("nfs", translate("NFS Manage")) -- NFS Share -- s = m:section(TypedSection, "share", translate("Shared Directories")) s.anonymous = true s.addremove = true s.template = "cbi/tblsection" en = s:option(Flag, "enabled", translate("Enable")) en.rmempty = false en.default = "1" ph1 = s:option(Value, "path", translate("Path")) ph1.placeholder = "/mnt" ph1.rmempty = false ph1.optional = false ct = s:option(Value, "clients", translate("Clients")) ct.placeholder = "192.168.1.0/24" ct.rmempty = false ct.optional = false op = s:option(Value, "options", translate("options")) op.placeholder = "rw,sync,root_squash,all_squash,insecure,no_subtree_check" op.rmempty = false op.optional = false -- NFS Mount -- c = m:section(TypedSection, "mount", translate("Mounted Points")) c.anonymous = true c.addremove = true c.template = "cbi/tblsection" en = c:option(Flag, "enabled", translate("Enable")) en.default = "1" en.rmempty = false sr = c:option(Value, "source", translate("source")) sr.placeholder = "192.168.1.1:/mnt/*" sr.rmempty = false sr.optional = false ph2 = c:option(Value, "target", translate("target")) ph2.placeholder = "/mnt/nfs/*" ph2.rmempty = false ph2.optional = false op = c:option(Value, "options", translate("options")) op.placeholder = "rw,nolock" op.rmempty = false op.optional = false de = c:option(Value, "delay", translate("delay")) de.placeholder = "5" de.rmempty = false de.optional = false if nixio.fs.access("/etc/config/fstab") then ph1.titleref = luci.dispatcher.build_url("admin", "system", "mounts") ph2.titleref = luci.dispatcher.build_url("admin", "system", "mounts") end local apply = luci.http.formvalue("cbi.apply") if apply then io.popen("/etc/init.d/nfs reload") end return m
gpl-2.0
OpenPrograms/mpmxyz-Programs
home/lib/parser/automaton.lua
2
4368
----------------------------------------------------- --name : lib/parser/automaton.lua --description: automaton.merge allows converting a non deterministic finite automaton to a deterministic one --author : mpmxyz --github page: https://github.com/mpmxyz/ocprograms --forum page : none ----------------------------------------------------- local cache = require("mpm.cache").wrap local automaton = {} --registry for children local children = setmetatable({},{__mode="k"}) --getter for list of children function automaton.children(stateSet) return children[stateSet] end --cache: this, next -> merged --merges two automaton states to run them in parallel --This function does NOT actively enforce the 'equal set' == 'same object' --policy of sets.manager to avoid time and memory overhead. --(It also makes it possible to collect unused sets.) --Here is a reason why it still works without exploding memory usage: --Tables that were filled with the same keys in the same order have the same order of iteration. --(most of the time even independent from assignment order; --but that has problems with number keys and nil assignments) --This order helps reusing (first, second) pairs even if there is no explicit 'equal set' == 'equal object' code. --If the order changed between set creations or even 'pairs' calls --you'd have n! (first, second) pairs for every set of states with size n. --Their 'next state' would also be created randomly. --That would cause an exponential growth with a factorial base! -> (parallelStates!) ^ nSteps automaton.merge = cache(function(first) return cache(function(second) --only merge if both states exist and are not equal if first == second then return first elseif type(first) == "table" and type(second) == "table" then --don't create recursions if first already is a merged state local oldChildren1 = children[first] local oldChildren2 = children[second] local newChildren = {} --added some redundant code to avoid throwing around table sets with a single value only if oldChildren1 then if oldChildren2 then local somethingMissingIn1 = false local somethingMissingIn2 = false --no primitive for k, v in pairs(oldChildren1) do newChildren[k] = true if not oldChildren2[k] then somethingMissingIn2 = true end end for k in pairs(oldChildren2) do if not newChildren[k] then newChildren[k] = true somethingMissingIn1 = true end end if not somethingMissingIn1 then return first elseif not somethingMissingIn2 then return second end else --second is primitive if oldChildren1[second] then --return early if second is already within first return first else newChildren[second] = true end for k, v in pairs(oldChildren1) do newChildren[k] = true end end else if oldChildren2 then --first is primitive if oldChildren2[first] then --return early if first is already within second return second else newChildren[first] = true end for k, v in pairs(oldChildren2) do newChildren[k] = true end else --2 non equal primitives newChildren[first] = true newChildren[second] = true end end local mergedTable = cache(function(key) local output = false --calculate merged output, no recursion possible because there is no merged state in 'newChildren' for k in pairs(newChildren) do output = automaton.merge(output, k[key]) end return output end, "k", "automaton.merged state") children[mergedTable] = newChildren --[[ getmetatable(mergedTable).__tostring = function() return tostring(first) .. "|" .. tostring(second) end ]] return mergedTable else --either false + table or false + true return first or second end end, "k", "automaton.merge.second") end, "k", "automaton.merge.first") return automaton
mit
Scavenge/darkstar
scripts/globals/mobskills/Hexidiscs.lua
35
1129
--------------------------------------------- -- Hexidiscs -- -- Description: A sixfold attack damages targets in a fan-shaped area of effect. -- Type: Physical -- Utsusemi/Blink absorb: 6 shadows -- Range: Unknown cone -- Notes: Only used in "ball" form. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- --------------------------------------------------- -- onMobSkillCheck -- if not in Ball form, then ignore. --------------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:AnimationSub() ~=0) then return 1; else return 0; end end; function onMobWeaponSkill(target, mob, skill) local numhits = 6; local accmod = 1; local dmgmod = .7; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded); target:delHP(dmg); return dmg; end;
gpl-3.0
nirs/libguestfs
lua/examples/create_disk.lua
4
1857
-- Example showing how to create a disk image. local G = require "guestfs" local output = "disk.img" local g = G.create () -- Create a raw-format sparse disk image, 512 MB in size. file = io.open (output, "w") file:seek ("set", 512 * 1024 * 1024) file:write (' ') file:close () -- Set the trace flag so that we can see each libguestfs call. g:set_trace (true) -- Attach the disk image to libguestfs. g:add_drive (output, { format = "raw", readonly = false }) -- Run the libguestfs back-end. g:launch () -- Get the list of devices. Because we only added one drive -- above, we expect that this list should contain a single -- element. devices = g:list_devices () if table.getn (devices) ~= 1 then error "expected a single device from list-devices" end -- Partition the disk as one single MBR partition. g:part_disk (devices[1], "mbr") -- Get the list of partitions. We expect a single element, which -- is the partition we have just created. partitions = g:list_partitions () if table.getn (partitions) ~= 1 then error "expected a single partition from list-partitions" end -- Create a filesystem on the partition. g:mkfs ("ext4", partitions[1]) -- Now mount the filesystem so that we can add files. g:mount (partitions[1], "/") -- Create some files and directories. g:touch ("/empty") message = "Hello, world\n" g:write ("/hello", message) g:mkdir ("/foo") -- This one uploads the local file /etc/resolv.conf into -- the disk image. g:upload ("/etc/resolv.conf", "/foo/resolv.conf") -- Because we wrote to the disk and we want to detect write -- errors, call g:shutdown. You don't need to do this: -- g:close will do it implicitly. g:shutdown () -- Note also that handles are automatically closed if they are -- reaped by the garbage collector. You only need to call close -- if you want to close the handle right away. g:close ()
gpl-2.0
Scavenge/darkstar
scripts/zones/East_Ronfaure_[S]/npcs/qm3.lua
29
1569
----------------------------------- -- Area: East Ronfaure [S] -- NPC: qm3 "???" -- Involved in Quests: Steamed Rams -- @pos 312.821 -30.495 -67.15 ----------------------------------- package.loaded["scripts/zones/East_Ronfaure_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/campaign"); require("scripts/zones/East_Ronfaure_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(CRYSTAL_WAR,STEAMED_RAMS) == QUEST_ACCEPTED) then if (player:hasKeyItem(CHARRED_PROPELLER)) then player:messageSpecial(NOTHING_OUT_OF_ORDINARY); else player:startEvent(0x0001); end 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 Action ----------------------------------- function onEventFinish(player,csid,option) -- print("CSID:",csid); -- print("RESULT:",option); if (csid == 0x0001) then player:addKeyItem(CHARRED_PROPELLER); player:messageSpecial(KEYITEM_OBTAINED,CHARRED_PROPELLER); end end;
gpl-3.0
Scavenge/darkstar
scripts/globals/items/melon_pie.lua
12
1259
----------------------------------------- -- ID: 4421 -- Item: melon_pie -- Food Effect: 30Min, All Races ----------------------------------------- -- Magic 25 -- Agility -1 -- Intelligence 4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4421); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 25); target:addMod(MOD_AGI, -1); target:addMod(MOD_INT, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 25); target:delMod(MOD_AGI, -1); target:delMod(MOD_INT, 4); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Throne_Room/npcs/_4l4.lua
66
1207
----------------------------------- -- Area: Throne Room -- NPC: Ore Door ------------------------------------- require("scripts/globals/bcnm"); ----------------------------------- -- onTrade 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
Scavenge/darkstar
scripts/zones/Quicksand_Caves/npcs/Grounds_Tome.lua
30
1100
----------------------------------- -- Area: Quicksand Caves -- 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_QUICKSAND_CAVES,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,812,813,814,815,816,817,818,819,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,812,813,814,815,816,817,818,819,0,0,GOV_MSG_QUICKSAND_CAVES); end;
gpl-3.0
XingxingZhang/lstm-lm
nnets/lstmutil.lua
1
2027
local lstmutil = {} function lstmutil.createLSTM(x_t, c_tm1, h_tm1, nin, nhid) -- compute activations of four gates all together local x2h = nn.Linear(nin, nhid * 4)(x_t) local h2h = nn.Linear(nhid, nhid * 4)(h_tm1) local allGatesActs = nn.CAddTable()({x2h, h2h}) local allGatesActsSplits = nn.SplitTable(2)( nn.Reshape(4, nhid)(allGatesActs) ) -- unpack all gate activations local i_t = nn.Sigmoid()( nn.SelectTable(1)( allGatesActsSplits ) ) local f_t = nn.Sigmoid()( nn.SelectTable(2)( allGatesActsSplits ) ) local o_t = nn.Sigmoid()( nn.SelectTable(3)( allGatesActsSplits ) ) local n_t = nn.Tanh()( nn.SelectTable(4)( allGatesActsSplits ) ) -- compute new cell local c_t = nn.CAddTable()({ nn.CMulTable()({ i_t, n_t }), nn.CMulTable()({ f_t, c_tm1 }) }) -- compute new hidden state local h_t = nn.CMulTable()({ o_t, nn.Tanh()( c_t ) }) return c_t, h_t end -- what attributes are needed in opts? -- nivocab, nin, nlayers, nhid, useGPU function lstmutil.createDeepLSTM(opts) local emb = nn.LookupTable(opts.nivocab, opts.nin) local x_t = nn.Identity()() local s_tm1 = nn.Identity()() local in_t = {[0] = emb(x_t)} local s_t = {} local splits_tm1 = {s_tm1:split(2 * opts.nlayers)} for i = 1, opts.nlayers do local c_tm1_i = splits_tm1[i + i - 1] local h_tm1_i = splits_tm1[i + i] local x_t_i = in_t[i - 1] local c_t_i, h_t_i = nil, nil if opts.dropout > 0 then printf( 'lstm layer %d, dropout = %f\n', i, opts.dropout) x_t_i = nn.Dropout(opts.dropout)(x_t_i) end if i == 1 then c_t_i, h_t_i = lstmutil.createLSTM(x_t_i, c_tm1_i, h_tm1_i, opts.nin, opts.nhid) else c_t_i, h_t_i = lstmutil.createLSTM(x_t_i, c_tm1_i, h_tm1_i, opts.nhid, opts.nhid) end s_t[i+i-1] = c_t_i s_t[i+i] = h_t_i in_t[i] = h_t_i end local model = nn.gModule({x_t, s_tm1}, {nn.Identity()(s_t)}) if opts.useGPU then return model:cuda() else return model end end return lstmutil
apache-2.0
Scavenge/darkstar
scripts/zones/Port_San_dOria/npcs/Fiva.lua
17
1912
----------------------------------- -- Area: Port San d'Oria -- NPC: Fiva -- Only sells when San d'Oria controls Kolshushu ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/conquest"); require("scripts/globals/quests"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local RegionOwner = GetRegionOwner(KOLSHUSHU); if (RegionOwner ~= NATION_SANDORIA) then player:showText(npc,FIVA_CLOSED_DIALOG); else player:showText(npc,FIVA_OPEN_DIALOG); local stock = {0x1197,184, --Buburimu Grape 0x0460,1620, --Casablanca 0x1107,220, --Dhalmel Meat 0x0266,72, --Mhaura Garlic 0x115d,40} --Yagudo Cherry showShop(player,SANDORIA,stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Grand_Palace_of_HuXzoi/npcs/_iyc.lua
14
1036
----------------------------------- -- Area: Grand Palace of Hu'Xzoi -- NPC: Particle Gate -- @pos -39 0 -319 34 ----------------------------------- package.loaded["scripts/zones/Grand_Palace_of_HuXzoi/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Grand_Palace_of_HuXzoi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00ac); return 1; 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
Scavenge/darkstar
scripts/zones/Chateau_dOraguille/npcs/_6h0.lua
14
4838
----------------------------------- -- Area: Chateau d'Oraguille -- Door: Prince Royal's -- Finishes Quest: A Boy's Dream, Under Oath -- Involved in Missions: 3-1, 5-2, 8-2 -- @pos -38 -3 73 233 ----------------------------------- package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/globals/titles"); require("scripts/zones/Chateau_dOraguille/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local currentMission = player:getCurrentMission(SANDORIA); local MissionStatus = player:getVar("MissionStatus"); local infiltrateDavoi = player:hasCompletedMission(SANDORIA,INFILTRATE_DAVOI); local Wait1DayRanperre = player:getVar("Wait1DayForRanperre_date"); local osdate = tonumber(os.date("%j")); if (player:getVar("aBoysDreamCS") == 8) then player:startEvent(0x0058); elseif (player:getQuestStatus(SANDORIA,A_BOY_S_DREAM) == QUEST_COMPLETED and player:getQuestStatus(SANDORIA,UNDER_OATH) == QUEST_AVAILABLE and player:getMainJob() == JOBS.PLD) then player:startEvent(0x005A); elseif (player:getVar("UnderOathCS") == 8) then player:startEvent(0x0059); elseif (currentMission == INFILTRATE_DAVOI and infiltrateDavoi == false and MissionStatus == 0) then player:startEvent(0x0229,0,ROYAL_KNIGHTS_DAVOI_REPORT); elseif (currentMission == INFILTRATE_DAVOI and MissionStatus == 4) then player:startEvent(0x022a,0,ROYAL_KNIGHTS_DAVOI_REPORT); elseif (currentMission == THE_SHADOW_LORD and MissionStatus == 1) then player:startEvent(0x0223); elseif (currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 0) then player:startEvent(0x0051); elseif (CurrentMission == RANPERRE_S_FINAL_REST and MissionStatus == 4 and Wait1DayRanperre ~= osdate) then -- Ready now. player:startEvent(0x0015); elseif (currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 7) then player:startEvent(0x0015); elseif (player:hasCompletedMission(SANDORIA,LIGHTBRINGER) and player:getRank() == 9 and player:getVar("Cutscenes_8-2") == 0) then player:startEvent(0x003F); else player:startEvent(0x020a); end return 1; 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 == 0x0229) then player:setVar("MissionStatus",2); elseif (csid == 0x0223) then player:setVar("MissionStatus",2); elseif (csid == 0x022a) then finishMissionTimeline(player,3,csid,option); elseif (csid == 0x0058) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14095); else if (player:getMainJob() == JOBS.PLD) then player:addQuest(SANDORIA,UNDER_OATH); end player:delKeyItem(KNIGHTS_BOOTS); player:addItem(14095); player:messageSpecial(ITEM_OBTAINED,14095); -- Gallant Leggings player:setVar("aBoysDreamCS",0); player:addFame(SANDORIA,AF2_FAME); player:completeQuest(SANDORIA,A_BOY_S_DREAM); end elseif (csid == 0x005A and option ==1) then player:addQuest(SANDORIA,UNDER_OATH); player:setVar("UnderOathCS",0); elseif (csid == 0x0059) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12644); else player:addItem(12644); player:messageSpecial(ITEM_OBTAINED,12644); -- Gallant Surcoat player:setVar("UnderOathCS",9); player:addFame(SANDORIA,AF3_FAME); player:setTitle(PARAGON_OF_PALADIN_EXCELLENCE); player:completeQuest(SANDORIA,UNDER_OATH); end elseif (csid == 0x0051) then player:setVar("MissionStatus",1); elseif (csid == 0x0015) then player:setVar("Wait1DayForRanperre_date",0); player:setVar("MissionStatus",8); elseif (csid == 0x003F) then player:setVar("Cutscenes_8-2",1) end end;
gpl-3.0
SHIELDTM/shield5
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
Scavenge/darkstar
scripts/globals/items/mushroom_crepe.lua
12
1465
----------------------------------------- -- ID: 5773 -- Item: mushroom_crepe -- Food Effect: 30Min, All Races ----------------------------------------- -- Mind 2 -- MP % 10 (cap 30) -- Magic Accuracy +10 -- Magic Def. Bonus +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,1800,5773); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MND, 2); target:addMod(MOD_FOOD_MPP, 10); target:addMod(MOD_FOOD_MP_CAP, 30); target:addMod(MOD_MACC, 10); target:addMod(MOD_MDEF, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MND, 2); target:delMod(MOD_FOOD_MPP, 10); target:delMod(MOD_FOOD_MP_CAP, 30); target:delMod(MOD_MACC, 10); target:delMod(MOD_MDEF, 5); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Northern_San_dOria/npcs/Anilla.lua
14
1745
----------------------------------- -- Area: Northern San d'Oria -- NPC: Anilla -- Involved in Quest: Lure of the Wildcat (San d'Oria) -- @pos 8 0.1 61 231 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatSandy = player:getVar("WildcatSandy"); if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,6) == false) then player:startEvent(0x0328); else player:startEvent(0x024a); 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 == 0x0328) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",6,true); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Quicksand_Caves/npcs/HomePoint#2.lua
27
1270
----------------------------------- -- Area: Quicksand_Caves -- NPC: HomePoint#2 -- @pos 573 9 -500 208 ----------------------------------- package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Quicksand_Caves/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fd, 96); 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
Scavenge/darkstar
scripts/zones/Bastok_Markets/npcs/Raghd.lua
15
1319
----------------------------------- -- Area: Bastok Markets -- NPC: Raghd -- Standard Merchant NPC -- -- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,RAGHD_SHOP_DIALOG); stock = { 0x3490, 1125,1, --Silver Ring 0x340F, 1125,1, --Silver Earring 0x3499, 180,2, --Brass Ring 0x348E, 68,3 --Copper Ring } showNationShop(player, NATION_BASTOK, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Kyklas/luci-proto-hso
modules/admin-full/luasrc/model/cbi/admin_network/vlan.lua
6
8984
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- m = Map("network", translate("Switch"), translate("The network ports on this device can be combined to several <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s in which computers can communicate directly with each other. <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s are often used to separate different network segments. Often there is by default one Uplink port for a connection to the next greater network like the internet and other ports for a local network.")) local fs = require "nixio.fs" local switches = { } m.uci:foreach("network", "switch", function(x) local sid = x['.name'] local switch_name = x.name or sid local has_vlan = nil local has_learn = nil local has_vlan4k = nil local has_jumbo3 = nil local has_mirror = nil local min_vid = 0 local max_vid = 16 local num_vlans = 16 local cpu_port = tonumber(fs.readfile("/proc/switch/eth0/cpuport") or 5) local num_ports = cpu_port + 1 local switch_title local enable_vlan4k = false -- Parse some common switch properties from swconfig help output. local swc = io.popen("swconfig dev %q help 2>/dev/null" % switch_name) if swc then local is_port_attr = false local is_vlan_attr = false while true do local line = swc:read("*l") if not line then break end if line:match("^%s+%-%-vlan") then is_vlan_attr = true elseif line:match("^%s+%-%-port") then is_vlan_attr = false is_port_attr = true elseif line:match("cpu @") then switch_title = line:match("^switch%d: %w+%((.-)%)") num_ports, cpu_port, num_vlans = line:match("ports: (%d+) %(cpu @ (%d+)%), vlans: (%d+)") num_ports = tonumber(num_ports) or 6 num_vlans = tonumber(num_vlans) or 16 cpu_port = tonumber(cpu_port) or 5 min_vid = 1 elseif line:match(": pvid") or line:match(": tag") or line:match(": vid") then if is_vlan_attr then has_vlan4k = line:match(": (%w+)") end elseif line:match(": enable_vlan4k") then enable_vlan4k = true elseif line:match(": enable_vlan") then has_vlan = "enable_vlan" elseif line:match(": enable_learning") then has_learn = "enable_learning" elseif line:match(": enable_mirror_rx") then has_mirror = "enable_mirror_rx" elseif line:match(": max_length") then has_jumbo3 = "max_length" end end swc:close() end -- Switch properties s = m:section(NamedSection, x['.name'], "switch", switch_title and translatef("Switch %q (%s)", switch_name, switch_title) or translatef("Switch %q", switch_name)) s.addremove = false if has_vlan then s:option(Flag, has_vlan, translate("Enable VLAN functionality")) end if has_learn then x = s:option(Flag, has_learn, translate("Enable learning and aging")) x.default = x.enabled end if has_jumbo3 then x = s:option(Flag, has_jumbo3, translate("Enable Jumbo Frame passthrough")) x.enabled = "3" x.rmempty = true end -- Does this switch support port mirroring? if has_mirror then s:option(Flag, "enable_mirror_rx", translate("Enable mirroring of incoming packets")) s:option(Flag, "enable_mirror_tx", translate("Enable mirroring of outgoing packets")) local sp = s:option(ListValue, "mirror_source_port", translate("Mirror source port")) local mp = s:option(ListValue, "mirror_monitor_port", translate("Mirror monitor port")) local pt for pt = 0, num_ports - 1 do local name name = (pt == cpu_port) and translate("CPU") or translatef("Port %d", pt) sp:value(pt, name) mp:value(pt, name) end end -- VLAN table s = m:section(TypedSection, "switch_vlan", switch_title and translatef("VLANs on %q (%s)", switch_name, switch_title) or translatef("VLANs on %q", switch_name)) s.template = "cbi/tblsection" s.addremove = true s.anonymous = true -- Filter by switch s.filter = function(self, section) local device = m:get(section, "device") return (device and device == switch_name) end -- Override cfgsections callback to enforce row ordering by vlan id. s.cfgsections = function(self) local osections = TypedSection.cfgsections(self) local sections = { } local section for _, section in luci.util.spairs( osections, function(a, b) return (tonumber(m:get(osections[a], has_vlan4k or "vlan")) or 9999) < (tonumber(m:get(osections[b], has_vlan4k or "vlan")) or 9999) end ) do sections[#sections+1] = section end return sections end -- When creating a new vlan, preset it with the highest found vid + 1. s.create = function(self, section, origin) -- Filter by switch if m:get(origin, "device") ~= switch_name then return end local sid = TypedSection.create(self, section) local max_nr = 0 local max_id = 0 m.uci:foreach("network", "switch_vlan", function(s) if s.device == switch_name then local nr = tonumber(s.vlan) local id = has_vlan4k and tonumber(s[has_vlan4k]) if nr ~= nil and nr > max_nr then max_nr = nr end if id ~= nil and id > max_id then max_id = id end end end) m:set(sid, "device", switch_name) m:set(sid, "vlan", max_nr + 1) if has_vlan4k then m:set(sid, has_vlan4k, max_id + 1) end return sid end local port_opts = { } local untagged = { } -- Parse current tagging state from the "ports" option. local portvalue = function(self, section) local pt for pt in (m:get(section, "ports") or ""):gmatch("%w+") do local pc, tu = pt:match("^(%d+)([tu]*)") if pc == self.option then return (#tu > 0) and tu or "u" end end return "" end -- Validate port tagging. Ensure that a port is only untagged once, -- bail out if not. local portvalidate = function(self, value, section) -- ensure that the ports appears untagged only once if value == "u" then if not untagged[self.option] then untagged[self.option] = true elseif min_vid > 0 or tonumber(self.option) ~= cpu_port then -- enable multiple untagged cpu ports due to weird broadcom default setup return nil, translatef("Port %d is untagged in multiple VLANs!", tonumber(self.option) + 1) end end return value end local vid = s:option(Value, has_vlan4k or "vlan", "VLAN ID", "<div id='portstatus-%s'></div>" % switch_name) local mx_vid = has_vlan4k and 4094 or (num_vlans - 1) vid.rmempty = false vid.forcewrite = true vid.vlan_used = { } vid.datatype = "and(uinteger,range("..min_vid..","..mx_vid.."))" -- Validate user provided VLAN ID, make sure its within the bounds -- allowed by the switch. vid.validate = function(self, value, section) local v = tonumber(value) local m = has_vlan4k and 4094 or (num_vlans - 1) if v ~= nil and v >= min_vid and v <= m then if not self.vlan_used[v] then self.vlan_used[v] = true return value else return nil, translatef("Invalid VLAN ID given! Only unique IDs are allowed") end else return nil, translatef("Invalid VLAN ID given! Only IDs between %d and %d are allowed.", min_vid, m) end end -- When writing the "vid" or "vlan" option, serialize the port states -- as well and write them as "ports" option to uci. vid.write = function(self, section, value) local o local p = { } for _, o in ipairs(port_opts) do local v = o:formvalue(section) if v == "t" then p[#p+1] = o.option .. v elseif v == "u" then p[#p+1] = o.option end end if enable_vlan4k then m:set(sid, "enable_vlan4k", "1") end m:set(section, "ports", table.concat(p, " ")) return Value.write(self, section, value) end -- Fallback to "vlan" option if "vid" option is supported but unset. vid.cfgvalue = function(self, section) return m:get(section, has_vlan4k or "vlan") or m:get(section, "vlan") end -- Build per-port off/untagged/tagged choice lists. local pt for pt = 0, num_ports - 1 do local title if pt == cpu_port then title = translate("CPU") else title = translatef("Port %d", pt) end local po = s:option(ListValue, tostring(pt), title) po:value("", translate("off")) po:value("u", translate("untagged")) po:value("t", translate("tagged")) po.cfgvalue = portvalue po.validate = portvalidate po.write = function() end port_opts[#port_opts+1] = po end switches[#switches+1] = switch_name end ) -- Switch status template s = m:section(SimpleSection) s.template = "admin_network/switch_status" s.switches = switches return m
apache-2.0
Scavenge/darkstar
scripts/zones/Newton_Movalpolos/npcs/Moblin_Showman.lua
14
1064
----------------------------------- -- Area: Newton Movalpolos -- NPC: Moblin Showman - Bugbear Matman -- @pos 124.544 19.988 -60.670 12 ----------------------------------- package.loaded["scripts/zones/Newton_Movalpolos/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Newton_Movalpolos/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (GetMobAction(16826570) == 0 and trade:hasItemQty(1878,1) and trade:getItemCount() == 1) then -- Air tank player:tradeComplete(); player:showText(npc, SHOWMAN_ACCEPT); -- Moblin Showman's dialogue SpawnMob(16826570):updateClaim(player); -- Bugbear Matman npc:setStatus(STATUS_DISAPPEAR); else player:showText(npc, SHOWMAN_DECLINE); -- Moblin Showman refuses your trade end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, SHOWMAN_TRIGGER); end;
gpl-3.0
Kyklas/luci-proto-hso
applications/luci-firewall/luasrc/model/cbi/firewall/zones.lua
84
2233
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local ds = require "luci.dispatcher" local fw = require "luci.model.firewall" local m, s, o, p, i, v m = Map("firewall", translate("Firewall - Zone Settings"), translate("The firewall creates zones over your network interfaces to control network traffic flow.")) fw.init(m.uci) s = m:section(TypedSection, "defaults", translate("General Settings")) s.anonymous = true s.addremove = false s:option(Flag, "syn_flood", translate("Enable SYN-flood protection")) o = s:option(Flag, "drop_invalid", translate("Drop invalid packets")) o.default = o.disabled p = { s:option(ListValue, "input", translate("Input")), s:option(ListValue, "output", translate("Output")), s:option(ListValue, "forward", translate("Forward")) } for i, v in ipairs(p) do v:value("REJECT", translate("reject")) v:value("DROP", translate("drop")) v:value("ACCEPT", translate("accept")) end s = m:section(TypedSection, "zone", translate("Zones")) s.template = "cbi/tblsection" s.anonymous = true s.addremove = true s.extedit = ds.build_url("admin", "network", "firewall", "zones", "%s") function s.create(self) local z = fw:new_zone() if z then luci.http.redirect( ds.build_url("admin", "network", "firewall", "zones", z.sid) ) end end function s.remove(self, section) return fw:del_zone(section) end o = s:option(DummyValue, "_info", translate("Zone ⇒ Forwardings")) o.template = "cbi/firewall_zoneforwards" o.cfgvalue = function(self, section) return self.map:get(section, "name") end p = { s:option(ListValue, "input", translate("Input")), s:option(ListValue, "output", translate("Output")), s:option(ListValue, "forward", translate("Forward")) } for i, v in ipairs(p) do v:value("REJECT", translate("reject")) v:value("DROP", translate("drop")) v:value("ACCEPT", translate("accept")) end s:option(Flag, "masq", translate("Masquerading")) s:option(Flag, "mtu_fix", translate("MSS clamping")) return m
apache-2.0
Zero-K-Experiments/Zero-K-Experiments
units/corjamt.lua
3
4048
unitDef = { unitname = [[corjamt]], name = [[Aegis]], description = [[Area Shield]], acceleration = 0, activateWhenBuilt = true, brakeRate = 0, buildCostEnergy = 525, buildCostMetal = 525, builder = false, buildingGroundDecalDecaySpeed = 30, buildingGroundDecalSizeX = 4, buildingGroundDecalSizeY = 4, buildingGroundDecalType = [[corjamt_aoplane.dds]], buildPic = [[CORJAMT.png]], buildTime = 525, canAttack = false, category = [[SINK UNARMED]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[30 39 30]], collisionVolumeType = [[box]], corpse = [[DEAD]], explodeAs = [[BIG_UNITEX]], floater = true, footprintX = 2, footprintZ = 2, iconType = [[defenseshield]], idleAutoHeal = 5, idleTime = 1800, levelGround = false, maxDamage = 900, maxSlope = 36, maxVelocity = 0, minCloakDistance = 150, noAutoFire = false, objectName = [[m-8.s3o]], onoffable = true, script = [[corjamt.lua]], seismicSignature = 4, selfDestructAs = [[BIG_UNITEX]], sightDistance = 200, turnRate = 0, useBuildingGroundDecal = true, workerTime = 0, yardMap = [[oooo]], customParams = { description_de = [[Leichte Abschirmeinrichtung]], helptext = [[The Aegis protects a modest area with its bubble shield that stops incoming projectiles (but not AoE effects). The shield has a significant energy upkeep and does not block very powerful weapons.]], helptext_de = [[Aegis schützt deine Einheiten in mit seinem Schild vor Angriffen, die durch den Schild absorbiert werden können, aber nur solange die nötige Energieversorgung gewährleistet ist und der Beschuss nicht zu stark wird.]], removewait = 1, morphto = [[core_spectre]], morphtime = [[30]], priority_misc = 1, -- Medium unarmed = true, }, weapons = { { def = [[COR_SHIELD_SMALL]], maxAngleDif = 1, }, }, weaponDefs = { COR_SHIELD_SMALL = { name = [[Energy Shield]], craterMult = 0, damage = { default = 10, }, exteriorShield = true, impulseFactor = 0, interceptedByShieldType = 1, shieldAlpha = 0.2, shieldBadColor = [[1 0.1 0.1]], shieldGoodColor = [[0.1 0.1 1]], shieldInterceptType = 3, shieldPower = 3600, shieldPowerRegen = 50, shieldPowerRegenEnergy = 9, shieldRadius = 350, shieldRepulser = false, smartShield = true, texture1 = [[shield3mist]], visibleShield = true, visibleShieldHitFrames = 4, visibleShieldRepulse = true, weaponType = [[Shield]], }, }, featureDefs = { DEAD = { blocking = true, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, object = [[shield_dead.s3o]], }, HEAP = { blocking = false, footprintX = 2, footprintZ = 2, object = [[debris2x2a.s3o]], }, }, } return lowerkeys({ corjamt = unitDef })
gpl-2.0
Kyklas/luci-proto-hso
applications/luci-asterisk/luasrc/asterisk.lua
80
18044
--[[ LuCI - Lua Configuration Interface Asterisk PBX interface library Copyright 2009 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.asterisk", package.seeall) require("luci.asterisk.cc_idd") local _io = require("io") local uci = require("luci.model.uci").cursor() local sys = require("luci.sys") local util = require("luci.util") AST_BIN = "/usr/sbin/asterisk" AST_FLAGS = "-r -x" --- LuCI Asterisk - Resync uci context function uci_resync() uci = luci.model.uci.cursor() end --- LuCI Asterisk io interface -- Handles low level io. -- @type module io = luci.util.class() --- Execute command and return output -- @param command String containing the command to execute -- @return String containing the command output function io.exec(command) local fh = _io.popen( "%s %s %q" %{ AST_BIN, AST_FLAGS, command }, "r" ) assert(fh, "Failed to invoke asterisk") local buffer = fh:read("*a") fh:close() return buffer end --- Execute command and invoke given callback for each readed line -- @param command String containing the command to execute -- @param callback Function to call back for each line -- @return Always true function io.execl(command, callback) local ln local fh = _io.popen( "%s %s %q" %{ AST_BIN, AST_FLAGS, command }, "r" ) assert(fh, "Failed to invoke asterisk") repeat ln = fh:read("*l") callback(ln) until not ln fh:close() return true end --- Execute command and return an iterator that returns one line per invokation -- @param command String containing the command to execute -- @return Iterator function function io.execi(command) local fh = _io.popen( "%s %s %q" %{ AST_BIN, AST_FLAGS, command }, "r" ) assert(fh, "Failed to invoke asterisk") return function() local ln = fh:read("*l") if not ln then fh:close() end return ln end end --- LuCI Asterisk - core status core = luci.util.class() --- Retrive version string. -- @return String containing the reported asterisk version function core.version(self) local version = io.exec("core show version") return version:gsub(" *\n", "") end --- LuCI Asterisk - SIP information. -- @type module sip = luci.util.class() --- Get a list of known SIP peers -- @return Table containing each SIP peer function sip.peers(self) local head = false local peers = { } for line in io.execi("sip show peers") do if not head then head = true elseif not line:match(" sip peers ") then local online, delay, id, uid local name, host, dyn, nat, acl, port, status = line:match("(.-) +(.-) +([D ]) ([N ]) (.) (%d+) +(.+)") if host == '(Unspecified)' then host = nil end if port == '0' then port = nil else port = tonumber(port) end dyn = ( dyn == 'D' and true or false ) nat = ( nat == 'N' and true or false ) acl = ( acl ~= ' ' and true or false ) online, delay = status:match("(OK) %((%d+) ms%)") if online == 'OK' then online = true delay = tonumber(delay) elseif status ~= 'Unmonitored' then online = false delay = 0 else online = nil delay = 0 end id, uid = name:match("(.+)/(.+)") if not ( id and uid ) then id = name .. "..." uid = nil end peers[#peers+1] = { online = online, delay = delay, name = id, user = uid, dynamic = dyn, nat = nat, acl = acl, host = host, port = port } end end return peers end --- Get informations of given SIP peer -- @param peer String containing the name of the SIP peer function sip.peer(peer) local info = { } local keys = { } for line in io.execi("sip show peer " .. peer) do if #line > 0 then local key, val = line:match("(.-) *: +(.*)") if key and val then key = key:gsub("^ +",""):gsub(" +$", "") val = val:gsub("^ +",""):gsub(" +$", "") if key == "* Name" then key = "Name" elseif key == "Addr->IP" then info.address, info.port = val:match("(.+) Port (.+)") info.port = tonumber(info.port) elseif key == "Status" then info.online, info.delay = val:match("(OK) %((%d+) ms%)") if info.online == 'OK' then info.online = true info.delay = tonumber(info.delay) elseif status ~= 'Unmonitored' then info.online = false info.delay = 0 else info.online = nil info.delay = 0 end end if val == 'Yes' or val == 'yes' or val == '<Set>' then val = true elseif val == 'No' or val == 'no' then val = false elseif val == '<Not set>' or val == '(none)' then val = nil end keys[#keys+1] = key info[key] = val end end end return info, keys end --- LuCI Asterisk - Internal helpers -- @type module tools = luci.util.class() --- Convert given value to a list of tokens. Split by white space. -- @param val String or table value -- @return Table containing tokens function tools.parse_list(v) local tokens = { } v = type(v) == "table" and v or { v } for _, v in ipairs(v) do if type(v) == "string" then for v in v:gmatch("(%S+)") do tokens[#tokens+1] = v end end end return tokens end --- Convert given list to a collection of hyperlinks -- @param list Table of tokens -- @param url String pattern or callback function to construct urls (optional) -- @param sep String containing the seperator (optional, default is ", ") -- @return String containing the html fragment function tools.hyperlinks(list, url, sep) local html local function mkurl(p, t) if type(p) == "string" then return p:format(t) elseif type(p) == "function" then return p(t) else return '#' end end list = list or { } url = url or "%s" sep = sep or ", " for _, token in ipairs(list) do html = ( html and html .. sep or '' ) .. '<a href="%s">%s</a>' %{ mkurl(url, token), token } end return html or '' end --- LuCI Asterisk - International Direct Dialing Prefixes -- @type module idd = luci.util.class() --- Lookup the country name for the given IDD code. -- @param country String containing IDD code -- @return String containing the country name function idd.country(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[3]) == "table" then for _, v2 in ipairs(v[3]) do if v2 == tostring(c) then return v[1] end end elseif v[3] == tostring(c) then return v[1] end end end --- Lookup the country code for the given IDD code. -- @param country String containing IDD code -- @return Table containing the country code(s) function idd.cc(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[3]) == "table" then for _, v2 in ipairs(v[3]) do if v2 == tostring(c) then return type(v[2]) == "table" and v[2] or { v[2] } end end elseif v[3] == tostring(c) then return type(v[2]) == "table" and v[2] or { v[2] } end end end --- Lookup the IDD code(s) for the given country. -- @param idd String containing the country name -- @return Table containing the IDD code(s) function idd.idd(c) for _, v in ipairs(cc_idd.CC_IDD) do if v[1]:lower():match(c:lower()) then return type(v[3]) == "table" and v[3] or { v[3] } end end end --- Populate given CBI field with IDD codes. -- @param field CBI option object -- @return (nothing) function idd.cbifill(o) for i, v in ipairs(cc_idd.CC_IDD) do o:value("_%i" % i, util.pcdata(v[1])) end o.formvalue = function(...) local val = luci.cbi.Value.formvalue(...) if val:sub(1,1) == "_" then val = tonumber((val:gsub("^_", ""))) if val then return type(cc_idd.CC_IDD[val][3]) == "table" and cc_idd.CC_IDD[val][3] or { cc_idd.CC_IDD[val][3] } end end return val end o.cfgvalue = function(...) local val = luci.cbi.Value.cfgvalue(...) if val then val = tools.parse_list(val) for i, v in ipairs(cc_idd.CC_IDD) do if type(v[3]) == "table" then if v[3][1] == val[1] then return "_%i" % i end else if v[3] == val[1] then return "_%i" % i end end end end return val end end --- LuCI Asterisk - Country Code Prefixes -- @type module cc = luci.util.class() --- Lookup the country name for the given CC code. -- @param country String containing CC code -- @return String containing the country name function cc.country(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[2]) == "table" then for _, v2 in ipairs(v[2]) do if v2 == tostring(c) then return v[1] end end elseif v[2] == tostring(c) then return v[1] end end end --- Lookup the international dialing code for the given CC code. -- @param cc String containing CC code -- @return String containing IDD code function cc.idd(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[2]) == "table" then for _, v2 in ipairs(v[2]) do if v2 == tostring(c) then return type(v[3]) == "table" and v[3] or { v[3] } end end elseif v[2] == tostring(c) then return type(v[3]) == "table" and v[3] or { v[3] } end end end --- Lookup the CC code(s) for the given country. -- @param country String containing the country name -- @return Table containing the CC code(s) function cc.cc(c) for _, v in ipairs(cc_idd.CC_IDD) do if v[1]:lower():match(c:lower()) then return type(v[2]) == "table" and v[2] or { v[2] } end end end --- Populate given CBI field with CC codes. -- @param field CBI option object -- @return (nothing) function cc.cbifill(o) for i, v in ipairs(cc_idd.CC_IDD) do o:value("_%i" % i, util.pcdata(v[1])) end o.formvalue = function(...) local val = luci.cbi.Value.formvalue(...) if val:sub(1,1) == "_" then val = tonumber((val:gsub("^_", ""))) if val then return type(cc_idd.CC_IDD[val][2]) == "table" and cc_idd.CC_IDD[val][2] or { cc_idd.CC_IDD[val][2] } end end return val end o.cfgvalue = function(...) local val = luci.cbi.Value.cfgvalue(...) if val then val = tools.parse_list(val) for i, v in ipairs(cc_idd.CC_IDD) do if type(v[2]) == "table" then if v[2][1] == val[1] then return "_%i" % i end else if v[2] == val[1] then return "_%i" % i end end end end return val end end --- LuCI Asterisk - Dialzone -- @type module dialzone = luci.util.class() --- Parse a dialzone section -- @param zone Table containing the zone info -- @return Table with parsed information function dialzone.parse(z) if z['.name'] then return { trunks = tools.parse_list(z.uses), name = z['.name'], description = z.description or z['.name'], addprefix = z.addprefix, matches = tools.parse_list(z.match), intlmatches = tools.parse_list(z.international), countrycode = z.countrycode, localzone = z.localzone, localprefix = z.localprefix } end end --- Get a list of known dial zones -- @return Associative table of zones and table of zone names function dialzone.zones() local zones = { } local znames = { } uci:foreach("asterisk", "dialzone", function(z) zones[z['.name']] = dialzone.parse(z) znames[#znames+1] = z['.name'] end) return zones, znames end --- Get a specific dial zone -- @param name Name of the dial zone -- @return Table containing zone information function dialzone.zone(n) local zone uci:foreach("asterisk", "dialzone", function(z) if z['.name'] == n then zone = dialzone.parse(z) end end) return zone end --- Find uci section hash for given zone number -- @param idx Zone number -- @return String containing the uci hash pointing to the section function dialzone.ucisection(i) local hash local index = 1 i = tonumber(i) uci:foreach("asterisk", "dialzone", function(z) if not hash and index == i then hash = z['.name'] end index = index + 1 end) return hash end --- LuCI Asterisk - Voicemailbox -- @type module voicemail = luci.util.class() --- Parse a voicemail section -- @param zone Table containing the mailbox info -- @return Table with parsed information function voicemail.parse(z) if z.number and #z.number > 0 then local v = { id = '%s@%s' %{ z.number, z.context or 'default' }, number = z.number, context = z.context or 'default', name = z.name or z['.name'] or 'OpenWrt', zone = z.zone or 'homeloc', password = z.password or '0000', email = z.email or '', page = z.page or '', dialplans = { } } uci:foreach("asterisk", "dialplanvoice", function(s) if s.dialplan and #s.dialplan > 0 and s.voicebox == v.number then v.dialplans[#v.dialplans+1] = s.dialplan end end) return v end end --- Get a list of known voicemail boxes -- @return Associative table of boxes and table of box numbers function voicemail.boxes() local vboxes = { } local vnames = { } uci:foreach("asterisk", "voicemail", function(z) local v = voicemail.parse(z) if v then local n = '%s@%s' %{ v.number, v.context } vboxes[n] = v vnames[#vnames+1] = n end end) return vboxes, vnames end --- Get a specific voicemailbox -- @param number Number of the voicemailbox -- @return Table containing mailbox information function voicemail.box(n) local box n = n:gsub("@.+$","") uci:foreach("asterisk", "voicemail", function(z) if z.number == tostring(n) then box = voicemail.parse(z) end end) return box end --- Find all voicemailboxes within the given dialplan -- @param plan Dialplan name or table -- @return Associative table containing extensions mapped to mailbox info function voicemail.in_dialplan(p) local plan = type(p) == "string" and p or p.name local boxes = { } uci:foreach("asterisk", "dialplanvoice", function(s) if s.extension and #s.extension > 0 and s.dialplan == plan then local box = voicemail.box(s.voicebox) if box then boxes[s.extension] = box end end end) return boxes end --- Remove voicemailbox and associated extensions from config -- @param box Voicemailbox number or table -- @param ctx UCI context to use (optional) -- @return Boolean indicating success function voicemail.remove(v, ctx) ctx = ctx or uci local box = type(v) == "string" and v or v.number local ok1 = ctx:delete_all("asterisk", "voicemail", {number=box}) local ok2 = ctx:delete_all("asterisk", "dialplanvoice", {voicebox=box}) return ( ok1 or ok2 ) and true or false end --- LuCI Asterisk - MeetMe Conferences -- @type module meetme = luci.util.class() --- Parse a meetme section -- @param room Table containing the room info -- @return Table with parsed information function meetme.parse(r) if r.room and #r.room > 0 then local v = { room = r.room, pin = r.pin or '', adminpin = r.adminpin or '', description = r._description or '', dialplans = { } } uci:foreach("asterisk", "dialplanmeetme", function(s) if s.dialplan and #s.dialplan > 0 and s.room == v.room then v.dialplans[#v.dialplans+1] = s.dialplan end end) return v end end --- Get a list of known meetme rooms -- @return Associative table of rooms and table of room numbers function meetme.rooms() local mrooms = { } local mnames = { } uci:foreach("asterisk", "meetme", function(r) local v = meetme.parse(r) if v then mrooms[v.room] = v mnames[#mnames+1] = v.room end end) return mrooms, mnames end --- Get a specific meetme room -- @param number Number of the room -- @return Table containing room information function meetme.room(n) local room uci:foreach("asterisk", "meetme", function(r) if r.room == tostring(n) then room = meetme.parse(r) end end) return room end --- Find all meetme rooms within the given dialplan -- @param plan Dialplan name or table -- @return Associative table containing extensions mapped to room info function meetme.in_dialplan(p) local plan = type(p) == "string" and p or p.name local rooms = { } uci:foreach("asterisk", "dialplanmeetme", function(s) if s.extension and #s.extension > 0 and s.dialplan == plan then local room = meetme.room(s.room) if room then rooms[s.extension] = room end end end) return rooms end --- Remove meetme room and associated extensions from config -- @param room Voicemailbox number or table -- @param ctx UCI context to use (optional) -- @return Boolean indicating success function meetme.remove(v, ctx) ctx = ctx or uci local room = type(v) == "string" and v or v.number local ok1 = ctx:delete_all("asterisk", "meetme", {room=room}) local ok2 = ctx:delete_all("asterisk", "dialplanmeetme", {room=room}) return ( ok1 or ok2 ) and true or false end --- LuCI Asterisk - Dialplan -- @type module dialplan = luci.util.class() --- Parse a dialplan section -- @param plan Table containing the plan info -- @return Table with parsed information function dialplan.parse(z) if z['.name'] then local plan = { zones = { }, name = z['.name'], description = z.description or z['.name'] } -- dialzones for _, name in ipairs(tools.parse_list(z.include)) do local zone = dialzone.zone(name) if zone then plan.zones[#plan.zones+1] = zone end end -- voicemailboxes plan.voicemailboxes = voicemail.in_dialplan(plan) -- meetme conferences plan.meetmerooms = meetme.in_dialplan(plan) return plan end end --- Get a list of known dial plans -- @return Associative table of plans and table of plan names function dialplan.plans() local plans = { } local pnames = { } uci:foreach("asterisk", "dialplan", function(p) plans[p['.name']] = dialplan.parse(p) pnames[#pnames+1] = p['.name'] end) return plans, pnames end --- Get a specific dial plan -- @param name Name of the dial plan -- @return Table containing plan information function dialplan.plan(n) local plan uci:foreach("asterisk", "dialplan", function(p) if p['.name'] == n then plan = dialplan.parse(p) end end) return plan end
apache-2.0
cyclonetm/XmakanX
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
mrvigeo/pride
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
Joker-Developer/jokersuper
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
A-N-bot/anonymous
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
Tele-Fox/self
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
PicoleDeLimao/Ninpou2
game/dota_addons/ninpou2/scripts/vscripts/libraries/timers.lua
11
6560
TIMERS_VERSION = "1.05" --[[ -- A timer running every second that starts immediately on the next frame, respects pauses Timers:CreateTimer(function() print ("Hello. I'm running immediately and then every second thereafter.") return 1.0 end ) -- The same timer as above with a shorthand call Timers(function() print ("Hello. I'm running immediately and then every second thereafter.") return 1.0 end) -- A timer which calls a function with a table context Timers:CreateTimer(GameMode.someFunction, GameMode) -- A timer running every second that starts 5 seconds in the future, respects pauses Timers:CreateTimer(5, function() print ("Hello. I'm running 5 seconds after you called me and then every second thereafter.") return 1.0 end ) -- 10 second delayed, run once using gametime (respect pauses) Timers:CreateTimer({ endTime = 10, -- when this timer should first execute, you can omit this if you want it to run first on the next frame callback = function() print ("Hello. I'm running 10 seconds after when I was started.") end }) -- 10 second delayed, run once regardless of pauses Timers:CreateTimer({ useGameTime = false, endTime = 10, -- when this timer should first execute, you can omit this if you want it to run first on the next frame callback = function() print ("Hello. I'm running 10 seconds after I was started even if someone paused the game.") end }) -- A timer running every second that starts after 2 minutes regardless of pauses Timers:CreateTimer("uniqueTimerString3", { useGameTime = false, endTime = 120, callback = function() print ("Hello. I'm running after 2 minutes and then every second thereafter.") return 1 end }) -- A timer using the old style to repeat every second starting 5 seconds ahead Timers:CreateTimer("uniqueTimerString3", { useOldStyle = true, endTime = GameRules:GetGameTime() + 5, callback = function() print ("Hello. I'm running after 5 seconds and then every second thereafter.") return GameRules:GetGameTime() + 1 end }) ]] TIMERS_THINK = 0.01 if Timers == nil then print ( '[Timers] creating Timers' ) Timers = {} setmetatable(Timers, { __call = function(t, ...) return t:CreateTimer(...) end }) --Timers.__index = Timers end function Timers:start() Timers = self self.timers = {} --local ent = Entities:CreateByClassname("info_target") -- Entities:FindByClassname(nil, 'CWorld') local ent = SpawnEntityFromTableSynchronous("info_target", {targetname="timers_lua_thinker"}) ent:SetThink("Think", self, "timers", TIMERS_THINK) end function Timers:Think() --if GameRules:State_Get() >= DOTA_GAMERULES_STATE_POST_GAME then --return --end -- Track game time, since the dt passed in to think is actually wall-clock time not simulation time. local now = GameRules:GetGameTime() -- Process timers for k,v in pairs(Timers.timers) do local bUseGameTime = true if v.useGameTime ~= nil and v.useGameTime == false then bUseGameTime = false end local bOldStyle = false if v.useOldStyle ~= nil and v.useOldStyle == true then bOldStyle = true end local now = GameRules:GetGameTime() if not bUseGameTime then now = Time() end if v.endTime == nil then v.endTime = now end -- Check if the timer has finished if now >= v.endTime then -- Remove from timers list Timers.timers[k] = nil Timers.runningTimer = k Timers.removeSelf = false -- Run the callback local status, nextCall if v.context then status, nextCall = xpcall(function() return v.callback(v.context, v) end, function (msg) return msg..'\n'..debug.traceback()..'\n' end) else status, nextCall = xpcall(function() return v.callback(v) end, function (msg) return msg..'\n'..debug.traceback()..'\n' end) end Timers.runningTimer = nil -- Make sure it worked if status then -- Check if it needs to loop if nextCall and not Timers.removeSelf then -- Change its end time if bOldStyle then v.endTime = v.endTime + nextCall - now else v.endTime = v.endTime + nextCall end Timers.timers[k] = v end -- Update timer data --self:UpdateTimerData() else -- Nope, handle the error Timers:HandleEventError('Timer', k, nextCall) end end end return TIMERS_THINK end function Timers:HandleEventError(name, event, err) print(err) -- Ensure we have data name = tostring(name or 'unknown') event = tostring(event or 'unknown') err = tostring(err or 'unknown') -- Tell everyone there was an error --Say(nil, name .. ' threw an error on event '..event, false) --Say(nil, err, false) -- Prevent loop arounds if not self.errorHandled then -- Store that we handled an error self.errorHandled = true end end function Timers:CreateTimer(name, args, context) if type(name) == "function" then if args ~= nil then context = args end args = {callback = name} name = DoUniqueString("timer") elseif type(name) == "table" then args = name name = DoUniqueString("timer") elseif type(name) == "number" then args = {endTime = name, callback = args} name = DoUniqueString("timer") end if not args.callback then print("Invalid timer created: "..name) return end local now = GameRules:GetGameTime() if args.useGameTime ~= nil and args.useGameTime == false then now = Time() end if args.endTime == nil then args.endTime = now elseif args.useOldStyle == nil or args.useOldStyle == false then args.endTime = now + args.endTime end args.context = context Timers.timers[name] = args return name end function Timers:RemoveTimer(name) Timers.timers[name] = nil if Timers.runningTimer == name then Timers.removeSelf = true end end function Timers:RemoveTimers(killAll) local timers = {} Timers.removeSelf = true if not killAll then for k,v in pairs(Timers.timers) do if v.persist then timers[k] = v end end end Timers.timers = timers end if not Timers.timers then Timers:start() end GameRules.Timers = Timers
apache-2.0
Scavenge/darkstar
scripts/zones/Gusgen_Mines/Zone.lua
12
1638
----------------------------------- -- -- 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) UpdateTreasureSpawnPoint(17580403); 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
PicoleDeLimao/Ninpou2
game/dota_addons/ninpou2/scripts/vscripts/items/doton_kusanagi_no_tsurugi.lua
1
1157
--[[ Author: PicoleDeLimao Date: 03.04.2016 Deals area critical strike damage ]] function CriticalStrike(event) local caster = event.caster local target = event.target local ability = event.ability local bonus = ability:GetLevelSpecialValueFor("crit_bonus", ability:GetLevel() - 1) / 100.0 local radius = ability:GetLevelSpecialValueFor("crit_area", ability:GetLevel() - 1) local bashDuration = ability:GetLevelSpecialValueFor("bash_duration", ability:GetLevel() - 1) Units:FindEnemiesInRange({ unit = caster, point = target:GetAbsOrigin(), radius = radius, func = function(enemy) local damage = caster:GetAverageTrueAttackDamage(enemy) ApplyDamage({ victim = enemy, attacker = caster, damage = damage * bonus, damage_type = DAMAGE_TYPE_PHYSICAL}) local particle = Particles:CreateTimedParticle("particles/units/heroes/hero_centaur/centaur_warstomp.vpcf", enemy, 2.0) Particles:SetControl(particle, {1, 2}, 100) if not enemy:IsMagicImmune() then ability:ApplyDataDrivenModifier(caster, enemy, "modifier_item_doton_orb_stun", {duration = bashDuration}) end PopupCriticalDamage(enemy, damage * bonus) end }) end
apache-2.0