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
KayMD/Illarion-Content
item/id_72_fishingrod.lua
2
3855
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE items SET itm_script='item.id_72_fishingrod' WHERE itm_id=72; local common = require("base.common") local fishing = require("craft.gathering.fishing") local wood = require("item.general.wood") local M = {} M.LookAtItem = wood.LookAtItem local function getWaterTilePosition(User) local targetPos = common.GetFrontPosition(User) if (common.GetGroundType(world:getField(targetPos):tile()) == common.GroundType.water) then return targetPos end local Radius = 1; for x=-Radius,Radius do for y=-Radius,Radius do targetPos = position(User.pos.x + x, User.pos.y, User.pos.z) if (common.GetGroundType(world:getField(targetPos):tile()) == common.GroundType.water) then return targetPos end end end return nil; end local function getShoal(User, shoalId) local targetItem = common.GetFrontItem(User) if (targetItem ~= nil and targetItem.id == shoalId) then return targetItem; end local Radius = 1; for x=-Radius,Radius do for y=-Radius,Radius do local targetPos = position(User.pos.x + x, User.pos.y + y, User.pos.z) if (world:isItemOnField(targetPos)) then local targetItem = world:getItemOnField(targetPos) if (targetItem ~= nil and targetItem.id == shoalId) then return targetItem end end end end return nil; end function M.UseItem(User, SourceItem, ltstate) if (getWaterTilePosition(User) == nil) then -- fishing only possible on water tiles common.HighInformNLS(User, "Die Chance im Wasser einen Fisch zu fangen ist bedeutend höher als auf dem Land.", "The chance to catch a fish is much higher in the water than on the land.") return end local shoalItem = getShoal(User, 1170) if not shoalItem then shoalItem = getShoal(User, 1244) if shoalItem then User:inform("Die wenigen Fische hier scheinen nicht anbeißen zu wollen. Finde einen anderen Schwarm oder warte, bis sich hier mehr angesiedelt haben.","The few fish here don't seem willing to be caught. Look for another shoal or wait until there are more fish here.",Character.highPriority) return end end if not shoalItem then common.HighInformNLS(User, "Hier scheinen sich keine Fische zu befinden. Halte Ausschau nach einem Fischschwarm.", "There seems to be no fish here. Look for a shoal.") return end if User:getQuestProgress(688) ~= 1 then if User:getQuestProgress(718) == 3 or User:getQuestProgress(71) == 3 or common.Chance(1, 100) then common.InformNLS(User, "Müll gehört nicht ins Wasser. Du findest eine alte Pfanne, in der wohl früher mal Fische geräuchert wurden.", "Garbage doesn't belongs in the water. You find an old rusty pan that was used to smoke fish earlier.") User:setQuestProgress(688,1) common.CreateItem(User, 2495, 1, 117) return end end fishing.StartGathering(User, shoalItem, ltstate) end return M
agpl-3.0
miralireza2/gpf
plugins/stats.lua
4
3698
do local NUM_MSG_MAX = 3 local TIME_CHECK = 4 -- seconds local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..'👤|'..user_id..'|🗣' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = '' for k,user in pairs(users_info) do text = text..user.name..' => '..user.msgs..'\n-----------' end return text end -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then print('Service message') return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) -- Check flood local kick = chat_del_user(chat_id , user_id, ok_cb, true) vardump(kick) if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then chat_del_user('chat#id'..msg.to.id,'user#id'..msg.from.id,ok_cb,false) print('User '..msg.from.id..'is flooding '..msgs) msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nChats: '..r return text end local function run(msg, matches) if matches[1]:lower() == "stats" then if not matches[2] then if msg.to.type == 'chat' then local chat_id = msg.to.id return chat_stats(chat_id) else return 'Stats works only on chats' end end if matches[2] == "bot" then if not is_sudo(msg) then return "Bot stats requires privileged user" else return bot_stats() end end if matches[2] == "chat" then if not is_sudo(msg) then return "This command requires privileged user" else return chat_stats(matches[3]) end end end end return { description = "Plugin to update user stats.", usage = { "!stats: Returns a list of Username [telegram_id]: msg_num", "!stats chat <chat_id>: Show stats for chat_id", "!stats bot: Shows bot stats (sudo users)" }, patterns = { "^!([Ss]tats)$", "^!([Ss]tats) (chat) (%d+)", "^!([Ss]tats) (bot)" }, run = run, pre_process = pre_process } end
gpl-2.0
damoguyan8844/ABTestingGateway
lib/abtesting/adapter/runtime.lua
22
3599
--- -- @classmod abtesting.adapter.runtime -- @release 0.0.1 local modulename = "abtestingAdapterRuntime" local _M = {} local metatable = {__index = _M} _M._VERSION = "0.0.1" local ERRORINFO = require('abtesting.error.errcode').info --- -- @field fields -- @warning this is a conf, may other file later local fields= {} fields.divModulename = 'divModulename' fields.divDataKey = 'divDataKey' fields.userInfoModulename = 'userInfoModulename' local separator = ':' --- -- runtimeInfoIO new function -- @param database opened redis -- @param baseLibrary a library(prefix of redis key) of runtime info -- @return runtimeInfoIO object _M.new = function(self, database, baseLibrary) if not database then error{ERRORINFO.PARAMETER_NONE, 'need a object of redis'} end if not baseLibrary then error{ERRORINFO.PARAMETER_NONE, 'need a library of runtime info'} end self.database = database self.baseLibrary = baseLibrary return setmetatable(self, metatable) end --- -- set runtime info(diversion modulename and diversion metadata key) -- @param domain is a domain name to search runtime info -- @param ... now is diversion modulename and diversion data key -- @return if returned, the return value always SUCCESS _M.set = function(self, domain, ...) local info = {...} local divModulename = info[1] local divDataKey = info[2] local userInfoModulename = info[3] local database = self.database local divModulenamekey = table.concat({self.baseLibrary, domain, fields.divModulename}, separator) local divDataKeyOfKey = table.concat({self.baseLibrary, domain, fields.divDataKey}, separator) local userInfoModulenameKey = table.concat({self.baseLibrary, domain, fields.userInfoModulename}, separator) local ok, err = database:mset(divModulenamekey, divModulename, divDataKeyOfKey, divDataKey, userInfoModulenameKey, userInfoModulename) if not ok then error{ERRORINFO.REDIS_ERROR, err} end return ERRORINFO.SUCCESS end --- -- delete runtime info(diversion modulename and diversion metadata key) -- @param domain a domain of delete -- @return if returned, the return value always SUCCESS _M.del = function(self, domain) local database = self.database local divModulenamekey = table.concat({self.baseLibrary, domain, fields.divModulename}, separator) local divDataKeyOfKey = table.concat({self.baseLibrary, domain, fields.divDataKey}, separator) local userInfoModulenameKey = table.concat({self.baseLibrary, domain, fields.userInfoModulename}, separator) local ok, err = database:del(divModulenamekey, divDataKeyOfKey, userInfoModulenameKey) if not ok then error{ERRORINFO.REDIS_ERROR, err} end return ERRORINFO.SUCCESS end --- -- get runtime info(diversion modulename and diversion metadata key) -- @param domain is a domain name to search runtime info -- @return a table of diversion modulename and diversion metadata key _M.get = function(self, domain) local database = self.database local divModulenameKey = table.concat({self.baseLibrary, domain, fields.divModulename}, separator) local divDataKeyOfKey = table.concat({self.baseLibrary, domain, fields.divDataKey}, separator) local userInfoModulenameKey = table.concat({self.baseLibrary, domain, fields.userInfoModulename}, separator) local response, err = database:mget(divModulenameKey, divDataKeyOfKey, userInfoModulenameKey) if not response then error{ERRORINFO.REDIS_ERROR, err} end return response end return _M
mit
litnimax/luci
modules/base/luasrc/cbi.lua
76
40152
--[[ LuCI - Configuration Bind Interface Description: Offers an interface for binding configuration values to certain data types. Supports value and range validation and basic dependencies. FileId: $Id$ License: Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- module("luci.cbi", package.seeall) require("luci.template") local util = require("luci.util") require("luci.http") --local event = require "luci.sys.event" local fs = require("nixio.fs") local uci = require("luci.model.uci") local datatypes = require("luci.cbi.datatypes") local class = util.class local instanceof = util.instanceof FORM_NODATA = 0 FORM_PROCEED = 0 FORM_VALID = 1 FORM_DONE = 1 FORM_INVALID = -1 FORM_CHANGED = 2 FORM_SKIP = 4 AUTO = true CREATE_PREFIX = "cbi.cts." REMOVE_PREFIX = "cbi.rts." RESORT_PREFIX = "cbi.sts." FEXIST_PREFIX = "cbi.cbe." -- Loads a CBI map from given file, creating an environment and returns it function load(cbimap, ...) local fs = require "nixio.fs" local i18n = require "luci.i18n" require("luci.config") require("luci.util") local upldir = "/lib/uci/upload/" local cbidir = luci.util.libpath() .. "/model/cbi/" local func, err if fs.access(cbidir..cbimap..".lua") then func, err = loadfile(cbidir..cbimap..".lua") elseif fs.access(cbimap) then func, err = loadfile(cbimap) else func, err = nil, "Model '" .. cbimap .. "' not found!" end assert(func, err) local env = { translate=i18n.translate, translatef=i18n.translatef, arg={...} } setfenv(func, setmetatable(env, {__index = function(tbl, key) return rawget(tbl, key) or _M[key] or _G[key] end})) local maps = { func() } local uploads = { } local has_upload = false for i, map in ipairs(maps) do if not instanceof(map, Node) then error("CBI map returns no valid map object!") return nil else map:prepare() if map.upload_fields then has_upload = true for _, field in ipairs(map.upload_fields) do uploads[ field.config .. '.' .. (field.section.sectiontype or '1') .. '.' .. field.option ] = true end end end end if has_upload then local uci = luci.model.uci.cursor() local prm = luci.http.context.request.message.params local fd, cbid luci.http.setfilehandler( function( field, chunk, eof ) if not field then return end if field.name and not cbid then local c, s, o = field.name:gmatch( "cbid%.([^%.]+)%.([^%.]+)%.([^%.]+)" )() if c and s and o then local t = uci:get( c, s ) or s if uploads[c.."."..t.."."..o] then local path = upldir .. field.name fd = io.open(path, "w") if fd then cbid = field.name prm[cbid] = path end end end end if field.name == cbid and fd then fd:write(chunk) end if eof and fd then fd:close() fd = nil cbid = nil end end ) end return maps end -- -- Compile a datatype specification into a parse tree for evaluation later on -- local cdt_cache = { } function compile_datatype(code) local i local pos = 0 local esc = false local depth = 0 local stack = { } for i = 1, #code+1 do local byte = code:byte(i) or 44 if esc then esc = false elseif byte == 92 then esc = true elseif byte == 40 or byte == 44 then if depth <= 0 then if pos < i then local label = code:sub(pos, i-1) :gsub("\\(.)", "%1") :gsub("^%s+", "") :gsub("%s+$", "") if #label > 0 and tonumber(label) then stack[#stack+1] = tonumber(label) elseif label:match("^'.*'$") or label:match('^".*"$') then stack[#stack+1] = label:gsub("[\"'](.*)[\"']", "%1") elseif type(datatypes[label]) == "function" then stack[#stack+1] = datatypes[label] stack[#stack+1] = { } else error("Datatype error, bad token %q" % label) end end pos = i + 1 end depth = depth + (byte == 40 and 1 or 0) elseif byte == 41 then depth = depth - 1 if depth <= 0 then if type(stack[#stack-1]) ~= "function" then error("Datatype error, argument list follows non-function") end stack[#stack] = compile_datatype(code:sub(pos, i-1)) pos = i + 1 end end end return stack end function verify_datatype(dt, value) if dt and #dt > 0 then if not cdt_cache[dt] then local c = compile_datatype(dt) if c and type(c[1]) == "function" then cdt_cache[dt] = c else error("Datatype error, not a function expression") end end if cdt_cache[dt] then return cdt_cache[dt][1](value, unpack(cdt_cache[dt][2])) end end return true end -- Node pseudo abstract class Node = class() function Node.__init__(self, title, description) self.children = {} self.title = title or "" self.description = description or "" self.template = "cbi/node" end -- hook helper function Node._run_hook(self, hook) if type(self[hook]) == "function" then return self[hook](self) end end function Node._run_hooks(self, ...) local f local r = false for _, f in ipairs(arg) do if type(self[f]) == "function" then self[f](self) r = true end end return r end -- Prepare nodes function Node.prepare(self, ...) for k, child in ipairs(self.children) do child:prepare(...) end end -- Append child nodes function Node.append(self, obj) table.insert(self.children, obj) end -- Parse this node and its children function Node.parse(self, ...) for k, child in ipairs(self.children) do child:parse(...) end end -- Render this node function Node.render(self, scope) scope = scope or {} scope.self = self luci.template.render(self.template, scope) end -- Render the children function Node.render_children(self, ...) local k, node for k, node in ipairs(self.children) do node.last_child = (k == #self.children) node:render(...) end end --[[ A simple template element ]]-- Template = class(Node) function Template.__init__(self, template) Node.__init__(self) self.template = template end function Template.render(self) luci.template.render(self.template, {self=self}) end function Template.parse(self, readinput) self.readinput = (readinput ~= false) return Map.formvalue(self, "cbi.submit") and FORM_DONE or FORM_NODATA end --[[ Map - A map describing a configuration file ]]-- Map = class(Node) function Map.__init__(self, config, ...) Node.__init__(self, ...) self.config = config self.parsechain = {self.config} self.template = "cbi/map" self.apply_on_parse = nil self.readinput = true self.proceed = false self.flow = {} self.uci = uci.cursor() self.save = true self.changed = false if not self.uci:load(self.config) then error("Unable to read UCI data: " .. self.config) end end function Map.formvalue(self, key) return self.readinput and luci.http.formvalue(key) end function Map.formvaluetable(self, key) return self.readinput and luci.http.formvaluetable(key) or {} end function Map.get_scheme(self, sectiontype, option) if not option then return self.scheme and self.scheme.sections[sectiontype] else return self.scheme and self.scheme.variables[sectiontype] and self.scheme.variables[sectiontype][option] end end function Map.submitstate(self) return self:formvalue("cbi.submit") end -- Chain foreign config function Map.chain(self, config) table.insert(self.parsechain, config) end function Map.state_handler(self, state) return state end -- Use optimized UCI writing function Map.parse(self, readinput, ...) self.readinput = (readinput ~= false) self:_run_hooks("on_parse") if self:formvalue("cbi.skip") then self.state = FORM_SKIP return self:state_handler(self.state) end Node.parse(self, ...) if self.save then self:_run_hooks("on_save", "on_before_save") for i, config in ipairs(self.parsechain) do self.uci:save(config) end self:_run_hooks("on_after_save") if self:submitstate() and ((not self.proceed and self.flow.autoapply) or luci.http.formvalue("cbi.apply")) then self:_run_hooks("on_before_commit") for i, config in ipairs(self.parsechain) do self.uci:commit(config) -- Refresh data because commit changes section names self.uci:load(config) end self:_run_hooks("on_commit", "on_after_commit", "on_before_apply") if self.apply_on_parse then self.uci:apply(self.parsechain) self:_run_hooks("on_apply", "on_after_apply") else -- This is evaluated by the dispatcher and delegated to the -- template which in turn fires XHR to perform the actual -- apply actions. self.apply_needed = true end -- Reparse sections Node.parse(self, true) end for i, config in ipairs(self.parsechain) do self.uci:unload(config) end if type(self.commit_handler) == "function" then self:commit_handler(self:submitstate()) end end if self:submitstate() then if not self.save then self.state = FORM_INVALID elseif self.proceed then self.state = FORM_PROCEED else self.state = self.changed and FORM_CHANGED or FORM_VALID end else self.state = FORM_NODATA end return self:state_handler(self.state) end function Map.render(self, ...) self:_run_hooks("on_init") Node.render(self, ...) end -- Creates a child section function Map.section(self, class, ...) if instanceof(class, AbstractSection) then local obj = class(self, ...) self:append(obj) return obj else error("class must be a descendent of AbstractSection") end end -- UCI add function Map.add(self, sectiontype) return self.uci:add(self.config, sectiontype) end -- UCI set function Map.set(self, section, option, value) if type(value) ~= "table" or #value > 0 then if option then return self.uci:set(self.config, section, option, value) else return self.uci:set(self.config, section, value) end else return Map.del(self, section, option) end end -- UCI del function Map.del(self, section, option) if option then return self.uci:delete(self.config, section, option) else return self.uci:delete(self.config, section) end end -- UCI get function Map.get(self, section, option) if not section then return self.uci:get_all(self.config) elseif option then return self.uci:get(self.config, section, option) else return self.uci:get_all(self.config, section) end end --[[ Compound - Container ]]-- Compound = class(Node) function Compound.__init__(self, ...) Node.__init__(self) self.template = "cbi/compound" self.children = {...} end function Compound.populate_delegator(self, delegator) for _, v in ipairs(self.children) do v.delegator = delegator end end function Compound.parse(self, ...) local cstate, state = 0 for k, child in ipairs(self.children) do cstate = child:parse(...) state = (not state or cstate < state) and cstate or state end return state end --[[ Delegator - Node controller ]]-- Delegator = class(Node) function Delegator.__init__(self, ...) Node.__init__(self, ...) self.nodes = {} self.defaultpath = {} self.pageaction = false self.readinput = true self.allow_reset = false self.allow_cancel = false self.allow_back = false self.allow_finish = false self.template = "cbi/delegator" end function Delegator.set(self, name, node) assert(not self.nodes[name], "Duplicate entry") self.nodes[name] = node end function Delegator.add(self, name, node) node = self:set(name, node) self.defaultpath[#self.defaultpath+1] = name end function Delegator.insert_after(self, name, after) local n = #self.chain + 1 for k, v in ipairs(self.chain) do if v == after then n = k + 1 break end end table.insert(self.chain, n, name) end function Delegator.set_route(self, ...) local n, chain, route = 0, self.chain, {...} for i = 1, #chain do if chain[i] == self.current then n = i break end end for i = 1, #route do n = n + 1 chain[n] = route[i] end for i = n + 1, #chain do chain[i] = nil end end function Delegator.get(self, name) local node = self.nodes[name] if type(node) == "string" then node = load(node, name) end if type(node) == "table" and getmetatable(node) == nil then node = Compound(unpack(node)) end return node end function Delegator.parse(self, ...) if self.allow_cancel and Map.formvalue(self, "cbi.cancel") then if self:_run_hooks("on_cancel") then return FORM_DONE end end if not Map.formvalue(self, "cbi.delg.current") then self:_run_hooks("on_init") end local newcurrent self.chain = self.chain or self:get_chain() self.current = self.current or self:get_active() self.active = self.active or self:get(self.current) assert(self.active, "Invalid state") local stat = FORM_DONE if type(self.active) ~= "function" then self.active:populate_delegator(self) stat = self.active:parse() else self:active() end if stat > FORM_PROCEED then if Map.formvalue(self, "cbi.delg.back") then newcurrent = self:get_prev(self.current) else newcurrent = self:get_next(self.current) end elseif stat < FORM_PROCEED then return stat end if not Map.formvalue(self, "cbi.submit") then return FORM_NODATA elseif stat > FORM_PROCEED and (not newcurrent or not self:get(newcurrent)) then return self:_run_hook("on_done") or FORM_DONE else self.current = newcurrent or self.current self.active = self:get(self.current) if type(self.active) ~= "function" then self.active:populate_delegator(self) local stat = self.active:parse(false) if stat == FORM_SKIP then return self:parse(...) else return FORM_PROCEED end else return self:parse(...) end end end function Delegator.get_next(self, state) for k, v in ipairs(self.chain) do if v == state then return self.chain[k+1] end end end function Delegator.get_prev(self, state) for k, v in ipairs(self.chain) do if v == state then return self.chain[k-1] end end end function Delegator.get_chain(self) local x = Map.formvalue(self, "cbi.delg.path") or self.defaultpath return type(x) == "table" and x or {x} end function Delegator.get_active(self) return Map.formvalue(self, "cbi.delg.current") or self.chain[1] end --[[ Page - A simple node ]]-- Page = class(Node) Page.__init__ = Node.__init__ Page.parse = function() end --[[ SimpleForm - A Simple non-UCI form ]]-- SimpleForm = class(Node) function SimpleForm.__init__(self, config, title, description, data) Node.__init__(self, title, description) self.config = config self.data = data or {} self.template = "cbi/simpleform" self.dorender = true self.pageaction = false self.readinput = true end SimpleForm.formvalue = Map.formvalue SimpleForm.formvaluetable = Map.formvaluetable function SimpleForm.parse(self, readinput, ...) self.readinput = (readinput ~= false) if self:formvalue("cbi.skip") then return FORM_SKIP end if self:formvalue("cbi.cancel") and self:_run_hooks("on_cancel") then return FORM_DONE end if self:submitstate() then Node.parse(self, 1, ...) end local valid = true for k, j in ipairs(self.children) do for i, v in ipairs(j.children) do valid = valid and (not v.tag_missing or not v.tag_missing[1]) and (not v.tag_invalid or not v.tag_invalid[1]) and (not v.error) end end local state = not self:submitstate() and FORM_NODATA or valid and FORM_VALID or FORM_INVALID self.dorender = not self.handle if self.handle then local nrender, nstate = self:handle(state, self.data) self.dorender = self.dorender or (nrender ~= false) state = nstate or state end return state end function SimpleForm.render(self, ...) if self.dorender then Node.render(self, ...) end end function SimpleForm.submitstate(self) return self:formvalue("cbi.submit") end function SimpleForm.section(self, class, ...) if instanceof(class, AbstractSection) then local obj = class(self, ...) self:append(obj) return obj else error("class must be a descendent of AbstractSection") end end -- Creates a child field function SimpleForm.field(self, class, ...) local section for k, v in ipairs(self.children) do if instanceof(v, SimpleSection) then section = v break end end if not section then section = self:section(SimpleSection) end if instanceof(class, AbstractValue) then local obj = class(self, section, ...) obj.track_missing = true section:append(obj) return obj else error("class must be a descendent of AbstractValue") end end function SimpleForm.set(self, section, option, value) self.data[option] = value end function SimpleForm.del(self, section, option) self.data[option] = nil end function SimpleForm.get(self, section, option) return self.data[option] end function SimpleForm.get_scheme() return nil end Form = class(SimpleForm) function Form.__init__(self, ...) SimpleForm.__init__(self, ...) self.embedded = true end --[[ AbstractSection ]]-- AbstractSection = class(Node) function AbstractSection.__init__(self, map, sectiontype, ...) Node.__init__(self, ...) self.sectiontype = sectiontype self.map = map self.config = map.config self.optionals = {} self.defaults = {} self.fields = {} self.tag_error = {} self.tag_invalid = {} self.tag_deperror = {} self.changed = false self.optional = true self.addremove = false self.dynamic = false end -- Define a tab for the section function AbstractSection.tab(self, tab, title, desc) self.tabs = self.tabs or { } self.tab_names = self.tab_names or { } self.tab_names[#self.tab_names+1] = tab self.tabs[tab] = { title = title, description = desc, childs = { } } end -- Check whether the section has tabs function AbstractSection.has_tabs(self) return (self.tabs ~= nil) and (next(self.tabs) ~= nil) end -- Appends a new option function AbstractSection.option(self, class, option, ...) if instanceof(class, AbstractValue) then local obj = class(self.map, self, option, ...) self:append(obj) self.fields[option] = obj return obj elseif class == true then error("No valid class was given and autodetection failed.") else error("class must be a descendant of AbstractValue") end end -- Appends a new tabbed option function AbstractSection.taboption(self, tab, ...) assert(tab and self.tabs and self.tabs[tab], "Cannot assign option to not existing tab %q" % tostring(tab)) local l = self.tabs[tab].childs local o = AbstractSection.option(self, ...) if o then l[#l+1] = o end return o end -- Render a single tab function AbstractSection.render_tab(self, tab, ...) assert(tab and self.tabs and self.tabs[tab], "Cannot render not existing tab %q" % tostring(tab)) local k, node for k, node in ipairs(self.tabs[tab].childs) do node.last_child = (k == #self.tabs[tab].childs) node:render(...) end end -- Parse optional options function AbstractSection.parse_optionals(self, section) if not self.optional then return end self.optionals[section] = {} local field = self.map:formvalue("cbi.opt."..self.config.."."..section) for k,v in ipairs(self.children) do if v.optional and not v:cfgvalue(section) and not self:has_tabs() then if field == v.option then field = nil self.map.proceed = true else table.insert(self.optionals[section], v) end end end if field and #field > 0 and self.dynamic then self:add_dynamic(field) end end -- Add a dynamic option function AbstractSection.add_dynamic(self, field, optional) local o = self:option(Value, field, field) o.optional = optional end -- Parse all dynamic options function AbstractSection.parse_dynamic(self, section) if not self.dynamic then return end local arr = luci.util.clone(self:cfgvalue(section)) local form = self.map:formvaluetable("cbid."..self.config.."."..section) for k, v in pairs(form) do arr[k] = v end for key,val in pairs(arr) do local create = true for i,c in ipairs(self.children) do if c.option == key then create = false end end if create and key:sub(1, 1) ~= "." then self.map.proceed = true self:add_dynamic(key, true) end end end -- Returns the section's UCI table function AbstractSection.cfgvalue(self, section) return self.map:get(section) end -- Push events function AbstractSection.push_events(self) --luci.util.append(self.map.events, self.events) self.map.changed = true end -- Removes the section function AbstractSection.remove(self, section) self.map.proceed = true return self.map:del(section) end -- Creates the section function AbstractSection.create(self, section) local stat if section then stat = section:match("^[%w_]+$") and self.map:set(section, nil, self.sectiontype) else section = self.map:add(self.sectiontype) stat = section end if stat then for k,v in pairs(self.children) do if v.default then self.map:set(section, v.option, v.default) end end for k,v in pairs(self.defaults) do self.map:set(section, k, v) end end self.map.proceed = true return stat end SimpleSection = class(AbstractSection) function SimpleSection.__init__(self, form, ...) AbstractSection.__init__(self, form, nil, ...) self.template = "cbi/nullsection" end Table = class(AbstractSection) function Table.__init__(self, form, data, ...) local datasource = {} local tself = self datasource.config = "table" self.data = data or {} datasource.formvalue = Map.formvalue datasource.formvaluetable = Map.formvaluetable datasource.readinput = true function datasource.get(self, section, option) return tself.data[section] and tself.data[section][option] end function datasource.submitstate(self) return Map.formvalue(self, "cbi.submit") end function datasource.del(...) return true end function datasource.get_scheme() return nil end AbstractSection.__init__(self, datasource, "table", ...) self.template = "cbi/tblsection" self.rowcolors = true self.anonymous = true end function Table.parse(self, readinput) self.map.readinput = (readinput ~= false) for i, k in ipairs(self:cfgsections()) do if self.map:submitstate() then Node.parse(self, k) end end end function Table.cfgsections(self) local sections = {} for i, v in luci.util.kspairs(self.data) do table.insert(sections, i) end return sections end function Table.update(self, data) self.data = data end --[[ NamedSection - A fixed configuration section defined by its name ]]-- NamedSection = class(AbstractSection) function NamedSection.__init__(self, map, section, stype, ...) AbstractSection.__init__(self, map, stype, ...) -- Defaults self.addremove = false self.template = "cbi/nsection" self.section = section end function NamedSection.parse(self, novld) local s = self.section local active = self:cfgvalue(s) if self.addremove then local path = self.config.."."..s if active then -- Remove the section if self.map:formvalue("cbi.rns."..path) and self:remove(s) then self:push_events() return end else -- Create and apply default values if self.map:formvalue("cbi.cns."..path) then self:create(s) return end end end if active then AbstractSection.parse_dynamic(self, s) if self.map:submitstate() then Node.parse(self, s) end AbstractSection.parse_optionals(self, s) if self.changed then self:push_events() end end end --[[ TypedSection - A (set of) configuration section(s) defined by the type addremove: Defines whether the user can add/remove sections of this type anonymous: Allow creating anonymous sections validate: a validation function returning nil if the section is invalid ]]-- TypedSection = class(AbstractSection) function TypedSection.__init__(self, map, type, ...) AbstractSection.__init__(self, map, type, ...) self.template = "cbi/tsection" self.deps = {} self.anonymous = false end -- Return all matching UCI sections for this TypedSection function TypedSection.cfgsections(self) local sections = {} self.map.uci:foreach(self.map.config, self.sectiontype, function (section) if self:checkscope(section[".name"]) then table.insert(sections, section[".name"]) end end) return sections end -- Limits scope to sections that have certain option => value pairs function TypedSection.depends(self, option, value) table.insert(self.deps, {option=option, value=value}) end function TypedSection.parse(self, novld) if self.addremove then -- Remove local crval = REMOVE_PREFIX .. self.config local name = self.map:formvaluetable(crval) for k,v in pairs(name) do if k:sub(-2) == ".x" then k = k:sub(1, #k - 2) end if self:cfgvalue(k) and self:checkscope(k) then self:remove(k) end end end local co for i, k in ipairs(self:cfgsections()) do AbstractSection.parse_dynamic(self, k) if self.map:submitstate() then Node.parse(self, k, novld) end AbstractSection.parse_optionals(self, k) end if self.addremove then -- Create local created local crval = CREATE_PREFIX .. self.config .. "." .. self.sectiontype local origin, name = next(self.map:formvaluetable(crval)) if self.anonymous then if name then created = self:create(nil, origin) end else if name then -- Ignore if it already exists if self:cfgvalue(name) then name = nil; end name = self:checkscope(name) if not name then self.err_invalid = true end if name and #name > 0 then created = self:create(name, origin) and name if not created then self.invalid_cts = true end end end end if created then AbstractSection.parse_optionals(self, created) end end if self.sortable then local stval = RESORT_PREFIX .. self.config .. "." .. self.sectiontype local order = self.map:formvalue(stval) if order and #order > 0 then local sid local num = 0 for sid in util.imatch(order) do self.map.uci:reorder(self.config, sid, num) num = num + 1 end self.changed = (num > 0) end end if created or self.changed then self:push_events() end end -- Verifies scope of sections function TypedSection.checkscope(self, section) -- Check if we are not excluded if self.filter and not self:filter(section) then return nil end -- Check if at least one dependency is met if #self.deps > 0 and self:cfgvalue(section) then local stat = false for k, v in ipairs(self.deps) do if self:cfgvalue(section)[v.option] == v.value then stat = true end end if not stat then return nil end end return self:validate(section) end -- Dummy validate function function TypedSection.validate(self, section) return section end --[[ AbstractValue - An abstract Value Type null: Value can be empty valid: A function returning the value if it is valid otherwise nil depends: A table of option => value pairs of which one must be true default: The default value size: The size of the input fields rmempty: Unset value if empty optional: This value is optional (see AbstractSection.optionals) ]]-- AbstractValue = class(Node) function AbstractValue.__init__(self, map, section, option, ...) Node.__init__(self, ...) self.section = section self.option = option self.map = map self.config = map.config self.tag_invalid = {} self.tag_missing = {} self.tag_reqerror = {} self.tag_error = {} self.deps = {} self.subdeps = {} --self.cast = "string" self.track_missing = false self.rmempty = true self.default = nil self.size = nil self.optional = false end function AbstractValue.prepare(self) self.cast = self.cast or "string" end -- Add a dependencie to another section field function AbstractValue.depends(self, field, value) local deps if type(field) == "string" then deps = {} deps[field] = value else deps = field end table.insert(self.deps, {deps=deps, add=""}) end -- Generates the unique CBID function AbstractValue.cbid(self, section) return "cbid."..self.map.config.."."..section.."."..self.option end -- Return whether this object should be created function AbstractValue.formcreated(self, section) local key = "cbi.opt."..self.config.."."..section return (self.map:formvalue(key) == self.option) end -- Returns the formvalue for this object function AbstractValue.formvalue(self, section) return self.map:formvalue(self:cbid(section)) end function AbstractValue.additional(self, value) self.optional = value end function AbstractValue.mandatory(self, value) self.rmempty = not value end function AbstractValue.add_error(self, section, type, msg) self.error = self.error or { } self.error[section] = msg or type self.section.error = self.section.error or { } self.section.error[section] = self.section.error[section] or { } table.insert(self.section.error[section], msg or type) if type == "invalid" then self.tag_invalid[section] = true elseif type == "missing" then self.tag_missing[section] = true end self.tag_error[section] = true self.map.save = false end function AbstractValue.parse(self, section, novld) local fvalue = self:formvalue(section) local cvalue = self:cfgvalue(section) -- If favlue and cvalue are both tables and have the same content -- make them identical if type(fvalue) == "table" and type(cvalue) == "table" then local equal = #fvalue == #cvalue if equal then for i=1, #fvalue do if cvalue[i] ~= fvalue[i] then equal = false end end end if equal then fvalue = cvalue end end if fvalue and #fvalue > 0 then -- If we have a form value, write it to UCI local val_err fvalue, val_err = self:validate(fvalue, section) fvalue = self:transform(fvalue) if not fvalue and not novld then self:add_error(section, "invalid", val_err) end if fvalue and (self.forcewrite or not (fvalue == cvalue)) then if self:write(section, fvalue) then -- Push events self.section.changed = true --luci.util.append(self.map.events, self.events) end end else -- Unset the UCI or error if self.rmempty or self.optional then if self:remove(section) then -- Push events self.section.changed = true --luci.util.append(self.map.events, self.events) end elseif cvalue ~= fvalue and not novld then -- trigger validator with nil value to get custom user error msg. local _, val_err = self:validate(nil, section) self:add_error(section, "missing", val_err) end end end -- Render if this value exists or if it is mandatory function AbstractValue.render(self, s, scope) if not self.optional or self.section:has_tabs() or self:cfgvalue(s) or self:formcreated(s) then scope = scope or {} scope.section = s scope.cbid = self:cbid(s) Node.render(self, scope) end end -- Return the UCI value of this object function AbstractValue.cfgvalue(self, section) local value if self.tag_error[section] then value = self:formvalue(section) else value = self.map:get(section, self.option) end if not value then return nil elseif not self.cast or self.cast == type(value) then return value elseif self.cast == "string" then if type(value) == "table" then return value[1] end elseif self.cast == "table" then return { value } end end -- Validate the form value function AbstractValue.validate(self, value) if self.datatype and value then if type(value) == "table" then local v for _, v in ipairs(value) do if v and #v > 0 and not verify_datatype(self.datatype, v) then return nil end end else if not verify_datatype(self.datatype, value) then return nil end end end return value end AbstractValue.transform = AbstractValue.validate -- Write to UCI function AbstractValue.write(self, section, value) return self.map:set(section, self.option, value) end -- Remove from UCI function AbstractValue.remove(self, section) return self.map:del(section, self.option) end --[[ Value - A one-line value maxlength: The maximum length ]]-- Value = class(AbstractValue) function Value.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/value" self.keylist = {} self.vallist = {} end function Value.reset_values(self) self.keylist = {} self.vallist = {} end function Value.value(self, key, val) val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end -- DummyValue - This does nothing except being there DummyValue = class(AbstractValue) function DummyValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/dvalue" self.value = nil end function DummyValue.cfgvalue(self, section) local value if self.value then if type(self.value) == "function" then value = self:value(section) else value = self.value end else value = AbstractValue.cfgvalue(self, section) end return value end function DummyValue.parse(self) end --[[ Flag - A flag being enabled or disabled ]]-- Flag = class(AbstractValue) function Flag.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/fvalue" self.enabled = "1" self.disabled = "0" self.default = self.disabled end -- A flag can only have two states: set or unset function Flag.parse(self, section) local fexists = self.map:formvalue( FEXIST_PREFIX .. self.config .. "." .. section .. "." .. self.option) if fexists then local fvalue = self:formvalue(section) and self.enabled or self.disabled if fvalue ~= self.default or (not self.optional and not self.rmempty) then self:write(section, fvalue) else self:remove(section) end else self:remove(section) end end function Flag.cfgvalue(self, section) return AbstractValue.cfgvalue(self, section) or self.default end --[[ ListValue - A one-line value predefined in a list widget: The widget that will be used (select, radio) ]]-- ListValue = class(AbstractValue) function ListValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/lvalue" self.keylist = {} self.vallist = {} self.size = 1 self.widget = "select" end function ListValue.reset_values(self) self.keylist = {} self.vallist = {} end function ListValue.value(self, key, val, ...) if luci.util.contains(self.keylist, key) then return end val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) for i, deps in ipairs({...}) do self.subdeps[#self.subdeps + 1] = {add = "-"..key, deps=deps} end end function ListValue.validate(self, val) if luci.util.contains(self.keylist, val) then return val else return nil end end --[[ MultiValue - Multiple delimited values widget: The widget that will be used (select, checkbox) delimiter: The delimiter that will separate the values (default: " ") ]]-- MultiValue = class(AbstractValue) function MultiValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/mvalue" self.keylist = {} self.vallist = {} self.widget = "checkbox" self.delimiter = " " end function MultiValue.render(self, ...) if self.widget == "select" and not self.size then self.size = #self.vallist end AbstractValue.render(self, ...) end function MultiValue.reset_values(self) self.keylist = {} self.vallist = {} end function MultiValue.value(self, key, val) if luci.util.contains(self.keylist, key) then return end val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end function MultiValue.valuelist(self, section) local val = self:cfgvalue(section) if not(type(val) == "string") then return {} end return luci.util.split(val, self.delimiter) end function MultiValue.validate(self, val) val = (type(val) == "table") and val or {val} local result for i, value in ipairs(val) do if luci.util.contains(self.keylist, value) then result = result and (result .. self.delimiter .. value) or value end end return result end StaticList = class(MultiValue) function StaticList.__init__(self, ...) MultiValue.__init__(self, ...) self.cast = "table" self.valuelist = self.cfgvalue if not self.override_scheme and self.map:get_scheme(self.section.sectiontype, self.option) then local vs = self.map:get_scheme(self.section.sectiontype, self.option) if self.value and vs.values and not self.override_values then for k, v in pairs(vs.values) do self:value(k, v) end end end end function StaticList.validate(self, value) value = (type(value) == "table") and value or {value} local valid = {} for i, v in ipairs(value) do if luci.util.contains(self.keylist, v) then table.insert(valid, v) end end return valid end DynamicList = class(AbstractValue) function DynamicList.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/dynlist" self.cast = "table" self.keylist = {} self.vallist = {} end function DynamicList.reset_values(self) self.keylist = {} self.vallist = {} end function DynamicList.value(self, key, val) val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end function DynamicList.write(self, section, value) local t = { } if type(value) == "table" then local x for _, x in ipairs(value) do if x and #x > 0 then t[#t+1] = x end end else t = { value } end if self.cast == "string" then value = table.concat(t, " ") else value = t end return AbstractValue.write(self, section, value) end function DynamicList.cfgvalue(self, section) local value = AbstractValue.cfgvalue(self, section) if type(value) == "string" then local x local t = { } for x in value:gmatch("%S+") do if #x > 0 then t[#t+1] = x end end value = t end return value end function DynamicList.formvalue(self, section) local value = AbstractValue.formvalue(self, section) if type(value) == "string" then if self.cast == "string" then local x local t = { } for x in value:gmatch("%S+") do t[#t+1] = x end value = t else value = { value } end end return value end --[[ TextValue - A multi-line value rows: Rows ]]-- TextValue = class(AbstractValue) function TextValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/tvalue" end --[[ Button ]]-- Button = class(AbstractValue) function Button.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/button" self.inputstyle = nil self.rmempty = true end FileUpload = class(AbstractValue) function FileUpload.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/upload" if not self.map.upload_fields then self.map.upload_fields = { self } else self.map.upload_fields[#self.map.upload_fields+1] = self end end function FileUpload.formcreated(self, section) return AbstractValue.formcreated(self, section) or self.map:formvalue("cbi.rlf."..section.."."..self.option) or self.map:formvalue("cbi.rlf."..section.."."..self.option..".x") end function FileUpload.cfgvalue(self, section) local val = AbstractValue.cfgvalue(self, section) if val and fs.access(val) then return val end return nil end function FileUpload.formvalue(self, section) local val = AbstractValue.formvalue(self, section) if val then if not self.map:formvalue("cbi.rlf."..section.."."..self.option) and not self.map:formvalue("cbi.rlf."..section.."."..self.option..".x") then return val end fs.unlink(val) self.value = nil end return nil end function FileUpload.remove(self, section) local val = AbstractValue.formvalue(self, section) if val and fs.access(val) then fs.unlink(val) end return AbstractValue.remove(self, section) end FileBrowser = class(AbstractValue) function FileBrowser.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/browser" end
apache-2.0
cecile/Cecile_QuickLaunch
src/Cecile_QuickLaunch/libs/AceGUI-3.0/widgets/AceGUIWidget-Label.lua
11
4774
--[[----------------------------------------------------------------------------- Label Widget Displays text and optionally an icon. -------------------------------------------------------------------------------]] local Type, Version = "Label", 27 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local max, select, pairs = math.max, select, pairs -- WoW APIs local CreateFrame, UIParent = CreateFrame, UIParent -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: GameFontHighlightSmall --[[----------------------------------------------------------------------------- Support functions -------------------------------------------------------------------------------]] local function UpdateImageAnchor(self) if self.resizing then return end local frame = self.frame local width = frame.width or frame:GetWidth() or 0 local image = self.image local label = self.label local height label:ClearAllPoints() image:ClearAllPoints() if self.imageshown then local imagewidth = image:GetWidth() if (width - imagewidth) < 200 or (label:GetText() or "") == "" then -- image goes on top centered when less than 200 width for the text, or if there is no text image:SetPoint("TOP") label:SetPoint("TOP", image, "BOTTOM") label:SetPoint("LEFT") label:SetWidth(width) height = image:GetHeight() + label:GetStringHeight() else -- image on the left image:SetPoint("TOPLEFT") if image:GetHeight() > label:GetStringHeight() then label:SetPoint("LEFT", image, "RIGHT", 4, 0) else label:SetPoint("TOPLEFT", image, "TOPRIGHT", 4, 0) end label:SetWidth(width - imagewidth - 4) height = max(image:GetHeight(), label:GetStringHeight()) end else -- no image shown label:SetPoint("TOPLEFT") label:SetWidth(width) height = label:GetStringHeight() end -- avoid zero-height labels, since they can used as spacers if not height or height == 0 then height = 1 end self.resizing = true frame:SetHeight(height) frame.height = height self.resizing = nil end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) -- set the flag to stop constant size updates self.resizing = true -- height is set dynamically by the text and image size self:SetWidth(200) self:SetText() self:SetImage(nil) self:SetImageSize(16, 16) self:SetColor() self:SetFontObject() self:SetJustifyH("LEFT") self:SetJustifyV("TOP") -- reset the flag self.resizing = nil -- run the update explicitly UpdateImageAnchor(self) end, -- ["OnRelease"] = nil, ["OnWidthSet"] = function(self, width) UpdateImageAnchor(self) end, ["SetText"] = function(self, text) self.label:SetText(text) UpdateImageAnchor(self) end, ["SetColor"] = function(self, r, g, b) if not (r and g and b) then r, g, b = 1, 1, 1 end self.label:SetVertexColor(r, g, b) end, ["SetImage"] = function(self, path, ...) local image = self.image image:SetTexture(path) if image:GetTexture() then self.imageshown = true local n = select("#", ...) if n == 4 or n == 8 then image:SetTexCoord(...) else image:SetTexCoord(0, 1, 0, 1) end else self.imageshown = nil end UpdateImageAnchor(self) end, ["SetFont"] = function(self, font, height, flags) self.label:SetFont(font, height, flags) UpdateImageAnchor(self) end, ["SetFontObject"] = function(self, font) self:SetFont((font or GameFontHighlightSmall):GetFont()) end, ["SetImageSize"] = function(self, width, height) self.image:SetWidth(width) self.image:SetHeight(height) UpdateImageAnchor(self) end, ["SetJustifyH"] = function(self, justifyH) self.label:SetJustifyH(justifyH) end, ["SetJustifyV"] = function(self, justifyV) self.label:SetJustifyV(justifyV) end, } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local frame = CreateFrame("Frame", nil, UIParent) frame:Hide() local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlightSmall") local image = frame:CreateTexture(nil, "BACKGROUND") -- create widget local widget = { label = label, image = image, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
artistic-2.0
KayMD/Illarion-Content
monster/race_63_bone_dragon/id_637_golden.lua
3
1044
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local base = require("monster.base.base") local boneDragons = require("monster.race_63_bone_dragon.base") local M = boneDragons.generateCallbacks() local orgOnSpawn = M.onSpawn function M.onSpawn(monster) if orgOnSpawn ~= nil then orgOnSpawn(monster) end base.setColor{monster = monster, target = base.SKIN_COLOR, red = 215, green = 180, blue = 100} end return M
agpl-3.0
KayMD/Illarion-Content
triggerfield/noobia_viola.lua
4
2503
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- INSERT INTO triggerfields VALUES (36,95,100,'triggerfield.noobia_viola'); local common = require("base.common") local M = {} function M.MoveToField(Character) -- for Noobia: the char has to walk to a field (this triggerfield); he gets a message and we change a queststatus so that we remember he was at the field local find = Character.effects:find(13) --Noob effect if find then --Is this even a noob? local value = Character:getQuestProgress(314); if (value == 0) then --Didn't visit the triggerfield yet Character:setQuestProgress(314, 1) --player passed the triggerfield local callbackNewbie = function() end --empty callback local dialogText = common.GetNLS(Character, "Dies ist nun die letzte Station des Tutorials. Wähle ein Reich aus, welchem dein Charakter zukünftig angehören wird - Cadomyr, Galmair oder Runewick? Gehe hierzu durch eines der Portale auf den kleinen Inseln.\n\nDu kannst diese Entscheidung später im Spiel jederzeit revidieren. Viola Baywillow kann dir einiges über die drei Reiche erzählen, frage sie einfach nach 'Hilfe'.\n\nUnd nebenbei - hast du den Markierungsstein gesehen?", "This is the final station of the tutorial. Please choose which realm you desire to be the home for your character by stepping through the corresponding portal on the three islands - Cadomyr, Galmair or Runewick?\n\nYou can reconsider this decision at any time once you have joined the game. Viola Baywillow will provide you with more information on the three available realms, just ask her for 'help'.\n\nBy the way - did you notice the marker stone?") local dialogNewbie = MessageDialog("Tutorial", dialogText, callbackNewbie) Character:requestMessageDialog(dialogNewbie) end end end return M
agpl-3.0
gajop/Zero-K
lups/loadConfig.lua
14
1234
-- $Id: loadConfig.lua 3171 2008-11-06 09:06:29Z det $ --------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------- -- -- file: loadConfig.lua -- brief: loads LUPS config files -- authors: jK -- last updated: Feb. 2008 -- -- Copyright (C) 2008. -- Licensed under the terms of the GNU GPL, v2 or later. -- --------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------- function LoadConfig(configFile) if (VFS.FileExists(configFile)) then local fileStr = VFS.LoadFile(configFile):gsub("//","--") local func, message = loadstring(fileStr) if not func then print(PRIO_MAJOR,"LUPS: Can't parse config! Error is:\n" .. message) end local env = {} setfenv(func, env) --// fill the env table with user config local success = pcall(func) if success then local res = {} for i,v in pairs(env) do if (type(v)~="function") then res[i:lower()] = v end end return res end end return {} end
gpl-2.0
gajop/Zero-K
LuaRules/Deploy/draw.lua
8
15493
-- $Id: draw.lua 3171 2008-11-06 09:06:29Z det $ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- file: LuaRules/Deploy/draw.lua -- brief: deployment game mode -- author: Dave Rodgers -- -- Copyright (C) 2007. -- Licensed under the terms of the GNU GPL, v2 or later. -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- VFS.Include('LuaRules/colors.h.lua') featureLabel = 'Deployment' -- FIXME if (string.find(string.lower(Game.modName), 'tactics')) then featureLabel = 'Tactics' end local useLuaUI = false local teamRangeLists = {} local circleList = 0 local miniMapXformList = 0 local worldDivs = 1024 local minimapDivs = 256 local toothTex = 'LuaRules/Deploy/ringTooth.png' -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Select and View -- local function SelectViewComm() local teamID = Spring.GetLocalTeamID() local team = SYNCED.teams and SYNCED.teams[teamID] or nil if (not team) then return end Spring.SelectUnitArray({ team.comm }) Spring.SetCameraTarget(team.x, team.y, team.z, 0.75) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Update() -- local function LuaUITeamTable(team) return { id = team.id, ready = team.ready, x = team.x, y = team.y, z = team.z, radius = SYNCED.maxRadius, color = { Spring.GetTeamColor(team.id) }, frames = SYNCED.frames, units = #team.units, metal = team.metal, energy = team.energy, maxFrames = SYNCED.maxFrames, maxUnits = SYNCED.maxUnits, maxMetal = SYNCED.maxMetal, maxEnergy = SYNCED.maxEnergy, } end function Update() local teamID = Spring.GetLocalTeamID() local teams = SYNCED.teams if (not teams) then return end local team = teams and teams[teamID] or nil if (not team) then return end local spec, fullview = Spring.GetSpectatingState() if (not Script.LuaUI('DeployUpdate')) then useLuaUI = false else useLuaUI = true local uiTable = {} local readys = {} for id, team in spairs(teams) do if (team) then readys[team.id] = team.ready if (fullview or Spring.AreTeamsAllied(teamID, team.id)) then uiTable[team.id] = LuaUITeamTable(team) end end end Script.LuaUI.DeployUpdate(uiTable, readys) end local units = Spring.GetSelectedUnits() if (not fullview) then if (#units <= 0) then SelectViewComm() end else if (#units <= 0) then SelectViewComm() end end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- RecvFromSynced() -- function RecvFromSynced(...) if (select(1,...) == 'NewRadius') then for teamID,listID in pairs(teamRangeLists) do gl.DeleteList(listID) teamRangeLists[teamID] = nil end elseif (select(1,...) == 'StartGame') then SelectViewComm() gl.DeleteTexture(toothTex) gl.DeleteList(circleList) gl.DeleteList(miniMapXformList) for _,listID in pairs(teamRangeLists) do gl.DeleteList(listID) end Update = nil; Script.UpdateCallIn('Update') DrawWorld = nil; Script.UpdateCallIn('DrawWorld') DrawScreen = nil; Script.UpdateCallIn('DrawScreen') DrawInMiniMap = nil; Script.UpdateCallIn('DrawInMiniMap') RecvFromSynced = nil; Script.UpdateCallIn('RecvFromSynced') VFS.Include('LuaRules/gadgets.lua') elseif (select(1,...) == 'urun') then local chunk, err = loadstring(select(2,...), 'urun', _G) if (chunk) then chunk() end return elseif (select(1,...) == 'uecho') then local chunk, err = loadstring('return ' .. select(2,...), 'uecho', _G) if (chunk) then Spring.Echo(chunk()) end return end if (Script.LuaUI('DeployUpdate')) then Script.LuaUI.DeployUpdate(...) end end do if (Script.LuaUI('DeployUpdate')) then Script.LuaUI.DeployUpdate('NewRadius') end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Create Lists -- local function MakeWorldRangeListXXX(px, py, pz, radius, width) local rads = (2 * math.pi) / worldDivs local points = {} local lengths = {} local normals = {} for i = 0, worldDivs do local a = rads * i local x = px + (math.sin(a) * radius) local z = pz + (math.cos(a) * radius) local y = Spring.GetGroundHeight(x, z) points[i] = { x = x, y = y, z = z } local nx, ny, nz = Spring.GetGroundNormal(x, z) normals[i] = { x = nx, y = ny, z = nz } if (i > 0) then local dx = points[i].x - points[i - 1].x local dy = points[i].y - points[i - 1].y local dz = points[i].z - points[i - 1].z lengths[i] = math.sqrt((dx * dx) + (dy * dy) + (dz * dz)) end end -- local xTexStep = math.floor(4 * radius / width) / worldDivs --[[ gl.BeginEnd(GL.QUAD_STRIP, function() local ox = px + (math.sin(a) * (radius + width)) local oz = pz + (math.cos(a) * (radius + width)) local oy = Spring.GetGroundHeight(ox, oz) local isx, isy, isz = Spring.GetGroundNormal(ix, iz) local osx, osy, osz = Spring.GetGroundNormal(ox, oz) local f = 5 ix, iy, iz = (ix + (isx * f)), (iy + (isy * f)), (iz + (isz * f)) ox, oy, oz = (ox + (osx * f)), (oy + (osy * f)), (oz + (osz * f)) local dx, dy, dz = (ox - ix), (oy - iy), (oz - iz) local len = math.sqrt((dx * dx) + (dy * dy) + (dz * dz)) local lf = width / len ox, oy, oz = (ix + (dx * lf)), (iy + (dy * lf)), (iz + (dz * lf)) -- gl.Color(1, 0, 0, 0.5) gl.TexCoord(i * xTexStep, 1.0) gl.Vertex(ix, iy, iz) -- gl.Color(1, 0, 0, 0.0) gl.TexCoord(i * xTexStep, 0.125) gl.Vertex(ox, oy, oz) end end) --]] end local function MakeWorldRangeList(px, py, pz, radius, width) local rads = (2 * math.pi) / worldDivs local xTexStep = math.floor(4 * radius / width) / worldDivs gl.BeginEnd(GL.QUAD_STRIP, function() for i = 0, worldDivs do local a = rads * i local ix = px + (math.sin(a) * radius) local iz = pz + (math.cos(a) * radius) local iy = Spring.GetGroundHeight(ix, iz) local ox = px + (math.sin(a) * (radius + width)) local oz = pz + (math.cos(a) * (radius + width)) local oy = Spring.GetGroundHeight(ox, oz) local isx, isy, isz = Spring.GetGroundNormal(ix, iz) local osx, osy, osz = Spring.GetGroundNormal(ox, oz) local f = 5 ix, iy, iz = (ix + (isx * f)), (iy + (isy * f)), (iz + (isz * f)) ox, oy, oz = (ox + (osx * f)), (oy + (osy * f)), (oz + (osz * f)) local dx, dy, dz = (ox - ix), (oy - iy), (oz - iz) local len = math.sqrt((dx * dx) + (dy * dy) + (dz * dz)) local lf = width / len ox, oy, oz = (ix + (dx * lf)), (iy + (dy * lf)), (iz + (dz * lf)) oy = Spring.GetGroundHeight(ox, oz) -- gl.Color(1, 0, 0, 0.5) gl.TexCoord(i * xTexStep, 1.0) gl.Vertex(ix, iy, iz) -- gl.Color(1, 0, 0, 0.0) gl.TexCoord(i * xTexStep, 0.125) gl.Vertex(ox, oy, oz) end end) end circleList = gl.CreateList(function() local rads = (2 * math.pi) / minimapDivs gl.BeginEnd(GL.LINE_LOOP, function() for i = 0, minimapDivs-1 do local a = rads * i gl.Vertex(math.sin(a), 0, math.cos(a)) end end) end) miniMapXformList = gl.CreateList(function() local mapX = Game.mapX * 512 local mapY = Game.mapY * 512 -- this will probably be a common display -- list for widgets that use DrawInMiniMap() gl.LoadIdentity() gl.Translate(0, 1, 0) gl.Scale(1 / mapX, 1 / mapY, 1) gl.Rotate(90, 1, 0, 0) end) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- DrawMexRanges() -- local function DrawMexRanges(teamID) if (Spring.GetMapDrawMode() ~= 'metal') then return end gl.Color(1, 0, 0, 0.5) gl.LineWidth(1.49) local units = Spring.GetTeamUnits(teamID) for _,unitID in ipairs(units) do local udid = Spring.GetUnitDefID(unitID) local ud = udid and UnitDefs[udid] or nil if (ud and (ud.extractsMetal > 0)) then local x, y, z = Spring.GetUnitBasePosition(unitID) if (x) then gl.DrawGroundCircle(x, y, z, ud.extractRange, 64) end end end gl.LineWidth(1.0) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- DrawWorld() -- local function DrawTeamWorld(team) if (useLuaUI) then return end local list = teamRangeLists[team.id] if (list == nil) then local radius = SYNCED.maxRadius list = gl.CreateList(MakeWorldRangeList, team.x, 0, team.z, radius, 40) teamRangeLists[team.id] = list end local dtime = Spring.GetGameSeconds() local alpha = 0.25 + 0.5 * math.abs(0.5 - ((dtime * 2) % 1)) gl.Texture(toothTex) gl.MatrixMode(GL.TEXTURE) gl.Translate(-(dtime % 1), 0, 0) gl.MatrixMode(GL.MODELVIEW) gl.LineWidth(2) gl.DepthTest(GL.GREATER) gl.Color(0.5, 0.5, 0.5, 0.5) gl.CallList(list) gl.DepthTest(GL.LEQUAL) local r, g, b = Spring.GetTeamColor(team.id) gl.Color(r, g, b, 0.5)--alpha) gl.CallList(list) gl.DepthTest(GL.LEQUAL) gl.DepthTest(false) gl.LineWidth(1) gl.Texture(false) gl.MatrixMode(GL.TEXTURE) gl.LoadIdentity() gl.MatrixMode(GL.MODELVIEW) DrawMexRanges(team.id) end function DrawWorld() if (useLuaUI) then return end local teams = SYNCED.teams local spec, fullview = Spring.GetSpectatingState() if (not fullview) then local teamID = Spring.GetLocalTeamID() local team = teamID and teams and teams[teamID] or nil if (team) then DrawTeamWorld(team) end else for teamID, team in spairs(teams) do if (team) then DrawTeamWorld(team) end end end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- DrawInMiniMap() -- local bitpat = (65536 - 775) local function DrawTeamMiniMap(team) local radius = SYNCED.maxRadius gl.LineWidth(2.49) gl.DepthTest(false) local dtime = Spring.GetGameSeconds() local alpha = 0.25 + 0.5 * math.abs(0.5 - ((dtime * 2) % 1)) local shift = math.floor((dtime * 16) % 16) gl.PushMatrix() gl.CallList(miniMapXformList) DrawMexRanges(team.id) gl.LineStipple(1, bitpat, -shift) local r, g, b = Spring.GetTeamColor(team.id) gl.Color(r, g, b, alpha) gl.Translate(team.x, team.y, team.z) gl.Scale(radius, 1, radius) gl.CallList(circleList) gl.LineStipple(false) gl.PopMatrix() gl.LineWidth(1) end function DrawInMiniMap(mmsx, mmsy) if (useLuaUI) then return end local teams = SYNCED.teams local spec, fullview = Spring.GetSpectatingState() if (not fullview) then local teamID = Spring.GetLocalTeamID() local team = teamID and teams and teams[teamID] or nil if (team) then DrawTeamMiniMap(team) end else for teamID, team in spairs(teams) do if (team) then DrawTeamMiniMap(team) end end end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- DrawScreen() -- local function DrawReadyTeams(vsx, vsy) local teams = SYNCED.teams if (not teams) then return end local readys = {} for teamID, team in spairs(teams) do local id, leader, active, dead = Spring.GetTeamInfo(teamID) if (leader) then local name = Spring.GetPlayerInfo(leader) if (name) then table.insert(readys, { name, team.ready }) end end end table.sort(readys, function(a, b) if (a[2] ~= b[2]) then return b[2] end return (a[1] > b[1]) end) local fs = 12 local fg = fs * 1.5 local x = vsx - (fs * 0.5) local count = #readys local y = 0.5 * (vsy - (fg * count)) for i = 1, count do local ready = readys[i] local color = ready[2] and '\255\64\255\64' or '\255\255\64\64' gl.Text(color .. ready[1], x, y, fs, 'or') y = y + fg end gl.Text('\255\255\255\1' .. 'READY', x, y, fs * 1.25, 'or') end local function DrawLevelBar(name, val, max, x, y, width, height, color) local hw = math.floor(width * 0.5) local x0, x1 = x - hw, x + hw local y0, y1 = y - 1, y + height + 2 local xm = x0 + (width * (val / max)) gl.Color(color[1], color[2], color[3], 0.5) gl.Rect(x0, y0, xm, y1) gl.Color(0, 0, 0, 0.5) gl.Rect(xm, y0, x1, y1) val = math.floor(val) max = math.floor(max) local preStr = val .. ':' .. name local postStr = name .. ':' .. max local g = math.floor(height / 2) gl.Color(1, 1, 1, 0.75) gl.Text(name, x, y0, height, 'ocn') gl.LineWidth(1) gl.PolygonMode(GL.FRONT_AND_BACK, GL.LINE) gl.Color(1, 1, 1, 0.75) gl.Rect(x0 - 0.5, y0 - 0.5, x1 + 0.5, y1 + 0.5) gl.Color(0, 0, 0, 0.75) gl.Rect(x0 - 1.5, y0 - 1.5, x1 + 1.5, y1 + 1.5) gl.PolygonMode(GL.FRONT_AND_BACK, GL.FILL) gl.Text(val, x0 - g, y0, height, 'or') gl.Text(max, x1 + g, y0, height, 'o') end function DrawScreen(vsx, vsy) if (useLuaUI) then return end local teamID = Spring.GetLocalTeamID() local team = teamID and SYNCED.teams and SYNCED.teams[teamID] or nil if (team == nil) then return end local cx, cy = vsx * 0.5, 111 --vsy * 0.125 local fs = (vsy / 70) fs = (fs > 10) and fs or 10 fs = math.floor(fs) local fg = math.floor(fs * 1.8) local lsx = cx local strwidth = fs * gl.GetTextWidth('Energy Left: ') local nsx = lsx + strwidth local y = cy local width = (fs * 1.6) * gl.GetTextWidth(featureLabel) if (team) then local maxEnergy = SYNCED.maxEnergy if (maxEnergy < 1e9) then DrawLevelBar('Energy', team.energy, maxEnergy, cx, y, width, fs, { 1, 1, 0, 0.5 }) y = y + fg end local maxMetal = SYNCED.maxMetal if (maxMetal < 1e9) then DrawLevelBar('Metal', team.metal, maxMetal, cx, y, width, fs, { 0, 1, 1, 0.5 }) y = y + fg end local maxUnits = SYNCED.maxUnits if (maxUnits < 1e9) then DrawLevelBar('Units', #team.units, maxUnits, cx, y, width, fs, { 0, 1, 0, 0.5 }) y = y + fg end end local maxFrames = SYNCED.maxFrames if (maxFrames < 1e9) then local gs = Game.gameSpeed DrawLevelBar('Time', (SYNCED.frames / gs), maxFrames / gs, cx, y, width, fs, { 1, 0, 0, 0.5 }) y = y + fg end gl.Color(0, 0, 0) gl.Text(featureLabel, lsx, y, fs * 1.6, 'Ocn') DrawReadyTeams(vsx, vsy) end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
coral-framework/coral
tests/lua/modules/lua/services/lua.services.lua
1
2593
require "lua.test" -------------------------------------------------------------------------------- -- Auxiliary Lua component that implements a dummy service -------------------------------------------------------------------------------- local DummyProvider = co.Component{ name = "lua.test.DummyProvider", provides = { dummy = "moduleA.IDummy" } } function DummyProvider.dummy:getFoo() return self.foo or "foo" end function DummyProvider.dummy:setFoo( foo ) self.foo = foo end function bindFooForType( fooValue, typeName ) local object = DummyProvider{ foo = fooValue } co.system.services:addServiceForType( co.Type "moduleA.IDummy", co.Type[typeName], object.dummy ) end -------------------------------------------------------------------------------- -- Module / Test Code -------------------------------------------------------------------------------- local M = {} function M:initialize( module ) -- make sure we don't have services registered for 'moduleA.IBat' nor 'moduleA.IHuman'. ASSERT_ERROR( function() co.getService "moduleA.IBat" end, "unknown service" ) ASSERT_ERROR( function() co.getService "moduleA.IHuman" end, "unknown service" ) -- we reuse "lua.bat.Component" from the lua.component test local bc = co.new "lua.bat.Component" -- register a global moduleA.IBat service: co.system.services:addService( co.Type "moduleA.IBat", bc.fruitBat ) -- now all queries should return the global service ASSERT_EQ( co.getService "moduleA.IBat", bc.fruitBat ) ASSERT_EQ( co.getService( "moduleA.IBat", "moduleA.IHuman" ), bc.fruitBat ) -- now add a specialized bat for humans co.system.services:addServiceForType( co.Type "moduleA.IBat", co.Type "moduleA.IHuman", bc.vampireBat ) ASSERT_EQ( co.getService "moduleA.IBat", bc.fruitBat ) ASSERT_EQ( co.getService( "moduleA.IBat", "moduleA.IHuman" ), bc.vampireBat ) -- a query for 'moduleA.IHuman' on 'bc' should give us batman ASSERT_EQ( co.getService( "moduleA.IHuman", bc ), bc.batman ) ASSERT_EQ( co.getService( "moduleA.IHuman", bc.batman ), bc.batman ) ASSERT_EQ( co.getService( "moduleA.IHuman", bc.fruitBat ), bc.batman ) -- test for custom service providers implemented in Lua bindFooForType( "Bat", "moduleA.IBat" ) bindFooForType( "Human", "moduleA.IHuman" ) ASSERT_ERROR( function() co.getService "moduleA.IDummy" end, "service has no global instance" ) ASSERT_EQ( co.getService( "moduleA.IDummy", "moduleA.IBat" ).foo, "Bat" ) ASSERT_EQ( co.getService( "moduleA.IDummy", "moduleA.IHuman" ).foo, "Human" ) end return M
mit
Rawa/dotfiles
common/.config/nvim/lua/plugins.lua
1
2397
local use = require('packer').use local packer = require('packer') return packer.startup(function() -- PackerSync after save vim.cmd([[ augroup packer_user_config autocmd! autocmd BufWritePost plugins.lua source <afile> | PackerSync augroup end ]]) use 'wbthomason/packer.nvim' -- Packer Manager use 'tpope/vim-surround' use { 'numToStr/Comment.nvim', config = function() require('Comment').setup() end } use { 'scrooloose/nerdtree', config = [[require("config.nerdtree").setup()]], } -- nvim-cmp autocompletion use { 'hrsh7th/nvim-cmp', config = [[require("config.cmp").setup()]], } use { 'L3MON4D3/LuaSnip' } use { 'hrsh7th/cmp-buffer', 'hrsh7th/cmp-path', 'octaltree/cmp-look', 'hrsh7th/cmp-nvim-lua', 'hrsh7th/cmp-nvim-lsp' } use { 'saadparwaiz1/cmp_luasnip' } -- telescope use { { 'nvim-telescope/telescope.nvim', requires = { 'nvim-lua/plenary.nvim', 'vim-telescope/telescope-frecency.nvim', 'nvim-telescope/telescope-fzf-native.nvim' }, config = [[require("config.telescope").setup()]], }, { 'nvim-telescope/telescope-frecency.nvim', requires = 'tami5/sqlite.lua', }, { 'nvim-telescope/telescope-fzf-native.nvim', run = 'make', }, 'crispgm/telescope-heading.nvim', } -- lsp use { 'neovim/nvim-lspconfig', config = [[require("config.lsp").setup()]], require = { 'nvim-lua/plenary.nvim', 'kevinhwang91/nvim-bqf', -- better quickfix 'ray-x/lsp_signature.nvim', } } use 'easymotion/vim-easymotion' use 'bronson/vim-trailing-whitespace' use { 'xfyuan/vim-mac-dictionary', requires = {{ 'skywind3000/vim-quickui' }}, config = function() vim.cmd('nnoremap <silent><leader>ww :MacDictPopup<CR>') end } use { 'windwp/nvim-autopairs', config = [[require('nvim-autopairs').setup({})]] } -- Theme use { 'morhetz/gruvbox', config = function() vim.cmd('colorscheme gruvbox') end } end) --" Git Flog --Plug 'tpope/vim-fugitive' --Plug 'rbong/vim-flog' --nnoremap <silent> <leader>gl :Flog<CR> --Plug 'godlygeek/tabular' --" LANG --" MD --Plug 'plasticboy/vim-markdown' --let g:vim_markdown_folding_level = 3 --let g:vim_markdown_folding_disabled = 1
mit
Mutos/NAEV-StarsOfCall
dat/missions/neutral/reynir.lua
5
5171
--[[ MISSION: Hot dogs from space DESCRIPTION: An old man who owns a hot dog factory wants to go to space The old man has elevated pressure in his cochlea so he can't go to space. He's getting old and wants to go to space before he dies. He owns a hot dog factory and will pay you in hot dogs (food). Because of his illness, you can't land on any planet outside the system (the player doesn't know this). NOTE: This mission is best suited in systems with 2 or more planets, but can be used in any system with a planet. --]] -- Localization, choosing a language if naev is translated for non-english-speaking locales. lang = naev.lang() if lang == "es" then else -- Default to English -- This section stores the strings (text) for the mission. -- Bar information, describes how he appears in the bar bar_desc = "You see an old man with a cap on, on which the letters R-E-Y-N-I-R are imprinted." -- Mission details. We store some text for the mission with specific variables. misn_title = "Rich reward from space!" misn_reward = "Lots of cash" misn_desc = "Reynir wants to travel to space and will reward you richly." cargoname = "Food" -- Stage one title = {} --Each dialog box has a title. text = {} --We store mission text in tables. As we need them, we create them. title[1] = "Spaceport Bar" --Each chunk of text is stored by index in the table. text[1] = [["Do you like money?"]] --Use double brackets [[]] for block quotes over several lines. text[2] = [["Ever since I was a kid I've wanted to go to space. However, my doctor says I can't go to space because I have an elevated pressure in my cochlea, a common disease around here. "I am getting old now, as you can see. Before I die I want to travel to space, and I want you to fly me there! I own a hot dog factory, so I can reward you richly! Will you do it?"]] text[3] = [["Thank you so much! Just fly me around in the system, preferably near %s."]] title[4] = "Reynir" text[4] = [[Reynir walks out of the ship. You notice that he's bleeding out of both ears. "Where have you taken me?! Get me back to %s right now!!"]] text[5] = [["Thank you so much! Here's %s tons of hot dogs. They're worth more than their weight in gold, aren't they?"]] text[6] = [[Reynir walks out of the ship, amazed by the view. "So this is how %s looks like! I've always wondered... I want to go back to %s now, please."]] text[7] = [[Reynir doesn't look happy when you meet him outside the ship. "I lost my hearing out there! Damn you!! I made a promise, though, so I'd better keep it. Here's your reward, %d tons of hot dogs..."]] -- Comm chatter -- ?? talk = {} talk[1] = "" -- Other text for the mission -- ?? osd_msg = {} osd_msg[1] = "Fly around in the system, preferably near %s." osd_msg[2] = "Take Reynir home to %s." msg_abortTitle = "" msg_abort = [[]] end function create () -- Note: this mission does not make any system claims. misn.setNPC( "Reynir", "neutral/unique/reynir" ) misn.setDesc( bar_desc ) -- Mission variables misn_base, misn_base_sys = planet.cur() misn_bleeding = false end function accept () -- make sure there are at least 2 inhabited planets if (function () local count = 0 for i, p in ipairs (system.cur():planets()) do if p:services()["inhabited"] then count=count+1 end end return count > 1 end) () and tk.yesno( title[1], text[1] ) and tk.yesno( title[1], text[2] ) then misn.accept() -- For missions from the Bar only. misn.setTitle( misn_title ) misn.setReward( misn_reward ) misn.setDesc( misn_desc ) hook.land( "landed" ) tk.msg( title[4], string.format(text[3], misn_base:name()) ) misn.osdCreate(misn_title, {osd_msg[1]:format(misn_base:name())}) cargoID = misn.cargoAdd( "Civilians", 0 ) end end function landed() -- If landed on misn_base then give reward if planet.cur() == misn_base then misn.cargoRm( cargoID ) if misn_bleeding then reward = math.min(1, pilot.cargoFree(player.pilot())) reward_text = text[7] else reward = pilot.cargoFree(player.pilot()) reward_text = text[5] end tk.msg( title[4], string.format(reward_text, reward) ) pilot.cargoAdd( player.pilot(), cargoname, reward ) misn.finish(true) -- If we're in misn_base_sys but not on misn_base then... elseif system.cur() == misn_base_sys then tk.msg( title[4], string.format(text[6], planet.cur():name(), misn_base:name()) ) misn.osdCreate(misn_title, {osd_msg[2]:format(misn_base:name())}) -- If we're in another system then make Reynir bleed out his ears ;) else tk.msg( title[4], string.format(text[4], misn_base:name()) ) misn.osdCreate(misn_title, {osd_msg[2]:format(misn_base:name())}) misn_bleeding = true end end -- TODO: There should probably be more here function abort () -- Remove the passenger. misn.cargoRm( cargoID ) misn.finish(false) end
gpl-3.0
mt246/mt246
plugins/plugins.lua
325
6164
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'. '..v..' '..status..'\n' end end local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled' return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..v..' '..status..'\n' end end local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.' return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return 'Plugin '..plugin_name..' is enabled' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return 'Plugin '..plugin_name..' does not exists' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return 'Plugin '..name..' does not exists' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return 'Plugin '..name..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return 'Plugin '..plugin..' disabled on this chat' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return 'Plugin '..plugin..' is enabled again' end local function run(msg, matches) -- Show the available plugins if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == 'enable' and matches[3] == 'chat' then local receiver = get_receiver(msg) local plugin = matches[2] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin) end -- Enable a plugin if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end -- Disable a plugin on a chat if matches[1] == 'disable' and matches[3] == 'chat' then local plugin = matches[2] local receiver = get_receiver(msg) print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin) end -- Disable a plugin if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plugins disable [plugin] chat : disable plugin only this chat.", "!plugins enable [plugin] chat : enable plugin only this chat.", }, sudo = { "!plugins : list all plugins.", "!plugins enable [plugin] : enable plugin.", "!plugins disable [plugin] : disable plugin.", "!plugins reload : reloads all plugins." }, }, patterns = { "^!plugins$", "^!plugins? (enable) ([%w_%.%-]+)$", "^!plugins? (disable) ([%w_%.%-]+)$", "^!plugins? (enable) ([%w_%.%-]+) (chat)", "^!plugins? (disable) ([%w_%.%-]+) (chat)", "^!plugins? (reload)$" }, run = run, moderated = true, -- set to moderator mode --privileged = true } end
gpl-2.0
Flourish-Team/Flourish
Premake/source/binmodules/luasocket/src/tp.lua
51
3766
----------------------------------------------------------------------------- -- Unified SMTP/FTP subsystem -- LuaSocket toolkit. -- Author: Diego Nehab ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ----------------------------------------------------------------------------- local base = _G local string = require("string") local socket = require("socket") local ltn12 = require("ltn12") socket.tp = {} local _M = socket.tp ----------------------------------------------------------------------------- -- Program constants ----------------------------------------------------------------------------- _M.TIMEOUT = 60 ----------------------------------------------------------------------------- -- Implementation ----------------------------------------------------------------------------- -- gets server reply (works for SMTP and FTP) local function get_reply(c) local code, current, sep local line, err = c:receive() local reply = line if err then return nil, err end code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) if not code then return nil, "invalid server reply" end if sep == "-" then -- reply is multiline repeat line, err = c:receive() if err then return nil, err end current, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) reply = reply .. "\n" .. line -- reply ends with same code until code == current and sep == " " end return code, reply end -- metatable for sock object local metat = { __index = {} } function metat.__index:getpeername() return self.c:getpeername() end function metat.__index:getsockname() return self.c:getpeername() end function metat.__index:check(ok) local code, reply = get_reply(self.c) if not code then return nil, reply end if base.type(ok) ~= "function" then if base.type(ok) == "table" then for i, v in base.ipairs(ok) do if string.find(code, v) then return base.tonumber(code), reply end end return nil, reply else if string.find(code, ok) then return base.tonumber(code), reply else return nil, reply end end else return ok(base.tonumber(code), reply) end end function metat.__index:command(cmd, arg) cmd = string.upper(cmd) if arg then return self.c:send(cmd .. " " .. arg.. "\r\n") else return self.c:send(cmd .. "\r\n") end end function metat.__index:sink(snk, pat) local chunk, err = self.c:receive(pat) return snk(chunk, err) end function metat.__index:send(data) return self.c:send(data) end function metat.__index:receive(pat) return self.c:receive(pat) end function metat.__index:getfd() return self.c:getfd() end function metat.__index:dirty() return self.c:dirty() end function metat.__index:getcontrol() return self.c end function metat.__index:source(source, step) local sink = socket.sink("keep-open", self.c) local ret, err = ltn12.pump.all(source, sink, step or ltn12.pump.step) return ret, err end -- closes the underlying c function metat.__index:close() self.c:close() return 1 end -- connect with server and return c object function _M.connect(host, port, timeout, create) local c, e = (create or socket.tcp)() if not c then return nil, e end c:settimeout(timeout or _M.TIMEOUT) local r, e = c:connect(host, port) if not r then c:close() return nil, e end return base.setmetatable({c = c}, metat) end return _M
mit
Flourish-Team/Flourish
Premake/source/modules/vstudio/tests/vc200x/test_project_refs.lua
16
1831
-- -- tests/actions/vstudio/vc200x/test_project_refs.lua -- Validate project references in Visual Studio 200x C/C++ projects. -- Copyright (c) 2011-2012 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("vstudio_vs200x_project_refs") local vc200x = p.vstudio.vc200x -- -- Setup -- local wks, prj function suite.setup() p.action.set("vs2008") wks = test.createWorkspace() uuid "00112233-4455-6677-8888-99AABBCCDDEE" test.createproject(wks) end local function prepare(platform) prj = test.getproject(wks, 2) vc200x.projectReferences(prj) end -- -- If there are no sibling projects listed in links(), then the -- entire project references item group should be skipped. -- function suite.noProjectReferencesGroup_onNoSiblingReferences() prepare() test.isemptycapture() end -- -- If a sibling project is listed in links(), an item group should -- be written with a reference to that sibling project. -- function suite.projectReferenceAdded_onSiblingProjectLink() links { "MyProject" } prepare() test.capture [[ <ProjectReference ReferencedProjectIdentifier="{00112233-4455-6677-8888-99AABBCCDDEE}" RelativePathToProject=".\MyProject.vcproj" /> ]] end -- -- Project references should always be specified relative to the -- *solution* doing the referencing. Which is kind of weird, since it -- would be incorrect if the project were included in more than one -- solution file, yes? -- function suite.referencesAreRelative_onDifferentProjectLocation() links { "MyProject" } location "build/MyProject2" project("MyProject") location "build/MyProject" prepare() test.capture [[ <ProjectReference ReferencedProjectIdentifier="{00112233-4455-6677-8888-99AABBCCDDEE}" RelativePathToProject=".\build\MyProject\MyProject.vcproj" /> ]] end
mit
LinusU/cunnx
LazyKBest.lua
4
1252
local LazyKBest, parent = torch.class('nn.LazyKBest', 'nn.Module') ------------------------------------------------------------------------ --[[ LazyKBest ]]-- -- For example, divides the input into k sub-arrays and takes the -- max value of each. Allowed value for k are, 1, 2, 4, 8, 16 and 32. -- Returns a table of the k-best {indices, inputs} -- Used with BlockSparse instead of nn.Sort ------------------------------------------------------------------------ function LazyKBest:__init(k) parent.__init(self) self.k = k self._indice = torch.LongTensor() self._output = torch.Tensor() self.output = {self._indice, self._output} end function LazyKBest:updateOutput(input) assert(input:dim() == 2, "Only works with matrices") input.nn.LazyKBest_updateOutput(self, input) return self.output end function LazyKBest:updateGradInput(input, gradOutput) input.nn.LazyKBest_updateGradInput(self, input, self._indice, gradOutput[2]) return self.gradInput end function LazyKBest:type(type) self.gradInput = self.gradInput:type(type) self._output = self._output:type(type) if (type == 'torch.CudaTensor') then self._indice = self._indice:type(type) end self.output = {self._indice, self._output} end
bsd-3-clause
gajop/Zero-K
LuaRules/Gadgets/unit_dont_fire_at_radar.lua
7
7244
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if not gadgetHandler:IsSyncedCode() then return end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Dont fire at radar", desc = "Adds state toggle for units to not fire at radar dots.", author = "Google Frog", date = "8 April 2012", license = "GNU GPL, v2 or later", layer = 0, enabled = true -- loaded by default? } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local spValidUnitID = Spring.ValidUnitID local spGetUnitAllyTeam = Spring.GetUnitAllyTeam local spGetUnitTeam = Spring.GetUnitTeam local spGiveOrderToUnit = Spring.GiveOrderToUnit local spSetUnitRulesParam = Spring.SetUnitRulesParam local spFindUnitCmdDesc = Spring.FindUnitCmdDesc local spEditUnitCmdDesc = Spring.EditUnitCmdDesc local spInsertUnitCmdDesc = Spring.InsertUnitCmdDesc local spGetUnitLosState = Spring.GetUnitLosState local spGetCommandQueue = Spring.GetCommandQueue local spSetUnitTarget = Spring.SetUnitTarget local spGetUnitDefID = Spring.GetUnitDefID local spGetUnitPosition = Spring.GetUnitPosition local spGetUnitStates = Spring.GetUnitStates local CMD_ATTACK = CMD.ATTACK local CMD_OPT_INTERNAL = CMD.OPT_INTERNAL local CMD_FIRE_STATE = CMD.FIRE_STATE local CMD_INSERT = CMD.INSERT local CMD_REMOVE = CMD.REMOVE ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- include("LuaRules/Configs/customcmds.h.lua") local dontFireAtRadarCmdDesc = { id = CMD_DONT_FIRE_AT_RADAR, type = CMDTYPE.ICON_MODE, name = "Don't fire at radar", action = 'dontfireatradar', tooltip = 'Fire at radar dots: Disable to prevent firing at radar dots.', params = {0, 'Fire at radar',"Don't fire at radar"} } ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local canHandleUnit = {} -- unitIDs that CAN be handled local units = {} local wantGoodTarget = {} ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local function canShootAtUnit(targetID, allyTeam) local see = spGetUnitLosState(targetID,allyTeam,false) local raw = spGetUnitLosState(targetID,allyTeam,true) --GG.tableEcho(see) if see and see.los then return true elseif raw and raw > 2 then local unitDefID = spGetUnitDefID(targetID) if unitDefID and UnitDefs[unitDefID] and UnitDefs[unitDefID].speed == 0 then return true end end return false end local function isTheRightSortOfCommand(cQueue, index) return #cQueue >= index and cQueue[index].options.internal and cQueue[index].id == CMD_ATTACK and #cQueue[index].params == 1 end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- function gadget:AllowWeaponTarget(unitID, targetID, attackerWeaponNum, attackerWeaponDefID, defPriority) if units[unitID] then local data = units[unitID] --Spring.Echo("AllowWeaponTarget frame " .. Spring.GetGameFrame()) if spValidUnitID(targetID) and canShootAtUnit(targetID, spGetUnitAllyTeam(unitID)) then --GG.unitEcho(targetID, "target") if wantGoodTarget[unitID] then wantGoodTarget[unitID] = nil spGiveOrderToUnit(unitID, CMD_INSERT, {0, CMD_ATTACK, CMD_OPT_INTERNAL, targetID }, {"alt"} ) local cQueue = spGetCommandQueue(unitID, 2) if isTheRightSortOfCommand(cQueue, 2) then spGiveOrderToUnit(unitID, CMD_REMOVE, {cQueue[2].tag}, {} ) end end return true, defPriority else --GG.unitEcho(targetID, "No") return false, defPriority end else return true, defPriority end end function GG.DontFireRadar_CheckAim(unitID) if units[unitID] then local cQueue = spGetCommandQueue(unitID, 1) local data = units[unitID] if isTheRightSortOfCommand(cQueue, 1) and not canShootAtUnit(cQueue[1].params[1], spGetUnitAllyTeam(unitID)) then local firestate = spGetUnitStates(unitID).firestate spGiveOrderToUnit(unitID, CMD_FIRE_STATE, {0}, {} ) spGiveOrderToUnit(unitID, CMD_REMOVE, {cQueue[1].tag}, {} ) spGiveOrderToUnit(unitID, CMD_FIRE_STATE, {firestate}, {} ) wantGoodTarget[unitID] = {command = true} spSetUnitTarget(unitID,0) end end end function GG.DontFireRadar_CheckBlock(unitID, targetID) if units[unitID] and spValidUnitID(targetID) then local data = units[unitID] if canShootAtUnit(targetID, spGetUnitAllyTeam(unitID)) then return false else spSetUnitTarget(unitID,0) return true end end return false end -------------------------------------------------------------------------------- -- Command Handling local function DontFireAtRadarToggleCommand(unitID, cmdParams, cmdOptions) if canHandleUnit[unitID] then local state = cmdParams[1] local cmdDescID = spFindUnitCmdDesc(unitID, CMD_DONT_FIRE_AT_RADAR) if (cmdDescID) then dontFireAtRadarCmdDesc.params[1] = state spEditUnitCmdDesc(unitID, cmdDescID, { params = dontFireAtRadarCmdDesc.params}) end if state == 1 then if not units[unitID] then units[unitID] = true end else if units[unitID] then units[unitID] = nil end end end end function gadget:AllowCommand_GetWantedCommand() return {[CMD_DONT_FIRE_AT_RADAR] = true} end function gadget:AllowCommand_GetWantedUnitDefID() return true end function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions) if (cmdID ~= CMD_DONT_FIRE_AT_RADAR) then return true -- command was not used end DontFireAtRadarToggleCommand(unitID, cmdParams, cmdOptions) return false -- command was used end -------------------------------------------------------------------------------- -- Unit Handling function gadget:UnitCreated(unitID, unitDefID, teamID) if UnitDefs[unitDefID].customParams.dontfireatradarcommand=="1" then --Spring.SetUnitSensorRadius(unitID,"los",0) --Spring.SetUnitSensorRadius(unitID,"airLos",0) spInsertUnitCmdDesc(unitID, dontFireAtRadarCmdDesc) canHandleUnit[unitID] = true DontFireAtRadarToggleCommand(unitID, {1}) end end function gadget:UnitDestroyed(unitID) if canHandleUnit[unitID] then if units[unitID] then units[unitID] = nil end canHandleUnit[unitID] = nil end end function gadget:Initialize() -- register command gadgetHandler:RegisterCMDID(CMD_DONT_FIRE_AT_RADAR) -- load active units for _, unitID in ipairs(Spring.GetAllUnits()) do local unitDefID = spGetUnitDefID(unitID) local teamID = spGetUnitTeam(unitID) gadget:UnitCreated(unitID, unitDefID, teamID) end end
gpl-2.0
gajop/Zero-K
lups/ParticleClasses/Sphere.lua
14
4521
-- $Id: Sphere.lua 3171 2008-11-06 09:06:29Z det $ ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- local SphereParticle = {} SphereParticle.__index = SphereParticle local SphereList ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function SphereParticle.GetInfo() return { name = "Sphere", backup = "", --// backup class, if this class doesn't work (old cards,ati's,etc.) desc = "", layer = -24, --// extreme simply z-ordering :x --// gfx requirement fbo = false, shader = false, rtt = false, ctt = false, } end SphereParticle.Default = { pos = {0,0,0}, -- start pos layer = -24, life = 0, size = 0, sizeGrowth = 0, colormap = { {0, 0, 0, 0} }, texture = 'bitmaps/GPL/Lups/sphere.png', repeatEffect = false, genmipmap = true, -- todo } ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function SphereParticle:BeginDraw() gl.DepthMask(true) gl.Culling(GL.BACK) end function SphereParticle:EndDraw() gl.DepthMask(false) gl.Texture(false) gl.Color(1,1,1,1) gl.Culling(false) end function SphereParticle:Draw() gl.Texture(self.texture) gl.Color(self.color) gl.TexCoord(0, 0) gl.PushMatrix() gl.Translate(self.pos[1],self.pos[2],self.pos[3]) gl.Scale(self.size,self.size,self.size) gl.MatrixMode(GL.TEXTURE) gl.PushMatrix() gl.Translate(-0.5,-0.5,0) gl.Scale(0.5,-0.5,0) gl.TexGen(GL.S, GL.TEXTURE_GEN_MODE, GL.REFLECTION_MAP) gl.TexGen(GL.T, GL.TEXTURE_GEN_MODE, GL.REFLECTION_MAP) gl.TexGen(GL.R, GL.TEXTURE_GEN_MODE, GL.REFLECTION_MAP) gl.CallList(SphereList) gl.PopMatrix() gl.MatrixMode(GL.MODELVIEW) gl.TexGen(GL.S, false) gl.TexGen(GL.T, false) gl.TexGen(GL.R, false) gl.PopMatrix() end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function SphereParticle:Initialize() SphereList = gl.CreateList(DrawSphere,0,0,0,40,25) end function SphereParticle:Finalize() gl.DeleteList(SphereList) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function SphereParticle:CreateParticle() -- needed for repeat mode self.csize = self.size self.clife = self.life self.size = self.csize or self.size self.life_incr = 1/self.life self.life = 0 self.color = self.colormap[1] self.firstGameFrame = Spring.GetGameFrame() self.dieGameFrame = self.firstGameFrame + self.clife end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function SphereParticle:Update(n) if (self.life<1) then self.life = self.life + n*self.life_incr self.size = self.size + n*self.sizeGrowth self.color = {GetColor(self.colormap,self.life)} end end -- used if repeatEffect=true; function SphereParticle:ReInitialize() self.size = self.csize self.life = 0 self.color = self.colormap[1] self.dieGameFrame = self.dieGameFrame + self.clife end function SphereParticle.Create(Options) local newObject = MergeTable(Options, SphereParticle.Default) setmetatable(newObject,SphereParticle) -- make handle lookup newObject:CreateParticle() return newObject end function SphereParticle:Destroy() gl.DeleteTexture(self.texture) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- return SphereParticle
gpl-2.0
indexTM/index
plugins/boobs.lua
1
1596
do -- Recursive function local function getRandomButts(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.obutts.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt <= 3 then print('Cannot get that butts, trying another one...') return getRandomButts(attempt) end return 'http://media.obutts.ru/' .. data.preview end local function getRandomBoobs(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.oboobs.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt < 10 then print('Cannot get that boobs, trying another one...') return getRandomBoobs(attempt) end return 'http://media.oboobs.ru/' .. data.preview end local function run(msg, matches) local url = nil if matches[1] == "!boobs" then url = getRandomBoobs() end if matches[1] == "!butts" then url = getRandomButts() end if url ~= nil then local receiver = get_receiver(msg) send_photo_from_url(receiver, url) else return 'Error getting boobs/butts for you, please try again later.' end end return { description = "Gets a random boobs or butts pic", usage = { "!boobs: Get a boobs NSFW image. 🔞", "!butts: Get a butts NSFW image. 🔞" }, patterns = { "^!boobs$", "^!butts$" }, run = run }
gpl-2.0
KayMD/Illarion-Content
lte/teachmagic.lua
3
1748
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local M = {} function M.addEffect(teachEffect, Character) local year=world:getTime("year") year=(year-1)*31536000 -- (year-1)*((15*24) + 5)*24*60*60 local month=world:getTime("month") month=(month-1)*2073600 -- (month-1)*24*24*60*60 local day=world:getTime("day") day=(day-1)*86400 -- (day-1)*24*60*60 local hour=world:getTime("hour") hour=hour*3600 -- hour*60*60 local minute=world:getTime("minute") minute=minute*60 local second=world:getTime("second") second=second local waittime=1814400 local timestamp=year+month+day+hour+minute+second+waittime teachEffect:addValue("Rune1Index",timestamp) teachEffect:addValue("Rune2Index",1) end function M.callEffect(teachEffect, Character) -- Effect wird ausgeführt teachEffect.nextCalled =99999999999999 -- call it again in öhm...never! return true end function M.removeEffect( Effect, Character ) end function M.loadEffect(Effect, Character) end return M
agpl-3.0
nobie/sesame_fw
feeds/luci/applications/luci-statistics/luasrc/model/cbi/luci_statistics/ping.lua
80
1397
--[[ Luci configuration model for statistics - collectd ping plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("Ping Plugin Configuration"), translate( "The ping plugin will send icmp echo replies to selected " .. "hosts and measure the roundtrip time for each host." )) -- collectd_ping config section s = m:section( NamedSection, "collectd_ping", "luci_statistics" ) -- collectd_ping.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_ping.hosts (Host) hosts = s:option( Value, "Hosts", translate("Monitor hosts"), translate ("Add multiple hosts separated by space.")) hosts.default = "127.0.0.1" hosts:depends( "enable", 1 ) -- collectd_ping.ttl (TTL) ttl = s:option( Value, "TTL", translate("TTL for ping packets") ) ttl.isinteger = true ttl.default = 128 ttl:depends( "enable", 1 ) -- collectd_ping.interval (Interval) interval = s:option( Value, "Interval", translate("Interval for pings"), translate ("Seconds") ) interval.isinteger = true interval.default = 30 interval:depends( "enable", 1 ) return m
gpl-2.0
trappi-stone/Factorio-Stdlib
stdlib/area/position.lua
1
12588
--- Tools for working with `<x,y>` coordinates. -- The tables passed into the Position functions are mutated in-place. -- @module Position -- @usage local Position = require('stdlib/area/position') -- @see Area -- @see Concepts.Position -- @see defines.direction local Game = require 'stdlib/game' Position = {} --luacheck: allow defined top --- By default position tables are mutated in place set this to true to make the tables immutable. Position.immutable = false --- Machine Epsilon -- @see wiki Machine_epsilon -- @return epsilon Position.epsilon = 1.19e-07 --- Returns a correctly formated position object. -- @usage Position.new({0, 0}) -- returns {x = 0, y = 0} -- @tparam array pos_arr the position to convert -- @tparam[opt=false] boolean copy return a new copy -- @treturn Concepts.Position itself or a new correctly formated position with metatable function Position.new(pos_arr, copy) Game.fail_if_missing(pos_arr, 'missing position argument') if not copy and getmetatable(pos_arr) == Position._mt then return pos_arr end local pos if #pos_arr == 2 then pos = { x = pos_arr[1], y = pos_arr[2] } else pos = {x = pos_arr.x, y = pos_arr.y} end return setmetatable(pos, Position._mt) end --- Creates a position that is a copy of the given position. -- @tparam Concepts.Position pos the position to copy -- @treturn Concepts.Position a new position with values identical to the given position function Position.copy(pos) pos = Position.new(pos) return Position.new({ x = pos.x, y = pos.y }) end --- Deprecated --@function to_table --@see Position.new Position.to_table = Position.new --- Creates a table representing the position from x and y. -- @tparam number x x-position -- @tparam number y y-position -- @treturn Concepts.Position function Position.construct(x, y) Game.fail_if_missing(x, 'missing x position argument') Game.fail_if_missing(y, 'missing y position argument') return Position.new({ x = x, y = y }) end --- Converts a position to a string. -- @tparam Concepts.Position pos the position to convert -- @treturn string string representation of the position function Position.tostring(pos) pos = Position.new(pos) return '{x = ' .. pos.x .. ', y = ' .. pos.y .. '}' end --- Adds two positions. -- @tparam Concepts.Position pos1 the first position -- @tparam Concepts.Position pos2 the second position -- @treturn Concepts.Position a new position &rarr; { x = pos1.x + pos2.x, y = pos1.y + pos2.y} function Position.add(pos1, pos2) pos1 = Position.new(pos1) pos2 = Position.new(pos2) return Position.new({x = pos1.x + pos2.x, y = pos1.y + pos2.y}) end --- Subtracts two positions. -- @tparam Concepts.Position pos1 the first position -- @tparam Concepts.Position pos2 the second position -- @treturn Concepts.Position a new position &rarr; { x = pos1.x - pos2.x, y = pos1.y - pos2.y } function Position.subtract(pos1, pos2) pos1 = Position.new(pos1) pos2 = Position.new(pos2) return Position.new({x = pos1.x - pos2.x, y = pos1.y - pos2.y}) end --- Tests whether or not the two given positions are equal. -- @tparam Concepts.Position pos1 the first position -- @tparam Concepts.Position pos2 the second position -- @treturn boolean true if positions are equal function Position.equals(pos1, pos2) if not pos1 or not pos2 then return false end pos1 = Position.new(pos1) pos2 = Position.new(pos2) local epsilon = Position.epsilon local abs = math.abs return abs(pos1.x - pos2.x) < epsilon and abs(pos1.y - pos2.y) < epsilon end function Position.less_than(pos1, pos2) pos1 = Position.new(pos1) pos2 = Position.new(pos2) return pos1.x < pos2.x and pos1.y < pos2.y end function Position.less_than_eq(pos1, pos2) pos1 = Position.new(pos1) pos2 = Position.new(pos2) return pos1.x <= pos2.x and pos1.y <= pos2.y end --- Creates a position that is offset by x,y coordinates. -- @tparam Concepts.Position pos the position to offset -- @tparam number x the amount to offset the position on the x-axis -- @tparam number y the amount to offset the position on the y-axis -- @treturn Concepts.Position a new position, offset by the x,y coordinates function Position.offset(pos, x, y) Game.fail_if_missing(x, 'missing x-coordinate value') Game.fail_if_missing(y, 'missing y-coordinate value') pos = Position.new(pos) pos.x = pos.x + x pos.y = pos.y + y return pos end --- Translates a position in the given direction. -- @tparam Concepts.Position pos the position to translate -- @tparam defines.direction direction the direction of translation -- @tparam number distance distance of the translation -- @treturn Concepts.Position a new translated position function Position.translate(pos, direction, distance) Game.fail_if_missing(direction, 'missing direction argument') Game.fail_if_missing(distance, 'missing distance argument') pos = Position.new(pos) if direction == defines.direction.north then pos.x = pos.x pos.y = pos.y - distance elseif direction == defines.direction.northeast then pos.x = pos.x + distance pos.y = pos.y - distance elseif direction == defines.direction.east then pos.x = pos.x + distance pos.y = pos.y elseif direction == defines.direction.southeast then pos.x = pos.x + distance pos.y = pos.y + distance elseif direction == defines.direction.south then pos.x = pos.x pos.y = pos.y + distance elseif direction == defines.direction.southwest then pos.x = pos.x - distance pos.y = pos.y + distance elseif direction == defines.direction.west then pos.x = pos.x - distance pos.y = pos.y elseif direction == defines.direction.northwest then pos.x = pos.x - distance pos.y = pos.y - distance end return pos end --- Expands a position to a square area. -- @tparam Concepts.Position pos the position to expand into an area -- @tparam number radius half of the side length of the area -- @treturn Concepts.BoundingBox the area function Position.expand_to_area(pos, radius) pos = Position.new(pos) Game.fail_if_missing(radius, 'missing radius argument') local left_top = Position.new({pos.x - radius, pos.y - radius}) local right_bottom = Position.new({pos.x + radius, pos.y + radius}) --some way to return Area.new? return { left_top = left_top, right_bottom = right_bottom } end --- Calculates the Euclidean distance squared between two positions, useful when sqrt is not needed. -- @tparam Concepts.Position pos1 the first position -- @tparam Concepts.Position pos2 the second position -- @treturn number the square of the euclidean distance function Position.distance_squared(pos1, pos2) pos1 = Position.new(pos1) pos2 = Position.new(pos2) local axbx = pos1.x - pos2.x local ayby = pos1.y - pos2.y return axbx * axbx + ayby * ayby end --- Calculates the Euclidean distance between two positions. -- @tparam Concepts.Position pos1 the first position -- @tparam Concepts.Position pos2 the second position -- @treturn number the euclidean distance function Position.distance(pos1, pos2) pos1 = Position.new(pos1) pos2 = Position.new(pos2) return math.sqrt(Position.distance_squared(pos1, pos2)) end --- Calculates the manhatten distance between two positions. -- @tparam Concepts.Position pos1 the first position -- @tparam Concepts.Position pos2 the second position -- @treturn number the manhatten distance -- @see https://en.wikipedia.org/wiki/Taxicab_geometry Taxicab geometry (manhatten distance) function Position.manhattan_distance(pos1, pos2) pos1 = Position.new(pos1) pos2 = Position.new(pos2) return math.abs(pos2.x - pos1.x) + math.abs(pos2.y - pos1.y) end --- Increment a position each time it is called. -- This can be used to increment or even decrement a position quickly. -- <p>Do not store function closures in the global object; use them in the current tick. -- @usage -- local next_pos = Position.increment({0,0}) -- for i = 1, 5 do next_pos(0,1) -- returns {x = 0, y = 1} {x = 0, y = 2} {x = 0, y = 3} {x = 0, y = 4} {x = 0, y = 5} -- @usage -- local next_pos = Position.increment({0, 0}, 1) -- next_pos() -- returns {1, 0} -- next_pos(0, 5) -- returns {1, 5} -- next_pos(nil, 5) -- returns {2, 10} -- @usage -- local next_pos = Position.increment({0, 0}, 0, 1) -- surface.create_entity{name = 'flying-text', text = 'text', position = next_pos()} -- surface.create_entity{name = 'flying-text', text = 'text', position = next_pos()} -- creates two flying text entities 1 tile apart -- @tparam Concepts.Position pos the position to start with -- @tparam[opt=0] number inc_x optional increment x by this amount -- @tparam[opt=0] number inc_y optional increment y by this amount -- @treturn function @{increment_closure} a function closure that returns an incremented position function Position.increment(pos, inc_x, inc_y) pos = Position.new(pos) local x, y = pos.x, pos.y inc_x, inc_y = inc_x or 0, inc_y or 0 --- -- @function increment_closure A closure which the @{increment} function returns. --> Do not call this directly and do not store this in the global object. -- @see increment -- @tparam[opt=0] number new_inc_x -- @tparam[opt=0] number new_inc_y -- @treturn Concepts.Position the incremented position return function(new_inc_x, new_inc_y) x = x + (new_inc_x or inc_x) y = y + (new_inc_y or inc_y) return Position.new({x, y}) end end --- Gets the center position of a tile where the given position resides. -- @tparam Concepts.Position pos the position which resides somewhere on a tile -- @treturn Concepts.Position the position at the center of the tile function Position.center(pos) pos = Position.new(pos) local x, y = pos.x, pos.y x = x >= 0 and math.floor(x) + 0.5 or math.ceil(x) - 0.5 y = y >= 0 and math.floor(y) + 0.5 or math.ceil(y) - 0.5 pos.x = x pos.y = y return pos end local opposites = (defines and defines.direction) and { [defines.direction.north] = defines.direction.south, [defines.direction.south] = defines.direction.north, [defines.direction.east] = defines.direction.west, [defines.direction.west] = defines.direction.east, [defines.direction.northeast] = defines.direction.southwest, [defines.direction.southwest] = defines.direction.northeast, [defines.direction.northwest] = defines.direction.southeast, [defines.direction.southeast] = defines.direction.northwest, } or {[0]=4, [1]=5, [2]=6, [3]=7, [4]=0, [5]=1, [6]=2, [7]=3} --- Returns the opposite direction &mdash; adapted from Factorio util.lua. -- @release 0.8.1 -- @tparam defines.direction direction the direction -- @treturn defines.direction the opposite direction function Position.opposite_direction(direction) return opposites[direction or defines.direction.north] end --- Returns the next direction. --> For entities that only support two directions, see @{opposite_direction}. -- @tparam defines.direction direction the starting direction -- @tparam[opt=false] boolean reverse true to get the next direction in counter-clockwise fashion, false otherwise -- @tparam[opt=false] boolean eight_way true to get the next direction in 8-way (note: not many prototypes support 8-way) -- @treturn defines.direction the next direction function Position.next_direction(direction, reverse, eight_way) Game.fail_if_missing(direction, 'missing starting direction') local next_dir = direction + (eight_way and ((reverse and -1) or 1) or ((reverse and -2) or 2)) return (next_dir > 7 and next_dir-next_dir) or (reverse and next_dir < 0 and 8 + next_dir) or next_dir end --- Position tables are returned with these metamethods attached -- @table Metamethods Position._mt = { __index = Position, -- If key is not found, see if there is one availble in the Position module. __tostring = Position.tostring, -- Returns a string representation of the position __add = Position.add, -- Adds two position together. __sub = Position.subtract, -- Subtracts one position from another. __eq = Position.equals, -- Are two positions the same. __lt = Position.less_than, -- Is position1 less than position2. __le = Position.less_than_eq, -- Is position1 less than or equal to position2. __concat = Game._concat -- calls tostring on both sides of concact. } return setmetatable(Position, Game._protect("Position"))
isc
artfullyContrived/wrk
deps/luajit/src/jit/bcsave.lua
87
18141
---------------------------------------------------------------------------- -- LuaJIT module to save/list bytecode. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module saves or lists the bytecode for an input file. -- It's run by the -b command line option. -- ------------------------------------------------------------------------------ local jit = require("jit") assert(jit.version_num == 20004, "LuaJIT core/library version mismatch") local bit = require("bit") -- Symbol name prefix for LuaJIT bytecode. local LJBC_PREFIX = "luaJIT_BC_" ------------------------------------------------------------------------------ local function usage() io.stderr:write[[ Save LuaJIT bytecode: luajit -b[options] input output -l Only list bytecode. -s Strip debug info (default). -g Keep debug info. -n name Set module name (default: auto-detect from input name). -t type Set output file type (default: auto-detect from output name). -a arch Override architecture for object files (default: native). -o os Override OS for object files (default: native). -e chunk Use chunk string as input. -- Stop handling options. - Use stdin as input and/or stdout as output. File types: c h obj o raw (default) ]] os.exit(1) end local function check(ok, ...) if ok then return ok, ... end io.stderr:write("luajit: ", ...) io.stderr:write("\n") os.exit(1) end local function readfile(input) if type(input) == "function" then return input end if input == "-" then input = nil end return check(loadfile(input)) end local function savefile(name, mode) if name == "-" then return io.stdout end return check(io.open(name, mode)) end ------------------------------------------------------------------------------ local map_type = { raw = "raw", c = "c", h = "h", o = "obj", obj = "obj", } local map_arch = { x86 = true, x64 = true, arm = true, ppc = true, ppcspe = true, mips = true, mipsel = true, } local map_os = { linux = true, windows = true, osx = true, freebsd = true, netbsd = true, openbsd = true, dragonfly = true, solaris = true, } local function checkarg(str, map, err) str = string.lower(str) local s = check(map[str], "unknown ", err) return s == true and str or s end local function detecttype(str) local ext = string.match(string.lower(str), "%.(%a+)$") return map_type[ext] or "raw" end local function checkmodname(str) check(string.match(str, "^[%w_.%-]+$"), "bad module name") return string.gsub(str, "[%.%-]", "_") end local function detectmodname(str) if type(str) == "string" then local tail = string.match(str, "[^/\\]+$") if tail then str = tail end local head = string.match(str, "^(.*)%.[^.]*$") if head then str = head end str = string.match(str, "^[%w_.%-]+") else str = nil end check(str, "cannot derive module name, use -n name") return string.gsub(str, "[%.%-]", "_") end ------------------------------------------------------------------------------ local function bcsave_tail(fp, output, s) local ok, err = fp:write(s) if ok and output ~= "-" then ok, err = fp:close() end check(ok, "cannot write ", output, ": ", err) end local function bcsave_raw(output, s) local fp = savefile(output, "wb") bcsave_tail(fp, output, s) end local function bcsave_c(ctx, output, s) local fp = savefile(output, "w") if ctx.type == "c" then fp:write(string.format([[ #ifdef _cplusplus extern "C" #endif #ifdef _WIN32 __declspec(dllexport) #endif const char %s%s[] = { ]], LJBC_PREFIX, ctx.modname)) else fp:write(string.format([[ #define %s%s_SIZE %d static const char %s%s[] = { ]], LJBC_PREFIX, ctx.modname, #s, LJBC_PREFIX, ctx.modname)) end local t, n, m = {}, 0, 0 for i=1,#s do local b = tostring(string.byte(s, i)) m = m + #b + 1 if m > 78 then fp:write(table.concat(t, ",", 1, n), ",\n") n, m = 0, #b + 1 end n = n + 1 t[n] = b end bcsave_tail(fp, output, table.concat(t, ",", 1, n).."\n};\n") end local function bcsave_elfobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7]; uint16_t type, machine; uint32_t version; uint32_t entry, phofs, shofs; uint32_t flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx; } ELF32header; typedef struct { uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7]; uint16_t type, machine; uint32_t version; uint64_t entry, phofs, shofs; uint32_t flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx; } ELF64header; typedef struct { uint32_t name, type, flags, addr, ofs, size, link, info, align, entsize; } ELF32sectheader; typedef struct { uint32_t name, type; uint64_t flags, addr, ofs, size; uint32_t link, info; uint64_t align, entsize; } ELF64sectheader; typedef struct { uint32_t name, value, size; uint8_t info, other; uint16_t sectidx; } ELF32symbol; typedef struct { uint32_t name; uint8_t info, other; uint16_t sectidx; uint64_t value, size; } ELF64symbol; typedef struct { ELF32header hdr; ELF32sectheader sect[6]; ELF32symbol sym[2]; uint8_t space[4096]; } ELF32obj; typedef struct { ELF64header hdr; ELF64sectheader sect[6]; ELF64symbol sym[2]; uint8_t space[4096]; } ELF64obj; ]] local symname = LJBC_PREFIX..ctx.modname local is64, isbe = false, false if ctx.arch == "x64" then is64 = true elseif ctx.arch == "ppc" or ctx.arch == "ppcspe" or ctx.arch == "mips" then isbe = true end -- Handle different host/target endianess. local function f32(x) return x end local f16, fofs = f32, f32 if ffi.abi("be") ~= isbe then f32 = bit.bswap function f16(x) return bit.rshift(bit.bswap(x), 16) end if is64 then local two32 = ffi.cast("int64_t", 2^32) function fofs(x) return bit.bswap(x)*two32 end else fofs = f32 end end -- Create ELF object and fill in header. local o = ffi.new(is64 and "ELF64obj" or "ELF32obj") local hdr = o.hdr if ctx.os == "bsd" or ctx.os == "other" then -- Determine native hdr.eosabi. local bf = assert(io.open("/bin/ls", "rb")) local bs = bf:read(9) bf:close() ffi.copy(o, bs, 9) check(hdr.emagic[0] == 127, "no support for writing native object files") else hdr.emagic = "\127ELF" hdr.eosabi = ({ freebsd=9, netbsd=2, openbsd=12, solaris=6 })[ctx.os] or 0 end hdr.eclass = is64 and 2 or 1 hdr.eendian = isbe and 2 or 1 hdr.eversion = 1 hdr.type = f16(1) hdr.machine = f16(({ x86=3, x64=62, arm=40, ppc=20, ppcspe=20, mips=8, mipsel=8 })[ctx.arch]) if ctx.arch == "mips" or ctx.arch == "mipsel" then hdr.flags = 0x50001006 end hdr.version = f32(1) hdr.shofs = fofs(ffi.offsetof(o, "sect")) hdr.ehsize = f16(ffi.sizeof(hdr)) hdr.shentsize = f16(ffi.sizeof(o.sect[0])) hdr.shnum = f16(6) hdr.shstridx = f16(2) -- Fill in sections and symbols. local sofs, ofs = ffi.offsetof(o, "space"), 1 for i,name in ipairs{ ".symtab", ".shstrtab", ".strtab", ".rodata", ".note.GNU-stack", } do local sect = o.sect[i] sect.align = fofs(1) sect.name = f32(ofs) ffi.copy(o.space+ofs, name) ofs = ofs + #name+1 end o.sect[1].type = f32(2) -- .symtab o.sect[1].link = f32(3) o.sect[1].info = f32(1) o.sect[1].align = fofs(8) o.sect[1].ofs = fofs(ffi.offsetof(o, "sym")) o.sect[1].entsize = fofs(ffi.sizeof(o.sym[0])) o.sect[1].size = fofs(ffi.sizeof(o.sym)) o.sym[1].name = f32(1) o.sym[1].sectidx = f16(4) o.sym[1].size = fofs(#s) o.sym[1].info = 17 o.sect[2].type = f32(3) -- .shstrtab o.sect[2].ofs = fofs(sofs) o.sect[2].size = fofs(ofs) o.sect[3].type = f32(3) -- .strtab o.sect[3].ofs = fofs(sofs + ofs) o.sect[3].size = fofs(#symname+1) ffi.copy(o.space+ofs+1, symname) ofs = ofs + #symname + 2 o.sect[4].type = f32(1) -- .rodata o.sect[4].flags = fofs(2) o.sect[4].ofs = fofs(sofs + ofs) o.sect[4].size = fofs(#s) o.sect[5].type = f32(1) -- .note.GNU-stack o.sect[5].ofs = fofs(sofs + ofs + #s) -- Write ELF object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs)) bcsave_tail(fp, output, s) end local function bcsave_peobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint16_t arch, nsects; uint32_t time, symtabofs, nsyms; uint16_t opthdrsz, flags; } PEheader; typedef struct { char name[8]; uint32_t vsize, vaddr, size, ofs, relocofs, lineofs; uint16_t nreloc, nline; uint32_t flags; } PEsection; typedef struct __attribute((packed)) { union { char name[8]; uint32_t nameref[2]; }; uint32_t value; int16_t sect; uint16_t type; uint8_t scl, naux; } PEsym; typedef struct __attribute((packed)) { uint32_t size; uint16_t nreloc, nline; uint32_t cksum; uint16_t assoc; uint8_t comdatsel, unused[3]; } PEsymaux; typedef struct { PEheader hdr; PEsection sect[2]; // Must be an even number of symbol structs. PEsym sym0; PEsymaux sym0aux; PEsym sym1; PEsymaux sym1aux; PEsym sym2; PEsym sym3; uint32_t strtabsize; uint8_t space[4096]; } PEobj; ]] local symname = LJBC_PREFIX..ctx.modname local is64 = false if ctx.arch == "x86" then symname = "_"..symname elseif ctx.arch == "x64" then is64 = true end local symexport = " /EXPORT:"..symname..",DATA " -- The file format is always little-endian. Swap if the host is big-endian. local function f32(x) return x end local f16 = f32 if ffi.abi("be") then f32 = bit.bswap function f16(x) return bit.rshift(bit.bswap(x), 16) end end -- Create PE object and fill in header. local o = ffi.new("PEobj") local hdr = o.hdr hdr.arch = f16(({ x86=0x14c, x64=0x8664, arm=0x1c0, ppc=0x1f2, mips=0x366, mipsel=0x366 })[ctx.arch]) hdr.nsects = f16(2) hdr.symtabofs = f32(ffi.offsetof(o, "sym0")) hdr.nsyms = f32(6) -- Fill in sections and symbols. o.sect[0].name = ".drectve" o.sect[0].size = f32(#symexport) o.sect[0].flags = f32(0x00100a00) o.sym0.sect = f16(1) o.sym0.scl = 3 o.sym0.name = ".drectve" o.sym0.naux = 1 o.sym0aux.size = f32(#symexport) o.sect[1].name = ".rdata" o.sect[1].size = f32(#s) o.sect[1].flags = f32(0x40300040) o.sym1.sect = f16(2) o.sym1.scl = 3 o.sym1.name = ".rdata" o.sym1.naux = 1 o.sym1aux.size = f32(#s) o.sym2.sect = f16(2) o.sym2.scl = 2 o.sym2.nameref[1] = f32(4) o.sym3.sect = f16(-1) o.sym3.scl = 2 o.sym3.value = f32(1) o.sym3.name = "@feat.00" -- Mark as SafeSEH compliant. ffi.copy(o.space, symname) local ofs = #symname + 1 o.strtabsize = f32(ofs + 4) o.sect[0].ofs = f32(ffi.offsetof(o, "space") + ofs) ffi.copy(o.space + ofs, symexport) ofs = ofs + #symexport o.sect[1].ofs = f32(ffi.offsetof(o, "space") + ofs) -- Write PE object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs)) bcsave_tail(fp, output, s) end local function bcsave_machobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint32_t magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags; } mach_header; typedef struct { mach_header; uint32_t reserved; } mach_header_64; typedef struct { uint32_t cmd, cmdsize; char segname[16]; uint32_t vmaddr, vmsize, fileoff, filesize; uint32_t maxprot, initprot, nsects, flags; } mach_segment_command; typedef struct { uint32_t cmd, cmdsize; char segname[16]; uint64_t vmaddr, vmsize, fileoff, filesize; uint32_t maxprot, initprot, nsects, flags; } mach_segment_command_64; typedef struct { char sectname[16], segname[16]; uint32_t addr, size; uint32_t offset, align, reloff, nreloc, flags; uint32_t reserved1, reserved2; } mach_section; typedef struct { char sectname[16], segname[16]; uint64_t addr, size; uint32_t offset, align, reloff, nreloc, flags; uint32_t reserved1, reserved2, reserved3; } mach_section_64; typedef struct { uint32_t cmd, cmdsize, symoff, nsyms, stroff, strsize; } mach_symtab_command; typedef struct { int32_t strx; uint8_t type, sect; int16_t desc; uint32_t value; } mach_nlist; typedef struct { uint32_t strx; uint8_t type, sect; uint16_t desc; uint64_t value; } mach_nlist_64; typedef struct { uint32_t magic, nfat_arch; } mach_fat_header; typedef struct { uint32_t cputype, cpusubtype, offset, size, align; } mach_fat_arch; typedef struct { struct { mach_header hdr; mach_segment_command seg; mach_section sec; mach_symtab_command sym; } arch[1]; mach_nlist sym_entry; uint8_t space[4096]; } mach_obj; typedef struct { struct { mach_header_64 hdr; mach_segment_command_64 seg; mach_section_64 sec; mach_symtab_command sym; } arch[1]; mach_nlist_64 sym_entry; uint8_t space[4096]; } mach_obj_64; typedef struct { mach_fat_header fat; mach_fat_arch fat_arch[4]; struct { mach_header hdr; mach_segment_command seg; mach_section sec; mach_symtab_command sym; } arch[4]; mach_nlist sym_entry; uint8_t space[4096]; } mach_fat_obj; ]] local symname = '_'..LJBC_PREFIX..ctx.modname local isfat, is64, align, mobj = false, false, 4, "mach_obj" if ctx.arch == "x64" then is64, align, mobj = true, 8, "mach_obj_64" elseif ctx.arch == "arm" then isfat, mobj = true, "mach_fat_obj" else check(ctx.arch == "x86", "unsupported architecture for OSX") end local function aligned(v, a) return bit.band(v+a-1, -a) end local be32 = bit.bswap -- Mach-O FAT is BE, supported archs are LE. -- Create Mach-O object and fill in header. local o = ffi.new(mobj) local mach_size = aligned(ffi.offsetof(o, "space")+#symname+2, align) local cputype = ({ x86={7}, x64={0x01000007}, arm={7,12,12,12} })[ctx.arch] local cpusubtype = ({ x86={3}, x64={3}, arm={3,6,9,11} })[ctx.arch] if isfat then o.fat.magic = be32(0xcafebabe) o.fat.nfat_arch = be32(#cpusubtype) end -- Fill in sections and symbols. for i=0,#cpusubtype-1 do local ofs = 0 if isfat then local a = o.fat_arch[i] a.cputype = be32(cputype[i+1]) a.cpusubtype = be32(cpusubtype[i+1]) -- Subsequent slices overlap each other to share data. ofs = ffi.offsetof(o, "arch") + i*ffi.sizeof(o.arch[0]) a.offset = be32(ofs) a.size = be32(mach_size-ofs+#s) end local a = o.arch[i] a.hdr.magic = is64 and 0xfeedfacf or 0xfeedface a.hdr.cputype = cputype[i+1] a.hdr.cpusubtype = cpusubtype[i+1] a.hdr.filetype = 1 a.hdr.ncmds = 2 a.hdr.sizeofcmds = ffi.sizeof(a.seg)+ffi.sizeof(a.sec)+ffi.sizeof(a.sym) a.seg.cmd = is64 and 0x19 or 0x1 a.seg.cmdsize = ffi.sizeof(a.seg)+ffi.sizeof(a.sec) a.seg.vmsize = #s a.seg.fileoff = mach_size-ofs a.seg.filesize = #s a.seg.maxprot = 1 a.seg.initprot = 1 a.seg.nsects = 1 ffi.copy(a.sec.sectname, "__data") ffi.copy(a.sec.segname, "__DATA") a.sec.size = #s a.sec.offset = mach_size-ofs a.sym.cmd = 2 a.sym.cmdsize = ffi.sizeof(a.sym) a.sym.symoff = ffi.offsetof(o, "sym_entry")-ofs a.sym.nsyms = 1 a.sym.stroff = ffi.offsetof(o, "sym_entry")+ffi.sizeof(o.sym_entry)-ofs a.sym.strsize = aligned(#symname+2, align) end o.sym_entry.type = 0xf o.sym_entry.sect = 1 o.sym_entry.strx = 1 ffi.copy(o.space+1, symname) -- Write Macho-O object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, mach_size)) bcsave_tail(fp, output, s) end local function bcsave_obj(ctx, output, s) local ok, ffi = pcall(require, "ffi") check(ok, "FFI library required to write this file type") if ctx.os == "windows" then return bcsave_peobj(ctx, output, s, ffi) elseif ctx.os == "osx" then return bcsave_machobj(ctx, output, s, ffi) else return bcsave_elfobj(ctx, output, s, ffi) end end ------------------------------------------------------------------------------ local function bclist(input, output) local f = readfile(input) require("jit.bc").dump(f, savefile(output, "w"), true) end local function bcsave(ctx, input, output) local f = readfile(input) local s = string.dump(f, ctx.strip) local t = ctx.type if not t then t = detecttype(output) ctx.type = t end if t == "raw" then bcsave_raw(output, s) else if not ctx.modname then ctx.modname = detectmodname(input) end if t == "obj" then bcsave_obj(ctx, output, s) else bcsave_c(ctx, output, s) end end end local function docmd(...) local arg = {...} local n = 1 local list = false local ctx = { strip = true, arch = jit.arch, os = string.lower(jit.os), type = false, modname = false, } while n <= #arg do local a = arg[n] if type(a) == "string" and string.sub(a, 1, 1) == "-" and a ~= "-" then table.remove(arg, n) if a == "--" then break end for m=2,#a do local opt = string.sub(a, m, m) if opt == "l" then list = true elseif opt == "s" then ctx.strip = true elseif opt == "g" then ctx.strip = false else if arg[n] == nil or m ~= #a then usage() end if opt == "e" then if n ~= 1 then usage() end arg[1] = check(loadstring(arg[1])) elseif opt == "n" then ctx.modname = checkmodname(table.remove(arg, n)) elseif opt == "t" then ctx.type = checkarg(table.remove(arg, n), map_type, "file type") elseif opt == "a" then ctx.arch = checkarg(table.remove(arg, n), map_arch, "architecture") elseif opt == "o" then ctx.os = checkarg(table.remove(arg, n), map_os, "OS name") else usage() end end end else n = n + 1 end end if list then if #arg == 0 or #arg > 2 then usage() end bclist(arg[1], arg[2] or "-") else if #arg ~= 2 then usage() end bcsave(ctx, arg[1], arg[2]) end end ------------------------------------------------------------------------------ -- Public module functions. module(...) start = docmd -- Process -b command line option.
apache-2.0
Mutos/NAEV-StarsOfCall
dat/missions/neutral/cargo.lua
8
4208
--[[ -- These are regular cargo delivery missions. Pay is low, but so is difficulty. -- Most of these missions require BULK ships. Not for small ships! --]] include "dat/scripts/cargo_common.lua" include "dat/scripts/numstring.lua" lang = naev.lang() if lang == "es" then else -- default english misn_desc = "%s in the %s system needs a delivery of %d tons of %s." misn_reward = "%s credits" cargosize = {} cargosize[0] = "Small" -- Note: indexed from 0, to match mission tiers. cargosize[1] = "Medium" cargosize[2] = "Sizeable" cargosize[3] = "Large" cargosize[4] = "Bulk" title_p1 = {} title_p1[1] = " cargo delivery to %s in the %s system" title_p1[2] = " freight delivery to %s in the %s system" title_p1[3] = " transport to %s in the %s system" title_p1[4] = " delivery to %s in the %s system" -- Note: please leave the trailing space on the line below! Needed to make the newline show up. title_p2 = [[ Cargo: %s (%d tons) Jumps: %d Travel distance: %d]] full = {} full[1] = "No room in ship" full[2] = "You don't have enough cargo space to accept this mission. You need %d tons of free space (you need %d more)." --=Landing=-- cargo_land_title = "Delivery success!" cargo_land_p1 = {} cargo_land_p1[1] = "The crates of " cargo_land_p1[2] = "The drums of " cargo_land_p1[3] = "The containers of " cargo_land_p2 = {} cargo_land_p2[1] = " are carried out of your ship by a sullen group of workers. The job takes inordinately long to complete, and the leader pays you without speaking a word." cargo_land_p2[2] = " are rushed out of your vessel by a team shortly after you land. Before you can even collect your thoughts, one of them presses a credit chip in your hand and departs." cargo_land_p2[3] = " are unloaded by an exhausted-looking bunch of dockworkers. Still, they make fairly good time, delivering your pay upon completion of the job." cargo_land_p2[4] = " are unloaded by a team of robotic drones supervised by a human overseer, who hands you your pay when they finish." accept_title = "Mission Accepted" osd_title = "Cargo mission" osd_msg = "Fly to %s in the %s system." end -- Create the mission function create() -- Note: this mission does not make any system claims. -- Calculate the route, distance, jumps and cargo to take destplanet, destsys, numjumps, traveldist, cargo, tier = cargo_calculateRoute() if destplanet == nil then misn.finish(false) end -- Choose amount of cargo and mission reward. This depends on the mission tier. -- Note: Pay is independent from amount by design! Not all deals are equally attractive! finished_mod = 2.0 -- Modifier that should tend towards 1.0 as naev is finished as a game amount = rnd.rnd(5 + 25 * tier, 20 + 60 * tier) jumpreward = 200 distreward = 0.09 reward = 1.5^tier * (numjumps * jumpreward + traveldist * distreward) * finished_mod * (1. + 0.05*rnd.twosigma()) misn.setTitle(buildCargoMissionDescription( nil, amount, cargo, destplanet, destsys )) misn.markerAdd(destsys, "computer") misn.setDesc(cargosize[tier] .. title_p1[rnd.rnd(1, #title_p1)]:format(destplanet:name(), destsys:name()) .. title_p2:format(cargo, amount, numjumps, traveldist)) misn.setReward(misn_reward:format(numstring(reward))) end -- Mission is accepted function accept() if player.pilot():cargoFree() < amount then tk.msg(full[1], full[2]:format(amount, amount - player.pilot():cargoFree())) misn.finish() end misn.accept() misn.cargoAdd(cargo, amount) -- TODO: change to jettisonable cargo once custom commodities are in. For piracy purposes. misn.osdCreate(osd_title, {osd_msg:format(destplanet:name(), destsys:name())}) hook.land("land") end -- Land hook function land() if planet.cur() == destplanet then -- Semi-random message. tk.msg(cargo_land_title, cargo_land_p1[rnd.rnd(1, #cargo_land_p1)] .. cargo .. cargo_land_p2[rnd.rnd(1, #cargo_land_p2)]) player.pay(reward) misn.finish(true) end end function abort () misn.finish(false) end
gpl-3.0
LuaDist2/lua-jet
spec/radix_spec.lua
2
9595
local radix = require'jet.daemon.radix' describe( 'The jet.daemon.radix module', function() describe('Can add path',function() local match setup(function() local radix_tree = radix.new() radix_tree.add('abc') local radix_fetchers = {} radix_fetchers['equals'] = 'abc' radix_tree.match_parts(radix_fetchers) match = radix_tree.found_elements()['abc'] end) it('matches',function() assert.is_true(match) end) end) describe('Can remove path',function() local match local removed setup(function() local radix_tree = radix.new() radix_tree.add('abc') radix_tree.add('def') local radix_fetchers = {} radix_fetchers['equals'] = 'abc' radix_tree.match_parts(radix_fetchers) match = radix_tree.found_elements()['abc'] radix_tree.remove('abc') radix_tree.match_parts(radix_fetchers) removed = radix_tree.found_elements()['abc'] end) it('matches',function() assert.is_true(match) end) it('mismatches',function() assert.is_falsy(removed) end) end) describe('Can fetch equals',function() local match setup(function() local radix_tree = radix.new() radix_tree.add('abcdef') radix_tree.add('ddefghi') radix_tree.add('defghi') radix_tree.add('defghid') radix_tree.add('ddefghia') local radix_fetchers = {} radix_fetchers['equals'] = 'defghi' radix_tree.match_parts(radix_fetchers) match = function (word) return radix_tree.found_elements()[word] end end) it('matches',function() assert.is_true(match('defghi')) end) it('mismatches',function() assert.is_falsy(match('ddefghi')) assert.is_falsy(match('defghid')) assert.is_falsy(match('ddefghia')) assert.is_falsy(match('abcdef')) end) end) describe('Can fetch startsWith',function() local match setup(function() local radix_tree = radix.new() radix_tree.add('abcdef') radix_tree.add('defghi') radix_tree.add('abcghi') local radix_fetchers = {} radix_fetchers['startsWith'] = 'abc' radix_tree.match_parts(radix_fetchers) match = function (word) return radix_tree.found_elements()[word] end end) it('matches',function() assert.is_true(match('abcdef')) assert.is_true(match('abcghi')) end) it('mismatches',function() assert.is_falsy(match('abc')) assert.is_falsy(match('defghi')) end) end) describe('Can fetch contains',function() local match setup(function() local radix_tree = radix.new() radix_tree.add('abcdef') radix_tree.add('fgabcdef') radix_tree.add('abcdefg') radix_tree.add('defghi') radix_tree.add('abcfghi') local radix_fetchers = {} radix_fetchers['contains'] = 'fg' radix_tree.match_parts(radix_fetchers) match = function (word) return radix_tree.found_elements()[word] end end) it('matches',function() assert.is_true(match('defghi')) assert.is_true(match('abcfghi')) assert.is_true(match('fgabcdef')) assert.is_true(match('abcdefg')) end) it('mismatches',function() assert.is_falsy(match('fg')) assert.is_falsy(match('abcdef')) end) end) describe('Can fetch endsWith',function() local match setup(function() local radix_tree = radix.new() radix_tree.add('abcdeffg') radix_tree.add('defghi') radix_tree.add('abchifg') radix_tree.add('afbcfghi') local radix_fetchers = {} radix_fetchers['endsWith'] = 'fg' radix_tree.match_parts(radix_fetchers) match = function (word) return radix_tree.found_elements()[word] end end) it('matches',function() assert.is_true(match('abcdeffg')) assert.is_true(match('abchifg')) end) it('mismatches',function() assert.is_falsy(match('fg')) assert.is_falsy(match('defghi')) assert.is_falsy(match('afbcfghi')) end) end) describe('Can fetch startsWith + endsWith',function() local match setup(function() local radix_tree = radix.new() radix_tree.add('abcdeffg') radix_tree.add('defghi') radix_tree.add('abchifg') radix_tree.add('ahfbcfghi') radix_tree.add('ahi') local radix_fetchers = {} radix_fetchers['startsWith'] = 'ah' radix_fetchers['endsWith'] = 'hi' radix_tree.match_parts(radix_fetchers) match = function (word) return radix_tree.found_elements()[word] end end) it('matches',function() assert.is_true(match('ahfbcfghi')) end) it('mismatches',function() assert.is_falsy(match('a')) assert.is_falsy(match('hi')) assert.is_falsy(match('defghi')) assert.is_falsy(match('ahi')) assert.is_falsy(match('abcdeffg')) end) end) describe('Can fetch contains + endsWith',function() local match setup(function() local radix_tree = radix.new() radix_tree.add('hiabghcdeffhi') radix_tree.add('deghfghi') radix_tree.add('ahchifg') radix_tree.add('ahchifghi') radix_tree.add('ahfbcfghi') local radix_fetchers = {} radix_fetchers['contains'] = 'gh' radix_fetchers['endsWith'] = 'hi' radix_tree.match_parts(radix_fetchers) match = function (word) return radix_tree.found_elements()[word] end end) it('matches',function() assert.is_true(match('deghfghi')) assert.is_true(match('hiabghcdeffhi')) end) it('mismatches',function() assert.is_falsy(match('ahchifg')) assert.is_falsy(match('hi')) assert.is_falsy(match('gh')) assert.is_falsy(match('ahchifghi')) assert.is_falsy(match('ahchifg')) assert.is_falsy(match('ahfbcfghi')) end) end) describe('Can fetch startsWith + contains',function() local match setup(function() local radix_tree = radix.new() radix_tree.add('abcdeffg') radix_tree.add('defghi') radix_tree.add('ahchifg') radix_tree.add('ahchifghi') radix_tree.add('ahfbcfghi') radix_tree.add('ahia') local radix_fetchers = {} radix_fetchers['startsWith'] = 'ah' radix_fetchers['contains'] = 'hi' radix_tree.match_parts(radix_fetchers) match = function (word) return radix_tree.found_elements()[word] end end) it('matches',function() assert.is_true(match('ahfbcfghi')) assert.is_true(match('ahchifghi')) assert.is_true(match('ahchifg')) end) it('mismatches',function() assert.is_falsy(match('a')) assert.is_falsy(match('hi')) assert.is_falsy(match('defghi')) assert.is_falsy(match('ahia')) assert.is_falsy(match('abcdeffg')) end) end) describe('Can fetch startsWith + contains + endsWith',function() local match setup(function() local radix_tree = radix.new() radix_tree.add('defghi') radix_tree.add('ahchifg') radix_tree.add('ahicfg') radix_tree.add('ahfbcfghi') radix_tree.add('ahia') local radix_fetchers = {} radix_fetchers['startsWith'] = 'ah' radix_fetchers['contains'] = 'hi' radix_fetchers['endsWith'] = 'fg' radix_tree.match_parts(radix_fetchers) match = function (word) return radix_tree.found_elements()[word] end end) it('matches',function() assert.is_true(match('ahchifg')) end) it('mismatches',function() assert.is_falsy(match('ah')) assert.is_falsy(match('hi')) assert.is_falsy(match('ahicfg')) assert.is_falsy(match('defghi')) assert.is_falsy(match('ahfbcfghi')) end) end) end)
mit
dacrybabysuck/darkstar
scripts/globals/weaponskills/glory_slash.lua
10
1635
----------------------------------- -- Glory Slash -- Sword weapon skill -- Skill Level: NA -- Only avaliable during Campaign Battle while weilding Lex Talionis. -- Delivers and area attack that deals triple damage. Damage varies with TP. Additional effect Stun. -- Will stack with Sneak Attack. -- Aligned with the Flame Gorget & Light Gorget. -- Aligned with the Flame Belt & Light Belt. -- Element: Light -- Modifiers: STR:30% -- 100%TP 200%TP 300%TP -- 3.00 3.50 4.00 ----------------------------------- require("scripts/globals/weaponskills") require("scripts/globals/settings") require("scripts/globals/status") ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {} params.numHits = 1 params.ftp100 = 3 params.ftp200 = 3.5 params.ftp300 = 4 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.atk100 = 1; params.atk200 = 1; params.atk300 = 1; if (damage > 0 and target:hasStatusEffect(dsp.effect.STUN) == false) then local duration = (tp/500) * applyResistanceAddEffect(player,target,dsp.magic.ele.LIGHTNING,0) target:addStatusEffect(dsp.effect.STUN, 1, 0, duration) end local damage, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar) return tpHits, extraHits, damage end
gpl-3.0
dormantor/ofxCogEngine
COGengine/data/COGAssets/Scripts/base.lua
1
2750
--[[ -- methods for testing in lua console function BehaviorPrototype() return { RegisterDelegate = function(self, tb) print("Registering delegate "..tb.classname) end } end function CogRegisterBehaviorPrototype(tb) print("Registering behavior prototype "..tb.classname) end --]] -- create behavior base object Behavior = { -- function for creating instances from C++ code NewCpp = function(self, bproxy) local meta = self.CreateMeta(self) self:Constructor() bproxy:RegisterDelegate(meta) meta.proxy = bproxy return meta end, -- function for creating instances New = function(self, ...) local meta = self.CreateMeta(self) self:Constructor(...) local beh = BehaviorProxy() beh:RegisterDelegate(meta) meta.proxy = beh return meta end, -- function for defining new class Extend = function(self, classname, subtype) if (subtype) then -- copy methods into subtype subtype.NewCpp = self.NewCpp subtype.New = self.New subtype.Extend = self.Extend subtype.CreateMeta = self.CreateMeta subtype.Constructor = subtype.Constructor or self.Constructor subtype.OnInit = subtype.OnInit or self.OnInit subtype.OnMessage = subtype.OnMessage or self.OnMessage subtype.Update = subtype.Update or self.Update subtype.SubscribeForMessages = self.SubscribeForMessages subtype.SendMessage = self.SendMessage subtype.SendMessageWithData = self.SendMessageWithData -- override else subtype = self end if not(classname) or classname == "" then error("When called Extend(classname), a name of the new class must be specified") end local meta = subtype.CreateMeta(subtype) meta.classname = classname CogRegisterBehaviorPrototype(meta, classname) return meta end, -- create metatable CreateMeta = function(self, subtype) local meta = { __index = subtype } output = setmetatable( { }, { __index = self, -- Behavior() and Behavior:new() are the same __call = function(self, ...) return self:New(...) end } ) return output end, Constructor = function(self, ...) end, OnInit = function(self) end, OnMessage = function(self, msg) end, Update = function(self, delta, absolute) end, -- methods that will call assigned proxy object SubscribeForMessages = function(self, act) if(type(act) == "string") then act = StrId(act) end return self.proxy:SubscribeForMessages(act) end, SendMessage = function(self, msg) if(type(msg) == "string") then return self.proxy:SendMessage(StrId(msg)) else return self.proxy:SendMessage(msg) end end, SendMessageWithData = function(self, msg, data) if(type(msg) == "string") then return self.proxy:SendMessageWithData(StrId(msg), data) else return self.proxy:SendMessageWithData(msg, data) end end }
mit
Squ34k3rZ/SamsBday
Resources/DeprecatedClass.lua
15
74670
-- This is the DeprecatedClass DeprecatedClass = {} or DeprecatedClass --tip local function deprecatedTip(old_name,new_name) print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********") end --CCProgressTo class will be Deprecated,begin function DeprecatedClass.CCProgressTo() deprecatedTip("CCProgressTo","cc.ProgressTo") return cc.ProgressTo end _G["CCProgressTo"] = DeprecatedClass.CCProgressTo() --CCProgressTo class will be Deprecated,end --CCHide class will be Deprecated,begin function DeprecatedClass.CCHide() deprecatedTip("CCHide","cc.Hide") return cc.Hide end _G["CCHide"] = DeprecatedClass.CCHide() --CCHide class will be Deprecated,end --CCTransitionMoveInB class will be Deprecated,begin function DeprecatedClass.CCTransitionMoveInB() deprecatedTip("CCTransitionMoveInB","cc.TransitionMoveInB") return cc.TransitionMoveInB end _G["CCTransitionMoveInB"] = DeprecatedClass.CCTransitionMoveInB() --CCTransitionMoveInB class will be Deprecated,end --CCEaseSineIn class will be Deprecated,begin function DeprecatedClass.CCEaseSineIn() deprecatedTip("CCEaseSineIn","cc.EaseSineIn") return cc.EaseSineIn end _G["CCEaseSineIn"] = DeprecatedClass.CCEaseSineIn() --CCEaseSineIn class will be Deprecated,end --CCTransitionMoveInL class will be Deprecated,begin function DeprecatedClass.CCTransitionMoveInL() deprecatedTip("CCTransitionMoveInL","cc.TransitionMoveInL") return cc.TransitionMoveInL end _G["CCTransitionMoveInL"] = DeprecatedClass.CCTransitionMoveInL() --CCTransitionMoveInL class will be Deprecated,end --CCEaseInOut class will be Deprecated,begin function DeprecatedClass.CCEaseInOut() deprecatedTip("CCEaseInOut","cc.EaseInOut") return cc.EaseInOut end _G["CCEaseInOut"] = DeprecatedClass.CCEaseInOut() --CCEaseInOut class will be Deprecated,end --SimpleAudioEngine class will be Deprecated,begin function DeprecatedClass.SimpleAudioEngine() deprecatedTip("SimpleAudioEngine","cc.SimpleAudioEngine") return cc.SimpleAudioEngine end _G["SimpleAudioEngine"] = DeprecatedClass.SimpleAudioEngine() --SimpleAudioEngine class will be Deprecated,end --CCTransitionMoveInT class will be Deprecated,begin function DeprecatedClass.CCTransitionMoveInT() deprecatedTip("CCTransitionMoveInT","cc.TransitionMoveInT") return cc.TransitionMoveInT end _G["CCTransitionMoveInT"] = DeprecatedClass.CCTransitionMoveInT() --CCTransitionMoveInT class will be Deprecated,end --CCTransitionMoveInR class will be Deprecated,begin function DeprecatedClass.CCTransitionMoveInR() deprecatedTip("CCTransitionMoveInR","cc.TransitionMoveInR") return cc.TransitionMoveInR end _G["CCTransitionMoveInR"] = DeprecatedClass.CCTransitionMoveInR() --CCTransitionMoveInR class will be Deprecated,end --CCControlHuePicker class will be Deprecated,begin function DeprecatedClass.CCControlHuePicker() deprecatedTip("CCControlHuePicker","cc.ControlHuePicker") return cc.ControlHuePicker end _G["CCControlHuePicker"] = DeprecatedClass.CCControlHuePicker() --CCControlHuePicker class will be Deprecated,end --CCParticleSnow class will be Deprecated,begin function DeprecatedClass.CCParticleSnow() deprecatedTip("CCParticleSnow","cc.ParticleSnow") return cc.ParticleSnow end _G["CCParticleSnow"] = DeprecatedClass.CCParticleSnow() --CCParticleSnow class will be Deprecated,end --CCActionCamera class will be Deprecated,begin function DeprecatedClass.CCActionCamera() deprecatedTip("CCActionCamera","cc.ActionCamera") return cc.ActionCamera end _G["CCActionCamera"] = DeprecatedClass.CCActionCamera() --CCActionCamera class will be Deprecated,end --CCProgressFromTo class will be Deprecated,begin function DeprecatedClass.CCProgressFromTo() deprecatedTip("CCProgressFromTo","cc.ProgressFromTo") return cc.ProgressFromTo end _G["CCProgressFromTo"] = DeprecatedClass.CCProgressFromTo() --CCProgressFromTo class will be Deprecated,end --CCMoveTo class will be Deprecated,begin function DeprecatedClass.CCMoveTo() deprecatedTip("CCMoveTo","cc.MoveTo") return cc.MoveTo end _G["CCMoveTo"] = DeprecatedClass.CCMoveTo() --CCMoveTo class will be Deprecated,end --CCJumpBy class will be Deprecated,begin function DeprecatedClass.CCJumpBy() deprecatedTip("CCJumpBy","cc.JumpBy") return cc.JumpBy end _G["CCJumpBy"] = DeprecatedClass.CCJumpBy() --CCJumpBy class will be Deprecated,end --CCObject class will be Deprecated,begin function DeprecatedClass.CCObject() deprecatedTip("CCObject","cc.Object") return cc.Object end _G["CCObject"] = DeprecatedClass.CCObject() --CCObject class will be Deprecated,end --CCTransitionRotoZoom class will be Deprecated,begin function DeprecatedClass.CCTransitionRotoZoom() deprecatedTip("CCTransitionRotoZoom","cc.TransitionRotoZoom") return cc.TransitionRotoZoom end _G["CCTransitionRotoZoom"] = DeprecatedClass.CCTransitionRotoZoom() --CCTransitionRotoZoom class will be Deprecated,end --CCControlColourPicker class will be Deprecated,begin function DeprecatedClass.CCControlColourPicker() deprecatedTip("CCControlColourPicker","cc.ControlColourPicker") return cc.ControlColourPicker end _G["CCControlColourPicker"] = DeprecatedClass.CCControlColourPicker() --CCControlColourPicker class will be Deprecated,end --CCDirector class will be Deprecated,begin function DeprecatedClass.CCDirector() deprecatedTip("CCDirector","cc.Director") return cc.Director end _G["CCDirector"] = DeprecatedClass.CCDirector() --CCDirector class will be Deprecated,end --CCScheduler class will be Deprecated,begin function DeprecatedClass.CCScheduler() deprecatedTip("CCScheduler","cc.Scheduler") return cc.Scheduler end _G["CCScheduler"] = DeprecatedClass.CCScheduler() --CCScheduler class will be Deprecated,end --CCEaseElasticOut class will be Deprecated,begin function DeprecatedClass.CCEaseElasticOut() deprecatedTip("CCEaseElasticOut","cc.EaseElasticOut") return cc.EaseElasticOut end _G["CCEaseElasticOut"] = DeprecatedClass.CCEaseElasticOut() --CCEaseElasticOut class will be Deprecated,end --CCTableViewCell class will be Deprecated,begin function DeprecatedClass.CCTableViewCell() deprecatedTip("CCTableViewCell","cc.TableViewCell") return cc.TableViewCell end _G["CCTableViewCell"] = DeprecatedClass.CCTableViewCell() --CCTableViewCell class will be Deprecated,end --CCEaseBackOut class will be Deprecated,begin function DeprecatedClass.CCEaseBackOut() deprecatedTip("CCEaseBackOut","cc.EaseBackOut") return cc.EaseBackOut end _G["CCEaseBackOut"] = DeprecatedClass.CCEaseBackOut() --CCEaseBackOut class will be Deprecated,end --CCParticleSystemQuad class will be Deprecated,begin function DeprecatedClass.CCParticleSystemQuad() deprecatedTip("CCParticleSystemQuad","cc.ParticleSystemQuad") return cc.ParticleSystemQuad end _G["CCParticleSystemQuad"] = DeprecatedClass.CCParticleSystemQuad() --CCParticleSystemQuad class will be Deprecated,end --CCMenuItemToggle class will be Deprecated,begin function DeprecatedClass.CCMenuItemToggle() deprecatedTip("CCMenuItemToggle","cc.MenuItemToggle") return cc.MenuItemToggle end _G["CCMenuItemToggle"] = DeprecatedClass.CCMenuItemToggle() --CCMenuItemToggle class will be Deprecated,end --CCStopGrid class will be Deprecated,begin function DeprecatedClass.CCStopGrid() deprecatedTip("CCStopGrid","cc.StopGrid") return cc.StopGrid end _G["CCStopGrid"] = DeprecatedClass.CCStopGrid() --CCStopGrid class will be Deprecated,end --CCTransitionScene class will be Deprecated,begin function DeprecatedClass.CCTransitionScene() deprecatedTip("CCTransitionScene","cc.TransitionScene") return cc.TransitionScene end _G["CCTransitionScene"] = DeprecatedClass.CCTransitionScene() --CCTransitionScene class will be Deprecated,end --CCSkewBy class will be Deprecated,begin function DeprecatedClass.CCSkewBy() deprecatedTip("CCSkewBy","cc.SkewBy") return cc.SkewBy end _G["CCSkewBy"] = DeprecatedClass.CCSkewBy() --CCSkewBy class will be Deprecated,end --CCLayer class will be Deprecated,begin function DeprecatedClass.CCLayer() deprecatedTip("CCLayer","cc.Layer") return cc.Layer end _G["CCLayer"] = DeprecatedClass.CCLayer() --CCLayer class will be Deprecated,end --CCEaseElastic class will be Deprecated,begin function DeprecatedClass.CCEaseElastic() deprecatedTip("CCEaseElastic","cc.EaseElastic") return cc.EaseElastic end _G["CCEaseElastic"] = DeprecatedClass.CCEaseElastic() --CCEaseElastic class will be Deprecated,end --CCTMXTiledMap class will be Deprecated,begin function DeprecatedClass.CCTMXTiledMap() deprecatedTip("CCTMXTiledMap","cc.TMXTiledMap") return cc.TMXTiledMap end _G["CCTMXTiledMap"] = DeprecatedClass.CCTMXTiledMap() --CCTMXTiledMap class will be Deprecated,end --CCGrid3DAction class will be Deprecated,begin function DeprecatedClass.CCGrid3DAction() deprecatedTip("CCGrid3DAction","cc.Grid3DAction") return cc.Grid3DAction end _G["CCGrid3DAction"] = DeprecatedClass.CCGrid3DAction() --CCGrid3DAction class will be Deprecated,end --CCFadeIn class will be Deprecated,begin function DeprecatedClass.CCFadeIn() deprecatedTip("CCFadeIn","cc.FadeIn") return cc.FadeIn end _G["CCFadeIn"] = DeprecatedClass.CCFadeIn() --CCFadeIn class will be Deprecated,end --CCNodeRGBA class will be Deprecated,begin function DeprecatedClass.CCNodeRGBA() deprecatedTip("CCNodeRGBA","cc.Node") return cc.Node end _G["CCNodeRGBA"] = DeprecatedClass.CCNodeRGBA() --CCNodeRGBA class will be Deprecated,end --NodeRGBA class will be Deprecated,begin function DeprecatedClass.NodeRGBA() deprecatedTip("cc.NodeRGBA","cc.Node") return cc.Node end _G["cc"]["NodeRGBA"] = DeprecatedClass.NodeRGBA() --NodeRGBA class will be Deprecated,end --CCAnimationCache class will be Deprecated,begin function DeprecatedClass.CCAnimationCache() deprecatedTip("CCAnimationCache","cc.AnimationCache") return cc.AnimationCache end _G["CCAnimationCache"] = DeprecatedClass.CCAnimationCache() --CCAnimationCache class will be Deprecated,end --CCFlipY3D class will be Deprecated,begin function DeprecatedClass.CCFlipY3D() deprecatedTip("CCFlipY3D","cc.FlipY3D") return cc.FlipY3D end _G["CCFlipY3D"] = DeprecatedClass.CCFlipY3D() --CCFlipY3D class will be Deprecated,end --CCEaseSineInOut class will be Deprecated,begin function DeprecatedClass.CCEaseSineInOut() deprecatedTip("CCEaseSineInOut","cc.EaseSineInOut") return cc.EaseSineInOut end _G["CCEaseSineInOut"] = DeprecatedClass.CCEaseSineInOut() --CCEaseSineInOut class will be Deprecated,end --CCTransitionFlipAngular class will be Deprecated,begin function DeprecatedClass.CCTransitionFlipAngular() deprecatedTip("CCTransitionFlipAngular","cc.TransitionFlipAngular") return cc.TransitionFlipAngular end _G["CCTransitionFlipAngular"] = DeprecatedClass.CCTransitionFlipAngular() --CCTransitionFlipAngular class will be Deprecated,end --CCControl class will be Deprecated,begin function DeprecatedClass.CCControl() deprecatedTip("CCControl","cc.Control") return cc.Control end _G["CCControl"] = DeprecatedClass.CCControl() --CCControl class will be Deprecated,end --CCEaseElasticInOut class will be Deprecated,begin function DeprecatedClass.CCEaseElasticInOut() deprecatedTip("CCEaseElasticInOut","cc.EaseElasticInOut") return cc.EaseElasticInOut end _G["CCEaseElasticInOut"] = DeprecatedClass.CCEaseElasticInOut() --CCEaseElasticInOut class will be Deprecated,end --CCEaseBounce class will be Deprecated,begin function DeprecatedClass.CCEaseBounce() deprecatedTip("CCEaseBounce","cc.EaseBounce") return cc.EaseBounce end _G["CCEaseBounce"] = DeprecatedClass.CCEaseBounce() --CCEaseBounce class will be Deprecated,end --CCShow class will be Deprecated,begin function DeprecatedClass.CCShow() deprecatedTip("CCShow","cc.Show") return cc.Show end _G["CCShow"] = DeprecatedClass.CCShow() --CCShow class will be Deprecated,end --CCEditBox class will be Deprecated,begin function DeprecatedClass.CCEditBox() deprecatedTip("CCEditBox","cc.EditBox") return cc.EditBox end _G["CCEditBox"] = DeprecatedClass.CCEditBox() --CCEditBox class will be Deprecated,end --CCFadeOut class will be Deprecated,begin function DeprecatedClass.CCFadeOut() deprecatedTip("CCFadeOut","cc.FadeOut") return cc.FadeOut end _G["CCFadeOut"] = DeprecatedClass.CCFadeOut() --CCFadeOut class will be Deprecated,end --CCCallFunc class will be Deprecated,begin function DeprecatedClass.CCCallFunc() deprecatedTip("CCCallFunc","cc.CallFunc") return cc.CallFunc end _G["CCCallFunc"] = DeprecatedClass.CCCallFunc() --CCCallFunc class will be Deprecated,end --CCWaves3D class will be Deprecated,begin function DeprecatedClass.CCWaves3D() deprecatedTip("CCWaves3D","cc.Waves3D") return cc.Waves3D end _G["CCWaves3D"] = DeprecatedClass.CCWaves3D() --CCWaves3D class will be Deprecated,end --CCFlipX3D class will be Deprecated,begin function DeprecatedClass.CCFlipX3D() deprecatedTip("CCFlipX3D","cc.FlipX3D") return cc.FlipX3D end _G["CCFlipX3D"] = DeprecatedClass.CCFlipX3D() --CCFlipX3D class will be Deprecated,end --CCParticleFireworks class will be Deprecated,begin function DeprecatedClass.CCParticleFireworks() deprecatedTip("CCParticleFireworks","cc.ParticleFireworks") return cc.ParticleFireworks end _G["CCParticleFireworks"] = DeprecatedClass.CCParticleFireworks() --CCParticleFireworks class will be Deprecated,end --CCMenuItemImage class will be Deprecated,begin function DeprecatedClass.CCMenuItemImage() deprecatedTip("CCMenuItemImage","cc.MenuItemImage") return cc.MenuItemImage end _G["CCMenuItemImage"] = DeprecatedClass.CCMenuItemImage() --CCMenuItemImage class will be Deprecated,end --CCParticleFire class will be Deprecated,begin function DeprecatedClass.CCParticleFire() deprecatedTip("CCParticleFire","cc.ParticleFire") return cc.ParticleFire end _G["CCParticleFire"] = DeprecatedClass.CCParticleFire() --CCParticleFire class will be Deprecated,end --CCMenuItem class will be Deprecated,begin function DeprecatedClass.CCMenuItem() deprecatedTip("CCMenuItem","cc.MenuItem") return cc.MenuItem end _G["CCMenuItem"] = DeprecatedClass.CCMenuItem() --CCMenuItem class will be Deprecated,end --CCActionEase class will be Deprecated,begin function DeprecatedClass.CCActionEase() deprecatedTip("CCActionEase","cc.ActionEase") return cc.ActionEase end _G["CCActionEase"] = DeprecatedClass.CCActionEase() --CCActionEase class will be Deprecated,end --CCTransitionSceneOriented class will be Deprecated,begin function DeprecatedClass.CCTransitionSceneOriented() deprecatedTip("CCTransitionSceneOriented","cc.TransitionSceneOriented") return cc.TransitionSceneOriented end _G["CCTransitionSceneOriented"] = DeprecatedClass.CCTransitionSceneOriented() --CCTransitionSceneOriented class will be Deprecated,end --CCTransitionZoomFlipAngular class will be Deprecated,begin function DeprecatedClass.CCTransitionZoomFlipAngular() deprecatedTip("CCTransitionZoomFlipAngular","cc.TransitionZoomFlipAngular") return cc.TransitionZoomFlipAngular end _G["CCTransitionZoomFlipAngular"] = DeprecatedClass.CCTransitionZoomFlipAngular() --CCTransitionZoomFlipAngular class will be Deprecated,end --CCEaseIn class will be Deprecated,begin function DeprecatedClass.CCEaseIn() deprecatedTip("CCEaseIn","cc.EaseIn") return cc.EaseIn end _G["CCEaseIn"] = DeprecatedClass.CCEaseIn() --CCEaseIn class will be Deprecated,end --CCEaseExponentialInOut class will be Deprecated,begin function DeprecatedClass.CCEaseExponentialInOut() deprecatedTip("CCEaseExponentialInOut","cc.EaseExponentialInOut") return cc.EaseExponentialInOut end _G["CCEaseExponentialInOut"] = DeprecatedClass.CCEaseExponentialInOut() --CCEaseExponentialInOut class will be Deprecated,end --CCTransitionFlipX class will be Deprecated,begin function DeprecatedClass.CCTransitionFlipX() deprecatedTip("CCTransitionFlipX","cc.TransitionFlipX") return cc.TransitionFlipX end _G["CCTransitionFlipX"] = DeprecatedClass.CCTransitionFlipX() --CCTransitionFlipX class will be Deprecated,end --CCEaseExponentialOut class will be Deprecated,begin function DeprecatedClass.CCEaseExponentialOut() deprecatedTip("CCEaseExponentialOut","cc.EaseExponentialOut") return cc.EaseExponentialOut end _G["CCEaseExponentialOut"] = DeprecatedClass.CCEaseExponentialOut() --CCEaseExponentialOut class will be Deprecated,end --CCLabel class will be Deprecated,begin function DeprecatedClass.CCLabel() deprecatedTip("CCLabel","cc.Label") return cc.Label end _G["CCLabel"] = DeprecatedClass.CCLabel() --CCLabel class will be Deprecated,end --CCApplication class will be Deprecated,begin function DeprecatedClass.CCApplication() deprecatedTip("CCApplication","cc.Application") return cc.Application end _G["CCApplication"] = DeprecatedClass.CCApplication() --CCApplication class will be Deprecated,end --CCControlSlider class will be Deprecated,begin function DeprecatedClass.CCControlSlider() deprecatedTip("CCControlSlider","cc.ControlSlider") return cc.ControlSlider end _G["CCControlSlider"] = DeprecatedClass.CCControlSlider() --CCControlSlider class will be Deprecated,end --CCDelayTime class will be Deprecated,begin function DeprecatedClass.CCDelayTime() deprecatedTip("CCDelayTime","cc.DelayTime") return cc.DelayTime end _G["CCDelayTime"] = DeprecatedClass.CCDelayTime() --CCDelayTime class will be Deprecated,end --CCLabelAtlas class will be Deprecated,begin function DeprecatedClass.CCLabelAtlas() deprecatedTip("CCLabelAtlas","cc.LabelAtlas") return cc.LabelAtlas end _G["CCLabelAtlas"] = DeprecatedClass.CCLabelAtlas() --CCLabelAtlas class will be Deprecated,end --CCLabelBMFont class will be Deprecated,begin function DeprecatedClass.CCLabelBMFont() deprecatedTip("CCLabelBMFont","cc.LabelBMFont") return cc.LabelBMFont end _G["CCLabelBMFont"] = DeprecatedClass.CCLabelBMFont() --CCLabelBMFont class will be Deprecated,end --CCScale9Sprite class will be Deprecated,begin function DeprecatedClass.CCScale9Sprite() deprecatedTip("CCScale9Sprite","cc.Scale9Sprite") return cc.Scale9Sprite end _G["CCScale9Sprite"] = DeprecatedClass.CCScale9Sprite() --CCScale9Sprite class will be Deprecated,end --CCFadeOutTRTiles class will be Deprecated,begin function DeprecatedClass.CCFadeOutTRTiles() deprecatedTip("CCFadeOutTRTiles","cc.FadeOutTRTiles") return cc.FadeOutTRTiles end _G["CCFadeOutTRTiles"] = DeprecatedClass.CCFadeOutTRTiles() --CCFadeOutTRTiles class will be Deprecated,end --CCEaseElasticIn class will be Deprecated,begin function DeprecatedClass.CCEaseElasticIn() deprecatedTip("CCEaseElasticIn","cc.EaseElasticIn") return cc.EaseElasticIn end _G["CCEaseElasticIn"] = DeprecatedClass.CCEaseElasticIn() --CCEaseElasticIn class will be Deprecated,end --CCParticleSpiral class will be Deprecated,begin function DeprecatedClass.CCParticleSpiral() deprecatedTip("CCParticleSpiral","cc.ParticleSpiral") return cc.ParticleSpiral end _G["CCParticleSpiral"] = DeprecatedClass.CCParticleSpiral() --CCParticleSpiral class will be Deprecated,end --CCBReader class will be Deprecated,begin function DeprecatedClass.CCBReader() deprecatedTip("CCBReader","cc.BReader") return cc.BReader end _G["CCBReader"] = DeprecatedClass.CCBReader() --CCBReader class will be Deprecated,end --CCFiniteTimeAction class will be Deprecated,begin function DeprecatedClass.CCFiniteTimeAction() deprecatedTip("CCFiniteTimeAction","cc.FiniteTimeAction") return cc.FiniteTimeAction end _G["CCFiniteTimeAction"] = DeprecatedClass.CCFiniteTimeAction() --CCFiniteTimeAction class will be Deprecated,end --CCFadeOutDownTiles class will be Deprecated,begin function DeprecatedClass.CCFadeOutDownTiles() deprecatedTip("CCFadeOutDownTiles","cc.FadeOutDownTiles") return cc.FadeOutDownTiles end _G["CCFadeOutDownTiles"] = DeprecatedClass.CCFadeOutDownTiles() --CCFadeOutDownTiles class will be Deprecated,end --CCJumpTiles3D class will be Deprecated,begin function DeprecatedClass.CCJumpTiles3D() deprecatedTip("CCJumpTiles3D","cc.JumpTiles3D") return cc.JumpTiles3D end _G["CCJumpTiles3D"] = DeprecatedClass.CCJumpTiles3D() --CCJumpTiles3D class will be Deprecated,end --CCEaseBackIn class will be Deprecated,begin function DeprecatedClass.CCEaseBackIn() deprecatedTip("CCEaseBackIn","cc.EaseBackIn") return cc.EaseBackIn end _G["CCEaseBackIn"] = DeprecatedClass.CCEaseBackIn() --CCEaseBackIn class will be Deprecated,end --CCSpriteBatchNode class will be Deprecated,begin function DeprecatedClass.CCSpriteBatchNode() deprecatedTip("CCSpriteBatchNode","cc.SpriteBatchNode") return cc.SpriteBatchNode end _G["CCSpriteBatchNode"] = DeprecatedClass.CCSpriteBatchNode() --CCSpriteBatchNode class will be Deprecated,end --CCParticleSystem class will be Deprecated,begin function DeprecatedClass.CCParticleSystem() deprecatedTip("CCParticleSystem","cc.ParticleSystem") return cc.ParticleSystem end _G["CCParticleSystem"] = DeprecatedClass.CCParticleSystem() --CCParticleSystem class will be Deprecated,end --CCActionTween class will be Deprecated,begin function DeprecatedClass.CCActionTween() deprecatedTip("CCActionTween","cc.ActionTween") return cc.ActionTween end _G["CCActionTween"] = DeprecatedClass.CCActionTween() --CCActionTween class will be Deprecated,end --CCTransitionFadeDown class will be Deprecated,begin function DeprecatedClass.CCTransitionFadeDown() deprecatedTip("CCTransitionFadeDown","cc.TransitionFadeDown") return cc.TransitionFadeDown end _G["CCTransitionFadeDown"] = DeprecatedClass.CCTransitionFadeDown() --CCTransitionFadeDown class will be Deprecated,end --CCParticleSun class will be Deprecated,begin function DeprecatedClass.CCParticleSun() deprecatedTip("CCParticleSun","cc.ParticleSun") return cc.ParticleSun end _G["CCParticleSun"] = DeprecatedClass.CCParticleSun() --CCParticleSun class will be Deprecated,end --CCTransitionProgressHorizontal class will be Deprecated,begin function DeprecatedClass.CCTransitionProgressHorizontal() deprecatedTip("CCTransitionProgressHorizontal","cc.TransitionProgressHorizontal") return cc.TransitionProgressHorizontal end _G["CCTransitionProgressHorizontal"] = DeprecatedClass.CCTransitionProgressHorizontal() --CCTransitionProgressHorizontal class will be Deprecated,end --CCRipple3D class will be Deprecated,begin function DeprecatedClass.CCRipple3D() deprecatedTip("CCRipple3D","cc.Ripple3D") return cc.Ripple3D end _G["CCRipple3D"] = DeprecatedClass.CCRipple3D() --CCRipple3D class will be Deprecated,end --CCTMXLayer class will be Deprecated,begin function DeprecatedClass.CCTMXLayer() deprecatedTip("CCTMXLayer","cc.TMXLayer") return cc.TMXLayer end _G["CCTMXLayer"] = DeprecatedClass.CCTMXLayer() --CCTMXLayer class will be Deprecated,end --CCFlipX class will be Deprecated,begin function DeprecatedClass.CCFlipX() deprecatedTip("CCFlipX","cc.FlipX") return cc.FlipX end _G["CCFlipX"] = DeprecatedClass.CCFlipX() --CCFlipX class will be Deprecated,end --CCFlipY class will be Deprecated,begin function DeprecatedClass.CCFlipY() deprecatedTip("CCFlipY","cc.FlipY") return cc.FlipY end _G["CCFlipY"] = DeprecatedClass.CCFlipY() --CCFlipY class will be Deprecated,end --CCTransitionSplitCols class will be Deprecated,begin function DeprecatedClass.CCTransitionSplitCols() deprecatedTip("CCTransitionSplitCols","cc.TransitionSplitCols") return cc.TransitionSplitCols end _G["CCTransitionSplitCols"] = DeprecatedClass.CCTransitionSplitCols() --CCTransitionSplitCols class will be Deprecated,end --CCTimer class will be Deprecated,begin function DeprecatedClass.CCTimer() deprecatedTip("CCTimer","cc.Timer") return cc.Timer end _G["CCTimer"] = DeprecatedClass.CCTimer() --CCTimer class will be Deprecated,end --CCFadeTo class will be Deprecated,begin function DeprecatedClass.CCFadeTo() deprecatedTip("CCFadeTo","cc.FadeTo") return cc.FadeTo end _G["CCFadeTo"] = DeprecatedClass.CCFadeTo() --CCFadeTo class will be Deprecated,end --CCBAnimationManager class will be Deprecated,begin function DeprecatedClass.CCBAnimationManager() deprecatedTip("CCBAnimationManager","cc.BAnimationManager") return cc.BAnimationManager end _G["CCBAnimationManager"] = DeprecatedClass.CCBAnimationManager() --CCBAnimationManager class will be Deprecated,end --CCRepeatForever class will be Deprecated,begin function DeprecatedClass.CCRepeatForever() deprecatedTip("CCRepeatForever","cc.RepeatForever") return cc.RepeatForever end _G["CCRepeatForever"] = DeprecatedClass.CCRepeatForever() --CCRepeatForever class will be Deprecated,end --CCPlace class will be Deprecated,begin function DeprecatedClass.CCPlace() deprecatedTip("CCPlace","cc.Place") return cc.Place end _G["CCPlace"] = DeprecatedClass.CCPlace() --CCPlace class will be Deprecated,end --CCScrollView class will be Deprecated,begin function DeprecatedClass.CCScrollView() deprecatedTip("CCScrollView","cc.ScrollView") return cc.ScrollView end _G["CCScrollView"] = DeprecatedClass.CCScrollView() --CCScrollView class will be Deprecated,end --CCGLProgram class will be Deprecated,begin function DeprecatedClass.CCGLProgram() deprecatedTip("CCGLProgram","cc.GLProgram") return cc.GLProgram end _G["CCGLProgram"] = DeprecatedClass.CCGLProgram() --CCGLProgram class will be Deprecated,end --CCEaseBounceOut class will be Deprecated,begin function DeprecatedClass.CCEaseBounceOut() deprecatedTip("CCEaseBounceOut","cc.EaseBounceOut") return cc.EaseBounceOut end _G["CCEaseBounceOut"] = DeprecatedClass.CCEaseBounceOut() --CCEaseBounceOut class will be Deprecated,end --CCCardinalSplineBy class will be Deprecated,begin function DeprecatedClass.CCCardinalSplineBy() deprecatedTip("CCCardinalSplineBy","cc.CardinalSplineBy") return cc.CardinalSplineBy end _G["CCCardinalSplineBy"] = DeprecatedClass.CCCardinalSplineBy() --CCCardinalSplineBy class will be Deprecated,end --CCSpriteFrameCache class will be Deprecated,begin function DeprecatedClass.CCSpriteFrameCache() deprecatedTip("CCSpriteFrameCache","cc.SpriteFrameCache") return cc.SpriteFrameCache end _G["CCSpriteFrameCache"] = DeprecatedClass.CCSpriteFrameCache() --CCSpriteFrameCache class will be Deprecated,end --CCTransitionShrinkGrow class will be Deprecated,begin function DeprecatedClass.CCTransitionShrinkGrow() deprecatedTip("CCTransitionShrinkGrow","cc.TransitionShrinkGrow") return cc.TransitionShrinkGrow end _G["CCTransitionShrinkGrow"] = DeprecatedClass.CCTransitionShrinkGrow() --CCTransitionShrinkGrow class will be Deprecated,end --CCSplitCols class will be Deprecated,begin function DeprecatedClass.CCSplitCols() deprecatedTip("CCSplitCols","cc.SplitCols") return cc.SplitCols end _G["CCSplitCols"] = DeprecatedClass.CCSplitCols() --CCSplitCols class will be Deprecated,end --CCClippingNode class will be Deprecated,begin function DeprecatedClass.CCClippingNode() deprecatedTip("CCClippingNode","cc.ClippingNode") return cc.ClippingNode end _G["CCClippingNode"] = DeprecatedClass.CCClippingNode() --CCClippingNode class will be Deprecated,end --CCEaseBounceInOut class will be Deprecated,begin function DeprecatedClass.CCEaseBounceInOut() deprecatedTip("CCEaseBounceInOut","cc.EaseBounceInOut") return cc.EaseBounceInOut end _G["CCEaseBounceInOut"] = DeprecatedClass.CCEaseBounceInOut() --CCEaseBounceInOut class will be Deprecated,end --CCLiquid class will be Deprecated,begin function DeprecatedClass.CCLiquid() deprecatedTip("CCLiquid","cc.Liquid") return cc.Liquid end _G["CCLiquid"] = DeprecatedClass.CCLiquid() --CCLiquid class will be Deprecated,end --CCParticleFlower class will be Deprecated,begin function DeprecatedClass.CCParticleFlower() deprecatedTip("CCParticleFlower","cc.ParticleFlower") return cc.ParticleFlower end _G["CCParticleFlower"] = DeprecatedClass.CCParticleFlower() --CCParticleFlower class will be Deprecated,end --CCTableView class will be Deprecated,begin function DeprecatedClass.CCTableView() deprecatedTip("CCTableView","cc.TableView") return cc.TableView end _G["CCTableView"] = DeprecatedClass.CCTableView() --CCTableView class will be Deprecated,end --CCParticleSmoke class will be Deprecated,begin function DeprecatedClass.CCParticleSmoke() deprecatedTip("CCParticleSmoke","cc.ParticleSmoke") return cc.ParticleSmoke end _G["CCParticleSmoke"] = DeprecatedClass.CCParticleSmoke() --CCParticleSmoke class will be Deprecated,end --CCImage class will be Deprecated,begin function DeprecatedClass.CCImage() deprecatedTip("CCImage","cc.Image") return cc.Image end _G["CCImage"] = DeprecatedClass.CCImage() --CCImage class will be Deprecated,end --CCTurnOffTiles class will be Deprecated,begin function DeprecatedClass.CCTurnOffTiles() deprecatedTip("CCTurnOffTiles","cc.TurnOffTiles") return cc.TurnOffTiles end _G["CCTurnOffTiles"] = DeprecatedClass.CCTurnOffTiles() --CCTurnOffTiles class will be Deprecated,end --CCBlink class will be Deprecated,begin function DeprecatedClass.CCBlink() deprecatedTip("CCBlink","cc.Blink") return cc.Blink end _G["CCBlink"] = DeprecatedClass.CCBlink() --CCBlink class will be Deprecated,end --CCShaderCache class will be Deprecated,begin function DeprecatedClass.CCShaderCache() deprecatedTip("CCShaderCache","cc.ShaderCache") return cc.ShaderCache end _G["CCShaderCache"] = DeprecatedClass.CCShaderCache() --CCShaderCache class will be Deprecated,end --CCJumpTo class will be Deprecated,begin function DeprecatedClass.CCJumpTo() deprecatedTip("CCJumpTo","cc.JumpTo") return cc.JumpTo end _G["CCJumpTo"] = DeprecatedClass.CCJumpTo() --CCJumpTo class will be Deprecated,end --CCAtlasNode class will be Deprecated,begin function DeprecatedClass.CCAtlasNode() deprecatedTip("CCAtlasNode","cc.AtlasNode") return cc.AtlasNode end _G["CCAtlasNode"] = DeprecatedClass.CCAtlasNode() --CCAtlasNode class will be Deprecated,end --CCTransitionJumpZoom class will be Deprecated,begin function DeprecatedClass.CCTransitionJumpZoom() deprecatedTip("CCTransitionJumpZoom","cc.TransitionJumpZoom") return cc.TransitionJumpZoom end _G["CCTransitionJumpZoom"] = DeprecatedClass.CCTransitionJumpZoom() --CCTransitionJumpZoom class will be Deprecated,end --CCTransitionProgressVertical class will be Deprecated,begin function DeprecatedClass.CCTransitionProgressVertical() deprecatedTip("CCTransitionProgressVertical","cc.TransitionProgressVertical") return cc.TransitionProgressVertical end _G["CCTransitionProgressVertical"] = DeprecatedClass.CCTransitionProgressVertical() --CCTransitionProgressVertical class will be Deprecated,end --CCAnimationFrame class will be Deprecated,begin function DeprecatedClass.CCAnimationFrame() deprecatedTip("CCAnimationFrame","cc.AnimationFrame") return cc.AnimationFrame end _G["CCAnimationFrame"] = DeprecatedClass.CCAnimationFrame() --CCAnimationFrame class will be Deprecated,end --CCTintTo class will be Deprecated,begin function DeprecatedClass.CCTintTo() deprecatedTip("CCTintTo","cc.TintTo") return cc.TintTo end _G["CCTintTo"] = DeprecatedClass.CCTintTo() --CCTintTo class will be Deprecated,end --CCTiledGrid3DAction class will be Deprecated,begin function DeprecatedClass.CCTiledGrid3DAction() deprecatedTip("CCTiledGrid3DAction","cc.TiledGrid3DAction") return cc.TiledGrid3DAction end _G["CCTiledGrid3DAction"] = DeprecatedClass.CCTiledGrid3DAction() --CCTiledGrid3DAction class will be Deprecated,end --CCTMXTilesetInfo class will be Deprecated,begin function DeprecatedClass.CCTMXTilesetInfo() deprecatedTip("CCTMXTilesetInfo","cc.TMXTilesetInfo") return cc.TMXTilesetInfo end _G["CCTMXTilesetInfo"] = DeprecatedClass.CCTMXTilesetInfo() --CCTMXTilesetInfo class will be Deprecated,end --CCTMXObjectGroup class will be Deprecated,begin function DeprecatedClass.CCTMXObjectGroup() deprecatedTip("CCTMXObjectGroup","cc.TMXObjectGroup") return cc.TMXObjectGroup end _G["CCTMXObjectGroup"] = DeprecatedClass.CCTMXObjectGroup() --CCTMXObjectGroup class will be Deprecated,end --CCParticleGalaxy class will be Deprecated,begin function DeprecatedClass.CCParticleGalaxy() deprecatedTip("CCParticleGalaxy","cc.ParticleGalaxy") return cc.ParticleGalaxy end _G["CCParticleGalaxy"] = DeprecatedClass.CCParticleGalaxy() --CCParticleGalaxy class will be Deprecated,end --CCTwirl class will be Deprecated,begin function DeprecatedClass.CCTwirl() deprecatedTip("CCTwirl","cc.Twirl") return cc.Twirl end _G["CCTwirl"] = DeprecatedClass.CCTwirl() --CCTwirl class will be Deprecated,end --CCMenuItemLabel class will be Deprecated,begin function DeprecatedClass.CCMenuItemLabel() deprecatedTip("CCMenuItemLabel","cc.MenuItemLabel") return cc.MenuItemLabel end _G["CCMenuItemLabel"] = DeprecatedClass.CCMenuItemLabel() --CCMenuItemLabel class will be Deprecated,end --CCLayerColor class will be Deprecated,begin function DeprecatedClass.CCLayerColor() deprecatedTip("CCLayerColor","cc.LayerColor") return cc.LayerColor end _G["CCLayerColor"] = DeprecatedClass.CCLayerColor() --CCLayerColor class will be Deprecated,end --CCFadeOutBLTiles class will be Deprecated,begin function DeprecatedClass.CCFadeOutBLTiles() deprecatedTip("CCFadeOutBLTiles","cc.FadeOutBLTiles") return cc.FadeOutBLTiles end _G["CCFadeOutBLTiles"] = DeprecatedClass.CCFadeOutBLTiles() --CCFadeOutBLTiles class will be Deprecated,end --CCTransitionProgress class will be Deprecated,begin function DeprecatedClass.CCTransitionProgress() deprecatedTip("CCTransitionProgress","cc.TransitionProgress") return cc.TransitionProgress end _G["CCTransitionProgress"] = DeprecatedClass.CCTransitionProgress() --CCTransitionProgress class will be Deprecated,end --CCEaseRateAction class will be Deprecated,begin function DeprecatedClass.CCEaseRateAction() deprecatedTip("CCEaseRateAction","cc.EaseRateAction") return cc.EaseRateAction end _G["CCEaseRateAction"] = DeprecatedClass.CCEaseRateAction() --CCEaseRateAction class will be Deprecated,end --CCLayerGradient class will be Deprecated,begin function DeprecatedClass.CCLayerGradient() deprecatedTip("CCLayerGradient","cc.LayerGradient") return cc.LayerGradient end _G["CCLayerGradient"] = DeprecatedClass.CCLayerGradient() --CCLayerGradient class will be Deprecated,end --CCMenuItemSprite class will be Deprecated,begin function DeprecatedClass.CCMenuItemSprite() deprecatedTip("CCMenuItemSprite","cc.MenuItemSprite") return cc.MenuItemSprite end _G["CCMenuItemSprite"] = DeprecatedClass.CCMenuItemSprite() --CCMenuItemSprite class will be Deprecated,end --CCNode class will be Deprecated,begin function DeprecatedClass.CCNode() deprecatedTip("CCNode","cc.Node") return cc.Node end _G["CCNode"] = DeprecatedClass.CCNode() --CCNode class will be Deprecated,end --CCToggleVisibility class will be Deprecated,begin function DeprecatedClass.CCToggleVisibility() deprecatedTip("CCToggleVisibility","cc.ToggleVisibility") return cc.ToggleVisibility end _G["CCToggleVisibility"] = DeprecatedClass.CCToggleVisibility() --CCToggleVisibility class will be Deprecated,end --CCRepeat class will be Deprecated,begin function DeprecatedClass.CCRepeat() deprecatedTip("CCRepeat","cc.Repeat") return cc.Repeat end _G["CCRepeat"] = DeprecatedClass.CCRepeat() --CCRepeat class will be Deprecated,end --CCRenderTexture class will be Deprecated,begin function DeprecatedClass.CCRenderTexture() deprecatedTip("CCRenderTexture","cc.RenderTexture") return cc.RenderTexture end _G["CCRenderTexture"] = DeprecatedClass.CCRenderTexture() --CCRenderTexture class will be Deprecated,end --CCTransitionFlipY class will be Deprecated,begin function DeprecatedClass.CCTransitionFlipY() deprecatedTip("CCTransitionFlipY","cc.TransitionFlipY") return cc.TransitionFlipY end _G["CCTransitionFlipY"] = DeprecatedClass.CCTransitionFlipY() --CCTransitionFlipY class will be Deprecated,end --CCLayerMultiplex class will be Deprecated,begin function DeprecatedClass.CCLayerMultiplex() deprecatedTip("CCLayerMultiplex","cc.LayerMultiplex") return cc.LayerMultiplex end _G["CCLayerMultiplex"] = DeprecatedClass.CCLayerMultiplex() --CCLayerMultiplex class will be Deprecated,end --CCTMXLayerInfo class will be Deprecated,begin function DeprecatedClass.CCTMXLayerInfo() deprecatedTip("CCTMXLayerInfo","cc.TMXLayerInfo") return cc.TMXLayerInfo end _G["CCTMXLayerInfo"] = DeprecatedClass.CCTMXLayerInfo() --CCTMXLayerInfo class will be Deprecated,end --CCEaseBackInOut class will be Deprecated,begin function DeprecatedClass.CCEaseBackInOut() deprecatedTip("CCEaseBackInOut","cc.EaseBackInOut") return cc.EaseBackInOut end _G["CCEaseBackInOut"] = DeprecatedClass.CCEaseBackInOut() --CCEaseBackInOut class will be Deprecated,end --CCActionInstant class will be Deprecated,begin function DeprecatedClass.CCActionInstant() deprecatedTip("CCActionInstant","cc.ActionInstant") return cc.ActionInstant end _G["CCActionInstant"] = DeprecatedClass.CCActionInstant() --CCActionInstant class will be Deprecated,end --CCTargetedAction class will be Deprecated,begin function DeprecatedClass.CCTargetedAction() deprecatedTip("CCTargetedAction","cc.TargetedAction") return cc.TargetedAction end _G["CCTargetedAction"] = DeprecatedClass.CCTargetedAction() --CCTargetedAction class will be Deprecated,end --CCDrawNode class will be Deprecated,begin function DeprecatedClass.CCDrawNode() deprecatedTip("CCDrawNode","cc.DrawNode") return cc.DrawNode end _G["CCDrawNode"] = DeprecatedClass.CCDrawNode() --CCDrawNode class will be Deprecated,end --CCTransitionTurnOffTiles class will be Deprecated,begin function DeprecatedClass.CCTransitionTurnOffTiles() deprecatedTip("CCTransitionTurnOffTiles","cc.TransitionTurnOffTiles") return cc.TransitionTurnOffTiles end _G["CCTransitionTurnOffTiles"] = DeprecatedClass.CCTransitionTurnOffTiles() --CCTransitionTurnOffTiles class will be Deprecated,end --CCRotateTo class will be Deprecated,begin function DeprecatedClass.CCRotateTo() deprecatedTip("CCRotateTo","cc.RotateTo") return cc.RotateTo end _G["CCRotateTo"] = DeprecatedClass.CCRotateTo() --CCRotateTo class will be Deprecated,end --CCTransitionSplitRows class will be Deprecated,begin function DeprecatedClass.CCTransitionSplitRows() deprecatedTip("CCTransitionSplitRows","cc.TransitionSplitRows") return cc.TransitionSplitRows end _G["CCTransitionSplitRows"] = DeprecatedClass.CCTransitionSplitRows() --CCTransitionSplitRows class will be Deprecated,end --CCTransitionProgressRadialCCW class will be Deprecated,begin function DeprecatedClass.CCTransitionProgressRadialCCW() deprecatedTip("CCTransitionProgressRadialCCW","cc.TransitionProgressRadialCCW") return cc.TransitionProgressRadialCCW end _G["CCTransitionProgressRadialCCW"] = DeprecatedClass.CCTransitionProgressRadialCCW() --CCTransitionProgressRadialCCW class will be Deprecated,end --CCScaleTo class will be Deprecated,begin function DeprecatedClass.CCScaleTo() deprecatedTip("CCScaleTo","cc.ScaleTo") return cc.ScaleTo end _G["CCScaleTo"] = DeprecatedClass.CCScaleTo() --CCScaleTo class will be Deprecated,end --CCTransitionPageTurn class will be Deprecated,begin function DeprecatedClass.CCTransitionPageTurn() deprecatedTip("CCTransitionPageTurn","cc.TransitionPageTurn") return cc.TransitionPageTurn end _G["CCTransitionPageTurn"] = DeprecatedClass.CCTransitionPageTurn() --CCTransitionPageTurn class will be Deprecated,end --CCParticleExplosion class will be Deprecated,begin function DeprecatedClass.CCParticleExplosion() deprecatedTip("CCParticleExplosion","cc.ParticleExplosion") return cc.ParticleExplosion end _G["CCParticleExplosion"] = DeprecatedClass.CCParticleExplosion() --CCParticleExplosion class will be Deprecated,end --CCMenu class will be Deprecated,begin function DeprecatedClass.CCMenu() deprecatedTip("CCMenu","cc.Menu") return cc.Menu end _G["CCMenu"] = DeprecatedClass.CCMenu() --CCMenu class will be Deprecated,end --CCTexture2D class will be Deprecated,begin function DeprecatedClass.CCTexture2D() deprecatedTip("CCTexture2D","cc.Texture2D") return cc.Texture2D end _G["CCTexture2D"] = DeprecatedClass.CCTexture2D() --CCTexture2D class will be Deprecated,end --CCActionManager class will be Deprecated,begin function DeprecatedClass.CCActionManager() deprecatedTip("CCActionManager","cc.ActionManager") return cc.ActionManager end _G["CCActionManager"] = DeprecatedClass.CCActionManager() --CCActionManager class will be Deprecated,end --CCParticleBatchNode class will be Deprecated,begin function DeprecatedClass.CCParticleBatchNode() deprecatedTip("CCParticleBatchNode","cc.ParticleBatchNode") return cc.ParticleBatchNode end _G["CCParticleBatchNode"] = DeprecatedClass.CCParticleBatchNode() --CCParticleBatchNode class will be Deprecated,end --CCTransitionZoomFlipX class will be Deprecated,begin function DeprecatedClass.CCTransitionZoomFlipX() deprecatedTip("CCTransitionZoomFlipX","cc.TransitionZoomFlipX") return cc.TransitionZoomFlipX end _G["CCTransitionZoomFlipX"] = DeprecatedClass.CCTransitionZoomFlipX() --CCTransitionZoomFlipX class will be Deprecated,end --CCControlPotentiometer class will be Deprecated,begin function DeprecatedClass.CCControlPotentiometer() deprecatedTip("CCControlPotentiometer","cc.ControlPotentiometer") return cc.ControlPotentiometer end _G["CCControlPotentiometer"] = DeprecatedClass.CCControlPotentiometer() --CCControlPotentiometer class will be Deprecated,end --CCScaleBy class will be Deprecated,begin function DeprecatedClass.CCScaleBy() deprecatedTip("CCScaleBy","cc.ScaleBy") return cc.ScaleBy end _G["CCScaleBy"] = DeprecatedClass.CCScaleBy() --CCScaleBy class will be Deprecated,end --CCTileMapAtlas class will be Deprecated,begin function DeprecatedClass.CCTileMapAtlas() deprecatedTip("CCTileMapAtlas","cc.TileMapAtlas") return cc.TileMapAtlas end _G["CCTileMapAtlas"] = DeprecatedClass.CCTileMapAtlas() --CCTileMapAtlas class will be Deprecated,end --CCAction class will be Deprecated,begin function DeprecatedClass.CCAction() deprecatedTip("CCAction","cc.Action") return cc.Action end _G["CCAction"] = DeprecatedClass.CCAction() --CCAction class will be Deprecated,end --CCLens3D class will be Deprecated,begin function DeprecatedClass.CCLens3D() deprecatedTip("CCLens3D","cc.Lens3D") return cc.Lens3D end _G["CCLens3D"] = DeprecatedClass.CCLens3D() --CCLens3D class will be Deprecated,end --CCAnimation class will be Deprecated,begin function DeprecatedClass.CCAnimation() deprecatedTip("CCAnimation","cc.Animation") return cc.Animation end _G["CCAnimation"] = DeprecatedClass.CCAnimation() --CCAnimation class will be Deprecated,end --CCTransitionSlideInT class will be Deprecated,begin function DeprecatedClass.CCTransitionSlideInT() deprecatedTip("CCTransitionSlideInT","cc.TransitionSlideInT") return cc.TransitionSlideInT end _G["CCTransitionSlideInT"] = DeprecatedClass.CCTransitionSlideInT() --CCTransitionSlideInT class will be Deprecated,end --CCSpawn class will be Deprecated,begin function DeprecatedClass.CCSpawn() deprecatedTip("CCSpawn","cc.Spawn") return cc.Spawn end _G["CCSpawn"] = DeprecatedClass.CCSpawn() --CCSpawn class will be Deprecated,end --CCSet class will be Deprecated,begin function DeprecatedClass.CCSet() deprecatedTip("CCSet","cc.Set") return cc.Set end _G["CCSet"] = DeprecatedClass.CCSet() --CCSet class will be Deprecated,end --CCShakyTiles3D class will be Deprecated,begin function DeprecatedClass.CCShakyTiles3D() deprecatedTip("CCShakyTiles3D","cc.ShakyTiles3D") return cc.ShakyTiles3D end _G["CCShakyTiles3D"] = DeprecatedClass.CCShakyTiles3D() --CCShakyTiles3D class will be Deprecated,end --CCPageTurn3D class will be Deprecated,begin function DeprecatedClass.CCPageTurn3D() deprecatedTip("CCPageTurn3D","cc.PageTurn3D") return cc.PageTurn3D end _G["CCPageTurn3D"] = DeprecatedClass.CCPageTurn3D() --CCPageTurn3D class will be Deprecated,end --CCGrid3D class will be Deprecated,begin function DeprecatedClass.CCGrid3D() deprecatedTip("CCGrid3D","cc.Grid3D") return cc.Grid3D end _G["CCGrid3D"] = DeprecatedClass.CCGrid3D() --CCGrid3D class will be Deprecated,end --CCTransitionProgressInOut class will be Deprecated,begin function DeprecatedClass.CCTransitionProgressInOut() deprecatedTip("CCTransitionProgressInOut","cc.TransitionProgressInOut") return cc.TransitionProgressInOut end _G["CCTransitionProgressInOut"] = DeprecatedClass.CCTransitionProgressInOut() --CCTransitionProgressInOut class will be Deprecated,end --CCTransitionFadeBL class will be Deprecated,begin function DeprecatedClass.CCTransitionFadeBL() deprecatedTip("CCTransitionFadeBL","cc.TransitionFadeBL") return cc.TransitionFadeBL end _G["CCTransitionFadeBL"] = DeprecatedClass.CCTransitionFadeBL() --CCTransitionFadeBL class will be Deprecated,end --CCCamera class will be Deprecated,begin function DeprecatedClass.CCCamera() deprecatedTip("CCCamera","cc.Camera") return cc.Camera end _G["CCCamera"] = DeprecatedClass.CCCamera() --CCCamera class will be Deprecated,end --CCLayerRGBA class will be Deprecated,begin function DeprecatedClass.CCLayerRGBA() deprecatedTip("CCLayerRGBA","cc.Layer") return cc.Layer end _G["CCLayerRGBA"] = DeprecatedClass.CCLayerRGBA() --CCLayerRGBA class will be Deprecated,end --LayerRGBA class will be Deprecated,begin function DeprecatedClass.LayerRGBA() deprecatedTip("cc.LayerRGBA","cc.Layer") return cc.Layer end _G["cc"]["LayerRGBA"] = DeprecatedClass.LayerRGBA() --LayerRGBA class will be Deprecated,end --CCBezierTo class will be Deprecated,begin function DeprecatedClass.CCBezierTo() deprecatedTip("CCBezierTo","cc.BezierTo") return cc.BezierTo end _G["CCBezierTo"] = DeprecatedClass.CCBezierTo() --CCBezierTo class will be Deprecated,end --CCControlButton class will be Deprecated,begin function DeprecatedClass.CCControlButton() deprecatedTip("CCControlButton","cc.ControlButton") return cc.ControlButton end _G["CCControlButton"] = DeprecatedClass.CCControlButton() --CCControlButton class will be Deprecated,end --CCFollow class will be Deprecated,begin function DeprecatedClass.CCFollow() deprecatedTip("CCFollow","cc.Follow") return cc.Follow end _G["CCFollow"] = DeprecatedClass.CCFollow() --CCFollow class will be Deprecated,end --CCTintBy class will be Deprecated,begin function DeprecatedClass.CCTintBy() deprecatedTip("CCTintBy","cc.TintBy") return cc.TintBy end _G["CCTintBy"] = DeprecatedClass.CCTintBy() --CCTintBy class will be Deprecated,end --CCActionInterval class will be Deprecated,begin function DeprecatedClass.CCActionInterval() deprecatedTip("CCActionInterval","cc.ActionInterval") return cc.ActionInterval end _G["CCActionInterval"] = DeprecatedClass.CCActionInterval() --CCActionInterval class will be Deprecated,end --CCAnimate class will be Deprecated,begin function DeprecatedClass.CCAnimate() deprecatedTip("CCAnimate","cc.Animate") return cc.Animate end _G["CCAnimate"] = DeprecatedClass.CCAnimate() --CCAnimate class will be Deprecated,end --CCProgressTimer class will be Deprecated,begin function DeprecatedClass.CCProgressTimer() deprecatedTip("CCProgressTimer","cc.ProgressTimer") return cc.ProgressTimer end _G["CCProgressTimer"] = DeprecatedClass.CCProgressTimer() --CCProgressTimer class will be Deprecated,end --CCParticleMeteor class will be Deprecated,begin function DeprecatedClass.CCParticleMeteor() deprecatedTip("CCParticleMeteor","cc.ParticleMeteor") return cc.ParticleMeteor end _G["CCParticleMeteor"] = DeprecatedClass.CCParticleMeteor() --CCParticleMeteor class will be Deprecated,end --CCTransitionFadeTR class will be Deprecated,begin function DeprecatedClass.CCTransitionFadeTR() deprecatedTip("CCTransitionFadeTR","cc.TransitionFadeTR") return cc.TransitionFadeTR end _G["CCTransitionFadeTR"] = DeprecatedClass.CCTransitionFadeTR() --CCTransitionFadeTR class will be Deprecated,end --CCCatmullRomTo class will be Deprecated,begin function DeprecatedClass.CCCatmullRomTo() deprecatedTip("CCCatmullRomTo","cc.CatmullRomTo") return cc.CatmullRomTo end _G["CCCatmullRomTo"] = DeprecatedClass.CCCatmullRomTo() --CCCatmullRomTo class will be Deprecated,end --CCTransitionZoomFlipY class will be Deprecated,begin function DeprecatedClass.CCTransitionZoomFlipY() deprecatedTip("CCTransitionZoomFlipY","cc.TransitionZoomFlipY") return cc.TransitionZoomFlipY end _G["CCTransitionZoomFlipY"] = DeprecatedClass.CCTransitionZoomFlipY() --CCTransitionZoomFlipY class will be Deprecated,end --CCTransitionCrossFade class will be Deprecated,begin function DeprecatedClass.CCTransitionCrossFade() deprecatedTip("CCTransitionCrossFade","cc.TransitionCrossFade") return cc.TransitionCrossFade end _G["CCTransitionCrossFade"] = DeprecatedClass.CCTransitionCrossFade() --CCTransitionCrossFade class will be Deprecated,end --CCGridBase class will be Deprecated,begin function DeprecatedClass.CCGridBase() deprecatedTip("CCGridBase","cc.GridBase") return cc.GridBase end _G["CCGridBase"] = DeprecatedClass.CCGridBase() --CCGridBase class will be Deprecated,end --CCSkewTo class will be Deprecated,begin function DeprecatedClass.CCSkewTo() deprecatedTip("CCSkewTo","cc.SkewTo") return cc.SkewTo end _G["CCSkewTo"] = DeprecatedClass.CCSkewTo() --CCSkewTo class will be Deprecated,end --CCCardinalSplineTo class will be Deprecated,begin function DeprecatedClass.CCCardinalSplineTo() deprecatedTip("CCCardinalSplineTo","cc.CardinalSplineTo") return cc.CardinalSplineTo end _G["CCCardinalSplineTo"] = DeprecatedClass.CCCardinalSplineTo() --CCCardinalSplineTo class will be Deprecated,end --CCTMXMapInfo class will be Deprecated,begin function DeprecatedClass.CCTMXMapInfo() deprecatedTip("CCTMXMapInfo","cc.TMXMapInfo") return cc.TMXMapInfo end _G["CCTMXMapInfo"] = DeprecatedClass.CCTMXMapInfo() --CCTMXMapInfo class will be Deprecated,end --CCEaseExponentialIn class will be Deprecated,begin function DeprecatedClass.CCEaseExponentialIn() deprecatedTip("CCEaseExponentialIn","cc.EaseExponentialIn") return cc.EaseExponentialIn end _G["CCEaseExponentialIn"] = DeprecatedClass.CCEaseExponentialIn() --CCEaseExponentialIn class will be Deprecated,end --CCReuseGrid class will be Deprecated,begin function DeprecatedClass.CCReuseGrid() deprecatedTip("CCReuseGrid","cc.ReuseGrid") return cc.ReuseGrid end _G["CCReuseGrid"] = DeprecatedClass.CCReuseGrid() --CCReuseGrid class will be Deprecated,end --CCMenuItemAtlasFont class will be Deprecated,begin function DeprecatedClass.CCMenuItemAtlasFont() deprecatedTip("CCMenuItemAtlasFont","cc.MenuItemAtlasFont") return cc.MenuItemAtlasFont end _G["CCMenuItemAtlasFont"] = DeprecatedClass.CCMenuItemAtlasFont() --CCMenuItemAtlasFont class will be Deprecated,end --CCSpriteFrame class will be Deprecated,begin function DeprecatedClass.CCSpriteFrame() deprecatedTip("CCSpriteFrame","cc.SpriteFrame") return cc.SpriteFrame end _G["CCSpriteFrame"] = DeprecatedClass.CCSpriteFrame() --CCSpriteFrame class will be Deprecated,end --CCSplitRows class will be Deprecated,begin function DeprecatedClass.CCSplitRows() deprecatedTip("CCSplitRows","cc.SplitRows") return cc.SplitRows end _G["CCSplitRows"] = DeprecatedClass.CCSplitRows() --CCSplitRows class will be Deprecated,end --CCControlStepper class will be Deprecated,begin function DeprecatedClass.CCControlStepper() deprecatedTip("CCControlStepper","cc.ControlStepper") return cc.ControlStepper end _G["CCControlStepper"] = DeprecatedClass.CCControlStepper() --CCControlStepper class will be Deprecated,end --CCSprite class will be Deprecated,begin function DeprecatedClass.CCSprite() deprecatedTip("CCSprite","cc.Sprite") return cc.Sprite end _G["CCSprite"] = DeprecatedClass.CCSprite() --CCSprite class will be Deprecated,end --CCOrbitCamera class will be Deprecated,begin function DeprecatedClass.CCOrbitCamera() deprecatedTip("CCOrbitCamera","cc.OrbitCamera") return cc.OrbitCamera end _G["CCOrbitCamera"] = DeprecatedClass.CCOrbitCamera() --CCOrbitCamera class will be Deprecated,end --CCUserDefault class will be Deprecated,begin function DeprecatedClass.CCUserDefault() deprecatedTip("CCUserDefault","cc.UserDefault") return cc.UserDefault end _G["CCUserDefault"] = DeprecatedClass.CCUserDefault() --CCUserDefault class will be Deprecated,end --CCFadeOutUpTiles class will be Deprecated,begin function DeprecatedClass.CCFadeOutUpTiles() deprecatedTip("CCFadeOutUpTiles","cc.FadeOutUpTiles") return cc.FadeOutUpTiles end _G["CCFadeOutUpTiles"] = DeprecatedClass.CCFadeOutUpTiles() --CCFadeOutUpTiles class will be Deprecated,end --CCParticleRain class will be Deprecated,begin function DeprecatedClass.CCParticleRain() deprecatedTip("CCParticleRain","cc.ParticleRain") return cc.ParticleRain end _G["CCParticleRain"] = DeprecatedClass.CCParticleRain() --CCParticleRain class will be Deprecated,end --CCWaves class will be Deprecated,begin function DeprecatedClass.CCWaves() deprecatedTip("CCWaves","cc.Waves") return cc.Waves end _G["CCWaves"] = DeprecatedClass.CCWaves() --CCWaves class will be Deprecated,end --CCEaseOut class will be Deprecated,begin function DeprecatedClass.CCEaseOut() deprecatedTip("CCEaseOut","cc.EaseOut") return cc.EaseOut end _G["CCEaseOut"] = DeprecatedClass.CCEaseOut() --CCEaseOut class will be Deprecated,end --CCEaseBounceIn class will be Deprecated,begin function DeprecatedClass.CCEaseBounceIn() deprecatedTip("CCEaseBounceIn","cc.EaseBounceIn") return cc.EaseBounceIn end _G["CCEaseBounceIn"] = DeprecatedClass.CCEaseBounceIn() --CCEaseBounceIn class will be Deprecated,end --CCMenuItemFont class will be Deprecated,begin function DeprecatedClass.CCMenuItemFont() deprecatedTip("CCMenuItemFont","cc.MenuItemFont") return cc.MenuItemFont end _G["CCMenuItemFont"] = DeprecatedClass.CCMenuItemFont() --CCMenuItemFont class will be Deprecated,end --CCEaseSineOut class will be Deprecated,begin function DeprecatedClass.CCEaseSineOut() deprecatedTip("CCEaseSineOut","cc.EaseSineOut") return cc.EaseSineOut end _G["CCEaseSineOut"] = DeprecatedClass.CCEaseSineOut() --CCEaseSineOut class will be Deprecated,end --CCTextureCache class will be Deprecated,begin function DeprecatedClass.CCTextureCache() deprecatedTip("CCTextureCache","cc.TextureCache") return cc.TextureCache end _G["CCTextureCache"] = DeprecatedClass.CCTextureCache() --CCTextureCache class will be Deprecated,end --CCTiledGrid3D class will be Deprecated,begin function DeprecatedClass.CCTiledGrid3D() deprecatedTip("CCTiledGrid3D","cc.TiledGrid3D") return cc.TiledGrid3D end _G["CCTiledGrid3D"] = DeprecatedClass.CCTiledGrid3D() --CCTiledGrid3D class will be Deprecated,end --CCRemoveSelf class will be Deprecated,begin function DeprecatedClass.CCRemoveSelf() deprecatedTip("CCRemoveSelf","cc.RemoveSelf") return cc.RemoveSelf end _G["CCRemoveSelf"] = DeprecatedClass.CCRemoveSelf() --CCRemoveSelf class will be Deprecated,end --CCControlSaturationBrightnessPicker class will be Deprecated,begin function DeprecatedClass.CCControlSaturationBrightnessPicker() deprecatedTip("CCControlSaturationBrightnessPicker","cc.ControlSaturationBrightnessPicker") return cc.ControlSaturationBrightnessPicker end _G["CCControlSaturationBrightnessPicker"] = DeprecatedClass.CCControlSaturationBrightnessPicker() --CCControlSaturationBrightnessPicker class will be Deprecated,end --CCLabelTTF class will be Deprecated,begin function DeprecatedClass.CCLabelTTF() deprecatedTip("CCLabelTTF","cc.LabelTTF") return cc.LabelTTF end _G["CCLabelTTF"] = DeprecatedClass.CCLabelTTF() --CCLabelTTF class will be Deprecated,end --CCTouch class will be Deprecated,begin function DeprecatedClass.CCTouch() deprecatedTip("CCTouch","cc.Touch") return cc.Touch end _G["CCTouch"] = DeprecatedClass.CCTouch() --CCTouch class will be Deprecated,end --CCMoveBy class will be Deprecated,begin function DeprecatedClass.CCMoveBy() deprecatedTip("CCMoveBy","cc.MoveBy") return cc.MoveBy end _G["CCMoveBy"] = DeprecatedClass.CCMoveBy() --CCMoveBy class will be Deprecated,end --CCMotionStreak class will be Deprecated,begin function DeprecatedClass.CCMotionStreak() deprecatedTip("CCMotionStreak","cc.MotionStreak") return cc.MotionStreak end _G["CCMotionStreak"] = DeprecatedClass.CCMotionStreak() --CCMotionStreak class will be Deprecated,end --CCRotateBy class will be Deprecated,begin function DeprecatedClass.CCRotateBy() deprecatedTip("CCRotateBy","cc.RotateBy") return cc.RotateBy end _G["CCRotateBy"] = DeprecatedClass.CCRotateBy() --CCRotateBy class will be Deprecated,end --CCFileUtils class will be Deprecated,begin function DeprecatedClass.CCFileUtils() deprecatedTip("CCFileUtils","cc.FileUtils") return cc.FileUtils end _G["CCFileUtils"] = DeprecatedClass.CCFileUtils() --CCFileUtils class will be Deprecated,end --CCBezierBy class will be Deprecated,begin function DeprecatedClass.CCBezierBy() deprecatedTip("CCBezierBy","cc.BezierBy") return cc.BezierBy end _G["CCBezierBy"] = DeprecatedClass.CCBezierBy() --CCBezierBy class will be Deprecated,end --CCTransitionFade class will be Deprecated,begin function DeprecatedClass.CCTransitionFade() deprecatedTip("CCTransitionFade","cc.TransitionFade") return cc.TransitionFade end _G["CCTransitionFade"] = DeprecatedClass.CCTransitionFade() --CCTransitionFade class will be Deprecated,end --CCTransitionProgressOutIn class will be Deprecated,begin function DeprecatedClass.CCTransitionProgressOutIn() deprecatedTip("CCTransitionProgressOutIn","cc.TransitionProgressOutIn") return cc.TransitionProgressOutIn end _G["CCTransitionProgressOutIn"] = DeprecatedClass.CCTransitionProgressOutIn() --CCTransitionProgressOutIn class will be Deprecated,end --CCCatmullRomBy class will be Deprecated,begin function DeprecatedClass.CCCatmullRomBy() deprecatedTip("CCCatmullRomBy","cc.CatmullRomBy") return cc.CatmullRomBy end _G["CCCatmullRomBy"] = DeprecatedClass.CCCatmullRomBy() --CCCatmullRomBy class will be Deprecated,end --CCGridAction class will be Deprecated,begin function DeprecatedClass.CCGridAction() deprecatedTip("CCGridAction","cc.GridAction") return cc.GridAction end _G["CCGridAction"] = DeprecatedClass.CCGridAction() --CCGridAction class will be Deprecated,end --CCShaky3D class will be Deprecated,begin function DeprecatedClass.CCShaky3D() deprecatedTip("CCShaky3D","cc.Shaky3D") return cc.Shaky3D end _G["CCShaky3D"] = DeprecatedClass.CCShaky3D() --CCShaky3D class will be Deprecated,end --CCTransitionEaseScene class will be Deprecated,begin function DeprecatedClass.CCTransitionEaseScene() deprecatedTip("CCTransitionEaseScene","cc.TransitionEaseScene") return cc.TransitionEaseScene end _G["CCTransitionEaseScene"] = DeprecatedClass.CCTransitionEaseScene() --CCTransitionEaseScene class will be Deprecated,end --CCSequence class will be Deprecated,begin function DeprecatedClass.CCSequence() deprecatedTip("CCSequence","cc.Sequence") return cc.Sequence end _G["CCSequence"] = DeprecatedClass.CCSequence() --CCSequence class will be Deprecated,end --CCTransitionFadeUp class will be Deprecated,begin function DeprecatedClass.CCTransitionFadeUp() deprecatedTip("CCTransitionFadeUp","cc.TransitionFadeUp") return cc.TransitionFadeUp end _G["CCTransitionFadeUp"] = DeprecatedClass.CCTransitionFadeUp() --CCTransitionFadeUp class will be Deprecated,end --CCTransitionProgressRadialCW class will be Deprecated,begin function DeprecatedClass.CCTransitionProgressRadialCW() deprecatedTip("CCTransitionProgressRadialCW","cc.TransitionProgressRadialCW") return cc.TransitionProgressRadialCW end _G["CCTransitionProgressRadialCW"] = DeprecatedClass.CCTransitionProgressRadialCW() --CCTransitionProgressRadialCW class will be Deprecated,end --CCShuffleTiles class will be Deprecated,begin function DeprecatedClass.CCShuffleTiles() deprecatedTip("CCShuffleTiles","cc.ShuffleTiles") return cc.ShuffleTiles end _G["CCShuffleTiles"] = DeprecatedClass.CCShuffleTiles() --CCShuffleTiles class will be Deprecated,end --CCTransitionSlideInR class will be Deprecated,begin function DeprecatedClass.CCTransitionSlideInR() deprecatedTip("CCTransitionSlideInR","cc.TransitionSlideInR") return cc.TransitionSlideInR end _G["CCTransitionSlideInR"] = DeprecatedClass.CCTransitionSlideInR() --CCTransitionSlideInR class will be Deprecated,end --CCScene class will be Deprecated,begin function DeprecatedClass.CCScene() deprecatedTip("CCScene","cc.Scene") return cc.Scene end _G["CCScene"] = DeprecatedClass.CCScene() --CCScene class will be Deprecated,end --CCParallaxNode class will be Deprecated,begin function DeprecatedClass.CCParallaxNode() deprecatedTip("CCParallaxNode","cc.ParallaxNode") return cc.ParallaxNode end _G["CCParallaxNode"] = DeprecatedClass.CCParallaxNode() --CCParallaxNode class will be Deprecated,end --CCTransitionSlideInL class will be Deprecated,begin function DeprecatedClass.CCTransitionSlideInL() deprecatedTip("CCTransitionSlideInL","cc.TransitionSlideInL") return cc.TransitionSlideInL end _G["CCTransitionSlideInL"] = DeprecatedClass.CCTransitionSlideInL() --CCTransitionSlideInL class will be Deprecated,end --CCControlSwitch class will be Deprecated,begin function DeprecatedClass.CCControlSwitch() deprecatedTip("CCControlSwitch","cc.ControlSwitch") return cc.ControlSwitch end _G["CCControlSwitch"] = DeprecatedClass.CCControlSwitch() --CCControlSwitch class will be Deprecated,end --CCWavesTiles3D class will be Deprecated,begin function DeprecatedClass.CCWavesTiles3D() deprecatedTip("CCWavesTiles3D","cc.WavesTiles3D") return cc.WavesTiles3D end _G["CCWavesTiles3D"] = DeprecatedClass.CCWavesTiles3D() --CCWavesTiles3D class will be Deprecated,end --CCTransitionSlideInB class will be Deprecated,begin function DeprecatedClass.CCTransitionSlideInB() deprecatedTip("CCTransitionSlideInB","cc.TransitionSlideInB") return cc.TransitionSlideInB end _G["CCTransitionSlideInB"] = DeprecatedClass.CCTransitionSlideInB() --CCTransitionSlideInB class will be Deprecated,end --CCSpeed class will be Deprecated,begin function DeprecatedClass.CCSpeed() deprecatedTip("CCSpeed","cc.Speed") return cc.Speed end _G["CCSpeed"] = DeprecatedClass.CCSpeed() --CCSpeed class will be Deprecated,end --CCShatteredTiles3D class will be Deprecated,begin function DeprecatedClass.CCShatteredTiles3D() deprecatedTip("CCShatteredTiles3D","cc.ShatteredTiles3D") return cc.ShatteredTiles3D end _G["CCShatteredTiles3D"] = DeprecatedClass.CCShatteredTiles3D() --CCShatteredTiles3D class will be Deprecated,end --CCCallFuncN class will be Deprecated,begin function DeprecatedClass.CCCallFuncN() deprecatedTip("CCCallFuncN","cc.CallFunc") return cc.CallFunc end _G["CCCallFuncN"] = DeprecatedClass.CCCallFuncN() --CCCallFuncN class will be Deprecated,end --CCArmature class will be Deprecated,begin function DeprecatedClass.CCArmature() deprecatedTip("CCArmature","ccs.Armature") return ccs.Armature end _G["CCArmature"] = DeprecatedClass.CCArmature() --CCArmature class will be Deprecated,end --CCArmatureAnimation class will be Deprecated,begin function DeprecatedClass.CCArmatureAnimation() deprecatedTip("CCArmatureAnimation","ccs.ArmatureAnimation") return ccs.ArmatureAnimation end _G["CCArmatureAnimation"] = DeprecatedClass.CCArmatureAnimation() --CCArmatureAnimation class will be Deprecated,end --CCSkin class will be Deprecated,begin function DeprecatedClass.CCSkin() deprecatedTip("CCSkin","ccs.Skin") return ccs.Skin end _G["CCSkin"] = DeprecatedClass.CCSkin() --CCSkin class will be Deprecated,end --CCBone class will be Deprecated,begin function DeprecatedClass.CCBone() deprecatedTip("CCBone","ccs.Bone") return ccs.Bone end _G["CCBone"] = DeprecatedClass.CCBone() --CCBone class will be Deprecated,end --CCArmatureDataManager class will be Deprecated,begin function DeprecatedClass.CCArmatureDataManager() deprecatedTip("CCArmatureDataManager","ccs.ArmatureDataManager") return ccs.ArmatureDataManager end _G["CCArmatureDataManager"] = DeprecatedClass.CCArmatureDataManager() --CCArmatureDataManager class will be Deprecated,end --CCBatchNode class will be Deprecated,begin function DeprecatedClass.CCBatchNode() deprecatedTip("CCBatchNode","ccs.BatchNode") return ccs.BatchNode end _G["CCBatchNode"] = DeprecatedClass.CCBatchNode() --CCBatchNode class will be Deprecated,end --CCTween class will be Deprecated,begin function DeprecatedClass.CCTween() deprecatedTip("CCTween","ccs.Tween") return ccs.Tween end _G["CCTween"] = DeprecatedClass.CCTween() --CCTween class will be Deprecated,end --CCBaseData class will be Deprecated,begin function DeprecatedClass.CCBaseData() deprecatedTip("CCBaseData","ccs.BaseData") return ccs.BaseData end _G["CCBaseData"] = DeprecatedClass.CCBaseData() --CCBaseData class will be Deprecated,end --CCDisplayManager class will be Deprecated,begin function DeprecatedClass.CCDisplayManager() deprecatedTip("CCDisplayManager","ccs.DisplayManager") return ccs.DisplayManager end _G["CCDisplayManager"] = DeprecatedClass.CCDisplayManager() --CCDisplayManager class will be Deprecated,end --UIHelper class will be Deprecated,begin function DeprecatedClass.UIHelper() deprecatedTip("UIHelper","ccs.UIHelper") return ccs.UIHelper end _G["UIHelper"] = DeprecatedClass.UIHelper() --UIHelper class will be Deprecated,end --UILayout class will be Deprecated,begin function DeprecatedClass.UILayout() deprecatedTip("UILayout","ccs.UILayout") return ccs.UILayout end _G["UILayout"] = DeprecatedClass.UILayout() --UILayout class will be Deprecated,end --UIWidget class will be Deprecated,begin function DeprecatedClass.UIWidget() deprecatedTip("UIWidget","ccs.UIWidget") return ccs.UIWidget end _G["UIWidget"] = DeprecatedClass.UIWidget() --UIWidget class will be Deprecated,end --UILayer class will be Deprecated,begin function DeprecatedClass.UILayer() deprecatedTip("UILayer","ccs.UILayer") return ccs.UILayer end _G["UILayer"] = DeprecatedClass.UILayer() --UILayer class will be Deprecated,end --UIButton class will be Deprecated,begin function DeprecatedClass.UIButton() deprecatedTip("UIButton","ccs.UIButton") return ccs.UIButton end _G["UIButton"] = DeprecatedClass.UIButton() --UIButton class will be Deprecated,end --UICheckBox class will be Deprecated,begin function DeprecatedClass.UICheckBox() deprecatedTip("UICheckBox","ccs.UICheckBox") return ccs.UICheckBox end _G["UICheckBox"] = DeprecatedClass.UICheckBox() --UICheckBox class will be Deprecated,end --UIImageView class will be Deprecated,begin function DeprecatedClass.UIImageView() deprecatedTip("UIImageView","ccs.UIImageView") return ccs.UIImageView end _G["UIImageView"] = DeprecatedClass.UIImageView() --UIImageView class will be Deprecated,end --UILabel class will be Deprecated,begin function DeprecatedClass.UILabel() deprecatedTip("UILabel","ccs.UILabel") return ccs.UILabel end _G["UILabel"] = DeprecatedClass.UILabel() --UILabel class will be Deprecated,end --UILabelAtlas class will be Deprecated,begin function DeprecatedClass.UILabelAtlas() deprecatedTip("UILabelAtlas","ccs.UILabelAtlas") return ccs.UILabelAtlas end _G["UILabelAtlas"] = DeprecatedClass.UILabelAtlas() --UILabelAtlas class will be Deprecated,end --UILabelBMFont class will be Deprecated,begin function DeprecatedClass.UILabelBMFont() deprecatedTip("UILabelBMFont","ccs.UILabelBMFont") return ccs.UILabelBMFont end _G["UILabelBMFont"] = DeprecatedClass.UILabelBMFont() --UILabelBMFont class will be Deprecated,end --UILoadingBar class will be Deprecated,begin function DeprecatedClass.UILoadingBar() deprecatedTip("UILoadingBar","ccs.UILoadingBar") return ccs.UILoadingBar end _G["UILoadingBar"] = DeprecatedClass.UILoadingBar() --UILoadingBar class will be Deprecated,end --UISlider class will be Deprecated,begin function DeprecatedClass.UISlider() deprecatedTip("UISlider","ccs.UISlider") return ccs.UISlider end _G["UISlider"] = DeprecatedClass.UISlider() --UISlider class will be Deprecated,end --UITextField class will be Deprecated,begin function DeprecatedClass.UITextField() deprecatedTip("UITextField","ccs.UITextField") return ccs.UITextField end _G["UITextField"] = DeprecatedClass.UITextField() --UITextField class will be Deprecated,end --UIScrollView class will be Deprecated,begin function DeprecatedClass.UIScrollView() deprecatedTip("UIScrollView","ccs.UIScrollView") return ccs.UIScrollView end _G["UIScrollView"] = DeprecatedClass.UIScrollView() --UIScrollView class will be Deprecated,end --UIPageView class will be Deprecated,begin function DeprecatedClass.UIPageView() deprecatedTip("UIPageView","ccs.UIPageView") return ccs.UIPageView end _G["UIPageView"] = DeprecatedClass.UIPageView() --UIPageView class will be Deprecated,end --UIListView class will be Deprecated,begin function DeprecatedClass.UIListView() deprecatedTip("UIListView","ccs.UIListView") return ccs.UIListView end _G["UIListView"] = DeprecatedClass.UIListView() --UIListView class will be Deprecated,end --UILayoutParameter class will be Deprecated,begin function DeprecatedClass.UILayoutParameter() deprecatedTip("UILayoutParameter","ccs.UILayoutParameter") return ccs.UILayoutParameter end _G["UILayoutParameter"] = DeprecatedClass.UILayoutParameter() --UILayoutParameter class will be Deprecated,end --UILinearLayoutParameter class will be Deprecated,begin function DeprecatedClass.UILinearLayoutParameter() deprecatedTip("UILinearLayoutParameter","ccs.UILinearLayoutParameter") return ccs.UILinearLayoutParameter end _G["UILinearLayoutParameter"] = DeprecatedClass.UILinearLayoutParameter() --UILinearLayoutParameter class will be Deprecated,end --UIRelativeLayoutParameter class will be Deprecated,begin function DeprecatedClass.UIRelativeLayoutParameter() deprecatedTip("UIRelativeLayoutParameter","ccs.UIRelativeLayoutParameter") return ccs.UIRelativeLayoutParameter end _G["UIRelativeLayoutParameter"] = DeprecatedClass.UIRelativeLayoutParameter() --UIRelativeLayoutParameter class will be Deprecated,end --CCComController class will be Deprecated,begin function DeprecatedClass.CCComController() deprecatedTip("CCComController","ccs.ComController") return ccs.CCComController end _G["CCComController"] = DeprecatedClass.CCComController() --CCComController class will be Deprecated,end --CCComAudio class will be Deprecated,begin function DeprecatedClass.CCComAudio() deprecatedTip("CCComAudio","ccs.ComAudio") return ccs.ComAudio end _G["CCComAudio"] = DeprecatedClass.CCComAudio() --CCComAudio class will be Deprecated,end --CCComAttribute class will be Deprecated,begin function DeprecatedClass.CCComAttribute() deprecatedTip("CCComAttribute","ccs.ComAttribute") return ccs.ComAttribute end _G["CCComAttribute"] = DeprecatedClass.CCComAttribute() --CCComAttribute class will be Deprecated,end --CCComRender class will be Deprecated,begin function DeprecatedClass.CCComRender() deprecatedTip("CCComRender","ccs.ComRender") return ccs.ComRender end _G["CCComRender"] = DeprecatedClass.CCComRender() --CCComRender class will be Deprecated,end --ActionManager class will be Deprecated,begin function DeprecatedClass.ActionManager() deprecatedTip("ActionManager","ccs.ActionManagerEx") return ccs.ActionManagerEx end _G["ActionManager"] = DeprecatedClass.ActionManager() --CCComRender class will be Deprecated,end --SceneReader class will be Deprecated,begin function DeprecatedClass.SceneReader() deprecatedTip("SceneReader","ccs.SceneReader") return ccs.SceneReader end _G["SceneReader"] = DeprecatedClass.SceneReader() --SceneReader class will be Deprecated,end --GUIReader class will be Deprecated,begin function DeprecatedClass.GUIReader() deprecatedTip("GUIReader","ccs.GUIReader") return ccs.GUIReader end _G["GUIReader"] = DeprecatedClass.GUIReader() --GUIReader class will be Deprecated,end --UIRootWidget class will be Deprecated,begin function DeprecatedClass.UIRootWidget() deprecatedTip("UIRootWidget","ccs.UIRootWidget") return ccs.UIRootWidget end _G["UIRootWidget"] = DeprecatedClass.UIRootWidget() --UIRootWidget class will be Deprecated,end --ActionObject class will be Deprecated,begin function DeprecatedClass.ActionObject() deprecatedTip("ActionObject","ccs.ActionObject") return ccs.ActionObject end _G["ActionObject"] = DeprecatedClass.ActionObject() --ActionObject class will be Deprecated,end --CCEGLViewProtocol class will be Deprecated,begin function DeprecatedClass.CCEGLViewProtocol() deprecatedTip("CCEGLViewProtocol","cc.EGLViewProtocol") return cc.EGLViewProtocol end _G["CCEGLViewProtocol"] = DeprecatedClass.CCEGLViewProtocol() --CCEGLViewProtocol class will be Deprecated,end --CCEGLView class will be Deprecated,begin function DeprecatedClass.CCEGLView() deprecatedTip("CCEGLView","cc.EGLView") return cc.EGLView end _G["CCEGLView"] = DeprecatedClass.CCEGLView() --CCEGLView class will be Deprecated,end --CCBProxy class will be Deprecated,begin function DeprecatedClass.CCBProxy() deprecatedTip("CCBProxy","cc.CCBProxy") return cc.CCBProxy end _G["CCBProxy"] = DeprecatedClass.CCBProxy() --CCBProxy class will be Deprecated,end --WebSocket class will be Deprecated,begin function DeprecatedClass.WebSocket() deprecatedTip("WebSocket","cc.WebSocket") return cc.WebSocket end _G["WebSocket"] = DeprecatedClass.WebSocket() --WebSocket class will be Deprecated,end --XMLHttpRequest class will be Deprecated,begin function DeprecatedClass.XMLHttpRequest() deprecatedTip("XMLHttpRequest","cc.XMLHttpRequest") return cc.XMLHttpRequest end _G["XMLHttpRequest"] = DeprecatedClass.XMLHttpRequest() --XMLHttpRequest class will be Deprecated,end
mit
dacrybabysuck/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Yahsra.lua
11
2569
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Yahsra -- Type: Assault Mission Giver -- !pos 120.967 0.161 -44.002 50 ----------------------------------- require("scripts/globals/keyitems") local ID = require("scripts/zones/Aht_Urhgan_Whitegate/IDs") require("scripts/globals/besieged") require("scripts/globals/missions") require("scripts/globals/npc_util") ----------------------------------- function onTrade(player,npc,trade) end function onTrigger(player,npc) local rank = dsp.besieged.getMercenaryRank(player) local haveimperialIDtag local assaultPoints = player:getAssaultPoint(LEUJAOAM_ASSAULT_POINT) if player:hasKeyItem(dsp.ki.IMPERIAL_ARMY_ID_TAG) then haveimperialIDtag = 1 else haveimperialIDtag = 0 end --[[if (rank > 0) then player:startEvent(273,rank,haveimperialIDtag,assaultPoints,player:getCurrentAssault()) else]] player:startEvent(279) -- no rank --end end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) if csid == 273 then local selectiontype = bit.band(option, 0xF) if selectiontype == 1 then -- taken assault mission player:addAssault(bit.rshift(option,4)) player:delKeyItem(dsp.ki.IMPERIAL_ARMY_ID_TAG) player:addKeyItem(dsp.ki.LEUJAOAM_ASSAULT_ORDERS) player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.LEUJAOAM_ASSAULT_ORDERS) elseif selectiontype == 2 then -- purchased an item local item = bit.rshift(option,14) local itemID = 0 local price = 0 local items = { [1] = {itemid = 15970, price = 3000}, [2] = {itemid = 15775, price = 5000}, [3] = {itemid = 15521, price = 8000}, [4] = {itemid = 15884, price = 10000}, [5] = {itemid = 15490, price = 10000}, [6] = {itemid = 18408, price = 10000}, [7] = {itemid = 18485, price = 15000}, [8] = {itemid = 18365, price = 15000}, [9] = {itemid = 14933, price = 15000}, [10] = {itemid = 16069, price = 20000}, [11] = {itemid = 15606, price = 20000}, } local choice = items[item] if choice and npcUtil.giveItem(player, choice.itemid) then player:delAssaultPoint("LEUJAOAM_ASSAULT_POINT", choice.price) end end end end
gpl-3.0
lovelock/workspace
lua/functions.lua
1
2317
#!/usr/bin/env lua --[[ [function fib(n) [ if n < 2 then return 1 end [ return fib(n-2) + fib(n-1) [end [ [print(fib(6)) ]] --[[ [function newCounter() [ local i = 0 [ return function() [ i = i + 1 [ return i [ end [end [ [c1 = newCounter() [print(c1()) [print(c1()) ]] --[[ [function myPower(x) [ return function(y) return y^x end [end [ [power2 = myPower(2) [power3 = myPower(3) [ [print(power2(4)) [print(power3(5)) ]] -- name, age, bGay = 'haoel', 37, false, 'haoel@hotmail.com' --[[ [function getUserInfo(id) [ print(id) [ return "haoel", 37, "haoel@hotmail.com", "http://coolshell.cn" [end [ [name, age, email, website, bGay = getUserInfo() ]] --[[ [function foo(x) return x^2 end [foo = function(x) return x^2 end ]] -- table --[[ [haoel = { [ name = "ChenHao", [ age = 37, [ handsome = True [} [ [haoel.website = "http://coolshell.cn/" [local age = haoel.age [haoel.handsome = false [haoel.name = nil [ [t = { [ [200] = 100, [ ['name'] = "ChenHao", [ [3.14] = "PI" [} ]] --[[ [arr = {10, 20, 30, 40, 50} [print(arr[1]) ]] -- ==== -- arr = {[1]=10, [2]=20, [3]=30, [4]=40, [5]=50} --[[ [arr = { [ "string", [ 100, [ "haoel", [ function() print("coolshell.cn") end [} ]] -- call the function via arr[4]() --[[ [for i = 1, #arr do [ print(arr[i]) [end ]] -- variables are global by default unless it is declared with local -- to refer to a global variable, use _G -- _G.globalVar -- _G["globalVar"] --[[ [for k, v in pairs(t) do [ print(k, v) [end ]] -- MetaTable MetaMethod --[[ [fraction_a = {numerator=2, denominator=3} [fraction_b = {numerator=4, denominator=7} [ [fraction_op={} [function fraction_op.__add(f1, f2) [ ret = {} [ ret.numerator = f1.numerator * f2.denominator + f2.numerator * f1.denominator [ ret.denominator = f1.denominator * f2.denominator [ return ret [end [ [setmetatable(fraction_a, fraction_op) [setmetatable(fraction_b, fraction_op) [ [fraction_s = fraction_a + fraction_b [print(fraction_s) ]]
gpl-2.0
dacrybabysuck/darkstar
scripts/zones/Pashhow_Marshlands/IDs.lua
8
2651
----------------------------------- -- Area: Pashhow_Marshlands ----------------------------------- require("scripts/globals/zone") ----------------------------------- zones = zones or {} zones[dsp.zone.PASHHOW_MARSHLANDS] = { text = { NOTHING_HAPPENS = 141, -- Nothing happens... ITEM_CANNOT_BE_OBTAINED = 6404, -- You cannot obtain the <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6410, -- Obtained: <item>. GIL_OBTAINED = 6411, -- Obtained <number> gil. KEYITEM_OBTAINED = 6413, -- Obtained key item: <keyitem>. KEYITEM_LOST = 6414, -- Lost key item: <keyitem>. NOTHING_OUT_OF_ORDINARY = 6424, -- There is nothing out of the ordinary here. CONQUEST_BASE = 7071, -- Tallying conquest results... BEASTMEN_BANNER = 7152, -- There is a beastmen's banner. FISHING_MESSAGE_OFFSET = 7230, -- You can't fish here. DIG_THROW_AWAY = 7243, -- You dig up <item>, but your inventory is full. You regretfully throw the <item> away. FIND_NOTHING = 7245, -- You dig and you dig, but find nothing. PLAYER_OBTAINS_ITEM = 8457, -- <name> obtains <item>! UNABLE_TO_OBTAIN_ITEM = 8458, -- You were unable to obtain the item. PLAYER_OBTAINS_TEMP_ITEM = 8459, -- <name> obtains the temporary item: <item>! ALREADY_POSSESS_TEMP = 8460, -- You already possess that temporary item. NO_COMBINATION = 8465, -- You were unable to enter a combination. CONQUEST = 7919, -- You've earned conquest points! REGIME_REGISTERED = 10706, -- New training regime registered! COMMON_SENSE_SURVIVAL = 12817, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world. }, mob = { NI_ZHO_BLADEBENDER_PH = { [17223740] = 17223797, -- -429.953 24.5 -305.450 [17223789] = 17223797, -- 11.309 23.904 -337.923 }, JOLLY_GREEN_PH = { [17223888] = 17223889, -- 184.993 24.499 -41.790 }, BLOODPOOL_VORAX_PH = { [17224014] = 17224019, -- -351.884 24.014 513.531 }, BOWHO_WARMONGER = 17224104, }, npc = { CASKET_BASE = 17224275, OVERSEER_BASE = 17224326, }, } return zones[dsp.zone.PASHHOW_MARSHLANDS]
gpl-3.0
cmusatyalab/openface
training/attic/train.lua
8
10883
-- Copyright 2015-2016 Carnegie Mellon University -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- This code samples images and trains a triplet network with the -- following steps, which are referenced inline. -- -- [Step 1] -- Sample at most opt.peoplePerBatch * opt.imagesPerPerson -- images by choosing random people and images from the -- training set. -- -- [Step 2] -- Compute the embeddings of all of these images by doing forward -- passs with the current state of a network. -- This is done offline and the network is not modified. -- Since not all of the images will fit in GPU memory, this is -- split into minibatches. -- -- [Step 3] -- Select the semi-hard triplets as described in the FaceNet paper. -- -- [Step 4] -- Google is able to do a single forward and backward pass to process -- all the triplets and update the network's parameters at once since -- they use a distributed system. -- With a memory-limited GPU, OpenFace uses smaller mini-batches and -- does many forward and backward passes to iteratively update the -- network's parameters. -- -- -- -- Some other useful references for models with shared weights are: -- -- 1. Weinberger, K. Q., & Saul, L. K. (2009). -- Distance metric learning for large margin -- nearest neighbor classification. -- The Journal of Machine Learning Research, 10, 207-244. -- -- http://machinelearning.wustl.edu/mlpapers/paper_files/jmlr10_weinberger09a.pdf -- -- -- Citation from the FaceNet paper on their motivation for -- using the triplet loss. -- -- -- 2. Chopra, S., Hadsell, R., & LeCun, Y. (2005, June). -- Learning a similarity metric discriminatively, with application -- to face verification. -- In Computer Vision and Pattern Recognition, 2005. CVPR 2005. -- IEEE Computer Society Conference on (Vol. 1, pp. 539-546). IEEE. -- -- http://yann.lecun.com/exdb/publis/pdf/chopra-05.pdf -- -- -- The idea is to just look at pairs of images at a time -- rather than triplets, which they train with two networks -- in parallel with shared weights. -- -- 3. Hoffer, E., & Ailon, N. (2014). -- Deep metric learning using Triplet network. -- arXiv preprint arXiv:1412.6622. -- -- http://arxiv.org/abs/1412.6622 -- -- -- Not used in OpenFace or FaceNet, but another view of triplet -- networks that provides slightly more details about training using -- three networks with shared weights. -- The code uses Torch and is available on GitHub at -- https://github.com/eladhoffer/TripletNet require 'optim' require 'fbnn' require 'image' paths.dofile("OpenFaceOptim.lua") local optimMethod = optim.adadelta local optimState = {} -- Use for other algorithms like SGD local optimator = OpenFaceOptim(model, optimState) trainLogger = optim.Logger(paths.concat(opt.save, 'train.log')) local batchNumber local triplet_loss function train() print('==> doing epoch on training data:') print("==> online epoch # " .. epoch) batchNumber = 0 cutorch.synchronize() -- set the dropouts to training mode model:training() model:cuda() -- get it back on the right GPUs. local tm = torch.Timer() triplet_loss = 0 local i = 1 while batchNumber < opt.epochSize do -- queue jobs to data-workers donkeys:addjob( function() -- [Step 1]: Sample people/images from the dataset. local inputs, numPerClass = trainLoader:samplePeople(opt.peoplePerBatch, opt.imagesPerPerson) inputs = inputs:float() numPerClass = numPerClass:float() return sendTensor(inputs), sendTensor(numPerClass) end, trainBatch ) if i % 5 == 0 then donkeys:synchronize() end i = i + 1 end donkeys:synchronize() cutorch.synchronize() triplet_loss = triplet_loss / batchNumber trainLogger:add{ ['avg triplet loss (train set)'] = triplet_loss, } print(string.format('Epoch: [%d][TRAINING SUMMARY] Total Time(s): %.2f\t' .. 'average triplet loss (per batch): %.2f', epoch, tm:time().real, triplet_loss)) print('\n') collectgarbage() local function sanitize(net) net:apply(function (val) for name,field in pairs(val) do if torch.type(field) == 'cdata' then val[name] = nil end if name == 'homeGradBuffers' then val[name] = nil end if name == 'input_gpu' then val['input_gpu'] = {} end if name == 'gradOutput_gpu' then val['gradOutput_gpu'] = {} end if name == 'gradInput_gpu' then val['gradInput_gpu'] = {} end if (name == 'output' or name == 'gradInput') and torch.type(field) == 'torch.CudaTensor' then cutorch.withDevice(field:getDevice(), function() val[name] = field.new() end) end end end) end sanitize(model) torch.save(paths.concat(opt.save, 'model_' .. epoch .. '.t7'), model.modules[1]:float()) torch.save(paths.concat(opt.save, 'optimState_' .. epoch .. '.t7'), optimState) collectgarbage() end -- of train() local inputsCPU = torch.FloatTensor() local numPerClass = torch.FloatTensor() local timer = torch.Timer() function trainBatch(inputsThread, numPerClassThread) if batchNumber >= opt.epochSize then return end cutorch.synchronize() timer:reset() receiveTensor(inputsThread, inputsCPU) receiveTensor(numPerClassThread, numPerClass) -- [Step 2]: Compute embeddings. local numImages = inputsCPU:size(1) local embeddings = torch.Tensor(numImages, 128) local singleNet = model.modules[1] local beginIdx = 1 local inputs = torch.CudaTensor() while beginIdx <= numImages do local endIdx = math.min(beginIdx+opt.batchSize-1, numImages) local range = {{beginIdx,endIdx}} local sz = inputsCPU[range]:size() inputs:resize(sz):copy(inputsCPU[range]) local reps = singleNet:forward(inputs):float() embeddings[range] = reps beginIdx = endIdx + 1 end assert(beginIdx - 1 == numImages) -- [Step 3]: Select semi-hard triplets. local numTrips = numImages - opt.peoplePerBatch local as = torch.Tensor(numTrips, inputs:size(2), inputs:size(3), inputs:size(4)) local ps = torch.Tensor(numTrips, inputs:size(2), inputs:size(3), inputs:size(4)) local ns = torch.Tensor(numTrips, inputs:size(2), inputs:size(3), inputs:size(4)) function dist(emb1, emb2) local d = emb1 - emb2 return d:cmul(d):sum() end local tripIdx = 1 local shuffle = torch.randperm(numTrips) local embStartIdx = 1 local nRandomNegs = 0 for i = 1,opt.peoplePerBatch do local n = numPerClass[i] for j = 1,n-1 do local aIdx = embStartIdx local pIdx = embStartIdx+j as[shuffle[tripIdx]] = inputsCPU[aIdx] ps[shuffle[tripIdx]] = inputsCPU[pIdx] -- Select a semi-hard negative that has a distance -- further away from the positive exemplar. local posDist = dist(embeddings[aIdx], embeddings[pIdx]) local selNegIdx = embStartIdx while selNegIdx >= embStartIdx and selNegIdx <= embStartIdx+n-1 do selNegIdx = (torch.random() % numImages) + 1 end local selNegDist = dist(embeddings[aIdx], embeddings[selNegIdx]) local randomNeg = true for k = 1,numImages do if k < embStartIdx or k > embStartIdx+n-1 then local negDist = dist(embeddings[aIdx], embeddings[k]) if posDist < negDist and negDist < selNegDist and math.abs(posDist-negDist) < alpha then randomNeg = false selNegDist = negDist selNegIdx = k end end end if randomNeg then nRandomNegs = nRandomNegs + 1 end ns[shuffle[tripIdx]] = inputsCPU[selNegIdx] tripIdx = tripIdx + 1 end embStartIdx = embStartIdx + n end assert(embStartIdx - 1 == numImages) assert(tripIdx - 1 == numTrips) print((' + (nRandomNegs, nTrips) = (%d, %d)'):format(nRandomNegs, numTrips)) -- [Step 4]: Upate network parameters. beginIdx = 1 local asCuda = torch.CudaTensor() local psCuda = torch.CudaTensor() local nsCuda = torch.CudaTensor() -- Return early if the loss is 0 for `numZeros` iterations. local numZeros = 4 local zeroCounts = torch.IntTensor(numZeros):zero() local zeroIdx = 1 -- Return early if the loss shrinks too much. -- local firstLoss = nil -- TODO: Should be <=, but batches with just one image cause errors. while beginIdx < numTrips do local endIdx = math.min(beginIdx+opt.batchSize, numTrips) local range = {{beginIdx,endIdx}} local sz = as[range]:size() asCuda:resize(sz):copy(as[range]) psCuda:resize(sz):copy(ps[range]) nsCuda:resize(sz):copy(ns[range]) local err, _ = optimator:optimizeTriplet(optimMethod, {asCuda, psCuda, nsCuda}, criterion) cutorch.synchronize() batchNumber = batchNumber + 1 print(('Epoch: [%d][%d/%d]\tTime %.3f\ttripErr %.2e'):format( epoch, batchNumber, opt.epochSize, timer:time().real, err)) timer:reset() triplet_loss = triplet_loss + err -- Return early if the epoch is over. if batchNumber >= opt.epochSize then return end -- Return early if the loss is 0 for `numZeros` iterations. zeroCounts[zeroIdx] = (err == 0.0) and 1 or 0 -- Boolean to int. zeroIdx = (zeroIdx % numZeros) + 1 if zeroCounts:sum() == numZeros then return end -- Return early if the loss shrinks too much. -- if firstLoss == nil then -- firstLoss = err -- else -- -- Triplets trivially satisfied if err=0 -- if err ~= 0 and firstLoss/err > 4 then -- return -- end -- end beginIdx = endIdx + 1 end assert(beginIdx - 1 == numTrips or beginIdx == numTrips) end
apache-2.0
jnhwkim/rnn
examples/simple-bisequencer-network.lua
7
2590
require 'rnn' -- hyper-parameters batchSize = 8 rho = 5 -- sequence length hiddenSize = 7 nIndex = 10 lr = 0.1 -- forward rnn -- build simple recurrent neural network local fwd = nn.Recurrent( hiddenSize, nn.LookupTable(nIndex, hiddenSize), nn.Linear(hiddenSize, hiddenSize), nn.Sigmoid(), rho ) -- backward rnn (will be applied in reverse order of input sequence) local bwd = fwd:clone() bwd:reset() -- reinitializes parameters -- merges the output of one time-step of fwd and bwd rnns. -- You could also try nn.AddTable(), nn.Identity(), etc. local merge = nn.JoinTable(1, 1) -- we use BiSequencerLM because this is a language model (previous and next words to predict current word). -- If we used BiSequencer, x[t] would be used to predict y[t] = x[t] (which is cheating). -- Note that bwd and merge argument are optional and will default to the above. local brnn = nn.BiSequencerLM(fwd, bwd, merge) local rnn = nn.Sequential() :add(brnn) :add(nn.Sequencer(nn.Linear(hiddenSize*2, nIndex))) -- times two due to JoinTable :add(nn.Sequencer(nn.LogSoftMax())) print(rnn) -- build criterion criterion = nn.SequencerCriterion(nn.ClassNLLCriterion()) -- build dummy dataset (task is to predict next item, given previous) sequence_ = torch.LongTensor():range(1,10) -- 1,2,3,4,5,6,7,8,9,10 sequence = torch.LongTensor(100,10):copy(sequence_:view(1,10):expand(100,10)) sequence:resize(100*10) -- one long sequence of 1,2,3...,10,1,2,3...10... offsets = {} for i=1,batchSize do table.insert(offsets, math.ceil(math.random()*sequence:size(1))) end offsets = torch.LongTensor(offsets) -- training local iteration = 1 while true do -- 1. create a sequence of rho time-steps local inputs, targets = {}, {} for step=1,rho do -- a batch of inputs inputs[step] = sequence:index(1, offsets) -- incement indices offsets:add(1) for j=1,batchSize do if offsets[j] > sequence:size(1) then offsets[j] = 1 end end targets[step] = sequence:index(1, offsets) end -- 2. forward sequence through rnn rnn:zeroGradParameters() local outputs = rnn:forward(inputs) local err = criterion:forward(outputs, targets) print(string.format("Iteration %d ; NLL err = %f ", iteration, err)) -- 3. backward sequence through rnn (i.e. backprop through time) local gradOutputs = criterion:backward(outputs, targets) local gradInputs = rnn:backward(inputs, gradOutputs) -- 4. update rnn:updateParameters(lr) iteration = iteration + 1 end
bsd-3-clause
cmingjian/skynet
test/testsocket.lua
20
1085
local skynet = require "skynet" local socket = require "skynet.socket" local mode , id = ... local function echo(id) socket.start(id) while true do local str = socket.read(id) if str then socket.write(id, str) else socket.close(id) return end end end if mode == "agent" then id = tonumber(id) skynet.start(function() skynet.fork(function() echo(id) skynet.exit() end) end) else local function accept(id) socket.start(id) socket.write(id, "Hello Skynet\n") skynet.newservice(SERVICE_NAME, "agent", id) -- notice: Some data on this connection(id) may lost before new service start. -- So, be careful when you want to use start / abandon / start . socket.abandon(id) end skynet.start(function() local id = socket.listen("127.0.0.1", 8001) print("Listen socket :", "127.0.0.1", 8001) socket.start(id , function(id, addr) print("connect from " .. addr .. " " .. id) -- you have choices : -- 1. skynet.newservice("testsocket", "agent", id) -- 2. skynet.fork(echo, id) -- 3. accept(id) accept(id) end) end) end
mit
dacrybabysuck/darkstar
scripts/globals/mobskills/saucepan.lua
11
1123
--------------------------------------------- -- Saucepan -- Force feeds an unsavory dish. --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0 end function onMobWeaponSkill(target, mob, skill) local numhits = 1 local accmod = 1 local dmgmod = 0.8 local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.BLUNT,info.hitslanded) if (target:hasStatusEffect(dsp.effect.FOOD)) then target:delStatusEffectSilent(dsp.effect.FOOD) elseif (target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD)) then target:delStatusEffectSilent(dsp.effect.FIELD_SUPPORT_FOOD) end target:addStatusEffectEx(dsp.effect.FIELD_SUPPORT_FOOD,dsp.effect.FOOD, 255, 0, 1800) target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.BLUNT) return dmg end
gpl-3.0
cmingjian/skynet
lualib/http/internal.lua
95
2613
local table = table local type = type local M = {} local LIMIT = 8192 local function chunksize(readbytes, body) while true do local f,e = body:find("\r\n",1,true) if f then return tonumber(body:sub(1,f-1),16), body:sub(e+1) end if #body > 128 then -- pervent the attacker send very long stream without \r\n return end body = body .. readbytes() end end local function readcrln(readbytes, body) if #body >= 2 then if body:sub(1,2) ~= "\r\n" then return end return body:sub(3) else body = body .. readbytes(2-#body) if body ~= "\r\n" then return end return "" end end function M.recvheader(readbytes, lines, header) if #header >= 2 then if header:find "^\r\n" then return header:sub(3) end end local result local e = header:find("\r\n\r\n", 1, true) if e then result = header:sub(e+4) else while true do local bytes = readbytes() header = header .. bytes if #header > LIMIT then return end e = header:find("\r\n\r\n", -#bytes-3, true) if e then result = header:sub(e+4) break end if header:find "^\r\n" then return header:sub(3) end end end for v in header:gmatch("(.-)\r\n") do if v == "" then break end table.insert(lines, v) end return result end function M.parseheader(lines, from, header) local name, value for i=from,#lines do local line = lines[i] if line:byte(1) == 9 then -- tab, append last line if name == nil then return end header[name] = header[name] .. line:sub(2) else name, value = line:match "^(.-):%s*(.*)" if name == nil or value == nil then return end name = name:lower() if header[name] then local v = header[name] if type(v) == "table" then table.insert(v, value) else header[name] = { v , value } end else header[name] = value end end end return header end function M.recvchunkedbody(readbytes, bodylimit, header, body) local result = "" local size = 0 while true do local sz sz , body = chunksize(readbytes, body) if not sz then return end if sz == 0 then break end size = size + sz if bodylimit and size > bodylimit then return end if #body >= sz then result = result .. body:sub(1,sz) body = body:sub(sz+1) else result = result .. body .. readbytes(sz - #body) body = "" end body = readcrln(readbytes, body) if not body then return end end local tmpline = {} body = M.recvheader(readbytes, tmpline, body) if not body then return end header = M.parseheader(tmpline,1,header) return result, header end return M
mit
dacrybabysuck/darkstar
scripts/globals/items/crayfish.lua
11
1162
----------------------------------------- -- ID: 4472 -- Item: crayfish -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity -3 -- Vitality 1 -- defense +10% (unknown cap) ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if (target:getRace() ~= dsp.race.MITHRA) then result = dsp.msg.basic.CANNOT_EAT end if (target:getMod(dsp.mod.EAT_RAW_FISH) == 1) then result = 0 end if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,300,4472) end function onEffectGain(target,effect) target:addMod(dsp.mod.DEX, -3) target:addMod(dsp.mod.VIT, 1) target:addMod(dsp.mod.FOOD_DEFP, 10) end function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, -3) target:delMod(dsp.mod.VIT, 1) target:delMod(dsp.mod.FOOD_DEFP, 10) end
gpl-3.0
nimaghorbani/dozdi1
plugins/bugzilla.lua
611
3983
do local BASE_URL = "https://bugzilla.mozilla.org/rest/" local function bugzilla_login() local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password print("accessing " .. url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_check(id) -- data = bugzilla_login() local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey -- print(url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_listopened(email) local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey local res,code = https.request( url ) print(res) local data = json:decode(res) return data end local function run(msg, matches) local response = "" if matches[1] == "status" then local data = bugzilla_check(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator response = response .. "\n Last update: "..data.bugs[1].last_change_time response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] print(response) end elseif matches[1] == "list" then local data = bugzilla_listopened(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else -- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator -- response = response .. "\n Last update: "..data.bugs[1].last_change_time -- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution -- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard -- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] local total = table.map_length(data.bugs) print("total bugs: " .. total) local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2] if total > 0 then response = response .. ": " for tableKey, bug in pairs(data.bugs) do response = response .. "\n #" .. bug.id response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution response = response .. "\n Whiteboard: " .. bug.whiteboard response = response .. "\n Summary: " .. bug.summary end end end end return response end -- (table) -- [bugs] = (table) -- [1] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 927704 -- [whiteboard] = (string) [approved][full processed] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/ -- [2] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 1049337 -- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/ -- total bugs: 2 return { description = "Lookup bugzilla status update", usage = "/bot bugzilla [bug number]", patterns = { "^/bugzilla (status) (.*)$", "^/bugzilla (list) (.*)$" }, run = run } end
gpl-2.0
eagle14/kia12
plugins/bugzilla.lua
611
3983
do local BASE_URL = "https://bugzilla.mozilla.org/rest/" local function bugzilla_login() local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password print("accessing " .. url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_check(id) -- data = bugzilla_login() local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey -- print(url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_listopened(email) local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey local res,code = https.request( url ) print(res) local data = json:decode(res) return data end local function run(msg, matches) local response = "" if matches[1] == "status" then local data = bugzilla_check(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator response = response .. "\n Last update: "..data.bugs[1].last_change_time response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] print(response) end elseif matches[1] == "list" then local data = bugzilla_listopened(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else -- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator -- response = response .. "\n Last update: "..data.bugs[1].last_change_time -- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution -- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard -- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] local total = table.map_length(data.bugs) print("total bugs: " .. total) local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2] if total > 0 then response = response .. ": " for tableKey, bug in pairs(data.bugs) do response = response .. "\n #" .. bug.id response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution response = response .. "\n Whiteboard: " .. bug.whiteboard response = response .. "\n Summary: " .. bug.summary end end end end return response end -- (table) -- [bugs] = (table) -- [1] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 927704 -- [whiteboard] = (string) [approved][full processed] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/ -- [2] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 1049337 -- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/ -- total bugs: 2 return { description = "Lookup bugzilla status update", usage = "/bot bugzilla [bug number]", patterns = { "^/bugzilla (status) (.*)$", "^/bugzilla (list) (.*)$" }, run = run } end
gpl-2.0
worldforge/ember
src/components/ogre/widgets/ActionBarCreator.lua
1
6231
--[[ ActionBarCreator Responsible for creating and managing action bars. The use can create either horizontal or vertical action bars, as well as deleting existing bars by selecting them in the list and clicking delete. ]]-- ActionBarCreator = {} loadScript("DefaultEntityActions.lua") --Build the action bar creator widget. function ActionBarCreator:buildCEGUIWidget() self.widget = guiManager:createWidget() self.widget:loadMainSheet("ActionBarCreator.layout", "ActionBarCreator") self.widget:registerConsoleVisibilityToggleCommand("actionBarCreator") self.createHButton = CEGUI.toPushButton(self.widget:getWindow("Create_Horiz")) subscribe(self.connectors, self.createHButton, "Clicked", --Capture user clicks of the create horizontal action bar button. function() local type = "Horiz" self:createActionBar(type) return true end) self.createVButton = CEGUI.toPushButton(self.widget:getWindow("Create_Vert")) subscribe(self.connectors, self.createVButton, "Clicked", --Capture user clicks of the create vertical action bar button. function() local type = "Vert" self:createActionBar(type) return true end) self.deleteButton = CEGUI.toPushButton(self.widget:getWindow("Delete")) subscribe(self.connectors, self.deleteButton, "Clicked", --Capture user clicks of the delete button. function() self:deleteActionBar() return true end) self.wieldComboBox = CEGUI.toCombobox(self.widget:getWindow("WieldFunction")) subscribe(self.connectors, self.wieldComboBox, "ListSelectionChanged", function() local item = self.wieldComboBox:getSelectedItem() if item then local selectId = item:getID() if selectId == 0 then self.defaultActionList:setDefaultWearableFunction(self.defaultActionList.wield) elseif selectId == 1 then self.defaultActionList:setDefaultWearableFunction(self.defaultActionList.eat) end end return true end) self:populateCombobox(self.wieldComboBox) self.wieldComboBox:setItemSelectState(0, true) self.wieldComboBox:setShowVertScrollbar(true) self.edibleComboBox = CEGUI.toCombobox(self.widget:getWindow("EdibleFunction")) subscribe(self.connectors, self.edibleComboBox, "ListSelectionChanged", function() local item = self.edibleComboBox:getSelectedItem() if item then local selectId = item:getID() if selectId == 0 then self.defaultActionList:setDefaultBioMassFunction(self.defaultActionList.wield) elseif selectId == 1 then self.defaultActionList:setDefaultBioMassFunction(self.defaultActionList.eat) end end return true end) self:populateCombobox(self.edibleComboBox) self.edibleComboBox:setItemSelectState(1, true) self.edibleComboBox:setShowVertScrollbar(true) self.actionBarListbox = CEGUI.toListbox(self.widget:getWindow("ActionBarList")) --We only want the use to select one action bar at a time. self.actionBarListbox:setMultiselectEnabled(false) self.widget:hide() end --Create a new action bar. --@param layout Either "Horiz" or "Vert", represents the rotation of the action bar. function ActionBarCreator:createActionBar(layout) --Find the first available actionbar#. local i = 1 while self.actionbars["ActionBar" .. i] do i = i + 1 end --Name that will be used as the key and presented to the user. local name = "ActionBar" .. i --Create the new Actionbar. local a1 = ActionBar.new(layout, self.defaultActionList, self.erisAvatar) a1:init(name) --Insert into our dictionary. self.actionbars[name] = a1 --Add to the Listbox presented in the ActionBarCreator widget. local actionBar = Ember.OgreView.Gui.ColouredListItem.new(name) self.actionBarListbox:addItem(actionBar) self.actionbarCount = self.actionbarCount + 1 return a1 end --Delete the selected action bar in the list. function ActionBarCreator:deleteActionBar() --Get the selected Listbox item. local selectedItem = self.actionBarListbox:getFirstSelectedItem() --Check if the user has actually selected an action bar. if selectedItem then local name = selectedItem:getText() --Delete and remove from the dictionary. self.actionbars[name]:shutdown() self.actionbars[name] = nil --Remove from the Listbox. self.actionBarListbox:removeItem(selectedItem) else --No action bar has been selected, we update the help widget and present it to the user. local message = Ember.OgreView.Gui.HelpMessage.new("ActionBarCreator", "Select an ActionBar to remove from the list first.", "action bar creator", "actionBarCreatorMessage") Ember.OgreView.Gui.QuickHelp.getSingleton():updateText(message) end self.actionbarCount = self.actionbarCount - 1 end function ActionBarCreator:populateCombobox(combobox) local item = Ember.OgreView.Gui.ColouredListItem.new("Wield", 0) combobox:addItem(item) item = Ember.OgreView.Gui.ColouredListItem.new("Eat", 1) combobox:addItem(item) combobox:setItemSelectState(0, true) combobox:setSingleClickEnabled(true) end --Cleanup the widget. function ActionBarCreator:shutdown() --Delete all of the action bars for _, v in pairs(self.actionbars) do v:shutdown() end disconnectAll(self.connectors) guiManager:destroyWidget(self.widget) end --Creates a starting action bar for the user, and adds keyboard hooks. function ActionBarCreator:init() --Create an inital actionbar for the user. self:createActionBar("Horiz"):defaultKeyMapping() end --The widget should load when the player has logged in the game. ActionBarCreator.createdAvatarEntityConnector = emberOgre.EventCreatedAvatarEntity:connect(function() if emberOgre:getWorld():getAvatar():isAdmin() == false then ActionBarCreator.instance = { connectors = {}, actionbars = {}, defaultActionList = DefaultEntityActions.new(), actionbarCount = 0, erisAvatar = emberOgre:getWorld():getView():getAvatar() } setmetatable(ActionBarCreator.instance, { __index = ActionBarCreator }) ActionBarCreator.instance:buildCEGUIWidget() ActionBarCreator.instance:init() end end ) ActionBarCreator.destroyedConnector = emberServices:getServerService().DestroyedAvatar:connect(function() if ActionBarCreator.instance then ActionBarCreator.instance:shutdown() ActionBarCreator.instance = nil collectgarbage() end end )
gpl-3.0
deepmind/deepmind-research
tvt/dmlab/key_to_door_to_match.lua
1
1212
-- Copyright 2019 DeepMind Technologies Limited. All Rights Reserved. -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- http://www.apache.org/licenses/LICENSE-2.0 -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- ============================================================================ local factory = require 'visual_match_factory' return factory.createLevelApi{ exploreMapMode = 'KEY_TO_COLOR', episodeLengthSeconds = 45, secondOrderExploreLengthSeconds = 5, preExploreDistractorLengthSeconds = 15, exploreLengthSeconds = 5, distractorLengthSeconds = 15, differentDistractRoomTexture = true, differentRewardRoomTexture = true, differentSecondOrderRoomTexture = true, secondOrderExploreRoomSize = {4, 4}, correctReward = 10, incorrectReward = 1, }
apache-2.0
MrTheSoulz/NerdPack
Libs/DiesalTools-1.0/DiesalTools-1.0.lua
6
18632
-- $Id: DiesalTools-1.0.lua 61 2017-03-28 23:13:41Z diesal2010 $ local MAJOR, MINOR = "DiesalTools-1.0", "$Rev: 61 $" local DiesalTools, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not DiesalTools then return end -- No Upgrade needed. -- ~~| Libraries |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- ~~| Lua Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local type, select, pairs, tonumber, tostring = type, select, pairs, tonumber, tostring local table_concat = table.concat local setmetatable, getmetatable, next = setmetatable, getmetatable, next local sub, format, lower, upper,gsub = string.sub, string.format, string.lower, string.upper, string.gsub local floor, ceil, abs, modf = math.floor, math.ceil, math.abs, math.modf -- ~~| WoW Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local CreateFrame, UIParent, GetCursorPosition = CreateFrame, UIParent, GetCursorPosition local GetScreenWidth, GetScreenHeight = GetScreenWidth, GetScreenHeight -- ~~| Locals |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local escapeSequences = { [ "\a" ] = "\\a", -- Bell [ "\b" ] = "\\b", -- Backspace [ "\t" ] = "\\t", -- Horizontal tab [ "\n" ] = "\\n", -- Newline [ "\v" ] = "\\v", -- Vertical tab [ "\f" ] = "\\f", -- Form feed [ "\r" ] = "\\r", -- Carriage return [ "\\" ] = "\\\\", -- Backslash [ "\"" ] = "\\\"", -- Quotation mark [ "|" ] = "||", } local lua_keywords = { ["and"] = true, ["break"] = true, ["do"] = true, ["else"] = true, ["elseif"] = true, ["end"] = true, ["false"] = true, ["for"] = true, ["function"] = true, ["if"] = true, ["in"] = true, ["local"] = true, ["nil"] = true, ["not"] = true, ["or"] = true, ["repeat"] = true, ["return"] = true, ["then"] = true, ["true"] = true, ["until"] = true, ["while"] = true } local sub_table = { } local colors = { blue = '|cff'..'00aaff', darkblue = '|cff'..'004466', orange = '|cff'..'ffaa00', darkorange = '|cff'..'4c3300', grey = '|cff'..'7f7f7f', darkgrey = '|cff'..'414141', white = '|cff'..'ffffff', red = '|cff'..'ff0000', green = '|cff'..'00ff2b', yellow = '|cff'..'ffff00', lightyellow = '|cff'..'ffea7f', } local formattedArgs = {} local function GetCaller(level) -- ADDON:LogMessage(debugstack(10,2, 0)) for trace in debugstack(level,2, 0):gmatch("(.-)\n") do -- Blizzard Sandbox local match, _, file, line = trace:find("^.*\\(.-):(%d+)") if match then return format('%s[%s%s: %s%s%s]|r',colors.orange,colors.yellow,file,colors.lightyellow,line,colors.orange) end -- PQI DataFile local match, _, file,line = trace:find('^%[string "[%s%-]*(.-%.lua).-"%]:(%d+)') if match then return format('%s[%s%s: %s%s%s]|r',colors.orange,colors.yellow,file,colors.lightyellow,line,colors.orange) end -- PQR Ability code local match, _, file,line = trace:find('^%[string "(.-)"%]:(%d+)') if match then return format('%s[%s%s: %s%s%s]|r',colors.orange,colors.yellow,file,colors.lightyellow,line,colors.orange) end end return format('%s[%sUnknown Caller%s]|r',colors.orange,colors.red,colors.orange) end local function round(number, base) base = base or 1 return floor((number + base/2)/base) * base end local function getRGBColorValues(color,g,b) if type(color) == 'number' and type(g) == 'number' and type(b) == 'number' then if color <= 1 and g <= 1 and b <= 1 then return round(color*255), round(g*255), round(b*255) end return color[1], color[2], color[3] elseif type(color) == 'table' and type(color[1]) == 'number' and type(color[2]) == 'number' and type(color[3]) == 'number' then if color[1] <= 1 and color[2] <= 1 and color[3] <= 1 then return round(color[1]*255), round(color[2]*255), round(color[3]*255) end return color[1], color[2], color[3] elseif type(color) == 'string' then return tonumber(sub(color, 1, 2),16), tonumber(sub(color, 3, 4),16), tonumber(sub(color, 5, 6),16) end end function DiesalTools.GetColor(value) if not value then return end if type(value) == 'table' and #value >= 3 then return value[1]/255, value[2]/255, value[3]/255 elseif type(value) == 'string' then return tonumber(sub(value,1,2),16)/255, tonumber(sub(value,3,4),16)/255, tonumber(sub(value,5,6),16)/255 end end -- ~~| API |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ function DiesalTools.Stack() print("|r------------------------------| Stack Trace |-------------------------------") local stack = debugstack(1,12, 0) for trace in stack:gmatch("(.-)\n") do match, _, file, line, func = trace:find("^.*\\(.-):(%d+).-`(.*)'$") if match then print(format("%s[%s%s: %s%s%s] %sfunction|r %s|r",colors.orange,colors.yellow,file,colors.lightyellow,line,colors.orange,colors.blue,func)) end end print("|r--------------------------------------------------------------------------------") end --[[ copy = TableCopy(src, dest, metatable) @Arguments: dest Table to copy to src Table to copy metatable if true copies the metatable as well (boolean) @Returns: table copy of table --]] function DiesalTools.TableCopy(src,dest,metatable) if type(src) == 'table' then if not dest then dest = {} end for sk, sv in next, src, nil do dest[DiesalTools.TableCopy(sk)] = DiesalTools.TableCopy(sv) end if metatable then setmetatable(dest, DiesalTools.TableCopy(getmetatable(src))) end else -- number, string, boolean, etc dest = src end return dest end --[[ red, blue, green = GetColor(value) @Arguments: value Hex color code or a table contating R,G,B color values @Returns: red Red component of color (0-1) (number) green Green component of color(0-1) (number) blue Blue component of color (0-1) (number) -- ]] -- | Color Tools |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- converts a color from RGB[0-1], RGB[0-255], HEX or HSL to RGB[0-1], RGB[0-255] or HEX function DiesalTools.ConvertColor(from,to,v1,v2,v3) if not from or not to or not v1 then return end if type(v1) == 'table' then v1,v2,v3 = v1[1],v1[2],v1[3] end local r, g, b from, to = from:lower(), to:lower() if from == 'rgb255' and type(v1) == 'number' and type(v2) == 'number' and type(v3) == 'number' then r,g,b = v1, v2, v3 elseif from == 'rgb1' and type(v1) == 'number' and type(v2) == 'number' and type(v3) == 'number' then r,g,b = round(v1*255), round(v2*255), round(v3*255) elseif from == 'hex' and type(v1) == 'string' and #v1 > 5 then r,g,b = tonumber(sub(v1, 1, 2),16), tonumber(sub(v1, 3, 4),16), tonumber(sub(v1, 5, 6),16) elseif from == 'hsl' and type(v1) == 'number' and type(v2) == 'number' and type(v3) == 'number' then if v2 == 0 then v3 = round(v3 * 255) r,g,b = v3,v3,v3 else v1, v2, v3 = v1/360*6, min(max(0, v2), 1), min(max(0, v3), 1) local c = (1-abs(2*v3-1))*v2 local x = (1-abs(v1%2-1))*c local m = (v3-.5*c) r,g,b = 0,0,0 if v1 < 1 then r,g,b = c,x,0 elseif v1 < 2 then r,g,b = x,c,0 elseif v1 < 3 then r,g,b = 0,c,x elseif v1 < 4 then r,g,b = 0,x,c elseif v1 < 5 then r,g,b = x,0,c else r,g,b = c,0,x end r,g,b = round((r+m)*255),round((g+m)*255),round((b+m)*255) end else return end r,g,b = min(255,max(0,r)), min(255,max(0,g)), min(255,max(0,b)) if to == 'rgb255' then return r,g,b elseif to == 'rgb1' then return r/255,g/255,b/255 elseif to == 'hex' then return format("%02x%02x%02x",r,g,b) end end -- Mixes a color with pure white to produce a lighter color function DiesalTools.TintColor(color, percent, to, from) percent = min(1,max(0,percent)) from, to = from or 'hex', to and to:lower() or 'hex' local r,g,b = DiesalTools.ConvertColor(from,'rgb255',color) if to == 'rgb255' then return round((255-r)*percent+r), round((255-g)*percent+g), round((255-b)*percent+b) elseif to == 'rgb1' then return round( ((255-r)*percent+r) / 255 ), round( ((255-g)*percent+g) / 255 ), round( ((255-b)*percent+b) / 255 ) elseif to == 'hex' then return format("%02x%02x%02x", round((255-r)*percent+r), round((255-g)*percent+g), round((255-b)*percent+b) ) end -- return format("%02x%02x%02x", round((255-r)*percent+r), round((255-g)*percent+g), round((255-b)*percent+b) ) end -- Mixes a color with pure black to produce a darker color function DiesalTools.ShadeColor(color, percent, to, from) percent = min(1,max(0,percent)) from, to = from or 'hex', to and to:lower() or 'hex' local r,g,b = DiesalTools.ConvertColor(from,'rgb255',color) if to == 'rgb255' then return round(-r*percent+r), round(-g*percent+g), round(-b*percent+b) elseif to == 'rgb1' then return round( (-r*percent+r) / 255 ), round( (-g*percent+g) / 255 ), round( (-b*percent+b) / 255 ) elseif to == 'hex' then return format("%02x%02x%02x", round(-r*percent+r), round(-g*percent+g), round(-b*percent+b) ) end end -- Mixes a color with the another color to produce an intermediate color. function DiesalTools.MixColors(color1, color2, percent, to, from) percent = min(1,max(0,percent)) from, to = from or 'hex', to and to:lower() or 'hex' -- to = to and to:lower() or 'hex' local r1, g1, b1 = DiesalTools.ConvertColor(from,'rgb255',color1) local r2, g2, b2 = DiesalTools.ConvertColor(from,'rgb255',color2) if to == 'rgb255' then return round((r2-r1)*percent)+r1, round((g2-g1)*percent)+g1, round((b2-b1)*percent)+b1 elseif to == 'rgb1' then return round( ((r2-r1)*percent+r1) / 255 ), round( ((g2-g1)*percent+g1) / 255 ), round( ((b2-b1)*percent+b1) / 255 ) elseif to == 'hex' then return format("%02x%02x%02x", round((r2-r1)*percent)+r1, round((g2-g1)*percent)+g1, round((b2-b1)*percent)+b1 ) end end --- converts color HSL to HEX function DiesalTools.HSL(v1,v2,v3) if not v1 then return end if type(v1) == 'table' then v1,v2,v3 = v1[1],v1[2],v1[3] end local r, g, b if v2 == 0 then v3 = round(v3 * 255) r,g,b = v3,v3,v3 else v1, v2, v3 = v1/360*6, min(max(0, v2), 1), min(max(0, v3), 1) local c = (1-abs(2*v3-1))*v2 local x = (1-abs(v1%2-1))*c local m = (v3-.5*c) r,g,b = 0,0,0 if v1 < 1 then r,g,b = c,x,0 elseif v1 < 2 then r,g,b = x,c,0 elseif v1 < 3 then r,g,b = 0,c,x elseif v1 < 4 then r,g,b = 0,x,c elseif v1 < 5 then r,g,b = x,0,c else r,g,b = c,0,x end r,g,b = round((r+m)*255),round((g+m)*255),round((b+m)*255) end r,g,b = min(255,max(0,r)), min(255,max(0,g)), min(255,max(0,b)) return format("%02x%02x%02x",r,g,b) end --[[ GetTxtColor(value) @Arguments: value Hex color code or a table contating R,G,B color values @Returns: text coloring escape sequence (|cFFFFFFFF) -- ]] function DiesalTools.GetTxtColor(value) if not value then return end if type(value) =='table' then value = string.format("%02x%02x%02x", value[1], value[2], value[3]) end return format('|cff%s',value) end -- | Texture Tools |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --[[ Get a piece of a texture as a cooridnate refernce -- @Param column the column in the texture -- @Param row the row in the texture -- @Param size the size in the texture -- @Param textureWidth total texture width -- @Param textureHeight total texture height -- @Return edge coordinates for image cropping, plugs directly into Texture:SetTexCoord(left, right, top, bottom) ]] function DiesalTools.GetIconCoords(column,row,size,textureWidth,textureHeight) size = size or 16 textureWidth = textureWidth or 128 textureHeight = textureHeight or 16 return (column * size - size) / textureWidth, (column * size) / textureWidth, (row * size - size) / textureHeight, (row * size) / textureHeight end -- | String Tools |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --[[ Capitalize a string -- @Param str the string to capatilize -- @Return the capitilized string ]] function DiesalTools.Capitalize(str) return (str:gsub("^%l", upper)) end --[[ Escape all formatting in a WoW-lua string -- @Param str the string to escape -- @Return the escaped string ]] function DiesalTools.EscapeString(string) return string:gsub( "[%z\1-\31\"\\|\127-\255]", escapeSequences ) end --[[ ID = CreateID(s) -- @Param s string to parse -- @Return ID string stripped of all non letter characters and color codes.]] function DiesalTools.CreateID(s) return gsub(s:gsub('c%x%x%x%x%x%x%x%x', ''), '[^%a%d]', '') end --[[ str = TrimString(s) -- @Param s string to parse -- @Return str string stripped of leading and trailing spaces.]] function DiesalTools.TrimString(s) return s:gsub("^%s*(.-)%s*$", "%1") end --[[ string = SpliceString(string, start, End, txt) @Arguments: string string to splice start starting index of splice End ending index of splice txt new text to splice in (string) @Returns: string resulting string of the splice @example: DiesalTools.SpliceString("123456789",2,4,'NEW') -- returns: "1NEW56789" --]] function DiesalTools.SpliceString(string,start,End,txt) return string:sub(1, start-1)..txt..string:sub(End+1,-1) end --[[ string = Serialize(table) @Param table - table to to serialize @Return string - serialized table (string) @deserialization: local func,err = loadstring('serialized table') if err then error(err) end return func() ]] local function serialize_number(number) -- no argument checking - called very often local text = ("%.17g"):format(number) -- on the same platform tostring() and string.format() -- return the same results for 1/0, -1/0, 0/0 -- so we don't need separate substitution table return sub_table[text] or text end local function impl(t, cat, visited) local t_type = type(t) if t_type == "table" then if not visited[t] then visited[t] = true cat("{") -- Serialize numeric indices local next_i = 0 for i, v in ipairs(t) do if i > 1 then -- TODO: Move condition out of the loop cat(",") end impl(v, cat, visited) next_i = i end next_i = next_i + 1 -- Serialize hash part -- Skipping comma only at first element iff there is no numeric part. local need_comma = (next_i > 1) for k, v in pairs(t) do local k_type = type(k) if k_type == "string" then if need_comma then cat(",") end need_comma = true -- TODO: Need "%q" analogue, which would put quotes -- only if string does not match regexp below if not lua_keywords[k] and ("^[%a_][%a%d_]*$"):match(k) then cat(k) cat("=") else cat(format("[%q]=", k)) end impl(v, cat, visited) else if k_type ~= "number" or -- non-string non-number k >= next_i or k < 1 or -- integer key in hash part of the table k % 1 ~= 0 -- non-integer key then if need_comma then cat(",") end need_comma = true cat("[") impl(k, cat, visited) cat("]=") impl(v, cat, visited) end end end cat("}") visited[t] = nil else -- this loses information on recursive tables cat('"table (recursive)"') end elseif t_type == "number" then cat(serialize_number(t)) elseif t_type == "boolean" then cat(tostring(t)) elseif t == nil then cat("nil") else -- this converts non-serializable (functions) types to strings cat(format("%q", tostring(t))) end end local function tstr_cat(cat, t) impl(t, cat, {}) end function DiesalTools.Serialize(t) local buf = {} local cat = function(v) buf[#buf + 1] = v end impl(t, cat, {}) return format('return %s',table_concat(buf)) end -- | Math Tools |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --[[ Round a number -- @Param number the number to round -- @Param base the number to round to (can be a decimal) [Default:1] -- @Return the rounded number to base ]] function DiesalTools.Round(number, base) base = base or 1 return floor((number + base/2)/base) * base end --[[ Round a number for printing -- @Param number the number to round -- @Param idp number of decimal points to round to [Default:1] -- @Return the rounded number ]] function DiesalTools.RoundPrint(num, idp) return string.format("%." .. (idp or 0) .. "f", num) end -- | Frame Tools |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --[[ GetFrameQuadrant(frame) @Arguments: frame frame?!! @Returns: quadrant quadrant of the screen frames center is in -- ]] function DiesalTools.GetFrameQuadrant(frame) if not frame:GetCenter() then return "UNKNOWN", frame:GetName() end local x, y = frame:GetCenter() local screenWidth = GetScreenWidth() local screenHeight = GetScreenHeight() local quadrant if (x > (screenWidth / 4) and x < (screenWidth / 4)*3) and y > (screenHeight / 4)*3 then quadrant = "TOP" elseif x < (screenWidth / 4) and y > (screenHeight / 4)*3 then quadrant = "TOPLEFT" elseif x > (screenWidth / 4)*3 and y > (screenHeight / 4)*3 then quadrant = "TOPRIGHT" elseif (x > (screenWidth / 4) and x < (screenWidth / 4)*3) and y < (screenHeight / 4) then quadrant = "BOTTOM" elseif x < (screenWidth / 4) and y < (screenHeight / 4) then quadrant = "BOTTOMLEFT" elseif x > (screenWidth / 4)*3 and y < (screenHeight / 4) then quadrant = "BOTTOMRIGHT" elseif x < (screenWidth / 4) and (y > (screenHeight / 4) and y < (screenHeight / 4)*3) then quadrant = "LEFT" elseif x > (screenWidth / 4)*3 and y < (screenHeight / 4)*3 and y > (screenHeight / 4) then quadrant = "RIGHT" else quadrant = "CENTER" end return quadrant end -- | Misc Tools |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --[[ Pack(...) blizzard dosnt use 5.2 yet so will have to create this one @Arguments: ... arguments to pack into a table @Returns: a new table with all parameters stored into keys 1, 2, etc. and with a field "n" with the total number of parameters ]] function DiesalTools.Pack(...) return { n = select("#", ...), ... } end --[[ Unpack(...) @Arguments: t table to unpack @Returns: ... list of arguments ]] function DiesalTools.Unpack(t) if t.n then return unpack(t,1,t.n) end return unpack(table) end
mit
baishancloud/lua-acid
lib/acid/paxoshelper.lua
2
4861
local _M = { _VERSION = require("acid.paxos._ver") } local tableutil = require( "acid.tableutil" ) local base = require( "acid.paxos.base" ) local errors = base.errors local nr_retry = 5 function _M.get_or_elect_leader(paxos, lease) local rst, err, errmes = paxos:local_get( 'leader' ) if err then paxos:logerr( {err=err, errmes=errmes}, "while local_get('leader'):", paxos.member_id) return nil, err, errmes end -- start to track version change. if version changed, -- paxos stops any write operation. paxos.ver = rst.ver if rst.val ~= nil then return rst, nil, nil end paxos:logerr( rst, "leader not found for:", paxos.member_id) return _M.elect_leader( paxos, lease ) end function _M.elect_leader(paxos, lease) return paxos:set( 'leader', { ident = paxos.member_id.ident, __lease = lease, }) end function _M.change_view(paxos, changes) -- changes = { -- add = { a=1, b=1 }, -- del = { c=1, d=1 }, -- merge = { f1={ f2={} } }, -- } -- change_view push cluster to a consistent state: -- . changes applied to cluster -- . other process is in progress changing view, apply it and return -- error DuringChange -- . no change. do nothing and return error -- . paxos race condition. update it -- after this step completed, it is required to track version changing to -- make sure no other change_view to break this procedure. for _ = 1, nr_retry do local c, err, errmes = _M._change_view( paxos, changes ) if err == errors.QuorumFailure then _M._sleep(paxos) paxos:sync() else return c, err, errmes end end return nil, errors.QuorumFailure end function _M._change_view(paxos, changes) local c, err, errmes = paxos:read() if err then return nil, err, errmes end _M._merge_changes( c.val, changes.merge or {} ) local cval = c.val local view, err, errmes = _M._make_2group_view(cval.view, changes ) if err then if err == errors.DuringChange then paxos:sync() if #cval.view == 2 then table.remove( cval.view, 1 ) _M._set_change_view( paxos, c ) end elseif err == errors.NoChange then return c, nil, nil end return nil, err, errmes end cval.view = view local _, err, errmes = _M._set_change_view( paxos, c ) if err then return nil, err, errmes end -- After update to dual-group view, commit once more with the new view to -- create new member. local _, err, errmes = paxos:sync() if err then return nil, err, errmes end table.remove( cval.view, 1 ) return _M._set_change_view( paxos, c ) end function _M._set_change_view( paxos, c ) local _c, err, errmes = paxos:read() if err then return nil, err, errmes end if tableutil.eq( c.val, _c.val ) then local p, err, errmes = paxos:new_proposer() if err then return nil, err, errmes end local c, err, errmes = p:commit_specific(_c) if err then return nil, err, errmes end return c, nil, nil end local c, err, errmes = paxos:write(c.val) if err then return nil, err, errmes end return c, nil, nil end function _M.with_cluster_locked(paxos, f, exptime) local cluster_id = paxos.member_id.cluster_id local _mid = { cluster_id= cluster_id, ident='__admin', } local _l, err = paxos.impl:lock(_mid, exptime) if err then return nil, errors.LockTimeout, err end local rst, err, errmes = f() paxos.impl:unlock(_l) return rst, err, errmes end function _M._make_2group_view(view, changes) -- Create intermedia view. -- Intermedia view of val contains 2 groups: the current group and the -- group to change to. local view = tableutil.dup( view, true ) if view[ 2 ] ~= nil then return nil, errors.DuringChange end view[ 2 ] = tableutil.dup( view[ 1 ], true ) tableutil.merge( view[ 2 ], changes.add or {} ) for k, v in pairs(changes.del or {}) do view[ 2 ][ k ] = nil end if tableutil.eq( view[1], view[2] ) then return nil, errors.NoChange end return view, nil, nil end -- merge cannot be nested loop table function _M._merge_changes(c, merge) for k, v in pairs(merge) do if type(v) == 'table' and type(c[k]) == 'table' then _M._merge_changes( c[k], v ) else c[ k ] = v end end return c end function _M._sleep(paxos) if paxos.impl.sleep then paxos.impl:sleep() end end return _M
mit
dacrybabysuck/darkstar
scripts/zones/San_dOria-Jeuno_Airship/npcs/qm1.lua
11
1036
----------------------------------- -- Area: San d'Oria-Jeuno Airship -- NPC: ??? -- Involved In Quest: The Stars Of Ifrit -- !pos -9 -5 -13 223 ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/weather"); local ID = require("scripts/zones/San_dOria-Jeuno_Airship/IDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local TOTD = VanadielTOTD(); local TheStarsOfIfrit = player:getQuestStatus(BASTOK,dsp.quest.id.bastok.THE_STARS_OF_IFRIT); if (TOTD == dsp.time.NIGHT and IsMoonFull()) then if (TheStarsOfIfrit == QUEST_ACCEPTED and player:hasKeyItem(dsp.ki.CARRIER_PIGEON_LETTER) == false) then player:addKeyItem(dsp.ki.CARRIER_PIGEON_LETTER); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.CARRIER_PIGEON_LETTER); end end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
gpl-3.0
hussian1997/hk-_bot
plugins/anti-spam.lua
8
5854
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY(@AHMED_ALOBIDE ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY(@hussian_9 ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] 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
dacrybabysuck/darkstar
scripts/zones/PsoXja/npcs/_i98.lua
9
1161
----------------------------------- -- Area: Pso'Xja -- NPC: Stone Gate ----------------------------------- local ID = require("scripts/zones/PsoXja/IDs"); require("scripts/globals/missions"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getCurrentMission(COP) == dsp.mission.id.cop.THE_ENDURING_TUMULT_OF_WAR and player:getCharVar("PromathiaStatus")==3 and not GetMobByID(ID.mob.NUNYUNUWI):isSpawned()) then SpawnMob(ID.mob.NUNYUNUWI):updateClaim(player); elseif ( (player:getCurrentMission(COP) == dsp.mission.id.cop.THE_ENDURING_TUMULT_OF_WAR and player:getCharVar("PromathiaStatus")==4) or player:hasCompletedMission(COP,dsp.mission.id.cop.THE_ENDURING_TUMULT_OF_WAR) or player:hasCompletedMission(COP,dsp.mission.id.cop.THE_LAST_VERSE)) then if (player:getZPos() < 318) then player:startEvent(69); else player:startEvent(70); end else player:messageSpecial(ID.text.DOOR_LOCKED); end return 1; end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
gpl-3.0
dacrybabysuck/darkstar
scripts/zones/Balgas_Dais/bcnms/royal_succession.lua
9
1063
----------------------------------- -- Royal Succession -- Balga's Dais BCNM40, Star Orb -- !additem 1131 ----------------------------------- require("scripts/globals/battlefield") ----------------------------------- function onBattlefieldInitialise(battlefield) battlefield:setLocalVar("loot", 1) end function onBattlefieldTick(battlefield, tick) dsp.battlefield.onBattlefieldTick(battlefield, tick) end function onBattlefieldRegister(player, battlefield) end function onBattlefieldEnter(player, battlefield) end function onBattlefieldLeave(player, battlefield, leavecode) if leavecode == dsp.battlefield.leaveCode.WON then local name, clearTime, partySize = battlefield:getRecord() player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), 0) elseif leavecode == dsp.battlefield.leaveCode.LOST then player:startEvent(32002) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
gpl-3.0
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/skia/tools/lua/scrape_dashing.lua
160
2495
function tostr(t) local str = "" for k, v in next, t do if #str > 0 then str = str .. ", " end if type(k) == "number" then str = str .. "[" .. k .. "] = " else str = str .. tostring(k) .. " = " end if type(v) == "table" then str = str .. "{ " .. tostr(v) .. " }" else str = str .. tostring(v) end end return str end local total_found = {} -- accumulate() stores its data in here local total_total = {} local canvas -- holds the current canvas (from startcanvas()) --[[ startcanvas() is called at the start of each picture file, passing the canvas that we will be drawing into, and the name of the file. Following this call, there will be some number of calls to accumulate(t) where t is a table of parameters that were passed to that draw-op. t.verb is a string holding the name of the draw-op (e.g. "drawRect") when a given picture is done, we call endcanvas(canvas, fileName) ]] function sk_scrape_startcanvas(c, fileName) canvas = c end --[[ Called when the current canvas is done drawing. ]] function sk_scrape_endcanvas(c, fileName) canvas = nil end function increment(table, key) table[key] = (table[key] or 0) + 1 end local drawPointsTable = {} local drawPointsTable_direction = {} function sk_scrape_accumulate(t) increment(total_total, t.verb) local p = t.paint if p then local pe = p:getPathEffect(); if pe then increment(total_found, t.verb) end end if "drawPoints" == t.verb then local points = t.points increment(drawPointsTable, #points) if 2 == #points then if points[1].y == points[2].y then increment(drawPointsTable_direction, "hori") elseif points[1].x == points[2].x then increment(drawPointsTable_direction, "vert") else increment(drawPointsTable_direction, "other") end end end end --[[ lua_pictures will call this function after all of the pictures have been "accumulated". ]] function sk_scrape_summarize() for k, v in next, total_found do io.write(k, " = ", v, "/", total_total[k], "\n") end print("histogram of point-counts for all drawPoints calls") print(tostr(drawPointsTable)) print(tostr(drawPointsTable_direction)) end
gpl-3.0
Zorbash/linguaphone
lua/sieve_atkin.lua
1
1053
N = tonumber(arg[1]) or 1000 nsqrt = N^(0.5) is_prime = {} --Initialize array for i=1, N do is_prime[i] = false end for x = 1, nsqrt do for y = 1, nsqrt do n = 4 * (x^2) + y^2 if n <= N and (n % 12 == 1 or n % 12 == 5) then if is_prime[n] == true then is_prime[n] = false else is_prime[n] = true end end n = 3 * (x^2) + y^2 if n <= N and n % 12 == 7 then if is_prime[n] == true then is_prime[n] = false else is_prime[n] = true end end n = 3 * (x^2) - y^2 if x > y and n <= N and n % 12 == 11 then if is_prime[n] == true then is_prime[n] = false else is_prime[n] = true end end end end for n = 5, nsqrt do if is_prime[n] then for y = n^2, N, n^2 do is_prime[y] = false end end end is_prime[2] = true is_prime[3] = true primes = {} for x = 1, #is_prime - 1 do if is_prime[x] == true then table.insert(primes, x) end end for x = 1, #primes do print(primes[x]) end os.exit(0)
mit
uleelx/lupy
lupy.lua
1
1699
local metamethods = { "__add", "__sub", "__mul", "__div", "__mod", "__pow", "__unm", "__concat", "__len", "__eq", "__lt", "__le", "__newindex", "__call", "__pairs", "__ipairs", "__gc" } local function new(class, ...) local o = setmetatable({__class__ = class}, class) if class.__init__ then class.__init__(o, ...) end return o end local function include(m) debug.upvaluejoin(include, 1, debug.getinfo(2, 'f').func, 1) table.insert(_ENV.__type__, 2, m.__type__[1]) for k, v in pairs(m) do if k ~= "__index" and k ~= "__type__" then _ENV[k] = v end end end local function is(self, c) return string.match(table.concat(self.__type__, ','), (c or "([^,]+)")) end local function dig(self, member_name) local class = self.__class__ local member = class[member_name] if type(member) == "function" then return function(...) return member(self, ...) end else return member or class.__missing__ and function(...) return class.__missing__(self, member_name, ...) end end end local Object = {__index = _ENV, __type__ = {"Object"}, is = is, include = include} setmetatable(Object, Object) local function class(name) local env = _ENV local name, supername = string.match(name, "([%w_]*)%s*<?%s*([%w_]*)") local self = env[name] if not self then local super = env[supername] or Object self = {__index = dig, __type__ = {name, table.unpack(super.__type__)}} for _, k in ipairs(metamethods) do self[k] = super[k] end setmetatable(self, {__index = super, __call = new}) env[name] = self end debug.upvaluejoin(class, 1, debug.getinfo(2, 'f').func, 1) self._end = function() _ENV, _end = env end _ENV = self end return class
mit
jonleopard/dotfiles
nvim/.config/nvim/after/plugin/keymap/init.lua
1
1228
local Remap = require("jon.keymap") local nnoremap = Remap.nnoremap local vnoremap = Remap.vnoremap local inoremap = Remap.inoremap local xnoremap = Remap.xnoremap local nmap = Remap.nmap ---- UndoTree nnoremap("<leader>u", ":UndotreeToggle<CR>") -- greatest remap ever -- xnoremap("<leader>p", "\"_dP") -- next greatest remap ever : asbjornHaland -- nnoremap("<leader>y", "\"+y") -- vnoremap("<leader>y", "\"+y") -- nmap("<leader>Y", "\"+Y") -- format --keymap("n", "<leader>F", ":Format<cr>", opts) ---- Dirvish --keymap("n", "<leader>e", ":wincmd v<bar> :Dirvish <bar> :vertical resize 30<CR>", opts) -- Y yank rest of line nnoremap("Y", "yg$") -- Save nnoremap("<leader>s", ":update<CR>") nnoremap("<leader>w", ":update<CR>") -- Quit nnoremap("<leader>q", ":q<CR>") nnoremap("<leader>Q", ":qa!<CR>") -- Cancel inoremap("<C-c>", "<Esc>") ---- Buffers --keymap("n", "]b", ":bnext", opts) --keymap("n", "[b", ":bprev", opts) ---- To open a new empty buffer ---- This replaces :tabnew which I used to bind to this mapping --keymap("n", "<leader>T", ":enew<cr>", opts) --nnoremap("<leader>s", ":%s/\\<<C-r><C-w>\\>/<C-r><C-w>/gI<Left><Left><Left>") --nnoremap("<leader>x", "<cmd>!chmod +x %<CR>", { silent = true })
mit
dcourtois/premake-core
src/_premake_init.lua
2
32533
-- -- _premake_init.lua -- -- Prepares the runtime environment for the add-ons and user project scripts. -- -- Copyright (c) 2012-2015 Jason Perkins and the Premake project -- local p = premake local api = p.api local DOC_URL = "See https://github.com/premake/premake-core/wiki/" ----------------------------------------------------------------------------- -- -- Register the core API functions. -- ----------------------------------------------------------------------------- api.register { name = "architecture", scope = "config", kind = "string", allowed = { "universal", p.X86, p.X86_64, p.ARM, p.ARM64, }, aliases = { i386 = p.X86, amd64 = p.X86_64, x32 = p.X86, -- these should be DEPRECATED x64 = p.X86_64, }, } api.register { name = "atl", scope = "config", kind = "string", allowed = { "Off", "Dynamic", "Static", }, } api.register { name = "basedir", scope = "project", kind = "path" } api.register { name = "buildaction", scope = "config", kind = "string", } api.register { name = "buildcommands", scope = { "config", "rule" }, kind = "list:string", tokens = true, pathVars = true, } api.register { name = "buildcustomizations", scope = "project", kind = "list:string", } api.register { name = "builddependencies", scope = { "rule" }, kind = "list:string", tokens = true, pathVars = true, } api.register { name = "buildlog", scope = { "config" }, kind = "path", tokens = true, pathVars = true, } api.register { name = "buildmessage", scope = { "config", "rule" }, kind = "string", tokens = true, pathVars = true, } api.register { name = "buildoptions", scope = "config", kind = "list:string", tokens = true, pathVars = true, } api.register { name = "buildoutputs", scope = { "config", "rule" }, kind = "list:path", tokens = true, pathVars = false, } api.register { name = "buildinputs", scope = "config", kind = "list:path", tokens = true, pathVars = false, } api.register { name = "buildrule", -- DEPRECATED scope = "config", kind = "table", tokens = true, } api.register { name = "characterset", scope = "config", kind = "string", allowed = { "Default", "ASCII", "MBCS", "Unicode", } } api.register { name = "cleancommands", scope = "config", kind = "list:string", tokens = true, pathVars = true, } api.register { name = "cleanextensions", scope = "config", kind = "list:string", } api.register { name = "clr", scope = "config", kind = "string", allowed = { "Off", "On", "Pure", "Safe", "Unsafe", "NetCore", } } api.register { name = "compilebuildoutputs", scope = "config", kind = "boolean" } api.register { name = "compileas", scope = "config", kind = "string", allowed = { "Default", "C", "C++", "Objective-C", "Objective-C++", "Module", "ModulePartition", "HeaderUnit" } } api.register { name = "allmodulespublic", scope = "config", kind = "boolean" } api.register { name = "configmap", scope = "project", kind = "list:keyed:array:string", } api.register { name = "configurations", scope = "project", kind = "list:string", } api.register { name = "consumewinrtextension", scope = "config", kind = "boolean", } api.register { name = "copylocal", scope = "config", kind = "list:mixed", tokens = true, } api.register { name = "debugargs", scope = "config", kind = "list:string", tokens = true, pathVars = true, allowDuplicates = true, } api.register { name = "debugcommand", scope = "config", kind = "path", tokens = true, pathVars = true, } api.register { name = "debugconnectcommands", scope = "config", kind = "list:string", tokens = true, } api.register { name = "debugdir", scope = "config", kind = "path", tokens = true, pathVars = true, } api.register { name = "debugenvs", scope = "config", kind = "list:string", tokens = true, pathVars = true, } api.register { name = "debugextendedprotocol", scope = "config", kind = "boolean", } api.register { name = "debugformat", scope = "config", kind = "string", allowed = { "Default", "c7", "Dwarf", "SplitDwarf", }, } api.register { name = "debugger", scope = "config", kind = "string", allowed = { "Default", "GDB", "LLDB", } } api.register { name = "debuggertype", scope = "config", kind = "string", allowed = { "Mixed", "NativeOnly", "ManagedOnly", } } api.register { name = "debugpathmap", scope = "config", kind = "list:keyed:path", tokens = true, } api.register { name = "debugport", scope = "config", kind = "integer", } api.register { name = "debugremotehost", scope = "config", kind = "string", tokens = true, } api.register { name = "debugsearchpaths", scope = "config", kind = "list:path", tokens = true, } api.register { name = "debugstartupcommands", scope = "config", kind = "list:string", tokens = true, } api.register { name = "debugtoolargs", scope = "config", kind = "list:string", tokens = true, pathVars = true, } api.register { name = "debugtoolcommand", scope = "config", kind = "path", tokens = true, pathVars = true, } api.register { name = "defaultplatform", scope = "project", kind = "string", } api.register { name = "defines", scope = "config", kind = "list:string", tokens = true, } api.register { name = "dependson", scope = "config", kind = "list:string", tokens = true, } api.register { name = "disablewarnings", scope = "config", kind = "list:string", tokens = true, } api.register { name = "display", scope = "rule", kind = "string", } api.register { name = "dpiawareness", scope = "config", kind = "string", allowed = { "Default", "None", "High", "HighPerMonitor", } } api.register { name = "editandcontinue", scope = "config", kind = "string", allowed = { "Default", "On", "Off", }, } api.register { name = "exceptionhandling", scope = "config", kind = "string", allowed = { "Default", "On", "Off", "SEH", "CThrow", }, } api.register { name = "enablewarnings", scope = "config", kind = "list:string", tokens = true, } api.register { name = "endian", scope = "config", kind = "string", allowed = { "Default", "Little", "Big", }, } api.register { name = "entrypoint", scope = "config", kind = "string", } api.register { name = "fastuptodate", scope = "project", kind = "boolean", } api.register { name = "fatalwarnings", scope = "config", kind = "list:string", tokens = true, } api.register { name = "fileextension", scope = "rule", kind = "list:string", } api.register { name = "filename", scope = { "project", "rule" }, kind = "string", tokens = true, } api.register { name = "files", scope = "config", kind = "list:file", tokens = true, } api.register { name = "functionlevellinking", scope = "config", kind = "boolean" } api.register { name = "flags", scope = "config", kind = "list:string", allowed = { "Component", -- DEPRECATED "DebugEnvsDontMerge", "DebugEnvsInherit", "EnableSSE", -- DEPRECATED "EnableSSE2", -- DEPRECATED "ExcludeFromBuild", "ExtraWarnings", -- DEPRECATED "FatalCompileWarnings", "FatalLinkWarnings", "FloatFast", -- DEPRECATED "FloatStrict", -- DEPRECATED "LinkTimeOptimization", "Managed", -- DEPRECATED "Maps", "MFC", "MultiProcessorCompile", "NativeWChar", -- DEPRECATED "No64BitChecks", "NoCopyLocal", "NoEditAndContinue", -- DEPRECATED "NoFramePointer", -- DEPRECATED "NoImplicitLink", "NoImportLib", "NoIncrementalLink", "NoManifest", "NoMinimalRebuild", "NoNativeWChar", -- DEPRECATED "NoPCH", "NoRuntimeChecks", "NoBufferSecurityCheck", "NoWarnings", -- DEPRECATED "OmitDefaultLibrary", "Optimize", -- DEPRECATED "OptimizeSize", -- DEPRECATED "OptimizeSpeed", -- DEPRECATED "RelativeLinks", "ReleaseRuntime", -- DEPRECATED "ShadowedVariables", "StaticRuntime", -- DEPRECATED "Symbols", -- DEPRECATED "UndefinedIdentifiers", "WinMain", -- DEPRECATED "WPF", "C++11", -- DEPRECATED "C++14", -- DEPRECATED "C90", -- DEPRECATED "C99", -- DEPRECATED "C11", -- DEPRECATED }, aliases = { FatalWarnings = { "FatalWarnings", "FatalCompileWarnings", "FatalLinkWarnings" }, Optimise = 'Optimize', OptimiseSize = 'OptimizeSize', OptimiseSpeed = 'OptimizeSpeed', }, } api.register { name = "floatingpoint", scope = "config", kind = "string", allowed = { "Default", "Fast", "Strict", } } api.register { name = "floatingpointexceptions", scope = "config", kind = "boolean" } api.register { name = "inlining", scope = "config", kind = "string", allowed = { "Default", "Disabled", "Explicit", "Auto" } } api.register { name = "callingconvention", scope = "config", kind = "string", allowed = { "Cdecl", "FastCall", "StdCall", "VectorCall", } } api.register { name = "forceincludes", scope = "config", kind = "list:mixed", tokens = true, } api.register { name = "forceusings", scope = "config", kind = "list:file", tokens = true, } api.register { name = "fpu", scope = "config", kind = "string", allowed = { "Software", "Hardware", } } api.register { name = "dotnetframework", scope = "config", kind = "string", } api.register { name = "enabledefaultcompileitems", scope = "config", kind = "boolean", default = false } api.register { name = "csversion", scope = "config", kind = "string", } api.register { name = "gccprefix", scope = "config", kind = "string", tokens = true, } api.register { name = "ignoredefaultlibraries", scope = "config", kind = "list:mixed", tokens = true, } api.register { name = "inheritdependencies", scope = "config", kind = "boolean", } api.register { name = "icon", scope = "project", kind = "file", tokens = true, } api.register { name = "imageoptions", scope = "config", kind = "list:string", tokens = true, } api.register { name = "imagepath", scope = "config", kind = "path", tokens = true, } api.register { name = "implibdir", scope = "config", kind = "path", tokens = true, } api.register { name = "implibextension", scope = "config", kind = "string", tokens = true, } api.register { name = "implibname", scope = "config", kind = "string", tokens = true, } api.register { name = "implibprefix", scope = "config", kind = "string", tokens = true, } api.register { name = "implibsuffix", scope = "config", kind = "string", tokens = true, } api.register { name = "includedirs", scope = "config", kind = "list:directory", tokens = true, } api.register { name = "intrinsics", scope = "config", kind = "boolean" } api.register { name = "bindirs", scope = "config", kind = "list:directory", tokens = true, } api.register { name = "kind", scope = "config", kind = "string", allowed = { "ConsoleApp", "Makefile", "None", "SharedLib", "StaticLib", "WindowedApp", "Utility", "SharedItems", }, } api.register { name = "sharedlibtype", scope = "project", kind = "string", allowed = { "OSXBundle", "OSXFramework", "XCTest", }, } api.register { name = "language", scope = "project", kind = "string", allowed = { "C", "C++", "C#", "F#" } } api.register { name = "cdialect", scope = "config", kind = "string", allowed = { "Default", "C89", "C90", "C99", "C11", "C17", "gnu89", "gnu90", "gnu99", "gnu11", "gnu17" } } api.register { name = "cppdialect", scope = "config", kind = "string", allowed = { "Default", "C++latest", "C++98", "C++0x", "C++11", "C++1y", "C++14", "C++1z", "C++17", "C++2a", "C++20", "gnu++98", "gnu++0x", "gnu++11", "gnu++1y", "gnu++14", "gnu++1z", "gnu++17", "gnu++2a", "gnu++20", } } api.register { name = "conformancemode", scope = "config", kind = "boolean" } api.register { name = "usefullpaths", scope = "config", kind = "boolean" } api.register { name = "removeunreferencedcodedata", scope = "config", kind = "boolean" } api.register { name = "swiftversion", scope = "config", kind = "string", allowed = { "4.0", "4.2", "5.0", } } api.register { name = "libdirs", scope = "config", kind = "list:directory", tokens = true, } api.register { name = "frameworkdirs", scope = "config", kind = "list:directory", tokens = true, } api.register { name = "linkbuildoutputs", scope = "config", kind = "boolean" } api.register { name = "linkoptions", scope = "config", kind = "list:string", tokens = true, } api.register { name = "links", scope = "config", kind = "list:mixed", tokens = true, } api.register { name = "linkgroups", scope = "config", kind = "string", allowed = { "Off", "On", } } api.register { name = "locale", scope = "config", kind = "string", tokens = false, } api.register { name = "location", scope = { "project", "rule" }, kind = "path", tokens = true, } api.register { name = "makesettings", scope = "config", kind = "list:string", tokens = true, } api.register { name = "namespace", scope = "project", kind = "string", tokens = true, } api.register { name = "nativewchar", scope = "config", kind = "string", allowed = { "Default", "On", "Off", } } api.register { name = "nuget", scope = "config", kind = "list:string", tokens = true, } api.register { name = "nugetsource", scope = "project", kind = "string", tokens = true, } api.register { name = "objdir", scope = "config", kind = "path", tokens = true, } api.register { name = "optimize", scope = "config", kind = "string", allowed = { "Off", "On", "Debug", "Size", "Speed", "Full", } } api.register { name = "runpathdirs", scope = "config", kind = "list:path", tokens = true, } api.register { name = "runtime", scope = "config", kind = "string", allowed = { "Debug", "Release", } } api.register { name = "pchheader", scope = "config", kind = "string", tokens = true, } api.register { name = "pchsource", scope = "config", kind = "path", tokens = true, } api.register { name = "pic", scope = "config", kind = "string", allowed = { "Off", "On", } } api.register { name = "platforms", scope = "project", kind = "list:string", } api.register { name = "postbuildcommands", scope = "config", kind = "list:string", tokens = true, pathVars = true, allowDuplicates = true, } api.register { name = "postbuildmessage", scope = "config", kind = "string", tokens = true, pathVars = true, } api.register { name = "prebuildcommands", scope = "config", kind = "list:string", tokens = true, pathVars = true, allowDuplicates = true, } api.register { name = "prebuildmessage", scope = "config", kind = "string", tokens = true, pathVars = true, } api.register { name = "prelinkcommands", scope = "config", kind = "list:string", tokens = true, pathVars = true, } api.register { name = "prelinkmessage", scope = "config", kind = "string", tokens = true, pathVars = true, } api.register { name = "propertydefinition", scope = "rule", kind = "list:table", } api.register { name = "rebuildcommands", scope = "config", kind = "list:string", tokens = true, pathVars = true, } api.register { name = "resdefines", scope = "config", kind = "list:string", tokens = true, } api.register { name = "resincludedirs", scope = "config", kind = "list:directory", tokens = true, } api.register { name = "resoptions", scope = "config", kind = "list:string", tokens = true, } api.register { name = "resourcegenerator", scope = "project", kind = "string", allowed = { "internal", "public" } } api.register { name = "rtti", scope = "config", kind = "string", allowed = { "Default", "On", "Off", }, } api.register { name = "rules", scope = "project", kind = "list:string", } api.register { name = "startproject", scope = "workspace", kind = "string", tokens = true, } api.register { name = "staticruntime", scope = "config", kind = "string", allowed = { "Default", "On", "Off" } } api.register { name = "strictaliasing", scope = "config", kind = "string", allowed = { "Off", "Level1", "Level2", "Level3", } } api.register { name = "stringpooling", scope = "config", kind = "boolean" } api.register { name = "symbols", scope = "config", kind = "string", allowed = { "Default", "On", "Off", "FastLink", -- Visual Studio 2015+ only, considered 'On' for all other cases. "Full", -- Visual Studio 2017+ only, considered 'On' for all other cases. }, } api.register { name = "symbolspath", scope = "config", kind = "path", tokens = true, } api.register { name = "syslibdirs", scope = "config", kind = "list:directory", tokens = true, } api.register { name = "system", scope = "config", kind = "string", allowed = { "aix", "bsd", "haiku", "ios", "linux", "macosx", "solaris", "wii", "windows", }, } api.register { name = "systemversion", scope = "config", kind = "string", } api.register { name = "tags", scope = "config", kind = "list:string", } api.register { name = "tailcalls", scope = "config", kind = "boolean" } api.register { name = "targetdir", scope = "config", kind = "path", tokens = true, } api.register { name = "targetextension", scope = "config", kind = "string", tokens = true, } api.register { name = "targetname", scope = "config", kind = "string", tokens = true, } api.register { name = "targetprefix", scope = "config", kind = "string", tokens = true, } api.register { name = "targetsuffix", scope = "config", kind = "string", tokens = true, } api.register { name = "toolset", scope = "config", kind = "string", allowed = function(value) value = value:lower() local tool, version = p.tools.canonical(value) if tool then return p.tools.normalize(value) else return nil end end, } api.register { name = "toolsversion", scope = "project", kind = "string", tokens = true, } api.register { name = "customtoolnamespace", scope = "config", kind = "string", } api.register { name = "undefines", scope = "config", kind = "list:string", tokens = true, } api.register { name = "usingdirs", scope = "config", kind = "list:directory", tokens = true, } api.register { name = "uuid", scope = "project", kind = "string", allowed = function(value) local ok = true if (#value ~= 36) then ok = false end for i=1,36 do local ch = value:sub(i,i) if (not ch:find("[ABCDEFabcdef0123456789-]")) then ok = false end end if (value:sub(9,9) ~= "-") then ok = false end if (value:sub(14,14) ~= "-") then ok = false end if (value:sub(19,19) ~= "-") then ok = false end if (value:sub(24,24) ~= "-") then ok = false end if (not ok) then return nil, "invalid UUID" end return value:upper() end } api.register { name = "vectorextensions", scope = "config", kind = "string", allowed = { "Default", "AVX", "AVX2", "IA32", "SSE", "SSE2", "SSE3", "SSSE3", "SSE4.1", "SSE4.2", } } api.register { name = "isaextensions", scope = "config", kind = "list:string", allowed = { "MOVBE", "POPCNT", "PCLMUL", "LZCNT", "BMI", "BMI2", "F16C", "AES", "FMA", "FMA4", "RDRND", } } api.register { name = "vpaths", scope = "project", kind = "list:keyed:list:path", tokens = true, pathVars = true, } api.register { name = "warnings", scope = "config", kind = "string", allowed = { "Off", "Default", "High", "Extra", "Everything", } } api.register { name = "largeaddressaware", scope = "config", kind = "boolean", } api.register { name = "editorintegration", scope = "workspace", kind = "boolean", } api.register { name = "preferredtoolarchitecture", scope = "workspace", kind = "string", allowed = { "Default", p.X86, p.X86_64, } } api.register { name = "unsignedchar", scope = "config", kind = "boolean", } p.api.register { name = "structmemberalign", scope = "config", kind = "integer", allowed = { "1", "2", "4", "8", "16", } } api.register { name = "omitframepointer", scope = "config", kind = "string", allowed = { "Default", "On", "Off" } } api.register { name = "visibility", scope = "config", kind = "string", allowed = { "Default", "Hidden", "Internal", "Protected" } } api.register { name = "inlinesvisibility", scope = "config", kind = "string", allowed = { "Default", "Hidden" } } api.register { name = "assemblydebug", scope = "config", kind = "boolean" } api.register { name = "justmycode", scope = "project", kind = "string", allowed = { "On", "Off" } } api.register { name = "openmp", scope = "project", kind = "string", allowed = { "On", "Off" } } api.register { name = "externalincludedirs", scope = "config", kind = "list:directory", tokens = true, } api.register { name = "externalwarnings", scope = "config", kind = "string", allowed = { "Off", "Default", "High", "Extra", "Everything", } } api.register { -- DEPRECATED 2021-11-16 name = "sysincludedirs", scope = "config", kind = "list:directory", tokens = true, } api.deprecateField("sysincludedirs", 'Use `externalincludedirs` instead.', function(value) externalincludedirs(value) end) ----------------------------------------------------------------------------- -- -- Field name aliases for backward compatibility -- ----------------------------------------------------------------------------- api.alias("buildcommands", "buildCommands") api.alias("builddependencies", "buildDependencies") api.alias("buildmessage", "buildMessage") api.alias("buildoutputs", "buildOutputs") api.alias("cleanextensions", "cleanExtensions") api.alias("dotnetframework", "framework") api.alias("editandcontinue", "editAndContinue") api.alias("fileextension", "fileExtension") api.alias("propertydefinition", "propertyDefinition") api.alias("removefiles", "excludes") ----------------------------------------------------------------------------- -- -- Handlers for deprecated fields and values. -- ----------------------------------------------------------------------------- -- 13 Apr 2017 api.deprecateField("buildrule", 'Use `buildcommands`, `buildoutputs`, and `buildmessage` instead.', function(value) if value.description then buildmessage(value.description) end buildcommands(value.commands) buildoutputs(value.outputs) end) api.deprecateValue("flags", "Component", 'Use `buildaction "Component"` instead.', function(value) buildaction "Component" end) api.deprecateValue("flags", "EnableSSE", 'Use `vectorextensions "SSE"` instead.', function(value) vectorextensions("SSE") end, function(value) vectorextensions "Default" end) api.deprecateValue("flags", "EnableSSE2", 'Use `vectorextensions "SSE2"` instead.', function(value) vectorextensions("SSE2") end, function(value) vectorextensions "Default" end) api.deprecateValue("flags", "FloatFast", 'Use `floatingpoint "Fast"` instead.', function(value) floatingpoint("Fast") end, function(value) floatingpoint "Default" end) api.deprecateValue("flags", "FloatStrict", 'Use `floatingpoint "Strict"` instead.', function(value) floatingpoint("Strict") end, function(value) floatingpoint "Default" end) api.deprecateValue("flags", "NativeWChar", 'Use `nativewchar "On"` instead."', function(value) nativewchar("On") end, function(value) nativewchar "Default" end) api.deprecateValue("flags", "NoNativeWChar", 'Use `nativewchar "Off"` instead."', function(value) nativewchar("Off") end, function(value) nativewchar "Default" end) api.deprecateValue("flags", "Optimize", 'Use `optimize "On"` instead.', function(value) optimize ("On") end, function(value) optimize "Off" end) api.deprecateValue("flags", "OptimizeSize", 'Use `optimize "Size"` instead.', function(value) optimize ("Size") end, function(value) optimize "Off" end) api.deprecateValue("flags", "OptimizeSpeed", 'Use `optimize "Speed"` instead.', function(value) optimize ("Speed") end, function(value) optimize "Off" end) api.deprecateValue("flags", "ReleaseRuntime", 'Use `runtime "Release"` instead.', function(value) runtime "Release" end, function(value) end) api.deprecateValue("flags", "ExtraWarnings", 'Use `warnings "Extra"` instead.', function(value) warnings "Extra" end, function(value) warnings "Default" end) api.deprecateValue("flags", "NoWarnings", 'Use `warnings "Off"` instead.', function(value) warnings "Off" end, function(value) warnings "Default" end) api.deprecateValue("flags", "Managed", 'Use `clr "On"` instead.', function(value) clr "On" end, function(value) clr "Off" end) api.deprecateValue("flags", "NoEditAndContinue", 'Use editandcontinue "Off"` instead.', function(value) editandcontinue "Off" end, function(value) editandcontinue "On" end) -- 21 June 2016 api.deprecateValue("flags", "Symbols", 'Use `symbols "On"` instead', function(value) symbols "On" end, function(value) symbols "Default" end) -- 31 January 2017 api.deprecateValue("flags", "C++11", 'Use `cppdialect "C++11"` instead', function(value) cppdialect "C++11" end, function(value) cppdialect "Default" end) api.deprecateValue("flags", "C++14", 'Use `cppdialect "C++14"` instead', function(value) cppdialect "C++14" end, function(value) cppdialect "Default" end) api.deprecateValue("flags", "C90", 'Use `cdialect "gnu90"` instead', function(value) cdialect "gnu90" end, function(value) cdialect "Default" end) api.deprecateValue("flags", "C99", 'Use `cdialect "gnu99"` instead', function(value) cdialect "gnu99" end, function(value) cdialect "Default" end) api.deprecateValue("flags", "C11", 'Use `cdialect "gnu11"` instead', function(value) cdialect "gnu11" end, function(value) cdialect "Default" end) -- 13 April 2017 api.deprecateValue("flags", "WinMain", 'Use `entrypoint "WinMainCRTStartup"` instead', function(value) entrypoint "WinMainCRTStartup" end, function(value) entrypoint "mainCRTStartup" end) -- 31 October 2017 api.deprecateValue("flags", "StaticRuntime", 'Use `staticruntime "On"` instead', function(value) staticruntime "On" end, function(value) staticruntime "Default" end) -- 08 April 2018 api.deprecateValue("flags", "NoFramePointer", 'Use `omitframepointer "On"` instead.', function(value) omitframepointer("On") end, function(value) omitframepointer("Default") end) ----------------------------------------------------------------------------- -- -- Install Premake's default set of command line arguments. -- ----------------------------------------------------------------------------- newoption { category = "compilers", trigger = "cc", value = "VALUE", description = "Choose a C/C++ compiler set", allowed = { { "clang", "Clang (clang)" }, { "gcc", "GNU GCC (gcc/g++)" }, { "mingw", "MinGW GCC (gcc/g++)" }, } } newoption { category = "compilers", trigger = "dotnet", value = "VALUE", description = "Choose a .NET compiler set", allowed = { { "msnet", "Microsoft .NET (csc)" }, { "mono", "Novell Mono (mcs)" }, { "pnet", "Portable.NET (cscc)" }, } } newoption { trigger = "fatal", description = "Treat warnings from project scripts as errors" } newoption { trigger = "debugger", description = "Start MobDebug remote debugger. Works with ZeroBrane Studio" } newoption { trigger = "file", value = "FILE", description = "Read FILE as a Premake script; default is 'premake5.lua'" } newoption { trigger = "help", description = "Display this information" } newoption { trigger = "verbose", description = "Generate extra debug text output" } newoption { trigger = "interactive", description = "Interactive command prompt" } newoption { trigger = "os", value = "VALUE", description = "Generate files for a different operating system", allowed = { { "aix", "IBM AIX" }, { "bsd", "OpenBSD, NetBSD, or FreeBSD" }, { "haiku", "Haiku" }, { "hurd", "GNU/Hurd" }, { "ios", "iOS" }, { "linux", "Linux" }, { "macosx", "Apple Mac OS X" }, { "solaris", "Solaris" }, { "windows", "Microsoft Windows" }, } } newoption { trigger = "scripts", value = "PATH", description = "Search for additional scripts on the given path" } newoption { trigger = "systemscript", value = "FILE", description = "Override default system script (premake5-system.lua)" } newoption { trigger = "version", description = "Display version information" } if http ~= nil then newoption { trigger = "insecure", description = "forfit SSH certification checks." } end ----------------------------------------------------------------------------- -- -- Set up the global environment for the systems I know about. I would like -- to see at least some if not all of this moved into add-ons in the future. -- ----------------------------------------------------------------------------- characterset "Default" clr "Off" editorintegration "Off" exceptionhandling "Default" rtti "Default" symbols "Default" nugetsource "https://api.nuget.org/v3/index.json" -- Setting a default language makes some validation easier later language "C++" -- Use Posix-style target naming by default, since it is the most common. filter { "kind:SharedLib" } targetprefix "lib" targetextension ".so" filter { "kind:StaticLib" } targetprefix "lib" targetextension ".a" -- Add variations for other Posix-like systems. filter { "system:darwin", "kind:WindowedApp" } targetextension ".app" filter { "system:darwin", "kind:SharedLib" } targetextension ".dylib" filter { "system:darwin", "kind:SharedLib", "sharedlibtype:OSXBundle" } targetprefix "" targetextension ".bundle" filter { "system:darwin", "kind:SharedLib", "sharedlibtype:OSXFramework" } targetprefix "" targetextension ".framework" filter { "system:darwin", "kind:SharedLib", "sharedlibtype:XCTest" } targetprefix "" targetextension ".xctest" -- Windows and friends. filter { "system:Windows or language:C# or language:F#", "kind:ConsoleApp or WindowedApp" } targetextension ".exe" filter { "system:Windows", "kind:SharedLib" } targetprefix "" targetextension ".dll" implibextension ".lib" filter { "system:Windows", "kind:StaticLib" } targetprefix "" targetextension ".lib" filter { "language:C# or language:F#", "kind:SharedLib" } targetprefix "" targetextension ".dll" implibextension ".dll" filter { "kind:SharedLib", "system:not Windows" } pic "On" filter { "system:darwin" } toolset "clang" filter { "platforms:Win64" } architecture "x86_64" filter {}
bsd-3-clause
Kelwing/pvpgn
lua/handle_command.lua
7
3050
--[[ Copyright (C) 2014 HarpyWar (harpywar@gmail.com) This file is a part of the PvPGN Project http://pvpgn.pro Licensed under the same terms as Lua itself. ]]-- -- List of available lua commands -- (To create a new command - create a new file in directory "commands") local lua_command_table = { [1] = { ["/w3motd"] = command_w3motd, -- Quiz ["/quiz"] = command_quiz, -- GHost ["/ghost"] = command_ghost, ["/host"] = command_host, ["/chost"] = command_chost, ["/unhost"] = command_unhost, ["/ping"] = command_ping, ["/p"] = command_ping, ["/swap"] = command_swap, ["/open"] = command_open_close, ["/close"] = command_open_close, ["/start"] = command_start_abort_pub_priv, ["/abort"] = command_start_abort_pub_priv, ["/pub"] = command_start_abort_pub_priv, ["/priv"] = command_start_abort_pub_priv, ["/stats"] = command_stats, }, [8] = { ["/redirect"] = command_redirect, }, } -- Global function to handle commands -- ("return 1" from a command will allow next C++ code execution) function handle_command(account, text) -- find command in table for cg,cmdlist in pairs(lua_command_table) do for cmd,func in pairs(cmdlist) do if string.starts(text, cmd) then -- check if command group is in account commandgroups if math_and(account_get_auth_command_groups(account.name), cg) == 0 then api.message_send_text(account.name, message_type_error, account.name, localize(account.name, "This command is reserved for admins.")) return -1 end -- FIXME: we can use _G[func] if func is a text but not a function, -- like ["/dotastats"] = "command_dotastats" -- and function command_dotastats can be defined below, not only before return func(account, text) end end end return 1 end -- Executes before executing any command -- "return 0" stay with flood protection -- "return 1" allow ignore flood protection -- "return -1" will prevent next command execution silently function handle_command_before(account, text) -- special users for k,username in pairs(config.flood_immunity_users) do if (username == account.name) then return 1 end end if (config.ghost) then -- ghost bots for k,username in pairs(config.ghost_bots) do if (username == account.name) then return 1 end end end return 0 end -- Split command to arguments, -- index 0 is always a command name without a slash -- return table with arguments function split_command(text, args_count) local count = args_count local result = {} local tmp = "" -- remove slash from the command if not string:empty(text) then text = string.sub(text, 2) end i = 0 -- split by space for token in string.split(text) do if not string:empty(token) then if (i < count) then result[i] = token i = i + 1 else if not string:empty(tmp) then tmp = tmp .. " " end tmp = tmp .. token end end end -- push remaining text at the end if not string:empty(tmp) then result[count] = tmp end return result end
gpl-2.0
dacrybabysuck/darkstar
scripts/zones/Castle_Oztroja/IDs.lua
9
5125
----------------------------------- -- Area: Castle_Oztroja ----------------------------------- require("scripts/globals/zone") ----------------------------------- zones = zones or {} zones[dsp.zone.CASTLE_OZTROJA] = { text = { CANNOT_REACH_TARGET = 0, -- Cannot reach target. ITS_LOCKED = 1, -- It's locked. PROBABLY_WORKS_WITH_SOMETHING_ELSE = 3, -- It probably works with something else. TORCH_LIT = 5, -- The torch is lit. INCORRECT = 11, -- Incorrect. FIRST_WORD = 12, -- The first word. SECOND_WORD = 13, -- The second word. THIRD_WORD = 14, -- The third word. CONQUEST_BASE = 26, -- Tallying conquest results... ITEM_CANNOT_BE_OBTAINED = 6567, -- You cannot obtain the <item>. Come back after sorting your inventory. FULL_INVENTORY_AFTER_TRADE = 6571, -- You cannot obtain the <item>. Try trading again after sorting your inventory. ITEM_OBTAINED = 6573, -- Obtained: <item>. GIL_OBTAINED = 6574, -- Obtained <number> gil. KEYITEM_OBTAINED = 6576, -- Obtained key item: <keyitem>. NOT_ENOUGH_GIL = 6578, -- You do not have enough gil. ITEMS_OBTAINED = 6582, -- You obtain <number> <item>! NOTHING_OUT_OF_ORDINARY = 6587, -- There is nothing out of the ordinary here. SENSE_OF_FOREBODING = 6588, -- You are suddenly overcome with a sense of foreboding... FISHING_MESSAGE_OFFSET = 7253, -- You can't fish here. CHEST_UNLOCKED = 7424, -- You unlock the chest! YAGUDO_AVATAR_ENGAGE = 7445, -- Kahk-ka-ka... You filthy, dim-witted heretics! You have damned yourselves by coming here. YAGUDO_AVATAR_DEATH = 7446, -- Our lord, Tzee Xicu the Manifest! Even should our bodies be crushed and broken, may our souls endure into eternity... YAGUDO_KING_ENGAGE = 7447, -- You are not here as sacrifices, are you? Could you possibly be committing this affront in the face of a deity? Very well, I will personally mete out your divine punishment, kyah! YAGUDO_KING_DEATH = 7448, -- You have...bested me... However, I...am...a god... I will never die...never rot...never fade...never... COMMON_SENSE_SURVIVAL = 8293, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world. }, mob = { MEE_DEGGI_THE_PUNISHER_PH = { [17395798] = 17395800, -- -207.840 -0.498 109.939 [17395766] = 17395800, -- -178.119 -0.644 153.039 [17395769] = 17395800, -- -188.253 -0.087 158.955 [17395783] = 17395800, -- -233.116 -0.741 172.067 [17395784] = 17395800, -- -254.302 -0.057 163.759 [17395799] = 17395800, -- -227.415 -4.340 145.213 [17395761] = 17395800, -- -207.370 -0.056 106.537 [17395775] = 17395800, -- -235.639 -0.063 103.280 }, MOO_OUZI_THE_SWIFTBLADE_PH = { [17395809] = 17395816, -- -18.415 -0.075 -92.889 [17395813] = 17395816, -- -38.689 0.191 -101.068 }, QUU_DOMI_THE_GALLANT_PH = { [17395844] = 17395870, -- 103.948 -1.250 -189.869 [17395845] = 17395870, -- 67.103 -0.079 -176.981 [17395853] = 17395870, -- 99.000 -0.181 -149.000 [17395831] = 17395870, -- 46.861 0.343 -176.989 [17395868] = 17395870, -- 35.847 -0.500 -101.685 [17395867] = 17395870, -- 59.000 -4.000 -131.000 [17395829] = 17395870, -- 33.832 -0.068 -176.627 [17395837] = 17395870, -- 18.545 -0.056 -120.283 }, YAA_HAQA_THE_PROFANE_PH = { [17395950] = 17395954, -- -24.719 -16.250 -139.678 [17395951] = 17395954, -- -22.395 -16.250 -139.341 [17395952] = 17395954, -- -25.044 -16.250 -141.534 [17395953] = 17395954, -- -32.302 -16.250 -139.169 }, YAGUDO_AVATAR = 17396134, HUU_XALMO_THE_SAVAGE = 17396140, MIMIC = 17396144, }, npc = { HANDLE_DOOR_FLOOR_2 = 17396160, FIRST_PASSWORD_STATUE = 17396168, SECOND_PASSWORD_STATUE = 17396173, THIRD_PASSWORD_STATUE = 17396178, BRASS_DOOR_FLOOR_4_H7 = 17396185, TRAP_DOOR_FLOOR_4 = 17396191, FINAL_PASSWORD_STATUE = 17396192, HINT_HANDLE_OFFSET = 17396196, TREASURE_CHEST = 17396210, TREASURE_COFFER = 17396211, }, } return zones[dsp.zone.CASTLE_OZTROJA]
gpl-3.0
SHIELDPOWER/power-team
plugins/inrealm.lua
850
25085
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
zenedge/lua-resty-http
lib/resty/http_headers.lua
1
1790
local rawget, rawset, setmetatable = rawget, rawset, setmetatable local str_lower, str_gsub = string.lower, string.gsub local _M = { _VERSION = '0.10', } local function hyphenate(k) return str_gsub(k, "_", "-") end -- Returns an empty headers table with internalised case normalisation. -- Supports the same cases as in ngx_lua: -- -- headers.content_length -- headers["content-length"] -- headers["Content-Length"] function _M.new(self, opt) local mt = { header_names_unchanged = opt and opt.header_names_unchanged or false, normalised = {}, } mt.__index = function(t, k) local k_hyphened = hyphenate(k) local k_normalised = str_lower(k_hyphened) return rawget(t, mt.normalised[k_normalised]) end -- First check the normalised table. If there's no match (first time) add an entry for -- our current case in the normalised table. This is to preserve the human (prettier) case -- instead of outputting lowercased header names. -- -- If there's a match, we're being updated, just with a different case for the key. We use -- the normalised table to give us the original key, and perorm a rawset(). mt.__newindex = function(t, k, v) -- we support underscore syntax, so always hyphenate. local k_hyphened = hyphenate(k) -- lowercase hyphenated is "normalised" local k_normalised = str_lower(k_hyphened) if not mt.normalised[k_normalised] then local header_name = mt.header_names_unchanged and k or k_hyphened mt.normalised[k_normalised] = header_name rawset(t, header_name, v) else rawset(t, mt.normalised[k_normalised], v) end end return setmetatable({}, mt) end return _M
bsd-2-clause
dacrybabysuck/darkstar
scripts/globals/mobskills/impale.lua
8
1342
--------------------------------------------- -- Impale -- -- Description: Deals damage to a single target. Additional effect: Paralysis (NM version AE applies a strong poison effect and resets enmity on target) -- Type: Physical -- Utsusemi/Blink absorb: 1 shadow (NM version ignores shadows) -- Range: Melee -- Notes: --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target, mob, skill) return 0 end function onMobWeaponSkill(target, mob, skill) local typeEffect = dsp.effect.PARALYSIS local numhits = 1 local accmod = 1 local dmgmod = 2.3 local info = MobPhysicalMove(mob, target, skill, numhits, accmod, dmgmod, TP_NO_EFFECT) local shadows = info.hitslanded if mob:isMobType(MOBTYPE_NOTORIOUS) then shadows = MOBPARAM_IGNORE_SHADOWS typeEffect = dsp.effect.POISON mob:resetEnmity(target) end local dmg = MobFinalAdjustments(info.dmg, mob, skill,target, dsp.attackType.PHYSICAL, dsp.damageType.PIERCING,shadows) MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 20, 0, 120) target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.PIERCING) return dmg end
gpl-3.0
akbooer/openLuup
openLuup/wsapi.lua
1
32823
local ABOUT = { NAME = "openLuup.wsapi", VERSION = "2019.08.12", DESCRIPTION = "a WSAPI application connector for the openLuup port 3480 server", AUTHOR = "@akbooer", COPYRIGHT = "(c) 2013-2019 AKBooer", DOCUMENTATION = "https://github.com/akbooer/openLuup/tree/master/Documentation", LICENSE = [[ Copyright 2013-2019 AK Booer Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ----- This module also contains the WSAPI request and response libraries from the Kepler project see: https://keplerproject.github.io/wsapi/libraries.html Copyright © 2007-2014 Kepler Project. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] } -- This module implements a WSAPI (Web Server API) application connector for the openLuup port 3480 server. -- -- see: http://keplerproject.github.io/wsapi/ -- and: http://keplerproject.github.io/wsapi/license.html -- and: https://github.com/keplerproject/wsapi -- and: http://keplerproject.github.io/wsapi/manual.html -- The use of WSAPI concepts for handling openLuup CGI requests was itself inspired by @vosmont, -- see: http://forum.micasaverde.com/index.php/topic,36189.0.html -- 2016.02.18 -- 2016.02.26 add self parameter to input.read(), seems to be called from wsapi.request with colon syntax -- ...also util.lua shows that the same is true for the error.write(...) function. -- 2016.05.30 look in specified places for some missing CGI files -- 2016.07.05 use "require" for WSAPI files with a .lua extension (enables easy debugging) -- 2016.07.06 add 'method' to WSAPI server call for REQUEST_METHOD metavariable -- 2016.07.14 change cgi() parameter to request object -- 2016.07.15 three-parameters WSAPI return: status, headers, iterator -- 2016.10.17 use CGI aliases from external servertables module -- 2017.01.12 remove leading colon from REMOTE_PORT metavariable value -- 2018.07.14 improve error handling when calling CGI -- 2018.07.20 add the Kepler project request and response libraries -- 2018.07.27 export the util module with url_encode() and url_decode() -- 2019.05.06 improve CGI .lua log message -- 2019.07.17 include complete WSAPI util module rather than socket.url (to decode '+' signs correctly) -- 2019.07.28 create global make_env(), used by HTTP server to include in request objects --[[ Writing WSAPI connectors A WSAPI connector builds the environment from information passed by the web server and calls a WSAPI application, sending the response back to the web server. The first thing a connector needs is a way to specify which application to run, and this is highly connector specific. Most connectors receive the application entry point as a parameter (but WSAPI provides special applications called generic launchers as a convenience). The environment is a Lua table containing the CGI metavariables (at minimum the RFC3875 ones) plus any server-specific metainformation. It also contains an input field, a stream for the request's data, and an error field, a stream for the server's error log. The input field answers to the read([n]) method, where n is the number of bytes you want to read (or nil if you want the whole input). The error field answers to the write(...) method. The environment should return the empty string instead of nil for undefined metavariables, and the PATH_INFO variable should return "/" even if the path is empty. Behavior among the connectors should be uniform: SCRIPT_NAME should hold the URI up to the part where you identify which application you are serving, if applicable (again, this is highly connector specific), while PATH_INFO should hold the rest of the URL. After building the environment the connector calls the application passing the environment to it, and collecting three return values: the HTTP status code, a table with headers, and the output iterator. The connector sends the status and headers right away to the server, as WSAPI does not guarantee any buffering itself. After that it begins calling the iterator and sending output to the server until it returns nil. The connectors are careful to treat errors gracefully: if they occur before sending the status and headers they return an "Error 500" page instead, if they occur while iterating over the response they append the error message to the response. --]] local loader = require "openLuup.loader" -- to create new environment in which to execute CGI script local logs = require "openLuup.logs" -- used for wsapi_env.error:write() local tables = require "openLuup.servertables" -- used for CGI aliases -- local log local function _log (msg, name) logs.send (msg, name or ABOUT.NAME) end logs.banner (ABOUT) -- for version control -- utilities local cache = {} -- cache for compiled CGIs -- return a dummy WSAPI app with error code and message local function dummy_app (status, message) local function iterator () -- one-shot iterator, returns message, then nil local x = message message = nil return x end local function run () -- dummy app entry point return status, { ["Content-Type"] = "text/plain" }, iterator end _log (message) return run -- return the entry point end -- build makes an application function for the connector local function build (script) local file = script -- CGI aliases: any matching full CGI path is redirected local alternative = tables.cgi_alias[file] -- 2016.05.30 and 2016.10.17 if alternative then _log (table.concat {"using ", alternative, " for ", file}) file = alternative end local f = io.open (file) if not f then return dummy_app (404, "file not found: " .. (file or '?')) end local line = f: read "*l" -- looking for first line of "#!/usr/bin/env wsapi.cgi" for WSAPI application local code if not line:match "^%s*#!/usr/bin/env%s+wsapi.cgi%s*$" then return dummy_app (501, "file is not a WSAPI application: " .. (script or '?')) end -- if it has a .lua extension, then we can use 'require' and this means that -- it can be easily debugged because the file is recognised by the IDE local lua_env local lua_file = file: match "(.*)%.lua$" if lua_file then _log ("using REQUIRE to load CGI " .. file) f: close () -- don't need it open lua_file = lua_file: gsub ('/','.') -- replace path separators with periods, for require path lua_env = require (lua_file) if type(lua_env) ~= "table" then _log ("error - require failed: " .. lua_file) lua_env = nil end else -- do it the hard way... code = f:read "*a" f: close () -- compile and load local a, error_msg = loadstring (code, script) -- load it if not a or error_msg then return dummy_app (500, error_msg) -- 'internal server error' end lua_env = loader.new_environment (script) -- use new environment setfenv (a, lua_env) -- Lua 5.1 specific function environment handling a, error_msg = pcall(a) -- instantiate it if not a then return dummy_app (500, error_msg) -- 'internal server error' end end -- find application entry point local runner = (lua_env or {}).run if (not runner) or (type (runner) ~= "function") then return dummy_app (500, "can't find WSAPI application entry point") -- 'internal server error' end return runner -- success! return the entry point to the WSAPI application end --[[ see: http://www.ietf.org/rfc/rfc3875 meta-variable-name = "AUTH_TYPE" | "CONTENT_LENGTH" | "CONTENT_TYPE" | "GATEWAY_INTERFACE" | "PATH_INFO" | "PATH_TRANSLATED" | "QUERY_STRING" | "REMOTE_ADDR" | "REMOTE_HOST" | "REMOTE_IDENT" | "REMOTE_USER" | "REQUEST_METHOD" | "SCRIPT_NAME" | "SERVER_NAME" | "SERVER_PORT" | "SERVER_PROTOCOL" | "SERVER_SOFTWARE" | scheme | protocol-var-name | extension-var-name also: http://www.cgi101.com/book/ch3/text.html DOCUMENT_ROOT The root directory of your server HTTP_COOKIE The visitor's cookie, if one is set HTTP_HOST The hostname of the page being attempted HTTP_REFERER The URL of the page that called your program HTTP_USER_AGENT The browser type of the visitor HTTPS "on" if the program is being called through a secure server PATH The system path your server is running under QUERY_STRING The query string (see GET, below) REMOTE_ADDR The IP address of the visitor REMOTE_HOST The hostname of the visitor (if your server has reverse-name-lookups on; else this is the IP address again) REMOTE_PORT The port the visitor is connected to on the web server REMOTE_USER The visitor's username (for .htaccess-protected pages) REQUEST_METHOD GET or POST REQUEST_URI The interpreted pathname of the requested document or CGI (relative to the document root) SCRIPT_FILENAME The full pathname of the current CGI SCRIPT_NAME The interpreted pathname of the current CGI (relative to the document root) SERVER_ADMIN The email address for your server's webmaster SERVER_NAME Your server's fully qualified domain name (e.g. www.cgi101.com) SERVER_PORT The port number your server is listening on SERVER_SOFTWARE The server software you're using (e.g. Apache 1.3) --]] -- build a WSAPI environment from parameters: -- url.path, url.query , {headers}, post_content_string, method_string, http_version_string -- only the first parameter is required local function make_env (path, query, headers, post_content, method, http_version) headers = headers or {} post_content = post_content or '' local meta = { __index = function () return '' end; -- return the empty string instead of nil for undefined metavariables } local ptr = 1 local input = { read = function (self, n) n = tonumber (n) or #post_content local start, finish = ptr, ptr + n - 1 ptr = ptr + n return post_content:sub (start, finish) end } local error = { write = function (self, ...) local msg = {path or '?', ':', ...} for i, m in ipairs(msg) do msg[i] = tostring(m) end -- ensure everything is a string _log (table.concat (msg, ' '), "openLuup.wsapi.cgi") end; } local env = { -- the WSAPI standard (and CGI) is upper case for these metavariables TEST = {headers = headers}, -- so that test CGIs (or unit tests) can examine all the headers -- note that the metatable will return an empty string for any undefined environment parameters ["CONTENT_LENGTH"] = #post_content, ["CONTENT_TYPE"] = headers["Content-Type"], ["HTTP_USER_AGENT"] = headers["User-Agent"], ["HTTP_COOKIE"] = headers["Cookie"], ["REMOTE_HOST"] = headers ["Host"], ["REMOTE_PORT"] = (headers ["Host"] or ''): match ":(%d+)$", ["REQUEST_METHOD"] = method or "GET", ["SCRIPT_NAME"] = path, ["SERVER_PROTOCOL"] = http_version or "HTTP/1.1", ["PATH_INFO"] = '/', ["QUERY_STRING"] = query, -- methods input = input, error = error, } return setmetatable (env, meta) end -- cgi is called by the server when it receives a GET or POST CGI request local function cgi (wsapi_env) -- 2019.07.28 now called with a pre-built environment! local script = wsapi_env.SCRIPT_NAME script = script: match "^/?(.-)/?$" -- ignore leading and trailing '/' cache[script] = cache[script] or build (script) -- guaranteed to be something executable here, even it it's a dummy with error message -- three return values: the HTTP status code, a table with headers, and the output iterator. -- catch any error during CGI execution -- it's essential to return from here with SOME kind of HTML page, -- so the usual error catch-all in the scheduler context switching is not sufficient. -- Errors during response iteration are caught by the HTTP servlet. local ok, status, responseHeaders, iterator = pcall (cache[script], wsapi_env) if not ok then local message = status _log ("ERROR: " .. message) status = 500 -- Internal server error responseHeaders = { ["Content-Type"] = "text/plain" } iterator = function () local x = message; message = nil; return x end end return status, responseHeaders, iterator end ------------------------------------------------------ -- -- The original WSAPI has a number of additional libraries -- see: https://keplerproject.github.io/wsapi/libraries.html -- here, the request, response, and util libraries are included. -- use in a CGI file like this: -- local wsapi = require "openLuup.wsapi" -- local req = wsapi.request.new(wsapi_env) -- local res = wsapi.response.new([status, headers]) ------------------------------------------------------ -- -- utility library, this is the verbatim keplerproject code -- see: https://github.com/keplerproject/wsapi/blob/master/src/wsapi/util.lua -- local function _M_util () local _M = {} ---------------------------------------------------------------------------- -- Decode an URL-encoded string (see RFC 2396) ---------------------------------------------------------------------------- function _M.url_decode(str) if not str then return nil end str = string.gsub (str, "+", " ") str = string.gsub (str, "%%(%x%x)", function(h) return string.char(tonumber(h,16)) end) str = string.gsub (str, "\r\n", "\n") return str end ---------------------------------------------------------------------------- -- URL-encode a string (see RFC 2396) ---------------------------------------------------------------------------- function _M.url_encode(str) if not str then return nil end str = string.gsub (str, "\n", "\r\n") str = string.gsub (str, "([^%w ])", function (c) return string.format ("%%%02X", string.byte(c)) end) str = string.gsub (str, " ", "+") return str end ---------------------------------------------------------------------------- -- Sanitizes all HTML tags ---------------------------------------------------------------------------- function _M.sanitize(text) return text:gsub(">", "&gt;"):gsub("<", "&lt;") end ---------------------------------------------------------------------------- -- Checks whether s is not nil or the empty string ---------------------------------------------------------------------------- function _M.not_empty(s) if s and s ~= "" then return s else return nil end end ---------------------------------------------------------------------------- -- Wraps the WSAPI environment to make the input rewindable, so you -- can parse postdata more than once, call wsapi_env.input:rewind() ---------------------------------------------------------------------------- function _M.make_rewindable(wsapi_env) local new_env = { input = { position = 1, contents = "" } } function new_env.input:read(size) local left = #self.contents - self.position + 1 local s if left < size then self.contents = self.contents .. wsapi_env.input:read(size - left) s = self.contents:sub(self.position) self.position = #self.contents + 1 else s = self.contents:sub(self.position, self.position + size) self.position = self.position + size end if s == "" then return nil else return s end end function new_env.input:rewind() self.position = 1 end return setmetatable(new_env, { __index = wsapi_env, __newindex = wsapi_env }) end ---------------------------------------------------------------------------- -- getopt, POSIX style command line argument parser -- param arg contains the command line arguments in a standard table. -- param options is a string with the letters that expect string values. -- returns a table where associated keys are true, nil, or a string value. -- The following example styles are supported -- -a one ==> opts["a"]=="one" -- -bone ==> opts["b"]=="one" -- -c ==> opts["c"]==true -- --c=one ==> opts["c"]=="one" -- -cdaone ==> opts["c"]==true opts["d"]==true opts["a"]=="one" -- note POSIX demands the parser ends at the first non option -- this behavior isn't implemented. ---------------------------------------------------------------------------- function _M.getopt( arg, options ) local tab, args = {}, {} local k = 1 while k <= #arg do local v = arg[k] if string.sub( v, 1, 2) == "--" then local x = string.find( v, "=", 1, true ) if x then tab[ string.sub( v, 3, x-1 ) ] = string.sub( v, x+1 ) else tab[ string.sub( v, 3 ) ] = true end k = k + 1 elseif string.sub( v, 1, 1 ) == "-" then local y = 2 local l = #v local jopt local next = 1 while ( y <= l ) do jopt = string.sub( v, y, y ) if string.find( options, jopt, 1, true ) then if y < l then tab[ jopt ] = string.sub( v, y+1 ) y = l else tab[ jopt ] = arg[ k + 1 ] next = 2 end else tab[ jopt ] = true end y = y + 1 end k = k + next else args[#args + 1] = v k = k + 1 end end return tab, args end ---------------------------------------------------------------------------- -- Makes a mock WSAPI environment with GET method and the provided -- query string ---------------------------------------------------------------------------- function _M.make_env_get(qs) return { REQUEST_METHOD = "GET", QUERY_STRING = qs or "", CONTENT_LENGTH = 0, PATH_INFO = "/", SCRIPT_NAME = "", CONTENT_TYPE = "x-www-form-urlencoded", input = { read = function () return nil end }, error = { messages = {}, write = function (self, msg) self.messages[#self.messages+1] = msg end } } end ---------------------------------------------------------------------------- -- Makes a mock WSAPI environment with POST method and the provided -- postdata, type (x-www-form-urlenconded default) and query string ---------------------------------------------------------------------------- function _M.make_env_post(pd, type, qs) pd = pd or "" return { REQUEST_METHOD = "POST", QUERY_STRING = qs or "", CONTENT_LENGTH = #pd, PATH_INFO = "/", CONTENT_TYPE = type or "x-www-form-urlencoded", SCRIPT_NAME = "", input = { post_data = pd, current = 1, read = function (self, len) if self.current > #self.post_data then return nil end local s = self.post_data:sub(self.current, len) self.current = self.current + len return s end }, error = { messages = {}, write = function (self, msg) self.messages[#self.messages+1] = msg end } } end function _M.loadfile(filename, env) if _VERSION ~= "Lua 5.1" then return loadfile(filename, "bt", env) else local f, err = loadfile(filename) if not f then return nil, err end setfenv(f, env) return f end end return _M end local util = _M_util () -- create version for the following to access ---------- -- -- request library, this is the verbatim keplerproject code -- see: https://github.com/keplerproject/wsapi/blob/master/src/wsapi/request.lua -- local function _M_request () -- local util = require"wsapi.util" local _M = {} local function split_filename(path) local name_patt = "[/\\]?([^/\\]+)$" return (string.match(path, name_patt)) end local function insert_field (tab, name, value, overwrite) if overwrite or not tab[name] then tab[name] = value else local t = type (tab[name]) if t == "table" then table.insert (tab[name], value) else tab[name] = { tab[name], value } end end end local function parse_qs(qs, tab, overwrite) tab = tab or {} if type(qs) == "string" then local url_decode = util.url_decode for key, val in string.gmatch(qs, "([^&=]+)=([^&=]*)&?") do insert_field(tab, url_decode(key), url_decode(val), overwrite) end elseif qs then error("WSAPI Request error: invalid query string") end return tab end local function get_boundary(content_type) local boundary = string.match(content_type, "boundary%=(.-)$") return "--" .. tostring(boundary) end local function break_headers(header_data) local headers = {} for type, val in string.gmatch(header_data, '([^%c%s:]+):%s+([^\n]+)') do type = string.lower(type) headers[type] = val end return headers end local function read_field_headers(input, pos) local EOH = "\r\n\r\n" local s, e = string.find(input, EOH, pos, true) if s then return break_headers(string.sub(input, pos, s-1)), e+1 else return nil, pos end end local function get_field_names(headers) local disp_header = headers["content-disposition"] or "" local attrs = {} for attr, val in string.gmatch(disp_header, ';%s*([^%s=]+)="(.-)"') do attrs[attr] = val end return attrs.name, attrs.filename and split_filename(attrs.filename) end local function read_field_contents(input, boundary, pos) local boundaryline = "\r\n" .. boundary local s, e = string.find(input, boundaryline, pos, true) if s then return string.sub(input, pos, s-1), s-pos, e+1 else return nil, 0, pos end end local function file_value(file_contents, file_name, file_size, headers) local value = { contents = file_contents, name = file_name, size = file_size } for h, v in pairs(headers) do if h ~= "content-disposition" then value[h] = v end end return value end local function fields(input, boundary) local state, _ = { } _, state.pos = string.find(input, boundary, 1, true) state.pos = state.pos + 1 return function (state, _) local headers, name, file_name, value, size headers, state.pos = read_field_headers(input, state.pos) if headers then name, file_name = get_field_names(headers) if file_name then value, size, state.pos = read_field_contents(input, boundary, state.pos) value = file_value(value, file_name, size, headers) else value, size, state.pos = read_field_contents(input, boundary, state.pos) end end return name, value end, state end local function parse_multipart_data(input, input_type, tab, overwrite) tab = tab or {} local boundary = get_boundary(input_type) for name, value in fields(input, boundary) do insert_field(tab, name, value, overwrite) end return tab end local function parse_post_data(wsapi_env, tab, overwrite) tab = tab or {} local input_type = wsapi_env.CONTENT_TYPE if string.find(input_type, "x-www-form-urlencoded", 1, true) then local length = tonumber(wsapi_env.CONTENT_LENGTH) or 0 parse_qs(wsapi_env.input:read(length) or "", tab, overwrite) elseif string.find(input_type, "multipart/form-data", 1, true) then local length = tonumber(wsapi_env.CONTENT_LENGTH) or 0 if length > 0 then parse_multipart_data(wsapi_env.input:read(length) or "", input_type, tab, overwrite) end else local length = tonumber(wsapi_env.CONTENT_LENGTH) or 0 tab.post_data = wsapi_env.input:read(length) or "" end return tab end _M.methods = {} local methods = _M.methods function methods.__index(tab, name) local func if methods[name] then func = methods[name] else local route_name = name:match("link_([%w_]+)") if route_name then func = function (self, query, ...) return tab:route_link(route_name, query, ...) end end end tab[name] = func return func end function methods:qs_encode(query, url) local parts = {} for k, v in pairs(query or {}) do parts[#parts+1] = k .. "=" .. util.url_encode(v) end if #parts > 0 then return (url and (url .. "?") or "") .. table.concat(parts, "&") else return (url and url or "") end end function methods:route_link(route, query, ...) local builder = self.mk_app["link_" .. route] if builder then local uri = builder(self.mk_app, self.env, ...) local qs = self:qs_encode(query) return uri .. (qs ~= "" and ("?"..qs) or "") else error("there is no route named " .. route) end end function methods:link(url, query) local prefix = (self.mk_app and self.mk_app.prefix) or self.script_name -- local uri = prefix .. url local qs = self:qs_encode(query) return prefix .. url .. (qs ~= "" and ("?"..qs) or "") end function methods:absolute_link(url, query) local qs = self:qs_encode(query) return url .. (qs ~= "" and ("?"..qs) or "") end function methods:static_link(url) local prefix = (self.mk_app and self.mk_app.prefix) or self.script_name local is_script = prefix:match("(%.%w+)$") if not is_script then return self:link(url) end local vpath = prefix:match("(.*)/") or "" return vpath .. url end function methods:empty(s) return not s or string.match(s, "^%s*$") end function methods:empty_param(param) return self:empty(self.params[param]) end function _M.new(wsapi_env, options) options = options or {} local req = { GET = {}, POST = {}, method = wsapi_env.REQUEST_METHOD, path_info = wsapi_env.PATH_INFO, query_string = wsapi_env.QUERY_STRING, script_name = wsapi_env.SCRIPT_NAME, env = wsapi_env, mk_app = options.mk_app, doc_root = wsapi_env.DOCUMENT_ROOT, app_path = wsapi_env.APP_PATH } parse_qs(wsapi_env.QUERY_STRING, req.GET, options.overwrite) if options.delay_post then req.parse_post = function (self) parse_post_data(wsapi_env, self.POST, options.overwrite) self.parse_post = function () return nil, "postdata already parsed" end return self.POST end else parse_post_data(wsapi_env, req.POST, options.overwrite) req.parse_post = function () return nil, "postdata already parsed" end end req.params = {} setmetatable(req.params, { __index = function (tab, name) local var = req.GET[name] or req.POST[name] rawset(tab, name, var) return var end}) req.cookies = {} local cookies = string.gsub(";" .. (wsapi_env.HTTP_COOKIE or "") .. ";", "%s*;%s*", ";") setmetatable(req.cookies, { __index = function (tab, name) name = name local pattern = ";" .. name .. "=(.-);" local cookie = string.match(cookies, pattern) cookie = util.url_decode(cookie) rawset(tab, name, cookie) return cookie end}) return setmetatable(req, methods) end return _M end ---------- -- -- response library, this is the verbatim keplerproject code -- see: https://github.com/keplerproject/wsapi/blob/master/src/wsapi/response.lua -- local function _M_response () -- local util = require"wsapi.util" local date = os.date local format = string.format local _M = {} local methods = {} methods.__index = methods _M.methods = methods local unpack = table.unpack or unpack function methods:write(...) for _, s in ipairs{ ... } do if type(s) == "table" then self:write(unpack(s)) elseif s then local s = tostring(s) self.body[#self.body+1] = s self.length = self.length + #s end end end function methods:forward(url) self.env.PATH_INFO = url or self.env.PATH_INFO return "MK_FORWARD" end function methods:finish() self.headers["Content-Length"] = self.length return self.status, self.headers, coroutine.wrap(function () for _, s in ipairs(self.body) do coroutine.yield(s) end end) end local function optional (what, name) if name ~= nil and name ~= "" then return format("; %s=%s", what, name) else return "" end end local function optional_flag(what, isset) if isset then return format("; %s", what) end return "" end local function make_cookie(name, value) local options = {} local t if type(value) == "table" then options = value value = value.value end local cookie = name .. "=" .. util.url_encode(value) if options.expires then t = date("!%A, %d-%b-%Y %H:%M:%S GMT", options.expires) cookie = cookie .. optional("expires", t) end if options.max_age then t = date("!%A, %d-%b-%Y %H:%M:%S GMT", options.max_age) cookie = cookie .. optional("Max-Age", t) end cookie = cookie .. optional("path", options.path) cookie = cookie .. optional("domain", options.domain) cookie = cookie .. optional_flag("secure", options.secure) cookie = cookie .. optional_flag("HttpOnly", options.httponly) return cookie end function methods:set_cookie(name, value) local cookie = self.headers["Set-Cookie"] if type(cookie) == "table" then table.insert(self.headers["Set-Cookie"], make_cookie(name, value)) elseif type(cookie) == "string" then self.headers["Set-Cookie"] = { cookie, make_cookie(name, value) } else self.headers["Set-Cookie"] = make_cookie(name, value) end end function methods:delete_cookie(name, path, domain) self:set_cookie(name, { value = "xxx", expires = 1, path = path, domain = domain }) end function methods:redirect(url) self.status = 302 self.headers["Location"] = url self.body = {} return self:finish() end function methods:content_type(type) self.headers["Content-Type"] = type end function _M.new(status, headers) status = status or 200 headers = headers or {} if not headers["Content-Type"] then headers["Content-Type"] = "text/html" end return setmetatable({ status = status, headers = headers, body = {}, length = 0 }, methods) end return _M end ---------- return { ABOUT = ABOUT, TEST = {build = build}, -- access to 'build' for testing cgi = cgi, -- called by the server to process a CGI request make_env = make_env, -- create wsapi_env from basic HTTP request -- modules util = util, -- already instantiated request = _M_request (), response = _M_response (), } -----
apache-2.0
KittyCookie/skynet
service/launcher.lua
51
3199
local skynet = require "skynet" local core = require "skynet.core" require "skynet.manager" -- import manager apis local string = string local services = {} local command = {} local instance = {} -- for confirm (function command.LAUNCH / command.ERROR / command.LAUNCHOK) local function handle_to_address(handle) return tonumber("0x" .. string.sub(handle , 2)) end local NORET = {} function command.LIST() local list = {} for k,v in pairs(services) do list[skynet.address(k)] = v end return list end function command.STAT() local list = {} for k,v in pairs(services) do local stat = skynet.call(k,"debug","STAT") list[skynet.address(k)] = stat end return list end function command.KILL(_, handle) handle = handle_to_address(handle) skynet.kill(handle) local ret = { [skynet.address(handle)] = tostring(services[handle]) } services[handle] = nil return ret end function command.MEM() local list = {} for k,v in pairs(services) do local kb, bytes = skynet.call(k,"debug","MEM") list[skynet.address(k)] = string.format("%.2f Kb (%s)",kb,v) end return list end function command.GC() for k,v in pairs(services) do skynet.send(k,"debug","GC") end return command.MEM() end function command.REMOVE(_, handle, kill) services[handle] = nil local response = instance[handle] if response then -- instance is dead response(not kill) -- return nil to caller of newservice, when kill == false instance[handle] = nil end -- don't return (skynet.ret) because the handle may exit return NORET end local function launch_service(service, ...) local param = table.concat({...}, " ") local inst = skynet.launch(service, param) local response = skynet.response() if inst then services[inst] = service .. " " .. param instance[inst] = response else response(false) return end return inst end function command.LAUNCH(_, service, ...) launch_service(service, ...) return NORET end function command.LOGLAUNCH(_, service, ...) local inst = launch_service(service, ...) if inst then core.command("LOGON", skynet.address(inst)) end return NORET end function command.ERROR(address) -- see serivce-src/service_lua.c -- init failed local response = instance[address] if response then response(false) instance[address] = nil end services[address] = nil return NORET end function command.LAUNCHOK(address) -- init notice local response = instance[address] if response then response(true, address) instance[address] = nil end return NORET end -- for historical reasons, launcher support text command (for C service) skynet.register_protocol { name = "text", id = skynet.PTYPE_TEXT, unpack = skynet.tostring, dispatch = function(session, address , cmd) if cmd == "" then command.LAUNCHOK(address) elseif cmd == "ERROR" then command.ERROR(address) else error ("Invalid text command " .. cmd) end end, } skynet.dispatch("lua", function(session, address, cmd , ...) cmd = string.upper(cmd) local f = command[cmd] if f then local ret = f(address, ...) if ret ~= NORET then skynet.ret(skynet.pack(ret)) end else skynet.ret(skynet.pack {"Unknown command"} ) end end) skynet.start(function() end)
mit
aboshosho/aboshosho
plugins/ar-plugins.lua
13
7118
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY SAJJAD NOORI ▀▄ ▄▀ ▀▄ ▄▀ BY SAJAD NOORI (@SAJJADNOORI) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY SAJJAD NOORI ▀▄ ▄▀ ▀▄ ▄▀ plugins : تفعيل الملفات ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'. '..v..' '..status..'\n' end end local text = text..'\n الملفات المثبته 🔨. '..nsum..'\nالملفات المفعله ✔️ .'..nact..'\nغير مفعل 🚫 '..nsum-nact..'' return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..v..' '..status..'\n' end end local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.' return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return 'اَلـَمِلفَ 📙 '..plugin_name..' مفـَعـلَِ 👍🏻 ✔️' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return ''..plugin_name..' ✋🏿لآَ يـَوْجـدِ مـلفَ 📙 بأسـم ' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return ''..name..' ✋🏿لآَ يـَوْجـدِ مـلفَ 📙 بأسـم ' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return 'اَلـَمِلفَ 📙 '..name..' غـيرَ مفـَعـلَِ 👍🏻 ❌' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return 'Plugin '..plugin..' disabled on this chat' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return 'Plugin '..plugin..' is enabled again' end local function run(msg, matches) -- Show the available plugins if matches[1] == 'الملفات' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == 'تفعيل ملف' and matches[3] == 'chat' then local receiver = get_receiver(msg) local plugin = matches[2] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin) end -- Enable a plugin if matches[1] == 'تفعيل ملف' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end -- Disable a plugin on a chat if matches[1] == 'تعطيل ملف' and matches[3] == 'chat' then local plugin = matches[2] local receiver = get_receiver(msg) print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin) end -- Disable a plugin if matches[1] == 'تعطيل ملف' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == 'الملفات المفعله' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plugins disable [plugin] chat : disable plugin only this chat.", "!plugins enable [plugin] chat : enable plugin only this chat.", }, sudo = { "!plugins : list all plugins.", "!plugins enable [plugin] : enable plugin.", "!plugins disable [plugin] : disable plugin.", "!plugins reload : reloads all plugins." }, }, patterns = { "^الملفات$", "^(تفعيل ملف) ([%w_%.%-]+)$", "^(تعطيل ملف) ([%w_%.%-]+)$", "^(تفعيل ملف) ([%w_%.%-]+) (chat)", "^(تعطيل ملف) ([%w_%.%-]+) (chat)", "^(الملفات المفعله)$" }, run = run, moderated = true, -- set to moderator mode --privileged = true } end
agpl-3.0
fredcadete/meta-openembedded
meta-gnome/recipes-gnome/devilspie/files/default.lua
40
1194
-- Copyright (c) 2012 Andreas Müller <schnitzeltony@googlemail.com> -- -- this is an example -- * undecorating all windows opened maximized -- * maximizing and undecorating all appplication's windows in apps_list -- for further information see -- http://www.gusnan.se/devilspie2/manual.php wnd_type = get_window_type() if(wnd_type == "WINDOW_TYPE_NORMAL") then -- add only applications you want maximized+undecorated and -- which don't keep maximized state apps_list = { "Terminal", "ristretto", "xarchiver", } app_name = get_application_name() -- to have some informational output, start devilspie2 with --debug -- option and uncomment the following lines: --debug_print ("Window Name: " .. get_window_name()) --debug_print ("Application name: " .. app_name) --debug_print ("window-type: " .. wnd_type) -- undecorate all windows starting maximized if (get_window_is_maximized()) then undecorate_window() -- maximize/undecorate all windows in apps_list -- (unfortunately for some also their settings) else for line, str in ipairs(apps_list) do if (string.find(app_name, str)) then maximize() undecorate_window() break end end end end
mit
ralucah/splay-daemon-lua5.2
modules/splay/benc.lua
1
5232
--[[ Splay ### v1.2 ### Copyright 2006-2011 http://www.splay-project.org ]] --[[ This file is part of Splay. Splay is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Splay 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 Splayd. If not, see <http://www.gnu.org/licenses/>. ]] local table = require"table" local string = require"string" local llenc = require"splay.llenc" local misc = require"splay.misc" local pairs = pairs local pcall = pcall local setmetatable = setmetatable local tonumber = tonumber local tostring = tostring local type = type --module("splay.benc") local splay_benc = {} --_COPYRIGHT = "Copyright 2006 - 2011" --_DESCRIPTION = "Enhanced bencoding for Lua" --_VERSION = 1.0 local pos = 1 local data = nil local function pop() local t = string.sub(data, pos, pos) pos = pos + 1 return t end local function back() pos = pos - 1 end function splay_benc.decode(d) if d then data = d pos = 1 end local item = pop() if item == 'd' then -- dictionnary (table) local hash = {} item = pop() while item ~= 'e' do back() local key = decode() hash[key] = decode() item = pop() end return hash elseif item == 'n' then -- extension of benc return nil elseif item == 't' then -- extension of benc return true elseif item == 'f' then -- extension of benc return false elseif item == 'l' then -- list item = pop() local list = {} while item ~= 'e' do back() list[#list + 1] = decode() item = pop() end return list elseif item == 'i' then -- integer item = pop() local num = '' while item ~= 'e' do num = num..item item = pop() end return num * 1 else -- strings (default) local length = 0 while item ~= ':' do length = length * 10 + tonumber(item) item = pop() end pos = pos + length return string.sub(data, pos - length, pos - 1) end end --[[ Highly optimized version of encode(): avoid as much as possible string concatanation, do it only once at the end of the table traversal using fast table.concat. A secondary encode_table function supports this traversal. ]]-- local function encode_table(data,out) local t = type(data) if t == 'table' then -- list(array) or hash local i = 1 local list = true for k, v in pairs(data) do if k ~= i then list = false break end i = i + 1 end if list then out[out.n] = 'l' out.n = out.n + 1 for k, v in pairs(data) do encode_table(v, out) end else -- hash out[out.n] = 'd' out.n = out.n + 1 for k, v in pairs(data) do encode_table(k, out) encode_table(v, out) end end out[out.n] = 'e' out.n = out.n + 1 elseif t == 'string' then out[out.n] = tostring(#data); out.n = out.n + 1 out[out.n] = ":" out.n = out.n + 1 out[out.n] = data out.n = out.n + 1 elseif t == 'number' then -- we need to convert scientific notation to decimal out[out.n] = 'i' out.n = out.n + 1 out[out.n] = misc.to_dec_string(data) out.n = out.n + 1 out[out.n] = 'e' out.n = out.n + 1 elseif t == 'nil' then -- extension of benc out[out.n] = 'n' out.n = out.n + 1 elseif t == 'boolean' then -- extension of benc if data then out[out.n] = 't' out.n = out.n + 1 else out[out.n] = 'f' out.n = out.n + 1 end end end function splay_benc.encode(data) local out = { n=1 } encode_table(data, out) return table.concat(out) end function splay_benc.send(socket, data) return socket:send(splay_benc.encode(data)) end function splay_benc.receive(socket) local data, status = socket:receive() if not data then return nil, status end local ok, data = pcall(function() return splay_benc.decode(data) end) if ok then return data else return nil, "corrupted" end end -- Socket wrapper -- Use only with ':' methods or xxx.super:method() if you want to use the -- original one. function splay_benc.wrap(socket, err) if string.find(tostring(socket), "#BENC") then return socket end -- error forwarding if not socket then return nil, err end socket = llenc.wrap(socket) local wrap_obj = {} wrap_obj.super = socket local mt = {} -- This socket is called with ':', so the 'self' refer to him but, in -- the call, self is the wrapping table, we need to replace it by the socket. mt.__index = function(table, key) if type(socket[key]) ~= "function" then return socket[key] else return function(self, ...) return socket[key](socket, ...) end end end mt.__tostring = function() return "#BENC: " .. tostring(socket) end setmetatable(wrap_obj, mt) wrap_obj.send = function(self, data) return splay_benc.send(self.super, data) end wrap_obj.receive = function(self, max_length) return splay_benc.receive(self.super, max_length) end return wrap_obj end return splay_benc
gpl-3.0
dacrybabysuck/darkstar
scripts/commands/jail.lua
9
2044
--------------------------------------------------------------------------------------------------- -- func: jail -- desc: Sends the target player to jail. (Mordion Gaol) --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "sis" }; function onTrigger(player, target, cellId, reason) local jailCells = { -- Floor 1 (Bottom) {-620, 11, 660, 0}, {-180, 11, 660, 0}, {260, 11, 660, 0}, {700, 11, 660, 0}, {-620, 11, 220, 0}, {-180, 11, 220, 0}, {260, 11, 220, 0}, {700, 11, 220, 0}, {-620, 11, -220, 0}, {-180, 11, -220, 0}, {260, 11, -220, 0}, {700, 11, -220, 0}, {-620, 11, -620, 0}, {-180, 11, -620, 0}, {260, 11, -620, 0}, {700, 11, -620, 0}, -- Floor 2 (Top) {-620, -400, 660, 0}, {-180, -400, 660, 0}, {260, -400, 660, 0}, {700, -400, 660, 0}, {-620, -400, 220, 0}, {-180, -400, 220, 0}, {260, -400, 220, 0}, {700, -400, 220, 0}, {-620, -400, -220, 0}, {-180, -400, -220, 0}, {260, -400, -220, 0}, {700, -400, -220, 0}, {-620, -400, -620, 0}, {-180, -400, -620, 0}, {260, -400, -620, 0}, {700, -400, -620, 0}, }; -- Validate the target.. local targ = GetPlayerByName( target ); if (targ == nil) then player:PrintToPlayer( string.format( "Invalid player '%s' given.", target ) ); return; end -- Validate the cell id.. if (cellId == nil or cellId == 0 or cellId > 32) then cellId = 1; end -- Validate the reason.. if (reason == nil) then reason = "Unspecified."; end -- Print that we have jailed someone.. local message = string.format( '%s jailed %s(%d) into cell %d. Reason: %s', player:getName(), target, targ:getID(), cellId, reason ); printf( message ); -- Send the target to jail.. local dest = jailCells[ cellId ]; targ:setCharVar( "inJail", cellId ); targ:setPos( dest[1], dest[2], dest[3], dest[4], 131 ); end
gpl-3.0
cmingjian/skynet
lualib/skynet/datasheet/builder.lua
4
3802
local skynet = require "skynet" local dump = require "skynet.datasheet.dump" local core = require "skynet.datasheet.core" local service = require "skynet.service" local builder = {} local cache = {} local dataset = {} local address local unique_id = 0 local function unique_string(str) unique_id = unique_id + 1 return str .. tostring(unique_id) end local function monitor(pointer) skynet.fork(function() skynet.call(address, "lua", "collect", pointer) for k,v in pairs(cache) do if v == pointer then cache[k] = nil return end end end) end local function dumpsheet(v) if type(v) == "string" then return v else return dump.dump(v) end end function builder.new(name, v) assert(dataset[name] == nil) local datastring = unique_string(dumpsheet(v)) local pointer = core.stringpointer(datastring) skynet.call(address, "lua", "update", name, pointer) cache[datastring] = pointer dataset[name] = datastring monitor(pointer) end function builder.update(name, v) local lastversion = assert(dataset[name]) local newversion = dumpsheet(v) local diff = unique_string(dump.diff(lastversion, newversion)) local pointer = core.stringpointer(diff) skynet.call(address, "lua", "update", name, pointer) cache[diff] = pointer local lp = assert(cache[lastversion]) skynet.send(address, "lua", "release", lp) dataset[name] = diff monitor(pointer) end function builder.compile(v) return dump.dump(v) end local function datasheet_service() local skynet = require "skynet" local datasheet = {} local handles = {} -- handle:{ ref:count , name:name , collect:resp } local dataset = {} -- name:{ handle:handle, monitor:{monitors queue} } local function releasehandle(handle) local h = handles[handle] h.ref = h.ref - 1 if h.ref == 0 and h.collect then h.collect(true) h.collect = nil handles[handle] = nil end end -- from builder, create or update handle function datasheet.update(name, handle) local t = dataset[name] if not t then -- new datasheet t = { handle = handle, monitor = {} } dataset[name] = t handles[handle] = { ref = 1, name = name } else t.handle = handle -- report update to customers handles[handle] = { ref = 1 + #t.monitor, name = name } for k,v in ipairs(t.monitor) do v(true, handle) t.monitor[k] = nil end end skynet.ret() end -- from customers function datasheet.query(name) local t = assert(dataset[name], "create data first") local handle = t.handle local h = handles[handle] h.ref = h.ref + 1 skynet.ret(skynet.pack(handle)) end -- from customers, monitor handle change function datasheet.monitor(handle) local h = assert(handles[handle], "Invalid data handle") local t = dataset[h.name] if t.handle ~= handle then -- already changes skynet.ret(skynet.pack(t.handle)) else h.ref = h.ref + 1 table.insert(t.monitor, skynet.response()) end end -- from customers, release handle , ref count - 1 function datasheet.release(handle) -- send message, don't ret releasehandle(handle) end -- from builder, monitor handle release function datasheet.collect(handle) local h = assert(handles[handle], "Invalid data handle") if h.ref == 0 then handles[handle] = nil skynet.ret() else assert(h.collect == nil, "Only one collect allows") h.collect = skynet.response() end end skynet.dispatch("lua", function(_,_,cmd,...) datasheet[cmd](...) end) skynet.info_func(function() local info = {} local tmp = {} for k,v in pairs(handles) do tmp[k] = v end for k,v in pairs(dataset) do local h = handles[v.handle] tmp[v.handle] = nil info[k] = { handle = v.handle, monitors = #v.monitor, } end for k,v in pairs(tmp) do info[k] = v.ref end return info end) end skynet.init(function() address=service.new("datasheet", datasheet_service) end) return builder
mit
dacrybabysuck/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/Brazier.lua
9
2985
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Brazier -- Involved in Quests: Save my Sister -- !pos 101 -33 -59 195 (F-9) -- !pos 259 -33 99 195 (H-7) -- !pos 99 -33 98 195 (F-7) -- !pos 259 -33 -58 195 (H-9) ----------------------------------- local ID = require("scripts/zones/The_Eldieme_Necropolis/IDs") require("scripts/globals/keyitems") require("scripts/globals/quests") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) if player:getQuestStatus(JEUNO, dsp.quest.id.jeuno.SAVE_MY_SISTER) == QUEST_ACCEPTED and player:getCharVar("saveMySisterFireLantern") < 4 then player:setCharVar("saveMySisterLanternID", npc:getID()) player:startEvent(44) else player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if csid == 44 and option == 0 then local lanternOrder = player:getCharVar("saveMySisterFireLantern") local offset = player:getCharVar("saveMySisterLanternID") - ID.npc.BRAZIER_OFFSET player:setCharVar("saveMySisterLanternID", 0) if lanternOrder == 0 then if offset == 0 then -- (F-9) player:messageSpecial(ID.text.THE_LIGHT_DIMLY, 0, 0, 0, dsp.ki.DUCAL_GUARDS_LANTERN_LIT) player:setCharVar("saveMySisterFireLantern", 1) else player:messageSpecial(ID.text.REFUSE_TO_LIGHT, 0, 0, 0, dsp.ki.DUCAL_GUARDS_LANTERN_LIT) end elseif lanternOrder == 1 then if offset == 1 then -- (H-7) player:messageSpecial(ID.text.THE_LIGHT_HAS_INTENSIFIED, 0, 0, 0, dsp.ki.DUCAL_GUARDS_LANTERN_LIT) player:setCharVar("saveMySisterFireLantern", 2) else player:messageSpecial(ID.text.LANTERN_GOES_OUT, 0, 0, 0, dsp.ki.DUCAL_GUARDS_LANTERN_LIT) player:setCharVar("saveMySisterFireLantern", 0) end elseif lanternOrder == 2 then if offset == 2 then -- (F-7) player:messageSpecial(ID.text.THE_LIGHT_HAS_INTENSIFIED, 0, 0, 0, dsp.ki.DUCAL_GUARDS_LANTERN_LIT) player:setCharVar("saveMySisterFireLantern", 3) else player:messageSpecial(ID.text.LANTERN_GOES_OUT, 0, 0, 0, dsp.ki.DUCAL_GUARDS_LANTERN_LIT) player:setCharVar("saveMySisterFireLantern", 0) end elseif lanternOrder == 3 then if offset == 3 then -- (H-9) player:messageSpecial(ID.text.THE_LIGHT_IS_FULLY_LIT, 0, 0, 0, dsp.ki.DUCAL_GUARDS_LANTERN_LIT) player:setCharVar("saveMySisterFireLantern", 4) else player:messageSpecial(ID.text.LANTERN_GOES_OUT, 0, 0, 0, dsp.ki.DUCAL_GUARDS_LANTERN_LIT) player:setCharVar("saveMySisterFireLantern", 0) end end end end
gpl-3.0
dcourtois/premake-core
src/tools/msc.lua
2
8887
--- -- msc.lua -- Interface for the MS C/C++ compiler. -- Author Jason Perkins -- Modified by Manu Evans -- Copyright (c) 2009-2015 Jason Perkins and the Premake project --- local p = premake p.tools.msc = {} local msc = p.tools.msc local project = p.project local config = p.config -- -- Returns list of C preprocessor flags for a configuration. -- function msc.getcppflags(cfg) return {} end -- -- Returns list of C compiler flags for a configuration. -- local function getRuntimeFlag(cfg, isstatic) local rt = cfg.runtime local flag = iif(isstatic, "/MT", "/MD") if (rt == "Debug") or (rt == nil and config.isDebugBuild(cfg)) then flag = flag .. "d" end return flag end msc.shared = { clr = { On = "/clr", Unsafe = "/clr", Pure = "/clr:pure", Safe = "/clr:safe", }, flags = { FatalCompileWarnings = "/WX", LinkTimeOptimization = "/GL", MultiProcessorCompile = "/MP", NoMinimalRebuild = "/Gm-", OmitDefaultLibrary = "/Zl" }, floatingpoint = { Fast = "/fp:fast", Strict = "/fp:strict", }, floatingpointexceptions = { On = "/fp:except", Off = "/fp:except-", }, functionlevellinking = { On = "/Gy", Off = "/Gy-", }, callingconvention = { Cdecl = "/Gd", FastCall = "/Gr", StdCall = "/Gz", VectorCall = "/Gv", }, intrinsics = { On = "/Oi", }, optimize = { Off = "/Od", On = "/Ot", Debug = "/Od", Full = "/Ox", Size = "/O1", Speed = "/O2", }, vectorextensions = { AVX = "/arch:AVX", AVX2 = "/arch:AVX2", SSE = "/arch:SSE", SSE2 = "/arch:SSE2", SSE3 = "/arch:SSE2", SSSE3 = "/arch:SSE2", ["SSE4.1"] = "/arch:SSE2", ["SSE4.2"] = "/arch:SSE2", }, warnings = { Off = "/W0", High = "/W4", Extra = "/W4", Everything = "/Wall", }, externalwarnings = { Off = "/external:W0", Default = "/external:W3", High = "/external:W4", Extra = "/external:W4", Everything = "/external:W4", }, externalanglebrackets = { On = "/external:anglebrackets", }, staticruntime = { -- this option must always be emit (does it??) _ = function(cfg) return getRuntimeFlag(cfg, false) end, -- runtime defaults to dynamic in VS Default = function(cfg) return getRuntimeFlag(cfg, false) end, On = function(cfg) return getRuntimeFlag(cfg, true) end, Off = function(cfg) return getRuntimeFlag(cfg, false) end, }, stringpooling = { On = "/GF", Off = "/GF-", }, symbols = { On = "/Z7" }, unsignedchar = { On = "/J", }, omitframepointer = { On = "/Oy" }, justmycode = { On = "/JMC", Off = "/JMC-" }, openmp = { On = "/openmp", Off = "/openmp-" } } msc.cflags = { } function msc.getcflags(cfg) local shared = config.mapFlags(cfg, msc.shared) local cflags = config.mapFlags(cfg, msc.cflags) local flags = table.join(shared, cflags, msc.getwarnings(cfg)) return flags end -- -- Returns list of C++ compiler flags for a configuration. -- msc.cxxflags = { exceptionhandling = { Default = "/EHsc", On = "/EHsc", SEH = "/EHa", }, rtti = { Off = "/GR-" } } function msc.getcxxflags(cfg) local shared = config.mapFlags(cfg, msc.shared) local cxxflags = config.mapFlags(cfg, msc.cxxflags) local flags = table.join(shared, cxxflags, msc.getwarnings(cfg)) return flags end -- -- Decorate defines for the MSVC command line. -- msc.defines = { characterset = { Default = { '/D"_UNICODE"', '/D"UNICODE"' }, MBCS = '/D"_MBCS"', Unicode = { '/D"_UNICODE"', '/D"UNICODE"' }, ASCII = { }, } } function msc.getdefines(defines, cfg) local result -- HACK: I need the cfg to tell what the character set defines should be. But -- there's lots of legacy code using the old getdefines(defines) signature. -- For now, detect one or two arguments and apply the right behavior; will fix -- it properly when the I roll out the adapter overhaul if cfg and defines then result = config.mapFlags(cfg, msc.defines) else result = {} end for _, define in ipairs(defines) do table.insert(result, '/D"' .. define .. '"') end if cfg and cfg.exceptionhandling == p.OFF then table.insert(result, "/D_HAS_EXCEPTIONS=0") end return result end function msc.getundefines(undefines) local result = {} for _, undefine in ipairs(undefines) do table.insert(result, '/U"' .. undefine .. '"') end return result end -- -- Returns a list of forced include files, decorated for the compiler -- command line. -- -- @param cfg -- The project configuration. -- @return -- An array of force include files with the appropriate flags. -- function msc.getforceincludes(cfg) local result = {} table.foreachi(cfg.forceincludes, function(value) local fn = project.getrelative(cfg.project, value) table.insert(result, "/FI" .. p.quoted(fn)) end) return result end function msc.getrunpathdirs() return {} end -- -- Decorate include file search paths for the MSVC command line. -- function msc.getincludedirs(cfg, dirs, extdirs, frameworkdirs) local result = {} for _, dir in ipairs(dirs) do dir = project.getrelative(cfg.project, dir) table.insert(result, '-I' .. p.quoted(dir)) end for _, dir in ipairs(extdirs or {}) do dir = project.getrelative(cfg.project, dir) if cfg.toolset and cfg.toolset >= "msc-v143" then table.insert(result, '/external:I' .. p.quoted(dir)) else table.insert(result, '-I' .. p.quoted(dir)) end end return result end -- -- Return a list of linker flags for a specific configuration. -- msc.linkerFlags = { flags = { FatalLinkWarnings = "/WX", LinkTimeOptimization = "/LTCG", NoIncrementalLink = "/INCREMENTAL:NO", NoManifest = "/MANIFEST:NO", OmitDefaultLibrary = "/NODEFAULTLIB", }, kind = { SharedLib = "/DLL", WindowedApp = "/SUBSYSTEM:WINDOWS" }, symbols = { On = "/DEBUG" } } msc.librarianFlags = { flags = { FatalLinkWarnings = "/WX", } } function msc.getldflags(cfg) local map = iif(cfg.kind ~= p.STATICLIB, msc.linkerFlags, msc.librarianFlags) local flags = config.mapFlags(cfg, map) table.insert(flags, 1, "/NOLOGO") -- Ignore default libraries for i, ignore in ipairs(cfg.ignoredefaultlibraries) do -- Add extension if required if not msc.getLibraryExtensions()[ignore:match("[^.]+$")] then ignore = path.appendextension(ignore, ".lib") end table.insert(flags, '/NODEFAULTLIB:' .. ignore) end return flags end -- -- Build a list of additional library directories for a particular -- project configuration, decorated for the tool command line. -- -- @param cfg -- The project configuration. -- @return -- An array of decorated additional library directories. -- function msc.getLibraryDirectories(cfg) local flags = {} local dirs = table.join(cfg.libdirs, cfg.syslibdirs) for i, dir in ipairs(dirs) do dir = project.getrelative(cfg.project, dir) table.insert(flags, '/LIBPATH:"' .. dir .. '"') end return flags end -- -- Return a list of valid library extensions -- function msc.getLibraryExtensions() return { ["lib"] = true, ["obj"] = true, } end -- -- Return the list of libraries to link, decorated with flags as needed. -- function msc.getlinks(cfg, systemonly, nogroups) local links = {} -- If we need sibling projects to be listed explicitly, grab them first if not systemonly then links = config.getlinks(cfg, "siblings", "fullpath") end -- Then the system libraries, which come undecorated local system = config.getlinks(cfg, "system", "fullpath") for i = 1, #system do -- Add extension if required local link = system[i] if not p.tools.msc.getLibraryExtensions()[link:match("[^.]+$")] then link = path.appendextension(link, ".lib") end table.insert(links, link) end return links end -- -- Returns makefile-specific configuration rules. -- function msc.getmakesettings(cfg) return nil end -- -- Retrieves the executable command name for a tool, based on the -- provided configuration and the operating environment. -- -- @param cfg -- The configuration to query. -- @param tool -- The tool to fetch, one of "cc" for the C compiler, "cxx" for -- the C++ compiler, or "ar" for the static linker. -- @return -- The executable command name for a tool, or nil if the system's -- default value should be used. -- function msc.gettoolname(cfg, tool) return nil end function msc.getwarnings(cfg) local result = {} for _, enable in ipairs(cfg.enablewarnings) do table.insert(result, '/w1"' .. enable .. '"') end for _, disable in ipairs(cfg.disablewarnings) do table.insert(result, '/wd"' .. disable .. '"') end for _, fatal in ipairs(cfg.fatalwarnings) do table.insert(result, '/we"' .. fatal .. '"') end return result end
bsd-3-clause
avrem/ardupilot
libraries/AP_Scripting/examples/easter-egg.lua
12
2145
-- This script will select a random location (as defined from a lat long coordinate) -- and will play a set of tunes to navigate you towards that point, and select a new once -- once the point has been found. -- -- This script primarily serves to demo how to work with Locations, as well as how to -- use the tonealarm to play tones, and send status text messages local ACCEPTANCE_DISTANCE = 20.0 local TUNE_POINT = "MBNT255>A#8A#8A#8A#8A#8A#8A#8A#8A#8A#8A#8A#8A#8A#8A#8A#8" local TUNE_TOWARDS = "MFT100L8>B" local TUNE_AWAY = "MFT100L4>A#B#" local target = Location() local top_left = Location() top_left:lat(-353622666) top_left:lng(1491650479) local last_distance = 1e10 local notify_interval_ms = uint32_t(5000) local last_notify_time_ms = millis() local score = 0 function find_next_point () target:lat(top_left:lat()) target:lng(top_left:lng()) target:offset(math.random()*-100, math.random()*10) gcs:send_text(6, string.format("New target %d %d", target:lat(), target:lng())) local current = ahrs:get_position() if current then last_distance = current:get_distance(target) end last_distance = 1e10 return end function update () local current = ahrs:get_position() if current then local dist = target:get_distance(current) local now = millis() if dist < ACCEPTANCE_DISTANCE then notify:play_tune(TUNE_POINT) score = score + 1 gcs:send_text(6, string.format("Got a point! %d total", score)) find_next_point() elseif (now - last_notify_time_ms) > notify_interval_ms then last_notify_time_ms = now gcs:send_text(6, string.format("Distance: %.1f %.1f", target:get_distance(current), dist)) if dist < (last_distance - 1) then notify:play_tune(TUNE_TOWARDS) elseif dist > (last_distance + 1) then notify:play_tune(TUNE_AWAY) end end if math.abs(last_distance - dist) > 1.0 then last_distance = dist; end end return update, 100 end find_next_point() return update, 100
gpl-3.0
andeandr100/Crumbled-World
Lua/Custom/event_world0_tut3.lua
1
2623
require("Game/eventBase.lua") --this = SceneNode() local event = EventBase.new() function create() local mapInfo = MapInfo.new() local numWaves = mapInfo.getWaveCount() local goldEstimationEarnedPerWave = 500+(numWaves*5) local startGold = 1000 local interestOnKill = 0.0020 local goldMultiplayerOnKills = 1.0 local startLives = 20 local seed = mapInfo.getSead() local startSpawnWindow = mapInfo.getSpawnWindow() --how many group compositions that can spawn 2==[1,2,3] local level = mapInfo.getLevel() local waveFinishedGold = 200 --how much gold you get to finish a wave local difficult = mapInfo.getDifficulty() --(>0.70 the lower this value is the more time you have to collect on the interest local difficultIncreaser = mapInfo.getDifficultyIncreaser() --how large the exponential difficulty increase should be -- if mapInfo.getGameMode()=="default" then --nothing elseif mapInfo.getGameMode()=="rush" then --nothing elseif mapInfo.getGameMode()=="survival" then --lower the availabel gold to make the spawned npc's easier. (this will make it easier to get intrest in the available gold) startGold = startGold*0.5 --(makes the spawn easier, restored after the generating of the waves) interestOnKill = interestOnKill*0.5 --(makes the spawn easier, restored after the generating of the waves) numWaves = 100 elseif mapInfo.getGameMode()=="training" then --nothing, so the spawns will be the same as if in normal game elseif mapInfo.getGameMode()=="only interest" then --nonting, to calculate the wave unchanged elseif mapInfo.getGameMode()=="leveler" then startGold = 1000 interestOnKill = 0.0 end if not event.init(startGold,waveFinishedGold,interestOnKill,goldMultiplayerOnKills,startLives,level) then return false end -- event.disableUnit("hydra1") event.disableUnit("hydra2") event.disableUnit("hydra3") event.disableUnit("hydra4") event.disableUnit("hydra5") -- -- event.generateWaves(numWaves,difficult,difficultIncreaser,startSpawnWindow,seed) if mapInfo.getGameMode()=="survival" then startGold = startGold * 2.0 interestOnKill = interestOnKill * 2.0 elseif mapInfo.getGameMode()=="training" then startGold = 9000 waveFinishedGold = 0 interestOnKill = 0.0 goldMultiplayerOnKills = 0.0 elseif mapInfo.getGameMode()=="only interest" then waveFinishedGold = 0 goldMultiplayerOnKills = 0.0 startGold = 3000 elseif mapInfo.getGameMode()=="leveler" then goldMultiplayerOnKills = 0.0 end event.setDefaultGold(startGold,waveFinishedGold,interestOnKill,goldMultiplayerOnKills) update = event.update return true end
mit
dacrybabysuck/darkstar
scripts/zones/King_Ranperres_Tomb/IDs.lua
9
2326
----------------------------------- -- Area: King Ranperres Tomb (190) ----------------------------------- require("scripts/globals/zone") ----------------------------------- zones = zones or {} zones[dsp.zone.KING_RANPERRES_TOMB] = { text = { CONQUEST_BASE = 0, -- Tallying conquest results... ITEM_CANNOT_BE_OBTAINED = 6541, -- You cannot obtain the <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6547, -- Obtained: <item>. GIL_OBTAINED = 6548, -- Obtained <number> gil. KEYITEM_OBTAINED = 6550, -- Obtained key item: <keyitem>. GEOMAGNETRON_ATTUNED = 7169, -- Your <keyitem> has been attuned to a geomagnetic fount in the corresponding locale. CHEST_UNLOCKED = 7279, -- You unlock the chest! HEAVY_DOOR = 7307, -- It is a solid stone door. PLAYER_OBTAINS_ITEM = 8245, -- <name> obtains <item>! UNABLE_TO_OBTAIN_ITEM = 8246, -- You were unable to obtain the item. PLAYER_OBTAINS_TEMP_ITEM = 8247, -- <name> obtains the temporary item: <item>! ALREADY_POSSESS_TEMP = 8248, -- You already possess that temporary item. NO_COMBINATION = 8253, -- You were unable to enter a combination. REGIME_REGISTERED = 10331, -- New training regime registered! COMMON_SENSE_SURVIVAL = 11418, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world. }, mob = { GWYLLGI_PH = { [17555661] = 17555664, }, CRYPT_GHOST_PH = { [17555665] = 17555668, [17555666] = 17555668, [17555667] = 17555668, }, BARBASTELLE = 17555721, CHERRY_SAPLING_OFFSET = 17555853, VRTRA = 17555890, CORRUPTED_YORGOS = 17555898, CORRUPTED_SOFFEIL = 17555899, CORRUPTED_ULBRIG = 17555900, }, npc = { CASKET_BASE = 17555907, TREASURE_CHEST = 17555955, }, } return zones[dsp.zone.KING_RANPERRES_TOMB]
gpl-3.0
fetchbot/nodemcu-firmware
lua_modules/yeelink/yeelink_lib.lua
73
3136
-- *************************************************************************** -- Yeelink Updata Libiary Version 0.1.2 r1 -- -- Written by Martin -- but based on a script of zhouxu_o from bbs.nodemcu.com -- -- MIT license, http://opensource.org/licenses/MIT -- *************************************************************************** --==========================Module Part====================== local moduleName = ... local M = {} _G[moduleName] = M --=========================Local Args======================= local dns = "0.0.0.0" local device = "" local sensor = "" local apikey = "" --================================ local debug = true --<<<<<<<<<<<<< Don't forget to "false" it before using --================================ local sk=net.createConnection(net.TCP, 0) local datapoint = 0 --====DNS the yeelink ip advance(in order to save RAM)===== if wifi.sta.getip() == nil then print("Please Connect WIFI First") tmr.alarm(1,1000,1,function () if wifi.sta.getip() ~= nil then tmr.stop(1) sk:dns("api.yeelink.net",function(conn,ip) dns=ip print("DNS YEELINK OK... IP: "..dns) end) end end) end sk:dns("api.yeelink.net",function(conn,ip) dns=ip print("DNS YEELINK OK... IP: "..dns) end) --========Set the init function=========== --device->number --sensor->number -- apikey must be -> string <- -- e.g. xxx.init(00000,00000,"123j12b3jkb12k4b23bv54i2b5b3o4") --======================================== function M.init(_device, _sensor, _apikey) device = tostring(_device) sensor = tostring(_sensor) apikey = _apikey if dns == "0.0.0.0" then tmr.alarm(2,5000,1,function () if dns == "0.0.0.0" then print("Waiting for DNS...") end end) return false else return dns end end --========Check the DNS Status=========== --if DNS success, return the address(string) --if DNS fail(or processing), return nil -- -- --======================================== function M.getDNS() if dns == "0.0.0.0" then return nil else return dns end end --=====Update to Yeelink Sever(At least 10s per sencods))===== -- datapoint->number -- --e.g. xxx.update(233.333) --============================================================ function M.update(_datapoint) datapoint = tostring(_datapoint) sk:on("connection", function(conn) print("connect OK...") local a=[[{"value":]] local b=[[}]] local st=a..datapoint..b sk:send("POST /v1.0/device/"..device.."/sensor/"..sensor.."/datapoints HTTP/1.1\r\n" .."Host: www.yeelink.net\r\n" .."Content-Length: "..string.len(st).."\r\n"--the length of json is important .."Content-Type: application/x-www-form-urlencoded\r\n" .."U-ApiKey:"..apikey.."\r\n" .."Cache-Control: no-cache\r\n\r\n" ..st.."\r\n" ) end) sk:on("receive", function(sck, content) if debug then print("\r\n"..content.."\r\n") else print("Date Receive") end end) sk:connect(80,dns) end --================end========================== return M
mit
JFonS/Cult
lib/trailmesh.lua
1
4278
trailmesh = class:new() function trailmesh:init(x, y, img, width, lifetime, interval, method) self.type = "trailmesh" self.x = x self.y = y self.img = img self.width = width self.lifetime = lifetime self.interval = interval self.method = method or "stretch" self:reset() self.mesh = love.graphics.newMesh(self.verts,self.img,"strip") end function trailmesh:update(dt) self.timer = self.timer + dt if self.timer > self.interval then if self.method == "repeat" then self.length = self.points[1][5] end table.insert(self.points, 1, {self.x,self.y,self.lifetime}) self.timer = self.timer - self.interval end self.points[1] = {self.x,self.y,self.lifetime,self.width} for point,v in pairs(self.points) do local pv = self.points[point+1] local nv = self.points[point-1] if v[3] < -self.interval*1.1 then table.remove(self.points, #self.points) table.remove(self.verts, #self.verts) table.remove(self.verts, #self.verts) break end local lifetime = v[3]/self.lifetime if self.method == "stretch" then if point == 1 then local dist = math.sqrt((v[1]-pv[1])^2+(v[2]-pv[2])^2) local vert = {(v[2]-pv[2])*v[4]/(dist*2), (v[1]-pv[1])*v[4]/(dist*2)} self.verts[1] = { v[1]+vert[1], v[2]-vert[2], lifetime, 0} self.verts[2] = { v[1]-vert[1], v[2]+vert[2], lifetime, 1} elseif point == #self.points then local dist = math.sqrt((nv[1]-v[1])^2+(nv[2]-v[2])^2) local vert = {(nv[2]-v[2])*v[4]/(dist*2), -(nv[1]-v[1])*v[4]/(dist*2)} self.verts[#self.points*2-1] = { v[1]+vert[1], v[2]-vert[2], lifetime, 0} self.verts[#self.points*2] = { v[1]-vert[1], v[2]+vert[2], lifetime, 1} else local dist = math.sqrt((nv[1]-pv[1])^2+(nv[2]-pv[2])^2) local vert = {(nv[2]-pv[2])*v[4]/(dist*2), (nv[1]-pv[1])*v[4]/(dist*2)} self.verts[point*2-1] = { v[1]+vert[1], v[2]-vert[2], lifetime, 0} self.verts[point*2] = { v[1]-vert[1], v[2]+vert[2], lifetime, 1} end elseif self.method == "repeat" then if point == 1 then local dist = math.sqrt((v[1]-pv[1])^2+(v[2]-pv[2])^2) local vert = {(v[2]-pv[2])*v[4]/(dist*2), (v[1]-pv[1])*v[4]/(dist*2)} v[5] = dist/(self.img:getWidth()/(self.img:getHeight()/self.width)) + self.length self.verts[1] = { v[1]+vert[1], v[2]-vert[2], v[5], 0, 255, 255, 255, 255*lifetime} self.verts[2] = { v[1]-vert[1], v[2]+vert[2], v[5], 1, 255, 255, 255, 255*lifetime} elseif point == #self.points then local dist = math.sqrt((nv[1]-v[1])^2+(nv[2]-v[2])^2) local vert = {(nv[2]-v[2])*v[4]/(dist*2), -(nv[1]-v[1])*v[4]/(dist*2)} self.verts[#self.points*2-1] = { v[1]+vert[1], v[2]-vert[2], v[5], 0, 255, 255, 255, 1} self.verts[#self.points*2] = { v[1]-vert[1], v[2]+vert[2], v[5], 1, 255, 255, 255, 1} else local dist = math.sqrt((nv[1]-pv[1])^2+(nv[2]-pv[2])^2) local vert = {(nv[2]-pv[2])*v[4]/(dist*2), (nv[1]-pv[1])*v[4]/(dist*2)} self.verts[point*2-1] = { v[1]+vert[1], v[2]-vert[2], v[5], 0, 255, 255, 255, 255*(lifetime+self.interval)} self.verts[point*2] = { v[1]-vert[1], v[2]+vert[2], v[5], 1, 255, 255, 255, 255*(lifetime+self.interval)} end end self.points[point][3] = v[3] - dt end if #self.verts > 3 then self.mesh:setVertices(self.verts) end end function trailmesh:draw() love.graphics.draw(self.mesh) end function trailmesh:setWidth(size, part) if part == "base" or not part then self.width = size elseif part == "all" then for k,v in pairs(self.points) do v[4] = size end end end function trailmesh:reset() self.timer = 0 self.length = 0 self.points = {{self.x,self.y,self.lifetime,self.width,0},{self.x,self.y,self.lifetime-self.interval,self.width,0}} self.verts = {{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0}} end
gpl-3.0
shultays/bloodworks
game/resources/guns/plasmagun/plasmagun.lua
1
3902
function PlasmaGun.init(gun) gun.spreadAngle = 0.0 gun.crosshairDistance = 400.0 ShootTimer.initGun(gun, 0.35) SpreadHelper.initGun(gun) gun.data.maxSpread = 0.10 gun.data.spreadDecreaseStartTime = 0.0 gun.data.spreadDecreaseSpeed = 0.05 gun.data.checkAchievement = true gun.data.achievementProcess = 0 end function PlasmaGun.onTick(gun) SpreadHelper.onTick(gun) if gun.isTriggered and gun:hasAmmo() then if ShootTimer.checkGun(gun) then gun:consumeAmmo() SpreadHelper.onShoot(gun) local bullet = gun:addBullet() bullet:addTrailParticle("PlasmaTrailParticle", Vec2.new(0.0, 0.0), 3.0, {color = Vec3.new(0.0, 0.6, 0.8)}) end end end function PlasmaGun.onBulletHit(gun, bullet, monster) local data = gun.data if monster ~= nil then local m = monster local oldGameObjectPos = nil local count = 0 if monster.isDead then count = count + 1 end while m ~= nill do m:addIgnoreId(bullet.id) local gameObject = addGameObject("FadeOutImage") gameObject.data.startTime = time gameObject.data.fadeOutStartTime = 0.0 gameObject.data.fadeInDuration = 0.0 gameObject.data.fadeOutDuration = 0.3 gameObject:setLevel(RenderableLevel.monsters + 5) gameObject.data.renderable = gameObject:addTexture(PlasmaGun.basePath .. "bullet.png", "~/resources/default") gameObject.data.renderable:setAlignment(RenderableAlignment.world) gameObject.data.renderable:setWorldMatrix(Mat3.fromScale(6.0, 6.0)) if oldGameObjectPos ~= nil then gameObject:setPosition(m.position) local gameObject2 = addGameObject("FadeOutImage") gameObject2.data.startTime = time gameObject2.data.fadeOutStartTime = 0.0 gameObject2.data.fadeInDuration = 0.0 gameObject2.data.fadeOutDuration = 0.3 gameObject2:setLevel(RenderableLevel.monsters + 4) gameObject2.data.renderable = gameObject2:addTexture(PlasmaGun.basePath .. "line.png", "~/resources/default") gameObject2.data.renderable:setAlignment(RenderableAlignment.world) gameObject2.data.renderable:setWorldMatrix(Mat3.from( (m.position + oldGameObjectPos) * 0.5, Vec2:new((m.position - oldGameObjectPos):length() * 0.5 - 3, 3.0), -(m.position - oldGameObjectPos):getAngle() )) local args = {doNotStun = true} m:doDamageWithArgs(math.floor( ( 10 + 10 * math.random() ) ), (m.position - oldGameObjectPos):normalized(), args) if m.isDead then count = count + 1 end if math.random() < 0.5 then oldGameObjectPos = m.position end else gameObject:setPosition(bullet.position) oldGameObjectPos = bullet.position end m = getClosestMonsterInRangeWithIgnoreId(bullet.position, 80.0, {bullet.id}) end if data.checkAchievement then if hasAchievement( "ACH_PLASMA_GUN" ) or player.isDead or missionData.isSurvival ~= true then data.checkAchievement = false return end if count >= 3 then data.achievementProcess = data.achievementProcess + 1 if data.achievementProcess >= 20 then addAchievement( "ACH_PLASMA_GUN" ) data.checkAchievement = false end end end end end
gpl-3.0
shahabsaf12/x
plugins/banhammer.lua
44
9652
local function is_user_whitelisted(id) local hash = 'whitelist:user#id'..id local white = redis:get(hash) or false return white end local function is_chat_whitelisted(id) local hash = 'whitelist:chat#id'..id local white = redis:get(hash) or false return white end local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end local function ban_user(user_id, chat_id) -- Save to redis local hash = 'banned:'..chat_id..':'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function superban_user(user_id, chat_id) -- Save to redis local hash = 'superbanned:'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end 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 pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat if action == 'chat_add_user' or action == 'chat_add_user_link' then local user_id if msg.action.link_issuer then user_id = msg.from.id else user_id = msg.action.user.id end print('Checking invited user '..user_id) local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, msg.to.id) if superbanned or banned then print('User is banned!') kick_user(user_id, msg.to.id) end end -- No further checks return msg end -- BANNED USER TALKING if msg.to.type == 'chat' then local user_id = msg.from.id local chat_id = msg.to.id local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, chat_id) if superbanned then print('SuperBanned user talking!') superban_user(user_id, chat_id) msg.text = '' end if banned then print('Banned user talking!') ban_user(user_id, chat_id) msg.text = '' end end -- WHITELIST local hash = 'whitelist:enabled' local whitelist = redis:get(hash) local issudo = is_sudo(msg) -- Allow all sudo users even if whitelist is allowed if whitelist and not issudo then print('Whitelist enabled and not sudo') -- Check if user or chat is whitelisted local allowed = is_user_whitelisted(msg.from.id) if not allowed then print('User '..msg.from.id..' not whitelisted') if msg.to.type == 'chat' then allowed = is_chat_whitelisted(msg.to.id) if not allowed then print ('Chat '..msg.to.id..' not whitelisted') else print ('Chat '..msg.to.id..' whitelisted :)') end end else print('User '..msg.from.id..' allowed :)') end if not allowed then msg.text = '' end else print('Whitelist not enabled or is sudo') end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id local member = cb_extra.member local text = 'No @'..member..' in group' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if get_cmd == 'kick' then return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then send_large_msg(receiver, 'User @'..member..' ('..member_id..') BANNED!') return ban_user(member_id, chat_id) elseif get_cmd == 'globalban' then send_large_msg(receiver, 'User @'..member..' ('..member_id..') GLOBALLY BANNED!!') return superban_user(member_id, chat_id) elseif get_cmd == 'wlist user' then local hash = 'whitelist:user#id'..member_id redis:set(hash, true) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted') elseif get_cmd == 'wlist delete user' then local hash = 'whitelist:user#id'..member_id redis:del(hash) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist') end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1] == 'kickme' then kick_user(msg.from.id, msg.to.id) end if not is_momod(msg) then return nil end local receiver = get_receiver(msg) if matches[4] then get_cmd = matches[1]..' '..matches[2]..' '..matches[3] elseif matches[3] then get_cmd = matches[1]..' '..matches[2] else get_cmd = matches[1] end if matches[1] == 'ban' then local user_id = matches[3] local chat_id = msg.to.id if msg.to.type == 'chat' then if matches[2] == '+' then if string.match(matches[3], '^%d+$') then ban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' BANNED!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == '-' then local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) return 'User '..user_id..' UNbanned' end else return 'Only work in group' end end if matches[1] == 'globalban' and is_admin(msg) then local user_id = matches[3] local chat_id = msg.to.id if matches[2] == '+' then if string.match(matches[3], '^%d+$') then superban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' GLOBALLY BANNED!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == '-' then local hash = 'superbanned:'..user_id redis:del(hash) return 'User '..user_id..' GLOBALLY UNbanned' end end if matches[1] == 'kick' then if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then kick_user(matches[2], msg.to.id) else local member = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'Only work in group' end end if matches[1] == 'wlist' then if matches[2] == 'enable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:set(hash, true) return 'Enabled whitelist' end if matches[2] == 'disable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:del(hash) return 'Disabled whitelist' end if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then local hash = 'whitelist:user#id'..matches[3] redis:set(hash, true) return 'User '..matches[3]..' whitelisted' else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:set(hash, true) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted' end if matches[2] == 'delete' and matches[3] == 'user' then if string.match(matches[4], '^%d+$') then local hash = 'whitelist:user#id'..matches[4] redis:del(hash) return 'User '..matches[4]..' removed from whitelist' else local member = string.gsub(matches[4], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'delete' and matches[3] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:del(hash) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist' end end end return { description = "Group Members Manager System", usage = { user = "/kickme : leave group", moderator = { "/kick (@user) : kick user", "/kick (id) : kick user", "/ban + (@user) : kick user for ever", "/ban + (id) : kick user for ever", "/ban - (id) : unban user" }, admin = { "/globalban + (@user) : ban user from all groups", "/globalban + (id) : ban user from all groups", "/globalban - (id) : globally unban user" }, }, patterns = { "^[!/](wlist) (enable)$", "^[!/](wlist) (disable)$", "^[!/](wlist) (user) (.*)$", "^[!/](wlist) (chat)$", "^[!/](wlist) (delete) (user) (.*)$", "^[!/](wlist) (delete) (chat)$", "^[!/](ban) (+) (.*)$", "^[!/](ban) (-) (.*)$", "^[!/](globalban) (+) (.*)$", "^[!/](globalban) (-) (.*)$", "^[!/](kick) (.*)$", "^[!/](kickme)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
dacrybabysuck/darkstar
scripts/globals/items/bibikibo.lua
11
1047
----------------------------------------- -- ID: 4314 -- Item: Bibikibo -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 1 -- Mind -3 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if (target:getRace() ~= dsp.race.MITHRA) then result = dsp.msg.basic.CANNOT_EAT end if (target:getMod(dsp.mod.EAT_RAW_FISH) == 1) then result = 0 end if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,300,4314) end function onEffectGain(target, effect) target:addMod(dsp.mod.DEX, 1) target:addMod(dsp.mod.MND, -3) end function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, 1) target:delMod(dsp.mod.MND, -3) end
gpl-3.0
dacrybabysuck/darkstar
scripts/globals/abilities/pets/tail_whip.lua
11
1358
--------------------------------------------------- -- Tail Whip M=5 --------------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") require("scripts/globals/summon") --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0 end function onPetAbility(target, pet, skill) local numhits = 1 local accmod = 1 local dmgmod = 5 local totaldamage = 0 local damage = AvatarPhysicalMove(pet,target,skill,numhits,accmod,dmgmod,0,TP_NO_EFFECT,1,2,3) totaldamage = AvatarFinalAdjustments(damage.dmg,pet,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.PIERCING,numhits) local duration = 120 local resm = applyPlayerResistance(pet,-1,target,pet:getStat(dsp.mod.INT)-target:getStat(dsp.mod.INT),dsp.skill.ELEMENTAL_MAGIC, 5) if resm < 0.25 then resm = 0 end duration = duration * resm if (duration > 0 and AvatarPhysicalHit(skill, totaldamage) and target:hasStatusEffect(dsp.effect.WEIGHT) == false) then target:addStatusEffect(dsp.effect.WEIGHT, 50, 0, duration) end target:takeDamage(totaldamage, pet, dsp.attackType.PHYSICAL, dsp.damageType.PIERCING) target:updateEnmityFromDamage(pet,totaldamage) return totaldamage end
gpl-3.0
varunparkhe/Algorithm-Implementations
Lempel_Ziv_Welch/Lua/Yonaba/lzw.lua
24
1387
-- Lempel-Ziv Welch compression data algorithm implementation -- See : http://en.wikipedia.org/wiki/LZW local function lzw_encode(str) local w = '' local result = {} local dict_size = 256 -- Builds the dictionnary local dict = {} for i = 0, dict_size-1 do dict[string.char(i)] = i end local i = dict_size for char in str:gmatch('.') do -- Finds the longest string matching the input local wc = w .. char if dict[wc] then -- Save the current match index w = wc else -- Add the match to the dictionary table.insert(result, dict[w]) dict[wc] = i i = i + 1 w = char end end if w~='' then table.insert(result, dict[w]) end return result end local function lzw_decode(str) local dict_size = 256 -- Builds the dictionary local dict = {} for i = 0, dict_size-1 do dict[i] = string.char(i) end local w = string.char(str[1]) local result = w for i = 2, #str do local k = str[i] local entry = '' if dict[k] then entry = dict[k] elseif k == dict_size then entry = w .. w:sub(1,1) else return nil -- No match found, decoding error end result = result .. entry dict[dict_size] = w .. entry:sub(1,1) dict_size = dict_size + 1 w = entry end return result end return { encode = lzw_encode, decode = lzw_decode, }
mit
martinfelis/ggj15
Quickie/group.lua
15
4523
--[[ Copyright (c) 2012 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local stack = {n = 0} local default = { pos = {0,0}, grow = {0,0}, spacing = 2, size = {100, 30}, upper_left = {0,0}, lower_right = {0,0}, } local current = default local Grow = { none = { 0, 0}, up = { 0, -1}, down = { 0, 1}, left = {-1, 0}, right = { 1, 0} } -- {grow = grow, spacing = spacing, size = size, pos = pos} local function push(info) local grow = info.grow or "none" local spacing = info.spacing or default.spacing local size = { info.size and info.size[1] or current.size[1], info.size and info.size[2] or current.size[2] } local pos = {current.pos[1], current.pos[2]} if info.pos then pos[1] = pos[1] + (info.pos[1] or 0) pos[2] = pos[2] + (info.pos[2] or 0) end assert(size, "Size neither specified nor derivable from parent group.") assert(pos, "Position neither specified nor derivable from parent group.") grow = assert(Grow[grow], "Invalid grow: " .. tostring(grow)) current = { pos = pos, grow = grow, size = size, spacing = spacing, upper_left = { math.huge, math.huge}, lower_right = {-math.huge, -math.huge}, } stack.n = stack.n + 1 stack[stack.n] = current end local function advance(pos, size) current.upper_left[1] = math.min(current.upper_left[1], pos[1]) current.upper_left[2] = math.min(current.upper_left[2], pos[2]) current.lower_right[1] = math.max(current.lower_right[1], pos[1] + size[1]) current.lower_right[2] = math.max(current.lower_right[2], pos[2] + size[2]) if current.grow[1] ~= 0 then current.pos[1] = pos[1] + current.grow[1] * (size[1] + current.spacing) end if current.grow[2] ~= 0 then current.pos[2] = pos[2] + current.grow[2] * (size[2] + current.spacing) end return pos, size end local function getRect(pos, size) pos = {pos and pos[1] or 0, pos and pos[2] or 0} size = {size and size[1] or current.size[1], size and size[2] or current.size[2]} -- growing left/up: update current position to account for differnt size if current.grow[1] < 0 and current.size[1] ~= size[1] then current.pos[1] = current.pos[1] + (current.size[1] - size[1]) end if current.grow[2] < 0 and current.size[2] ~= size[2] then current.pos[2] = current.pos[2] - (current.size[2] - size[2]) end pos[1] = pos[1] + current.pos[1] pos[2] = pos[2] + current.pos[2] return advance(pos, size) end local function pop() assert(stack.n > 0, "Group stack is empty.") stack.n = stack.n - 1 local child = current current = stack[stack.n] or default local size = { child.lower_right[1] - math.max(child.upper_left[1], current.pos[1]), child.lower_right[2] - math.max(child.upper_left[2], current.pos[2]) } advance(current.pos, size) end local function beginFrame() current = default stack.n = 0 end local function endFrame() -- future use? end return setmetatable({ push = push, pop = pop, getRect = getRect, advance = advance, beginFrame = beginFrame, endFrame = endFrame, default = default, }, { __index = function(_,k) return ({size = current.size, pos = current.pos})[k] end, __call = function(_, info) assert(type(info) == 'table' and type(info[1]) == 'function') push(info) info[1]() pop() end, })
apache-2.0
varunparkhe/Algorithm-Implementations
Gale_Shapely/Lua/Yonaba/gale_shapely_test.lua
53
1896
-- Tests for binary_search.lua local binary_search = require 'binary_search' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end run('Performs a binary search', function() local t = {1, 2, 3, 4, 5} assert(binary_search(t, 1) == 1) assert(binary_search(t, 2) == 2) assert(binary_search(t, 3) == 3) assert(binary_search(t, 4) == 4) assert(binary_search(t, 5) == 5) end) run('Array values do not have to be consecutive',function() local t = {1, 3, 5, 10, 13} assert(binary_search(t, 1) == 1) assert(binary_search(t, 3) == 2) assert(binary_search(t, 5) == 3) assert(binary_search(t, 10) == 4) assert(binary_search(t, 13) == 5) end) run('But the array needs to be sorted',function() local t = {1, 15, 12, 14, 13} assert(binary_search(t, 13) == nil) assert(binary_search(t, 15) == nil) end) run('In case the value exists more than once, it returns any of them',function() local t = {1, 12, 12, 13, 15, 15, 16} assert(binary_search(t, 15) == 6) assert(binary_search(t, 12) == 2) end) run('Accepts comparison functions for reversed arrays',function() local t = {50, 33, 18, 12, 5, 1, 0} local comp = function(a, b) return a > b end assert(binary_search(t, 50, comp) == 1) assert(binary_search(t, 33, comp) == 2) assert(binary_search(t, 18, comp) == 3) assert(binary_search(t, 12, comp) == 4) assert(binary_search(t, 5, comp) == 5) assert(binary_search(t, 1, comp) == 6) assert(binary_search(t, 0, comp) == 7) end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
dkogan/notion.xfttest
contrib/statusbar/legacy/statusbar_workspace.lua
3
3451
-- Authors: Rico Schiekel <fire@paranetic.de>, Canaan Hadley-Voth, Kevin Granade <kevin.granade@gmail.com> -- License: Unknown -- Last Changed: 2007-05-09 -- -- statusbar_workspace.lua -- -- Show current workspace name or number in the statusbar. -- -- Put any of these in cfg_statusbar.lua's template-line: -- %workspace_name -- %workspace_frame -- %workspace_pager -- %workspace_name_pager -- %workspace_num_name_pager -- -- This is an internal statusbar monitor and does NOT require -- a dopath statement (effective after a 2006-02-12 build). -- -- version 1 -- author: Rico Schiekel <fire at paranetic dot de> -- -- version 2 -- added 2006-02-14 by Canaan Hadley-Voth: -- * %workspace_pager shows a list of workspace numbers -- with the current one indicated: -- -- 1i 2i [3f] 4p 5c -- -- i=WIonWS, f=WFloatWS, p=WPaneWS, c=WClientWin/other -- -- * %workspace_frame - name of the active frame. -- -- * Added statusbar_ to the filename (since it *is* -- an internal statusbar monitor) so that it works without -- a "dopath" call. -- -- * Removed timer. Only needs to run on hook. -- Much faster this way. -- -- version 3 -- update for ion-3rc-20070506 on 2007-05-09 -- by Kevin Granade <kevin dot granade at gmail dot com> -- -- Updated to use new wx_ api -- Replaced region_activated_hook with region_notify_hook -- Added %workspace_name_pager, which works similarly to %workspace_pager, -- but instead displays the name of each workspace -- Added display for WGroupWS to %workspace_pager, displayed as 'g' -- local function update_frame() local fr ioncore.defer( function() local cur=ioncore.current() if obj_is(cur, "WClientWin") and obj_is(cur:parent(), "WMPlex") then cur=cur:parent() end fr=cur:name() mod_statusbar.inform('workspace_frame', fr) mod_statusbar.update() end) end local function update_workspace() local scr=ioncore.find_screen_id(0) local curws = scr:mx_current() local wstype, c local pager="" local name_pager="" local name_pager_plus="" local curindex = scr:get_index(curws)+1 n = scr:mx_count(1) for i=1,n do tmpws=scr:mx_nth(i-1) wstype=obj_typename(tmpws) if wstype=="WIonWS" then c="i" elseif wstype=="WFloatWS" then c="f" elseif wstype=="WPaneWS" then c="p" elseif wstype=="WGroupWS" then c="g" else c="c" end if i==curindex then name_pager_plus=name_pager_plus.." ["..tmpws:name().."]" name_pager=name_pager.." ["..tmpws:name().."]" pager=pager.." ["..(i)..c.."] " else name_pager_plus=name_pager_plus.." "..(i)..":"..tmpws:name() name_pager=name_pager.." "..tmpws:name() pager=pager.." "..(i)..c.." " end end local fr,cur -- Older versions without an ioncore.current() should -- skip update_frame. update_frame() ioncore.defer( function() mod_statusbar.inform('workspace_pager', pager) mod_statusbar.inform('workspace_name', curws:name()) mod_statusbar.inform('workspace_name_pager', name_pager) mod_statusbar.inform('workspace_num_name_pager', name_pager_plus) mod_statusbar.update() end) end local function update_workspace_wrap(reg, how) if how ~= "name" then return end update_workspace() end ioncore.get_hook("region_notify_hook"):add(update_workspace_wrap) ioncore.get_hook("screen_managed_changed_hook"):add(update_workspace)
lgpl-2.1
dacrybabysuck/darkstar
scripts/globals/mobskills/throat_stab.lua
11
1190
--------------------------------------------- -- Throat Stab -- -- Description: Deals damage to a single target reducing their HP to 5%. Resets enmity. -- Type: Physical -- Utsusemi/Blink absorb: No -- Range: Single Target -- Notes: Very short range, easily evaded by walking away from it. --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") require("scripts/globals/magic") --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0 end function onMobWeaponSkill(target, mob, skill) local currentHP = target:getHP() -- remove all by 5% local damage = 0 -- if have more hp then 30%, then reduce to 5% if (currentHP / target:getMaxHP() > 0.2) then damage = currentHP * .95 else -- else you die damage = currentHP end local dmg = MobFinalAdjustments(damage,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.PIERCING,MOBPARAM_IGNORE_SHADOWS) target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.PIERCING) mob:resetEnmity(target) return dmg end
gpl-3.0
Noltari/openwrt-packages
net/dynapoint/src/dynapoint.lua
94
6369
#!/usr/bin/lua --[[ Copyright (C) 2016 Tobias Ilte <tobias.ilte@campus.tu-berlin.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] require "uci" require "ubus" require "uloop" log = require "nixio" --open sys-logging log.openlog("DynaPoint", "ndelay", "cons", "nowait"); local uci_cursor = uci.cursor() -- get all config sections with the given type function getConfType(conf_file,type) local ifce={} uci_cursor:foreach(conf_file,type,function(s) ifce[s[".index"]]=s end) return ifce end ubus = ubus.connect() if not ubus then error("Failed to connect to ubusd") end ubus:call("network", "reload", {}) local interval = uci_cursor:get("dynapoint", "internet", "interval") local timeout = uci_cursor:get("dynapoint", "internet", "timeout") local offline_threshold = tonumber(uci_cursor:get("dynapoint", "internet", "offline_threshold")) local hosts = uci_cursor:get("dynapoint", "internet", "hosts") local numhosts = #hosts local curl = tonumber(uci_cursor:get("dynapoint", "internet", "use_curl")) if (curl == 1) then curl_interface = uci_cursor:get("dynapoint", "internet", "curl_interface") end function get_system_sections(t) for pos,val in pairs(t) do if (type(val)=="table") then get_system_sections(val); elseif (type(val)=="string") then if (pos == "hostname") then localhostname = val end end end end if (tonumber(uci_cursor:get("dynapoint", "internet", "add_hostname_to_ssid")) == 1 ) then get_system_sections(getConfType("system","system")) if (not localhostname) then error("Failed to obtain system hostname") end end local table_names_rule = {} local table_names_not_rule = {} local ssids_with_hostname = {} local ssids_not_rule = {} function get_dynapoint_sections(t) for pos,val in pairs(t) do if (type(val)=="table") then get_dynapoint_sections(val); elseif (type(val)=="string") then if (pos == "dynapoint_rule") then if (val == "internet") then table_names_rule[#table_names_rule+1] = t[".name"] elseif (val == "!internet") then table_names_not_rule[#table_names_not_rule+1] = t[".name"] if (localhostname) then ssids_not_rule[#ssids_not_rule+1] = uci_cursor:get("wireless", t[".name"], "ssid") ssids_with_hostname[#ssids_with_hostname+1] = uci_cursor:get("wireless", t[".name"], "ssid").."_"..localhostname end end end end end end --print(table.getn(hosts)) get_dynapoint_sections(getConfType("wireless","wifi-iface")) -- revert all non-persistent ssid uci-changes regarding sections affecting dynapoint for i = 1, #table_names_not_rule do uci_cursor:revert("wireless", table_names_not_rule[i], "ssid") end local online = true if (#table_names_rule > 0) then if (tonumber(uci_cursor:get("wireless", table_names_rule[1], "disabled")) == 1) then online = false end else log.syslog("info","Not properly configured. Please add <option dynapoint_rule 'internet'> to /etc/config/wireless") end local timer local offline_counter = 0 uloop.init() function do_internet_check(host) if (curl == 1 ) then if (curl_interface) then result = os.execute("curl -s -m "..timeout.." --max-redirs 0 --interface "..curl_interface.." --head "..host.." > /dev/null") else result = os.execute("curl -s -m "..timeout.." --max-redirs 0 --head "..host.." > /dev/null") end else result = os.execute("wget -q --timeout="..timeout.." --spider "..host) end if (result == 0) then return true else return false end end function change_wireless_config(switch_to_offline) if (switch_to_offline == 1) then log.syslog("info","Switched to OFFLINE") for i = 1, #table_names_not_rule do uci_cursor:set("wireless",table_names_not_rule[i], "disabled", "0") if (localhostname) then uci_cursor:set("wireless", table_names_not_rule[i], "ssid", ssids_with_hostname[i]) end log.syslog("info","Bring up new AP "..uci_cursor:get("wireless", table_names_not_rule[i], "ssid")) end for i = 1, #table_names_rule do uci_cursor:set("wireless",table_names_rule[i], "disabled", "1") end else log.syslog("info","Switched to ONLINE") for i = 1, #table_names_not_rule do uci_cursor:set("wireless",table_names_not_rule[i], "disabled", "1") if (localhostname) then uci_cursor:set("wireless", table_names_not_rule[i], "ssid", ssids_not_rule[i]) end end for i = 1, #table_names_rule do uci_cursor:set("wireless",table_names_rule[i], "disabled", "0") log.syslog("info","Bring up new AP "..uci_cursor:get("wireless", table_names_rule[i], "ssid")) end end uci_cursor:save("wireless") ubus:call("network", "reload", {}) end local hostindex = 1 function check_internet_connection() print("checking "..hosts[hostindex].."...") if (do_internet_check(hosts[hostindex]) == true) then -- online print("...seems to be online") offline_counter = 0 hostindex = 1 if (online == false) then print("changed state to online") online = true change_wireless_config(0) end else --offline print("...seems to be offline") hostindex = hostindex + 1 if (hostindex <= numhosts) then check_internet_connection() else hostindex = 1 -- and activate offline-mode print("all hosts offline") if (online == true) then offline_counter = offline_counter + 1 if (offline_counter == offline_threshold) then print("changed state to offline") online = false change_wireless_config(1) end end end end timer:set(interval * 1000) end timer = uloop.timer(check_internet_connection) timer:set(interval * 1000) uloop.run()
gpl-2.0
Whit3Tig3R/FuCk3R
bot/seedbot.lua
1
9997
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '1.0' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) -- mark_read(receiver, ok_cb, false) end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "download_media", "invite", "all", "leave_ban" }, sudo_users = {114051964},--Sudo users disabled_channels = {}, moderation = {data = 'data/moderation.json'}, about_text = [[Teleseed v2 - Open Source An advance Administration bot based on yagop/telegram-bot https://github.com/SEEDTEAM/TeleSeed Admins @iwals [Founder] @imandaneshi [Developer] @Rondoozle [Developer] @seyedan25 [Manager] Special thanks to awkward_potato Siyanew topkecleon Vamptacus Our channels @teleseedch [English] @iranseed [persian] ]], help_text_realm = [[ Realm Commands: !creategroup [Name] Create a group !createrealm [Name] Create a realm !setname [Name] Set realm name !setabout [GroupID] [Text] Set a group's about text !setrules [GroupID] [Text] Set a group's rules !lock [GroupID] [setting] Lock a group's setting !unlock [GroupID] [setting] Unock a group's setting !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [GroupID] Kick all memebers and delete group !kill realm [RealmID] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !log Grt a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups Only sudo users can run this command !br [group_id] [text] !br 123456789 Hello ! This command will send text to [group_id] **U can use both "/" and "!" *Only admins and sudo can add bots in group *Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only admins and sudo can use res, setowner, commands ]], help_text = [[ Commands list : !kick [username|id] You can also do it by reply !ban [ username|id] You can also do it by reply !unban [id] You can also do it by reply !who Members list !modlist Moderators list !promote [username] Promote someone !demote [username] Demote someone !kickme Will kick user !about Group description !setphoto Set and locks group photo !setname [name] Set group name !rules Group rules !id return group id or user id !help !lock [member|name|bots|leave] Locks [member|name|bots|leaveing] !unlock [member|name|bots|leave] Unlocks [member|name|bots|leaving] !set rules <text> Set <text> as rules !set about <text> Set <text> as about !settings Returns group settings !newlink create/revoke your group link !link returns group link !owner returns group owner id !setowner [id] Will set id as owner !setflood [value] Set [value] as flood sensitivity !stats Simple message statistics !save [value] <text> Save <text> as [value] !get [value] Returns text of [value] !clean [modlist|rules|about] Will clear [modlist|rules|about] and set it to nil !res [username] returns user id "!res @username" !log will return group logs !banlist will return group ban list **U can use both "/" and "!" *Only owner and mods can add bots in group *Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only owner can use res,setowner,promote,demote and log commands ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
dacrybabysuck/darkstar
scripts/zones/Korroloka_Tunnel/globals.lua
10
1289
----------------------------------- -- Zone: Korroloka Tunnel (173) -- Desc: this file contains functions that are shared by multiple luas in this zone's directory ----------------------------------- local ID = require("scripts/zones/Korroloka_Tunnel/IDs") require("scripts/globals/status") ----------------------------------- KORROLOKA_TUNNEL = { --[[.............................................................................................. move Morion Worm QM ..............................................................................................]] moveMorionWormQM = function() local npc = GetNPCByID(ID.npc.MORION_WORM_QM) switch (math.random(1, 6)): caseof { [1] = function (x) npc:setPos(254.652, -6.039, 20.878) end, [2] = function (x) npc:setPos(273.350, -7.567, 95.349) end, [3] = function (x) npc:setPos(-43.004, -5.579, 96.528) end, [4] = function (x) npc:setPos(-96.798, -5.679, 94.728) end, [5] = function (x) npc:setPos(-373.924, -10.548, -27.850) end, [6] = function (x) npc:setPos(-376.787, -8.574, -54.842) end, } npc:timer(900000, function(npc) KORROLOKA_TUNNEL.moveMorionWormQM() end) end } return KORROLOKA_TUNNEL
gpl-3.0
dacrybabysuck/darkstar
scripts/zones/Mhaura/npcs/Dieh_Yamilsiah.lua
12
1612
----------------------------------- -- Area: Mhaura -- NPC: Dieh Yamilsiah -- Reports the time remaining before boat arrival. -- !pos 7.057 -2.364 2.489 249 ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) -- Each boat comes every 1152 seconds/8 game hours, 4 hour offset between Selbina and Aht Urghan -- Original timer: local timer = 1152 - ((os.time() - 1009810584)%1152); local timer = 1152 - ((os.time() - 1009810802)%1152); local destination = 0; -- Selbina, set to 1 for Al Zhabi local direction = 0; -- Arrive, 1 for depart local waiting = 216; -- Offset for Selbina -- Next ferry is Al Zhabi for higher values. if (timer >= 576) then destination = 1; timer = timer - 576; waiting = 193; end -- Logic to manipulate cutscene results. if (timer <= waiting) then direction = 1; -- Ship arrived, switch dialog from "arrive" to "depart" else timer = timer - waiting; -- Ship hasn't arrived, subtract waiting time to get time to arrival end player:startEvent(231,timer,direction,0,destination); -- timer arriving/departing ??? destination --[[Other cutscenes: 233 "This ship is headed for Selbina." 234 "The Selbina ferry will deparrrt soon! Passengers are to board the ship immediately!" Can't find a way to toggle the destination on 233 or 234, so they are not used. Users knowing which ferry is which > using all CSs.]] end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
gpl-3.0
dacrybabysuck/darkstar
scripts/zones/Inner_Horutoto_Ruins/npcs/_5c5.lua
8
1533
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: Gate: Magical Gizmo -- Involved In Mission: The Horutoto Ruins Experiment -- !pos 419 0 -27 192 ----------------------------------- local ID = require("scripts/zones/Inner_Horutoto_Ruins/IDs") require("scripts/globals/missions") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) if player:getCurrentMission(WINDURST) == dsp.mission.id.windurst.THE_HORUTOTO_RUINS_EXPERIMENT and player:getCharVar("MissionStatus") == 1 then player:startEvent(42) else player:showText(npc, ID.text.DOOR_FIRMLY_CLOSED) end return 1 end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if csid == 42 then player:setCharVar("MissionStatus", 2) -- Generate a random value to use for the next part of the mission -- where you have to examine 6 Magical Gizmo's, each of them having -- a number from 1 to 6 (Remember, setting 0 deletes the var) local random_value = math.random(1, 6) player:setCharVar("MissionStatus_rv", random_value) -- 'rv' = random value player:setCharVar("MissionStatus_op1", 1) player:setCharVar("MissionStatus_op2", 1) player:setCharVar("MissionStatus_op3", 1) player:setCharVar("MissionStatus_op4", 1) player:setCharVar("MissionStatus_op5", 1) player:setCharVar("MissionStatus_op6", 1) end end
gpl-3.0
thivod/forgottenserver
data/spells/scripts/party/enchant.lua
15
1811
local combat = createCombatObject() local area = createCombatArea(AREA_CROSS5X5) setCombatArea(combat, area) setCombatParam(combat, COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_RED) setCombatParam(combat, COMBAT_PARAM_AGGRESSIVE, 0) local condition = createConditionObject(CONDITION_ATTRIBUTES) setConditionParam(condition, CONDITION_PARAM_SUBID, 3) setConditionParam(condition, CONDITION_PARAM_BUFF_SPELL, 1) setConditionParam(condition, CONDITION_PARAM_TICKS, 2 * 60 * 1000) setConditionParam(condition, CONDITION_PARAM_STAT_MAGICPOINTS, 1) local baseMana = 120 function onCastSpell(cid, var) local pos = getCreaturePosition(cid) local membersList = getPartyMembers(cid) if(membersList == nil or type(membersList) ~= 'table' or #membersList <= 1) then doPlayerSendCancel(cid, "No party members in range.") doSendMagicEffect(pos, CONST_ME_POFF) return LUA_ERROR end local affectedList = {} for _, pid in ipairs(membersList) do if(getDistanceBetween(getCreaturePosition(pid), pos) <= 36) then table.insert(affectedList, pid) end end local tmp = #affectedList if(tmp <= 1) then doPlayerSendCancel(cid, "No party members in range.") doSendMagicEffect(pos, CONST_ME_POFF) return LUA_ERROR end local mana = math.ceil((0.9 ^ (tmp - 1) * baseMana) * tmp) if(getPlayerMana(cid) < mana) then doPlayerSendDefaultCancel(cid, RETURNVALUE_NOTENOUGHMANA) doSendMagicEffect(pos, CONST_ME_POFF) return LUA_ERROR end if(doCombat(cid, combat, var) ~= LUA_NO_ERROR) then doPlayerSendDefaultCancel(cid, RETURNVALUE_NOTPOSSIBLE) doSendMagicEffect(pos, CONST_ME_POFF) return LUA_ERROR end doPlayerAddMana(cid, -(mana - baseMana), FALSE) doPlayerAddManaSpent(cid, (mana - baseMana)) for _, pid in ipairs(affectedList) do doAddCondition(pid, condition) end return LUA_NO_ERROR end
gpl-2.0
dacrybabysuck/darkstar
scripts/globals/mobskills/crystal_weapon_water.lua
11
1048
--------------------------------------------- -- Crystal Weapon -- -- Description: Invokes the power of a crystal to deal magical damage of a random element to a single target. -- Type: Magical -- Utsusemi/Blink absorb: Ignores shadows -- Range: Unknown -- Notes: Can be Fire, Earth, Wind, or Water element. Functions even at a distance (outside of melee range). --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0 end function onMobWeaponSkill(target, mob, skill) local dmgmod = 1 local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg() * 3,dsp.magic.ele.WATER,dmgmod,TP_MAB_BONUS,1) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.WATER,MOBPARAM_IGNORE_SHADOWS) target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.WATER) return dmg end
gpl-3.0
eagle14/kia12
bot/utils.lua
239
13499
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end
gpl-2.0
22333322/i4bot
bot/utils.lua
239
13499
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end
gpl-2.0
25A0/Quadtastic
Quadtastic/res/style.lua
1
7448
return { _META = { image_path = "./style.png", version = "v0.6.2-15-gc6047cf", }, background = {x = 48, y = 16, w = 2, h = 2}, button_border = { b = {x = 3, y = 13, w = 1, h = 3}, bl = {x = 0, y = 13, w = 3, h = 3}, br = {x = 29, y = 13, w = 3, h = 3}, c = {x = 3, y = 3, w = 1, h = 1}, l = {x = 0, y = 3, w = 3, h = 1}, r = {x = 29, y = 3, w = 3, h = 1}, t = {x = 3, y = 0, w = 1, h = 3}, tl = {x = 0, y = 0, w = 3, h = 3}, tr = {x = 29, y = 0, w = 3, h = 3}, }, button_border_disabled = { b = {x = 3, y = 109, w = 1, h = 3}, bl = {x = 0, y = 109, w = 3, h = 3}, br = {x = 29, y = 109, w = 3, h = 3}, c = {x = 3, y = 99, w = 1, h = 1}, l = {x = 0, y = 99, w = 3, h = 1}, r = {x = 29, y = 99, w = 3, h = 1}, t = {x = 3, y = 96, w = 1, h = 3}, tl = {x = 0, y = 96, w = 3, h = 3}, tr = {x = 29, y = 96, w = 3, h = 3}, }, buttons = { delete = {x = 96, y = 64, w = 13, h = 13}, group = {x = 96, y = 48, w = 13, h = 13}, minus = {x = 69, y = 0, w = 5, h = 5}, plus = {x = 64, y = 0, w = 5, h = 5}, rename = {x = 48, y = 64, w = 13, h = 13}, sort = {x = 112, y = 64, w = 13, h = 13}, ungroup = {x = 112, y = 48, w = 13, h = 13}, }, checkbox = { checked = {x = 49, y = 81, w = 9, h = 9}, unchecked = {x = 33, y = 81, w = 9, h = 9}, }, checkbox_large = { checked = {x = 48, y = 32, w = 11, h = 11}, unchecked = {x = 32, y = 32, w = 11, h = 11}, }, crosshair = {x = 64, y = 32, w = 9, h = 9}, filebrowser = { directory = {x = 8, y = 80, w = 8, h = 11}, file = {x = 0, y = 80, w = 8, h = 11}, }, frame_border = { b = {x = 50, y = 14, w = 1, h = 2}, bl = {x = 48, y = 14, w = 2, h = 2}, br = {x = 62, y = 14, w = 2, h = 2}, c = {x = 50, y = 2, w = 1, h = 1}, l = {x = 48, y = 2, w = 2, h = 1}, r = {x = 62, y = 2, w = 2, h = 1}, t = {x = 50, y = 0, w = 1, h = 2}, tl = {x = 48, y = 0, w = 2, h = 2}, tr = {x = 62, y = 0, w = 2, h = 2}, }, input_field_border = { b = {x = 3, y = 29, w = 1, h = 3}, bl = {x = 0, y = 29, w = 3, h = 3}, br = {x = 29, y = 29, w = 3, h = 3}, c = {x = 3, y = 19, w = 1, h = 1}, l = {x = 0, y = 19, w = 3, h = 1}, r = {x = 29, y = 19, w = 3, h = 1}, t = {x = 3, y = 16, w = 1, h = 3}, tl = {x = 0, y = 16, w = 3, h = 3}, tr = {x = 29, y = 16, w = 3, h = 3}, }, menu = { arrow = {x = 96, y = 41, w = 7, h = 7}, b = {x = 98, y = 35, w = 1, h = 2}, bl = {x = 96, y = 35, w = 2, h = 2}, br = {x = 110, y = 35, w = 2, h = 2}, t = {x = 98, y = 32, w = 1, h = 2}, tl = {x = 96, y = 32, w = 2, h = 2}, tr = {x = 110, y = 32, w = 2, h = 2}, }, menu_checkbox = { checked = {x = 73, y = 81, w = 7, h = 7}, unchecked = {x = 65, y = 81, w = 7, h = 7}, }, palette = { image_editor = { bg_A = {x = 2, y = 112, w = 2, h = 2}, bg_B = {x = 2, y = 114, w = 2, h = 2}, }, scrollpane_background = {x = 2, y = 116, w = 2, h = 2}, shades = { bright = {x = 0, y = 118, w = 2, h = 2}, brightest = {x = 0, y = 120, w = 2, h = 2}, dark = {x = 0, y = 114, w = 2, h = 2}, darkest = {x = 0, y = 112, w = 2, h = 2}, neutral = {x = 0, y = 116, w = 2, h = 2}, white = {x = 0, y = 122, w = 2, h = 2}, }, }, panel = { arrow = {x = 9, y = 65, w = 3, h = 6}, b = {x = 4, y = 70, w = 1, h = 3}, bl = {x = 1, y = 70, w = 3, h = 3}, br = {x = 5, y = 70, w = 3, h = 3}, c = {x = 4, y = 68, w = 1, h = 1}, l = {x = 1, y = 68, w = 3, h = 1}, r = {x = 5, y = 68, w = 3, h = 1}, t = {x = 4, y = 65, w = 1, h = 3}, tl = {x = 1, y = 65, w = 3, h = 3}, tr = {x = 5, y = 65, w = 3, h = 3}, }, rowbackground = { collapsed = { default = {x = 17, y = 40, w = 7, h = 7}, hovered = {x = 10, y = 40, w = 7, h = 7}, pressed = {x = 3, y = 40, w = 7, h = 7}, }, default = { bottom = {x = 0, y = 46, w = 1, h = 2}, center = {x = 0, y = 34, w = 1, h = 1}, top = {x = 0, y = 32, w = 1, h = 2}, }, expanded = { default = {x = 17, y = 32, w = 7, h = 7}, hovered = {x = 10, y = 32, w = 7, h = 7}, pressed = {x = 3, y = 32, w = 7, h = 7}, }, hovered = { bottom = {x = 1, y = 46, w = 1, h = 2}, center = {x = 1, y = 34, w = 1, h = 1}, top = {x = 1, y = 32, w = 1, h = 2}, }, selected = { bottom = {x = 2, y = 46, w = 1, h = 2}, center = {x = 2, y = 34, w = 1, h = 1}, top = {x = 2, y = 32, w = 1, h = 2}, }, }, scrollpane = { buttons = { down = { default = {x = 80, y = 9, w = 7, h = 7}, hovered = {x = 112, y = 9, w = 7, h = 7}, pressed = {x = 112, y = 25, w = 7, h = 7}, }, left = { default = {x = 96, y = 9, w = 7, h = 7}, hovered = {x = 121, y = 9, w = 7, h = 7}, pressed = {x = 121, y = 25, w = 7, h = 7}, }, right = { default = {x = 96, y = 0, w = 7, h = 7}, hovered = {x = 121, y = 0, w = 7, h = 7}, pressed = {x = 121, y = 16, w = 7, h = 7}, }, up = { default = {x = 80, y = 0, w = 7, h = 7}, hovered = {x = 112, y = 0, w = 7, h = 7}, pressed = {x = 112, y = 16, w = 7, h = 7}, }, }, corner = {x = 105, y = 9, w = 7, h = 7}, scrollbar_h = { background = {x = 105, y = 0, w = 1, h = 7}, center = {x = 108, y = 0, w = 1, h = 7}, left = {x = 106, y = 0, w = 2, h = 7}, right = {x = 109, y = 0, w = 2, h = 7}, }, scrollbar_v = { background = {x = 105, y = 0, w = 7, h = 1}, bottom = {x = 105, y = 4, w = 7, h = 2}, center = {x = 105, y = 3, w = 7, h = 1}, top = {x = 105, y = 1, w = 7, h = 2}, }, }, toast = { b = {x = 2, y = 62, w = 1, h = 2}, bl = {x = 0, y = 62, w = 2, h = 2}, br = {x = 5, y = 62, w = 2, h = 2}, c = {x = 2, y = 59, w = 1, h = 1}, l = {x = 0, y = 59, w = 2, h = 1}, r = {x = 5, y = 59, w = 2, h = 1}, t = {x = 2, y = 57, w = 1, h = 2}, tl = {x = 0, y = 57, w = 2, h = 2}, tr = {x = 5, y = 57, w = 2, h = 2}, }, tools = { add = {x = 32, y = 48, w = 13, h = 13}, border = {x = 64, y = 48, w = 13, h = 13}, create = {x = 48, y = 48, w = 13, h = 13}, palette = {x = 32, y = 64, w = 13, h = 13}, select = {x = 64, y = 64, w = 13, h = 13}, strip = {x = 80, y = 48, w = 13, h = 13}, wand = {x = 80, y = 64, w = 13, h = 13}, }, tooltip = { border = { b = {x = 2, y = 51, w = 1, h = 2}, bl = {x = 0, y = 51, w = 2, h = 2}, br = {x = 3, y = 51, w = 2, h = 2}, c = {x = 2, y = 50, w = 1, h = 1}, l = {x = 0, y = 50, w = 2, h = 1}, r = {x = 3, y = 50, w = 2, h = 1}, t = {x = 2, y = 48, w = 1, h = 2}, tl = {x = 0, y = 48, w = 2, h = 2}, tr = {x = 3, y = 48, w = 2, h = 2}, }, tip = { downwards = {x = 5, y = 48, w = 9, h = 4}, upwards = {x = 5, y = 51, w = 9, h = 4}, }, }, window_border = { b = {x = 87, y = 41, w = 1, h = 7}, bl = {x = 80, y = 41, w = 7, h = 7}, br = {x = 89, y = 41, w = 7, h = 7}, c = {x = 87, y = 39, w = 1, h = 1}, l = {x = 80, y = 39, w = 7, h = 1}, r = {x = 89, y = 39, w = 7, h = 1}, t = {x = 87, y = 32, w = 1, h = 7}, tl = {x = 80, y = 32, w = 7, h = 7}, tr = {x = 89, y = 32, w = 7, h = 7}, }, }
mit
dacrybabysuck/darkstar
scripts/globals/items/istiridye.lua
11
1149
----------------------------------------- -- ID: 5456 -- Item: Istiridye -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity -5 -- Vitality 4 -- Defense +17.07% ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if (target:getRace() ~= dsp.race.MITHRA) then result = dsp.msg.basic.CANNOT_EAT end if (target:getMod(dsp.mod.EAT_RAW_FISH) == 1) then result = 0 end if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,300,5456) end function onEffectGain(target, effect) target:addMod(dsp.mod.DEX, -5) target:addMod(dsp.mod.VIT, 4) target:addMod(dsp.mod.DEFP, 17.07) end function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, -5) target:delMod(dsp.mod.VIT, 4) target:delMod(dsp.mod.DEFP, 17.07) end
gpl-3.0
SHIELDPOWER/power-team
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
MrTheSoulz/NerdPack
conditions/general.lua
1
4421
local NeP, g = NeP, NeP._G local function checkChanneling(target) local name, _, _, startTime, endTime, _, notInterruptible = g.UnitChannelInfo(target) if name then return name, startTime, endTime, notInterruptible end end local function checkCasting(target) local name, startTime, endTime, notInterruptible = checkChanneling(target) if name then return name, startTime, endTime, notInterruptible end name, _, _, startTime, endTime, _, _, notInterruptible = g.UnitCastingInfo(target) if name then return name, startTime, endTime, notInterruptible end end NeP.DSL:Register('true', function() return true end) NeP.DSL:Register('false', function() return false end) NeP.DSL:Register('timetomax', function(target) local max = g.UnitPowerMax(target) local curr = g.UnitPower(target) local regen = select(2, g.GetPowerRegen(target)) return (max - curr) * (1.0 / regen) end) NeP.DSL:Register('toggle', function(_, toggle) return NeP.Config:Read('TOGGLE_STATES', toggle:lower(), false) end) NeP.DSL:Register('casting.percent', function(target) local name, startTime, endTime = checkCasting(target) if name then local castLength = (endTime - startTime) / 1000 or 0 local secondsDone = g.GetTime() - (startTime / 1000) or 0 return ((secondsDone/castLength)*100) or 0 end return 0 end) NeP.DSL:Register('channeling.percent', function(target) local name, startTime, endTime = checkChanneling(target) if name then local castLength = (endTime - startTime) / 1000 or 0 local secondsDone = g.GetTime() - (startTime / 1000) or 0 return ((secondsDone/castLength)*100) or 0 end return 0 end) NeP.DSL:Register('casting.delta', function(target) local name, startTime, endTime, notInterruptible = checkCasting(target) if name and not notInterruptible then local castLength = (endTime - startTime) / 1000 or 0 local secondsLeft = endTime / 1000 - g.GetTime() or 0 return secondsLeft or 0, castLength or 0 end return 0 end) NeP.DSL:Register('channeling', function (target, spell) local name = checkChanneling(target) spell = NeP.Core:GetSpellName(spell) return spell and (name == spell) end) NeP.DSL:Register('casting', function(target, spell) local name = checkCasting(target) spell = NeP.Core:GetSpellName(spell) return spell and (name == spell) end) NeP.DSL:Register('interruptAt', function (target, spell) if NeP.DSL:Get('is')('player', target) then return false end if spell and NeP.DSL:Get('toggle')(nil, 'Interrupts') then local stopAt = (tonumber(spell) or 35) + math.random(-5, 5) local secondsLeft, castLength = NeP.DSL:Get('casting.delta')(target) return secondsLeft ~= 0 and (100 - (secondsLeft / castLength * 100)) > stopAt end end) local TimeOutTable ={} --USAGE: timeout(TIMER_NAME, SECONDS) NeP.DSL:Register('timeout', function(_, args) local name, time = g.strsplit(',', args, 2) if not TimeOutTable[name] then TimeOutTable[name] = true; g.C_Timer.After(tonumber(time), function() TimeOutTable[name] = nil end); return true; end return not TimeOutTable[name] end) local TimeOutUnitTable ={} --USAGE: UNIT.targettimeout(TIMER_NAME, SECONDS) NeP.DSL:Register('targettimeout', function(target, args) target = NeP.DSL:Get('guid')(target) local name, time = g.strsplit(',', args, 2) if not TimeOutUnitTable[target..name] then TimeOutUnitTable[target..name] = true; g.C_Timer.After(tonumber(time), function() TimeOutUnitTable[target..name] = nil end); return true; end return not TimeOutUnitTable[target..name] end) NeP.DSL:Register('isnear', function(target, args) local targetID, distance = g.strsplit(',', args, 2) targetID = tonumber(targetID) or 0 distance = tonumber(distance) or 60 for _, Obj in pairs(NeP.OM:Get('Enemy')) do if Obj.id == targetID then return NeP.Protected.Distance('player', target) <= distance end end end) NeP.DSL:Register('gcd', function() local class = select(3,g.UnitClass("player")) -- Some class's always have GCD = 1 if class == 4 or (class == 11 and g.GetShapeshiftForm() == 2) or (class == 10 and g.GetSpecialization() ~= 2) then return 1 end return math.floor((1.5 / ((g.GetHaste() / 100) + 1)) * 10^3 ) / 10^3 end) NeP.DSL:Register('ui', function(_, args) local key, UI_key = g.strsplit(",", args, 2) UI_key = UI_key or NeP.CR.CR.name return NeP.Interface:Fetch(UI_key, key) end)
mit
LuaDist2/lua-jet
src/jet/daemon/value_matcher.lua
2
3019
local jutils = require'jet.utils' local tinsert = table.insert local less_than = function(other) return function(x) return x < other end end local greater_than = function(other) return function(x) return x > other end end local equals = function(other) return function(x) return x == other end end local equals_not = function(other) return function(x) return x ~= other end end local is_type = function(typ) local lua_type if typ == 'object' then lua_type = 'table' else lua_type = typ end return function(x) return type(x) == lua_type end end local generators = { lessThan = less_than, greaterThan = greater_than, equals = equals, equalsNot = equals_not, isType = is_type, } local access_field = jutils.access_field local is_table = function(tab) return type(tab) == 'table' end -- given the fetcher options table, creates a function which matches an element (state) value -- against some defined rule. local create_value_matcher = function(options) -- sorting by value implicit defines value matcher rule against expected type. if options.sort then if options.sort.byValue then -- TODO: check that byValue is either 'number','string','boolean' options.value = options.value or {} options.value.isType = options.sort.byValue elseif options.sort.byValueField then local tmp = options.sort.byValueField local fieldname,typ = pairs(tmp)(tmp) options.valueField = options.valueField or {} options.valueField[fieldname] = options.valueField[fieldname] or {} options.valueField[fieldname].isType = typ end end if not options.value and not options.valueField then return nil end local predicates = {} if options.value then for op,comp in pairs(options.value) do local gen = generators[op] if gen then tinsert(predicates,gen(comp)) end end elseif options.valueField then for field_str,conf in pairs(options.valueField) do local accessor = access_field(field_str) local field_predicates = {} for op,comp in pairs(conf) do local gen = generators[op] if gen then tinsert(field_predicates,gen(comp)) end end local field_pred = function(value) if not is_table(value) then return false end local ok,field = pcall(accessor,value) if not ok or not field then return false end for _,pred in ipairs(field_predicates) do if not pred(field) then return false end end return true end tinsert(predicates,field_pred) end end return function(value) for _,pred in ipairs(predicates) do local ok,match = pcall(pred,value) if not ok or not match then return false end end return true end end return { new = create_value_matcher, _generators = generators, _access_field = access_field, }
mit
dacrybabysuck/darkstar
scripts/zones/Gusgen_Mines/npcs/qm2.lua
9
1607
----------------------------------- -- Area: Gusgen Mines -- NPC: qm2 (???) -- Involved In Mission: Bastok 3-2 -- !pos 206 -60 -101 196 ----------------------------------- local ID = require("scripts/zones/Gusgen_Mines/IDs"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/npc_util"); require("scripts/globals/quests"); require("scripts/globals/titles"); ----------------------------------- function onTrade(player,npc,trade) -- TO THE FORSAKEN MINES: Hare Meat if ( player:getCurrentMission(BASTOK) == dsp.mission.id.bastok.TO_THE_FORSAKEN_MINES and npcUtil.tradeHas(trade, 4358) and not player:hasItem(563) and not GetMobByID(ID.mob.BLIND_MOBY):isSpawned() ) then player:confirmTrade(); SpawnMob(ID.mob.BLIND_MOBY):updateClaim(player); -- BLADE OF DEATH: Chaosbringer elseif ( player:getQuestStatus(BASTOK, dsp.quest.id.bastok.BLADE_OF_DEATH) == QUEST_ACCEPTED and player:getCharVar("ChaosbringerKills") >= 200 and npcUtil.tradeHas(trade, 16607) ) then player:startEvent(10); end end; function onTrigger(player,npc) player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY); end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 10 and npcUtil.completeQuest(player, BASTOK, dsp.quest.id.bastok.BLADE_OF_DEATH, {item=16637, title=dsp.title.BLACK_DEATH, var="ChaosbringerKills"})) then player:confirmTrade(); player:delKeyItem(dsp.ki.LETTER_FROM_ZEID); end end;
gpl-3.0
andeandr100/Crumbled-World
Lua/Game/camera.lua
1
15768
require("Menu/settings.lua") --this = Camera() local ZOOM_LEVEL_MIN = 9.5 local ZOOM_LEVEL_MAX = 30.0 --Achievements local music = {} function restore(data) end function create() --Protection in multiplayer environment where multiple instances of this script is loaded local node = this:findNodeByTypeTowardsRoot(NodeId.playerNode) if node and node:getClientId() ~= 0 then return false end if this:getNodeType() == NodeId.camera then setRestoreData(true) local musicList = {"Music/Oceanfloor.wav","Music/Forward_Assault.wav","Music/Ancient_Troops_Amassing.wav","Music/Tower-Defense.wav"} for i=1, #musicList do music[#music+1] = Sound(musicList[i],SoundType.STEREO) end music.token = 1 stateBillboard = Core.getGameSessionBillboard("state") keyBinds = Core.getBillboard("keyBind"); keyBindForward = keyBinds:getKeyBind("Forward") keyBindBackward = keyBinds:getKeyBind("Backward") keyBindLeft = keyBinds:getKeyBind("Left") keyBindRight = keyBinds:getKeyBind("Right") keyBindRotateLeft = keyBinds:getKeyBind("Rotate left") keyBindRotateRight = keyBinds:getKeyBind("Rotate right") keyBindRaise = keyBinds:getKeyBind("Camera raise") keyBindLower = keyBinds:getKeyBind("Camera lower") keyBindChangeCameraMode = keyBinds:getKeyBind("Change mode") buildingBillboard = Core.getBillboard("buildings") billboardStats = Core.getBillboard("stats") updatePosition = true rootNode = this:getRootNode() worldNode = SceneNode() localCameraNode = SceneNode() rootNode:addChild(worldNode) worldNode:addChild(localCameraNode) local localCameraPosition = Vec3(0,13.5,-11) localCameraMatrix = Matrix() localCameraMatrix:createMatrix( localCameraPosition:normalizeV(), Vec3(0,1,0)) localCameraMatrix:setPosition(localCameraPosition) localCameraNode:setLocalMatrix(localCameraMatrix) freeRotation = Vec2(45,180) freePosition = Vec3(0,15,-15) --Try to find if the map have som camera start position information local nodeId = this:findNodeByType(NodeId.fileNode) local MapSettings = {} if nodeId and nodeId:contains("info.txt") then MapSettings = totable( nodeId:getFile("info.txt"):getContent() ) end cameraSpeed = 20 cameraLocalPos = MapSettings.cameraLocalPos and MapSettings.cameraLocalPos or Vec3(0,13.5,-11) cameraCenterPos = MapSettings.cameraCenterPos and MapSettings.cameraCenterPos or Vec3() cameraRotation = MapSettings.cameraRotation and MapSettings.cameraRotation or 0 if Core.getPlayerId() ~= 0 and MapSettings["camera"..Core.getPlayerId().."LocalPos"] then cameraLocalPos = MapSettings["camera"..Core.getPlayerId().."LocalPos"] and MapSettings["camera"..Core.getPlayerId().."LocalPos"] or cameraLocalPos cameraCenterPos = MapSettings["camera"..Core.getPlayerId().."CenterPos"] and MapSettings["camera"..Core.getPlayerId().."CenterPos"] or cameraCenterPos cameraRotation = MapSettings["camera"..Core.getPlayerId().."Rotation"] and MapSettings["camera"..Core.getPlayerId().."Rotation"] or cameraRotation end this:setLocalMatrix(localCameraNode:getGlobalMatrix()) worldMin = rootNode:getGlobalBoundingBox():getMinPos() worldMax = rootNode:getGlobalBoundingBox():getMaxPos() cameraMode = 0 pathBilboard = Core.getGlobalBillboard("Paths") tmpUpdate = update update = countDownUpdate resetTime = 1 previousTargetIsland = nil inShiftMode = false local test1 = this this:loadLuaScript("Enviromental/clouds.lua") --Core.setMainCamera(this) -- this:setClearColor(Vec4(Vec3(0.4),1)) settingsListener = Listener("Settings") settingsListener:registerEvent("Changed", settingsChanged) settingsChanged() cameraOveride = Listener("cameraOveride") cameraOveride:registerEvent("Pause", pauseCamera) cameraOveride:registerEvent("Resume", resumeCamera) else local camera = this:getRootNode():addChild(Camera(Text("MainCamera"), true)) --camera = Camera() camera = ConvertToCamera(camera) camera:setEnableUpdates(true) camera:setDirectionLight(Core.getDirectionalLight(this)) camera:setAmbientLight(Core.getAmbientLight(this)) camera:setDefferRenderShader(Settings.getDeferredShader()) camera:setUseShadow(Settings.shadow.getIsEnabled()) camera:setUseGlow(Settings.glow.getEnabled()) camera:setUseSelectedRender(true) camera:createWork() -- camera:setClearColor(Vec4(0.6,0.6,0.6,1)) --add information to which camera is the main camera Core.setDebug2DCamera(camera) --Move this script to the camera node camera:loadLuaScript(this:getCurrentScript():getFileName()); return false end return true end function pauseCamera() updatePosition = false end function resumeCamera() updatePosition = true end function settingsChanged() print("\n\n\n\n") Core.setRenderScale(Settings.renderScale.getValue()) -- Core.setRenderResolution(Settings.resolution.getResolution()) this:setDefferRenderShader(Settings.getDeferredShader()) this:setUseShadow(Settings.shadow.getIsEnabled()) this:setShadowScale(Settings.shadowResolution.getValue()) this:setDynamicLightsEnable(Settings.dynamicLights.getEnabled()) this:setUseGlow(Settings.glow.getEnabled()) this:setUseAntiAliasing(Settings.Antialiasing.getEnabled()) --Settings.resolution.getResolution() print("\n\n") end function getAtVec() local atVec = this:getGlobalMatrix():getAtVec() atVec.y = 0 return -atVec:normalizeV() end function getRightVec() local rightVec = this:getGlobalMatrix():getRightVec() rightVec.y = 0 return -rightVec:normalizeV() end function getIslandMovmentSpeed() if Core.isInEditor() then --island in editor should not move return Vec3() end local range = 15 --find all islands within 50m local islands = rootNode:getAllNodeByTypeTowardsLeafWithinSphere(NodeId.island, Sphere(cameraCenterPos,range)) local targetNormal = Vec3() local targetPosition = Vec3() local islandMovement = Vec3() local newWorldMin = worldMin local newWorldMax = worldMax local targetIsland = nil if #islands > 0 then --we start maxDist at 1 because we cant divide by 0 local data = {size = 0} newWorldMin = islands[1]:getGlobalBoundingBox():getMinPos() newWorldMax = islands[1]:getGlobalBoundingBox():getMaxPos() for i=1, #islands do newWorldMin:minimize(islands[i]:getGlobalBoundingBox():getMinPos()) newWorldMax:maximize(islands[i]:getGlobalBoundingBox():getMaxPos()) local pos = Vec3(cameraCenterPos) local dist = islands[i]:getDistanceToIsland(pos) if dist < range then if dist < 0.001 then targetIsland = islands[i] targetPosition = pos end data.size = data.size + 1 data[data.size] = {position = Vec3(pos), distance = math.max(dist,0.5), normal = islands[i]:getGlobalMatrix():getUpVec(), islandVelocity = islands[i]:getVelocity(), weight = 1 } end end if targetIsland then if previousTargetIsland ~= targetIsland then if previousTargetIsland then previousTargetIsland:unLockIslandMovment() end targetIsland:lockDownIslandMovment() previousTargetIsland = targetIsland end targetNormal = targetIsland:getGlobalMatrix():getUpVec() islandMovement = Vec3()-- targetIsland:getVelocity() else --calculate the weight local totalWeight = 0 local minDistance = range for i=1, data.size do if data[i].distance < minDistance then minDistance = data[i].distance end local weight = 0 for j=1, data.size do if not i == j then weight = weight + data[j].distance/data[i].distance end end data[i].weight = weight if data[i].weight == 0 then data[i].weight = 1 end totalWeight = totalWeight + weight end if totalWeight == 0 then totalWeight = 1 end if data.size > 0 then local totalWeightTest = 0; for i=1, data.size do local weight = minDistance / data[i].distance --data[i].weight / totalWeight; totalWeightTest = totalWeightTest + weight; islandMovement = islandMovement + data[i].islandVelocity * weight targetPosition = targetPosition + data[i].position * weight targetNormal = targetNormal + data[i].normal * weight end targetNormal:normalize() islandMovement = islandMovement / totalWeightTest targetPosition = targetPosition / totalWeightTest end end end worldMin:minimize(newWorldMin) worldMax:maximize(newWorldMax) targetPosition = targetPosition + islandMovement return targetIsland and Vec3() or islandMovement end function countDownUpdate() resetTime = resetTime - Core.getRealDeltaTime() print("\ncamera pre update\n") --only render the world when it's ready to be shown, or when a a very long time has passed if (resetTime < 0.0 and pathBilboard and pathBilboard:exist("spawnPortals")) or resetTime < -15 then Core.setMainCamera(this) Core.setSoundCamera(nil) update = tmpUpdate end print("DeltaTime: "..Core.getRealDeltaTime()) print("countDownUpdate: "..resetTime) return true end function update() if not worldNode then if backgroundSource then backgroundSource:stopFadeOut(0.5) end return false end --music if music.source then if Core.getTime()-music.timer > 300.0 then music.source:stopFadeOut(0.5) music.token = music[music.token+1] and music.token+1 or 1 music.source = music[music.token]:playSound(0.075, true) music.timer = Core.getTime() end else music.token = 1 music.source = music[music.token]:playSound(0.075, true) music.timer = Core.getTime() end if keyBindChangeCameraMode:getPressed() then if Core.isInEditor() or DEBUG or true then cameraMode = (cameraMode + 1) % 2 else cameraMode = 0 end end if cameraMode == 1 then local deltaTime = Core.getRealDeltaTime() local localMat = this:getLocalMatrix() if not Core.getPanelWithKeyboardFocus() then if keyBindForward:getHeld() then freePosition = freePosition - localMat:getAtVec() * deltaTime * 25 end if keyBindBackward:getHeld() then freePosition = freePosition + localMat:getAtVec() * deltaTime * 25 end if keyBindLeft:getHeld() then freePosition = freePosition - localMat:getRightVec() * deltaTime * 25 end if keyBindRight:getHeld() then freePosition = freePosition + localMat:getRightVec() * deltaTime * 25 end if Core.getInput():getKeyHeld(Key.space) then freeRotation.x = freeRotation.x + Core.getInput():getMouseDelta().y * 0.001 freeRotation.y = freeRotation.y + Core.getInput():getMouseDelta().x * 0.001 end end local qx = Quat(Vec3(1,0,0), freeRotation.x) local qy = Quat(Vec3(0,1,0), freeRotation.y) localMat = (qx * qy):getMatrix() localMat:setPosition(freePosition) this:setLocalMatrix(localMat) this:render() return true elseif cameraMode == 0 then --the camera should move in the same speed whatever the game speed is running at --clamp the time to protect from freze lag and extreme cases local deltaTime = math.clamp( Core.getRealDeltaTime(), 0, 0.2) if updatePosition and not stateBillboard:getBool("inMenu") then if not Core.getPanelWithKeyboardFocus() then if keyBindForward:getHeld() then cameraCenterPos = cameraCenterPos + getAtVec() * deltaTime * cameraSpeed end if keyBindBackward:getHeld() then cameraCenterPos = cameraCenterPos - getAtVec() * deltaTime * cameraSpeed end if keyBindLeft:getHeld() then cameraCenterPos = cameraCenterPos + getRightVec() * deltaTime * cameraSpeed end if keyBindRight:getHeld() then cameraCenterPos = cameraCenterPos - getRightVec() * deltaTime * cameraSpeed end end if Core.isInFullscreen() then local mousePos = Core.getInput():getMousePos() local screenSize = Core.getScreenResolution() if mousePos.x < 4.0 then cameraCenterPos = cameraCenterPos + getRightVec() * deltaTime * cameraSpeed elseif mousePos.x > screenSize.x - 4.0 then cameraCenterPos = cameraCenterPos - getRightVec() * deltaTime * cameraSpeed end if mousePos.y < 4.0 then cameraCenterPos = cameraCenterPos + getAtVec() * deltaTime * cameraSpeed elseif mousePos.y > screenSize.y - 4.0 then cameraCenterPos = cameraCenterPos - getAtVec() * deltaTime * cameraSpeed end end --Roation controll if keyBindRotateLeft:getHeld() or keyBindRotateRight:getHeld() or Core.getInput():getMouseHeld(MouseKey.middle) then if keyBindRotateLeft:getHeld() then cameraRotation = cameraRotation + deltaTime end if keyBindRotateRight:getHeld() then cameraRotation = cameraRotation - deltaTime end if Core.getInput():getMouseHeld(MouseKey.middle) then --support all screen resolution local screenResolution = Core.getScreenResolution() cameraRotation = cameraRotation + (Core.getInput():getMouseDelta().x/screenResolution.x) * 4 + (Core.getInput():getMouseDelta().y/screenResolution.x) * 4 end end if Core.getInput():getKeyHeld(Key.lshift) and not Core.getInput():getMouseHeld(MouseKey.middle) then inShiftMode = true Core.getCursor():setRelativeMouseMode(true) local screenResolution = Core.getScreenResolution() cameraRotation = cameraRotation + (Core.getInput():getMouseDelta().x/screenResolution.x) * 4 elseif inShiftMode then inShiftMode = false Core.getCursor():setRelativeMouseMode(false) Core.getCursor():warpMousePosition(Core.getScreenResolution() * 0.5) end --update camera Ypos --Mouse wheel ticket is only updated, when not in editor mode, or in build mode, or mouse is howering over a panel with scrollbar. local mousePanel = Core.getPanelWithMouseFocus() if not Core.isInEditor() and not (buildingBillboard and buildingBillboard:getBool("inBuildMode") and not Core.getInput():getKeyHeld(Key.lshift)) and billboardStats and billboardStats:getPanel("MainPanel") == mousePanel and not (mousePanel and mousePanel:getYScrollBar()) then local ticks = Core.getInput():getMouseWheelTicks() cameraLocalPos.y = math.clamp(cameraLocalPos.y - ticks * 0.4, ZOOM_LEVEL_MIN, ZOOM_LEVEL_MAX ) end if keyBindRaise:getHeld() then cameraLocalPos.y = math.clamp(cameraLocalPos.y + Core.getDeltaTime() * 4, ZOOM_LEVEL_MIN, ZOOM_LEVEL_MAX ) end if keyBindLower:getHeld() then cameraLocalPos.y = math.clamp(cameraLocalPos.y - Core.getDeltaTime() * 4, ZOOM_LEVEL_MIN, ZOOM_LEVEL_MAX ) end --Keep camera close to the island cameraCenterPos = cameraCenterPos + getIslandMovmentSpeed() * Core.getDeltaTime() if not Core.isInEditor() then cameraCenterPos = Vec3( math.clamp( cameraCenterPos.x, worldMin.x, worldMax.x ), 0, math.clamp( cameraCenterPos.z, worldMin.z, worldMax.z ) ) end -- Core.addDebugBox(Box(worldMin, worldMax),0, Vec3(1)) local camMatrix = Matrix(cameraCenterPos) camMatrix:rotate(Vec3(0,1,0), cameraRotation) camMatrix:setPosition( camMatrix * cameraLocalPos ) camMatrix:createMatrix( -(cameraCenterPos - camMatrix:getPosition()):normalizeV(), Vec3(0,1,0)) this:setLocalMatrix(camMatrix) end --prepare sound matrix local camAtLine = Line3D( this:getGlobalPosition(), this:getAtVec(), 15 ) local soundLine = Line3D( Vec3(camAtLine.startPos.x, 5, camAtLine.startPos.z), Vec3(camAtLine.endPos.x, 5, camAtLine.endPos.z)) local distance, collpos = Collision.lineSegmentLineSegmentLength2(camAtLine, soundLine) local globalMatrix =this:getGlobalMatrix() local camMatrix = Matrix(collpos) camMatrix:createMatrix( -globalMatrix:getAtVec(), globalMatrix:getUpVec() ) -- Core.addDebugSphere(Sphere(collpos, 0.3),0,Vec3(1,0,0)) --set sound matrix Core.setSoundCameraMatrix(camMatrix) this:render() return true; end this:render() return true end
mit
dacrybabysuck/darkstar
scripts/zones/Lufaise_Meadows/Zone.lua
9
2242
----------------------------------- -- -- Zone: Lufaise_Meadows (24) -- ----------------------------------- local ID = require("scripts/zones/Lufaise_Meadows/IDs"); require("scripts/globals/conquest"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/npc_util"); require("scripts/globals/titles"); require("scripts/globals/helm") ----------------------------------- function onInitialize(zone) zone:registerRegion(1,179,-26,327,219,-18,347); SetServerVariable("realPadfoot",math.random(1,5)); for _, v in pairs(ID.mob.PADFOOT) do SpawnMob(v); end dsp.conq.setRegionalConquestOverseers(zone:getRegionID()); dsp.helm.initZone(zone, dsp.helm.type.LOGGING) end; function onConquestUpdate(zone, updatetype) dsp.conq.onConquestUpdate(zone, updatetype) end; function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-475.825,-20.461,281.149,11); end if (player:getCurrentMission(COP) == dsp.mission.id.cop.AN_INVITATION_WEST and player:getCharVar("PromathiaStatus") == 0) then cs = 110; elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.CHAINS_AND_BONDS and player:getCharVar("PromathiaStatus") == 0) then cs = 111; end return cs; end; function onRegionEnter(player,region) local regionID = region:GetRegionID(); if (regionID == 1 and player:getCurrentMission(COP) == dsp.mission.id.cop.DAWN and player:getCharVar("PromathiaStatus") == 6) then player:startEvent(116); end end; function onRegionLeave(player,region) end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 110) then player:messageSpecial(ID.text.KI_STOLEN,0,dsp.ki.MYSTERIOUS_AMULET); player:delKeyItem(dsp.ki.MYSTERIOUS_AMULET); player:setCharVar("PromathiaStatus",1); elseif (csid == 111 and npcUtil.giveItem(player, 14657)) then player:setCharVar("PromathiaStatus",1); elseif (csid == 116) then player:setCharVar("PromathiaStatus",7); player:addTitle(dsp.title.BANISHER_OF_EMPTINESS); end end;
gpl-3.0
dacrybabysuck/darkstar
scripts/globals/pets.lua
14
30487
----------------------------------- -- -- PETS ID -- ----------------------------------- dsp = dsp or {} dsp.pet = dsp.pet or {} ----------------------------------- -- Pet types ----------------------------------- dsp.pet.type = { AVATAR = 0, WYVERN = 1, JUGPET = 2, CHARMED_MOB = 3, AUTOMATON = 4, ADVENTURING_FELLOW = 5, CHOCOBO = 6, } ----------------------------------- -- Pet IDs ----------------------------------- dsp.pet.id = { -- Summoner FIRE_SPIRIT = 0, ICE_SPIRIT = 1, AIR_SPIRIT = 2, EARTH_SPIRIT = 3, THUNDER_SPIRIT = 4, WATER_SPIRIT = 5, LIGHT_SPIRIT = 6, DARK_SPIRIT = 7, CARBUNCLE = 8, FENRIR = 9, IFRIT = 10, TITAN = 11, LEVIATHAN = 12, GARUDA = 13, SHIVA = 14, RAMUH = 15, DIABOLOS = 16, ALEXANDER = 17, ODIN = 18, ATOMOS = 19, CAIT_SITH = 20, -- Beastmaster SHEEP_FAMILIAR = 21, HARE_FAMILIAR = 22, CRAB_FAMILIAR = 23, COURIER_CARRIE = 24, HOMUNCULUS = 25, FLYTRAP_FAMILIAR = 26, TIGER_FAMILIAR = 27, FLOWERPOT_BILL = 28, EFT_FAMILIAR = 29, LIZARD_FAMILIAR = 30, MAYFLY_FAMILIAR = 31, FUNGUAR_FAMILIAR = 32, BEETLE_FAMILIAR = 33, ANTLION_FAMILIAR = 34, MITE_FAMILIAR = 35, LULLABY_MELODIA = 36, KEENEARED_STEFFI = 37, FLOWERPOT_BEN = 38, SABER_SIRAVARDE = 39, COLDBLOOD_COMO = 40, SHELLBUSTER_OROB = 41, VORACIOUS_AUDREY = 42, AMBUSHER_ALLIE = 43, LIFEDRINKER_LARS = 44, PANZER_GALAHAD = 45, CHOPSUEY_CHUCKY = 46, AMIGO_SABOTENDER = 47, -- Dragoon WYVERN = 48, -- Puppetmaster AUTOMATON = 69, } ----------------------------------- -- Pet names ----------------------------------- dsp.pet.name = { AZURE = 1, CERULEAN = 2, RYGOR = 3, FIREWING = 4, DELPHYNE = 5, EMBER = 6, ROVER = 7, MAX = 8, BUSTER = 9, DUKE = 10, OSCAR = 11, MAGGIE = 12, JESSIE = 13, LADY = 14, HIEN = 15, RAIDEN = 16, LUMIERE = 17, EISENZAHN = 18, PFEIL = 19, WUFFI = 20, GEORGE = 21, DONRYU = 22, QIQIRU = 23, KARAV_MARAV = 24, OBORO = 25, DARUG_BORUG = 26, MIKAN = 27, VHIKI = 28, SASAVI = 29, TATANG = 30, NANAJA = 31, KHOCHA = 32, DINO = 33, CHOMPER = 34, HUFFY = 35, POUNCER = 36, FIDO = 37, LUCY = 38, JAKE = 39, ROCKY = 40, REX = 41, RUSTY = 42, HIMMELSKRALLE = 43, GIZMO = 44, SPIKE = 45, SYLVESTER = 46, MILO = 47, TOM = 48, TOBY = 49, FELIX = 50, KOMET = 51, BO = 52, MOLLY = 53, UNRYU = 54, DAISY = 55, BARON = 56, GINGER = 57, MUFFIN = 58, LUMINEUX = 59, QUATREVENTS = 60, TORYU = 61, TATABA = 62, ETOILAZUREE = 63, GRISNUAGE = 64, BELORAGE = 65, CENTONNERRE = 66, NOUVELLUNE = 67, MISSY = 68, AMEDEO = 69, TRANCHEVENT = 70, SOUFFLEFEU = 71, ETOILE = 72, TONNERRE = 73, NUAGE = 74, FOUDRE = 75, HYUH = 76, ORAGE = 77, LUNE = 78, ASTRE = 79, WAFFENZAHN = 80, SOLEIL = 81, COURAGEUX = 82, KOFFLA_PAFFLA = 83, VENTEUSE = 84, LUNAIRE = 85, TORA = 86, CELESTE = 87, GALJA_MOGALJA = 88, GABOH = 89, VHYUN = 90, ORAGEUSE = 91, STELLAIRE = 92, SOLAIRE = 93, WIRBELWIND = 94, BLUTKRALLE = 95, BOGEN = 96, JUNKER = 97, FLINK = 98, KNIRPS = 99, BODO = 100, SORYU = 101, WAWARO = 102, TOTONA = 103, LEVIAN_MOVIAN = 104, KAGERO = 105, JOSEPH = 106, PAPARAL = 107, COCO = 108, RINGO = 109, NONOMI = 110, TETER = 111, GIGIMA = 112, GOGODAVI = 113, RURUMO = 114, TUPAH = 115, JYUBIH = 116, MAJHA = 117, LURON = 118, DRILLE = 119, TOURNEFOUX = 120, CHAFOUIN = 121, PLAISANTIN = 122, LOUSTIC = 123, HISTRION = 124, BOBECHE = 125, BOUGRION = 126, ROULETEAU = 127, ALLOUETTE = 128, SERENADE = 129, FICELETTE = 130, TOCADIE = 131, CAPRICE = 132, FOUCADE = 133, CAPILLOTTE = 134, QUENOTTE = 135, PACOTILLE = 136, COMEDIE = 137, KAGEKIYO = 138, TORAOH = 139, GENTA = 140, KINTOKI = 141, KOUMEI = 142, PAMAMA = 143, LOBO = 144, TSUKUSHI = 145, ONIWAKA = 146, KENBISHI = 147, HANNYA = 148, MASHIRA = 149, NADESHIKO = 150, E100 = 151, KOUME = 152, X_32 = 153, POPPO = 154, ASUKA = 155, SAKURA = 156, TAO = 157, MAO = 158, GADGET = 159, MARION = 160, WIDGET = 161, QUIRK = 162, SPROCKET = 163, COGETTE = 164, LECTER = 165, COPPELIA = 166, SPARKY = 167, CLANK = 168, CALCOBRENA = 169, CRACKLE = 170, RICOCHET = 171, JOSETTE = 172, FRITZ = 173, SKIPPY = 174, PINO = 175, MANDARIN = 176, JACKSTRAW = 177, GUIGNOL = 178, MOPPET = 179, NUTCRACKER = 180, ERWIN = 181, OTTO = 182, GUSTAV = 183, MUFFIN = 184, XAVER = 185, TONI = 186, INA = 187, GERDA = 188, PETRA = 189, VERENA = 190, ROSI = 191, SCHATZI = 192, WARASHI = 193, KLINGEL = 194, CLOCHETTE = 195, CAMPANELLO = 196, KAISERIN = 197, PRINCIPESSA = 198, BUTLER = 199, GRAF = 200, CARO = 201, CARA = 202, MADEMOISELLE = 203, HERZOG = 204, TRAMP = 205, V_1000 = 206, HIKOZAEMON = 207, NINE = 208, ACHT = 209, QUATTRO = 210, ZERO = 211, DREIZEHN = 212, SEIZE = 213, FUKUSUKE = 214, MATAEMON = 215, KANSUKE = 216, POLICHINELLE = 217, TOBISUKE = 218, SASUKE = 219, SHIJIMI = 220, CHOBI = 221, AURELIE = 222, MAGALIE = 223, AURORE = 224, CAROLINE = 225, ANDREA = 226, MACHINETTE = 227, CLARINE = 228, ARMELLE = 229, REINETTE = 230, DORLOTE = 231, TURLUPIN = 232, KLAXON = 233, BAMBINO = 234, POTIRON = 235, FUSTIGE = 236, AMIDON = 237, MACHIN = 238, BIDULON = 239, TANDEM = 240, PRESTIDIGE = 241, PURUTE_PORUTE = 242, BITO_RABITO = 243, COCOA = 244, TOTOMO = 245, CENTURION = 246, A7V = 247, SCIPIO = 248, SENTINEL = 249, PIONEER = 250, SENESCHAL = 251, GINJIN = 252, AMAGATSU = 253, DOLLY = 254, FANTOCCINI = 255, JOE = 256, KIKIZARU = 257, WHIPPET = 258, PUNCHINELLO = 259, CHARLIE = 260, MIDGE = 261, PETROUCHKA = 262, SCHNEIDER = 263, USHABTI = 264, NOEL = 265, YAJIROBE = 266, HINA = 267, NORA = 268, SHOKI = 269, KOBINA = 270, KOKESHI = 271, MAME = 272, BISHOP = 273, MARVIN = 274, DORA = 275, DATA = 276, ROBIN = 277, ROBBY = 278, PORLO_MOPERLO = 279, PAROKO_PURONKO= 280, PIPIMA = 281, GAGAJA = 282, MOBIL = 283, DONZEL = 284, ARCHER = 285, SHOOTER = 286, STEPHEN = 287, MK_IV = 288, CONJURER = 289, FOOTMAN = 290, TOKOTOKO = 291, SANCHO = 292, SARUMARO = 293, PICKET = 294, MUSHROOM = 295, G = 296, I = 297, Q = 298, V = 299, X = 300, Z = 301, II = 302, IV = 303, IX = 304, OR = 305, VI = 306, XI = 307, ACE = 308, AIR = 309, AKI = 310, AYU = 311, BAT = 312, BEC = 313, BEL = 314, BIG = 315, BON = 316, BOY = 317, CAP = 318, COQ = 319, CRY = 320, DOM = 321, DUC = 322, DUN = 323, END = 324, ETE = 325, EYE = 326, FAT = 327, FEE = 328, FER = 329, FEU = 330, FOG = 331, FOX = 332, HOT = 333, ICE = 334, ICE = 335, ICY = 336, III = 337, JET = 338, JOY = 339, LEG = 340, MAX = 341, NEO = 342, ONE = 343, PUR = 344, RAY = 345, RED = 346, ROI = 347, SEA = 348, SKY = 349, SUI = 350, SUN = 351, TEN = 352, VIF = 353, VII = 354, XII = 355, AILE = 356, ANGE = 357, ARDI = 358, BEAK = 359, BEAU = 360, BEST = 361, BLEU = 362, BLUE = 363, BONE = 364, CART = 365, CHIC = 366, CIEL = 367, CLAW = 368, COOL = 369, DAME = 370, DARK = 371, DORE = 372, DRAY = 373, DUKE = 374, EASY = 375, EDEL = 376, FACE = 377, FAST = 378, FIER = 379, FINE = 380, FIRE = 381, FOOT = 382, FURY = 383, FUYU = 384, GALE = 385, GIRL = 386, GOER = 387, GOLD = 388, GOOD = 389, GRAF = 390, GRAY = 391, GUST = 392, GUTE = 393, HAOH = 394, HARU = 395, HELD = 396, HERO = 397, HOPE = 398, IDOL = 399, IRIS = 400, IRON = 401, JACK = 402, JADE = 403, JOLI = 404, JUNG = 405, KIKU = 406, KING = 407, KOPF = 408, LADY = 409, LAST = 410, LILI = 411, LILY = 412, LINE = 413, LONG = 414, LORD = 415, LUFT = 416, LUNA = 417, LUNE = 418, MAMA = 419, MARS = 420, MIEL = 421, MISS = 422, MOMO = 423, MOND = 424, MOON = 425, NANA = 426, NICE = 427, NOIR = 428, NONO = 429, NOVA = 430, NUIT = 431, OCRE = 432, OLLE = 433, PAPA = 434, PERS = 435, PHAR = 436, PONY = 437, PURE = 438, RAIN = 439, RICE = 440, RICH = 441, ROAD = 442, ROSE = 443, ROTE = 444, ROUX = 445, RUBY = 446, SAGE = 447, SNOW = 448, STAR = 449, TAIL = 450, TROT = 451, VEGA = 452, VENT = 453, VERT = 454, VIII = 455, VIVE = 456, WAVE = 457, WEST = 458, WILD = 459, WIND = 460, WING = 461, XIII = 462, ZERO = 463, ACIER = 464, AGATE = 465, AGILE = 466, AGNES = 467, AILEE = 468, ALPHA = 469, AMBER = 470, AMBRE = 471, ANGEL = 472, ARDIE = 473, ARKIE = 474, ARROW = 475, AVIAN = 476, AZURE = 477, BARON = 478, BELLE = 479, BERYL = 480, BLACK = 481, BLADE = 482, BLAUE = 483, BLAZE = 484, BLEUE = 485, BLITZ = 486, BLOND = 487, BLOOD = 488, BONNE = 489, BRAVE = 490, BRIAN = 491, BRISE = 492, BURST = 493, CALME = 494, CHAOS = 495, CLAIR = 496, CLOUD = 497, COMET = 498, COMTE = 499, COURT = 500, CRAFT = 501, CRETE = 502, CROWN = 503, DANCE = 504, DANDY = 505, DEVIL = 506, DIANA = 507, DOREE = 508, DREAM = 509, EAGER = 510, EAGLE = 511, EBONY = 512, EISEN = 513, EMBER = 514, ENGEL = 515, FAIRY = 516, FATTY = 517, FEDER = 518, FEUER = 519, FIERE = 520, FIERY = 521, FINAL = 522, FLARE = 523, FLEET = 524, FLEUR = 525, FLIER = 526, FLOOD = 527, FLORA = 528, FLYER = 529, FRAIS = 530, FROST = 531, FUCHS = 532, GALOP = 533, GEIST = 534, GELBE = 535, GHOST = 536, GLORY = 537, GRAND = 538, GREAT = 539, GREEN = 540, GUTER = 541, GUTES = 542, HEART = 543, HELLE = 544, HIDEN = 545, HITEN = 546, HIVER = 547, HOBBY = 548, HYPER = 549, IVORY = 550, JAUNE = 551, JEUNE = 552, JINPU = 553, JOLIE = 554, JOLLY = 555, KLUGE = 556, KNIFE = 557, KOMET = 558, KUGEL = 559, LAHME = 560, LESTE = 561, LIGHT = 562, LILAS = 563, LUCKY = 564, LUNAR = 565, LUTIN = 566, MAGIC = 567, MERRY = 568, METAL = 569, NATSU = 570, NEDDY = 571, NIGHT = 572, NINJA = 573, NOBLE = 574, NOIRE = 575, NUAGE = 576, OCREE = 577, OLIVE = 578, OLLER = 579, OLLES = 580, OMEGA = 581, OPALE = 582, ORAGE = 583, PATTE = 584, PEACE = 585, PENNE = 586, PETIT = 587, PFEIL = 588, PLUIE = 589, PLUME = 590, PLUTO = 591, POINT = 592, POMME = 593, POWER = 594, QUAKE = 595, QUEEN = 596, QUEUE = 597, REINE = 598, REPPU = 599, RICHE = 600, RIEUR = 601, ROTER = 602, ROTES = 603, ROUGE = 604, ROYAL = 605, RUBIN = 606, RUBIS = 607, SAURE = 608, SERRE = 609, SMALT = 610, SNOWY = 611, SOLAR = 612, SPARK = 613, SPEED = 614, STEED = 615, STERN = 616, STONE = 617, STORM = 618, STURM = 619, STUTE = 620, SUPER = 621, SWEEP = 622, SWEET = 623, SWIFT = 624, TALON = 625, TEIOH = 626, TITAN = 627, TURBO = 628, ULTRA = 629, URARA = 630, VENUS = 631, VERTE = 632, VERVE = 633, VIVID = 634, VOGEL = 635, YOUNG = 636, ZIPPY = 637, AIRAIN = 638, AMBREE = 639, AMIRAL = 640, ARASHI = 641, ARCHER = 642, ARDENT = 643, ARGENT = 644, AUDACE = 645, AUTUMN = 646, BATTLE = 647, BEAUTE = 648, BEAUTY = 649, BEETLE = 650, BLAUER = 651, BLAUES = 652, BLEUET = 653, BLONDE = 654, BONBON = 655, BREEZE = 656, BRONZE = 657, BRUMBY = 658, BUCKER = 659, CAESAR = 660, CARMIN = 661, CERISE = 662, CERULE = 663, CHANCE = 664, CINDER = 665, CITRON = 666, CLAIRE = 667, COBALT = 668, CORAIL = 669, COURTE = 670, CUIVRE = 671, DANCER = 672, DARING = 673, DESERT = 674, DOBBIN = 675, DUNKLE = 676, ELANCE = 677, EMBLEM = 678, ENZIAN = 679, ESPRIT = 680, ETOILE = 681, FILANT = 682, FLAMME = 683, FLECHE = 684, FLIGHT = 685, FLINKE = 686, FLOWER = 687, FLURRY = 688, FLYING = 689, FOREST = 690, FREEZE = 691, FREUND = 692, FRIEND = 693, FROSTY = 694, FROZEN = 695, FUBUKI = 696, GALAXY = 697, GANGER = 698, GELBER = 699, GELBES = 700, GINGER = 701, GLOIRE = 702, GLORIE = 703, GOEMON = 704, GRANDE = 705, GRENAT = 706, GROOVE = 707, GROSSE = 708, GRUENE = 709, GUSTAV = 710, HAYATE = 711, HELDIN = 712, HELLER = 713, HELLES = 714, HENGST = 715, HERMES = 716, HERZOG = 717, HIMMEL = 718, HUMBLE = 719, IDATEN = 720, IMPACT = 721, INDIGO = 722, JAGGER = 723, JASMIN = 724, JOYEUX = 725, JUNGLE = 726, KAISER = 727, KEFFEL = 728, KLEINE = 729, KLUGER = 730, KLUGES = 731, KOLOSS = 732, LAHMER = 733, LAHMES = 734, LANCER = 735, LANDER = 736, LAUREL = 737, LEAPER = 738, LEGEND = 739, LIMBER = 740, LONGUE = 741, MELODY = 742, METEOR = 743, MIRAGE = 744, MISTER = 745, MOTION = 746, MUGUET = 747, NATURE = 748, NEBULA = 749, NETHER = 750, NIMBLE = 751, OLYMPE = 752, ORCHID = 753, OUTLAW = 754, PASSER = 755, PASTEL = 756, PELTER = 757, PENSEE = 758, PETITE = 759, PIMENT = 760, POETIC = 761, POULET = 762, PRESTE = 763, PRETTY = 764, PRINCE = 765, PURETE = 766, QUARTZ = 767, QUASAR = 768, RAFALE = 769, RAGING = 770, RAIDEN = 771, RAMAGE = 772, RAPIDE = 773, REICHE = 774, REMIGE = 775, RIEUSE = 776, RISING = 777, ROBUST = 778, ROYALE = 779, RUDOLF = 780, RUNNER = 781, SADDLE = 782, SAFRAN = 783, SAKURA = 784, SAPHIR = 785, SATURN = 786, SCHUSS = 787, SEKITO = 788, SELENE = 789, SENDEN = 790, SEREIN = 791, SHADOW = 792, SHIDEN = 793, SHINPU = 794, SIEGER = 795, SILBER = 796, SILENT = 797, SILVER = 798, SILVER = 799, SOLEIL = 800, SOMBRE = 801, SORREL = 802, SPHENE = 803, SPIRIT = 804, SPRING = 805, STREAM = 806, STRIKE = 807, SUMMER = 808, TEKIRO = 809, TERROR = 810, TICKET = 811, TIMIDE = 812, TOPAZE = 813, TULIPE = 814, TYCOON = 815, ULTIME = 816, URANUS = 817, VELOCE = 818, VELVET = 819, VICTOR = 820, VIOLET = 821, WALKER = 822, WEISSE = 823, WINGED = 824, WINNER = 825, WINNER = 826, WINTER = 827, WONDER = 828, XANTHE = 829, YELLOW = 830, ZEPHYR = 831, ARDENTE = 832, AUTOMNE = 833, AVENGER = 834, BARONNE = 835, BATTANT = 836, BLAZING = 837, BLITZER = 838, CAMELIA = 839, CANDIDE = 840, CARAMEL = 841, CELESTE = 842, CERULEE = 843, CHARBON = 844, CHARGER = 845, CHARIOT = 846, CLIPPER = 847, COUREUR = 848, CRIMSON = 849, CRISTAL = 850, CRYSTAL = 851, CUIVREE = 852, CYCLONE = 853, DANCING = 854, DANSEUR = 855, DIAMANT = 856, DIAMOND = 857, DRAFTER = 858, DUNKLER = 859, DUNKLES = 860, EASTERN = 861, EINHORN = 862, ELANCEE = 863, ELEGANT = 864, EMPEROR = 865, EMPRESS = 866, EXPRESS = 867, FARCEUR = 868, FEATHER = 869, FIGHTER = 870, FILANTE = 871, FLINKER = 872, FLINKES = 873, FORTUNE = 874, FRAICHE = 875, GAGNANT = 876, GALAXIE = 877, GALLANT = 878, GENESIS = 879, GEOELTE = 880, GROSSER = 881, GROSSES = 882, GRUENER = 883, GRUENES = 884, HARMONY = 885, HEROINE = 886, IKEZUKI = 887, IMPULSE = 888, JAVELIN = 889, JOYEUSE = 890, JUMPING = 891, JUPITER = 892, JUSTICE = 893, KLEINER = 894, KLEINES = 895, LAVANDE = 896, LEAPING = 897, LEGENDE = 898, LIBERTY = 899, LICORNE = 900, MAJESTY = 901, MARQUIS = 902, MAXIMAL = 903, MELODIE = 904, MERCURY = 905, MILLION = 906, MIRACLE = 907, MUSASHI = 908, MUSTANG = 909, NACARAT = 910, NATURAL = 911, NEMESIS = 912, NEPTUNE = 913, OEILLET = 914, OPTIMAL = 915, ORAGEUX = 916, OURAGAN = 917, PAPRIKA = 918, PARFAIT = 919, PARTNER = 920, PATIENT = 921, PATURON = 922, PEGASUS = 923, PENSIVE = 924, PERFECT = 925, PEUREUX = 926, PHOENIX = 927, PLUMAGE = 928, POURPRE = 929, POUSSIN = 930, PRANCER = 931, PREMIUM = 932, QUANTUM = 933, RADIANT = 934, RAINBOW = 935, RATTLER = 936, REICHER = 937, REICHES = 938, ROUGHIE = 939, SAMURAI = 940, SAUTANT = 941, SCARLET = 942, SCHWEIF = 943, SEREINE = 944, SERGENT = 945, SHINDEN = 946, SHINING = 947, SHOOTER = 948, SMOKING = 949, SOUFFLE = 950, SPECIAL = 951, STYLISH = 952, SUMPTER = 953, TEMPEST = 954, TEMPETE = 955, THUNDER = 956, TORNADO = 957, TORPEDO = 958, TRISTAN = 959, TROOPER = 960, TROTTER = 961, TYPHOON = 962, UNICORN = 963, VENGEUR = 964, VERMEIL = 965, VICTORY = 966, WARRIOR = 967, WEISSER = 968, WEISSES = 969, WESTERN = 970, WHISPER = 971, WINNING = 972, ZETSUEI = 973, ZILLION = 974, BARONESS = 975, BATTANTE = 976, BLIZZARD = 977, CANNELLE = 978, CAPUCINE = 979, CERULEAN = 980, CHANCEUX = 981, CHARISMA = 982, CHARMANT = 983, CHOCOLAT = 984, CLAYBANK = 985, COMTESSE = 986, COUREUSE = 987, DANSEUSE = 988, DUCHESSE = 989, ECARLATE = 990, ELEGANTE = 991, EMERAUDE = 992, FARCEUSE = 993, FARFADET = 994, FRINGANT = 995, GAGNANTE = 996, GALLOPER = 997, GALOPANT = 998, GEOELTER = 999, GEOELTES = 1000, GESCHOSS = 1001, GORGEOUS = 1002, HANAKAZE = 1003, HIGHLAND = 1004, HYPERION = 1005, ILLUSION = 1006, IMMORTAL = 1007, IMPERIAL = 1008, INCARNAT = 1009, INFINITY = 1010, INNOCENT = 1011, JACINTHE = 1012, KAISERIN = 1013, KRISTALL = 1014, MAHARAJA = 1015, MAHARANI = 1016, MARQUISE = 1017, MATAEMON = 1018, MEILLEUR = 1019, MERCEDES = 1020, MYOSOTIS = 1021, NEBULOUS = 1022, NEGATIVE = 1023, NENUPHAR = 1024, NORTHERN = 1025, NORTHERN = 1026, OBSIDIAN = 1027, ORAGEUSE = 1028, ORCHIDEE = 1029, PARFAITE = 1030, PATIENTE = 1031, PEUREUSE = 1032, POSITIVE = 1033, PRINCELY = 1034, PRINCESS = 1035, PRODIGUE = 1036, PUISSANT = 1037, RESTLESS = 1038, RHAPSODY = 1039, ROADSTER = 1040, RUTILANT = 1041, SAUTANTE = 1042, SCHWARZE = 1043, SHOOTING = 1044, SILBERNE = 1045, SOUTHERN = 1046, SPECIALE = 1047, STALLION = 1048, STARDUST = 1049, SURUSUMI = 1050, TONNERRE = 1051, TROTTEUR = 1052, ULTIMATE = 1053, UNIVERSE = 1054, VAILLANT = 1055, VENGEUSE = 1056, XANTHOUS = 1057, ZEPPELIN = 1058, AMBITIOUS = 1059, AUDACIEUX = 1060, BALLISTIC = 1061, BEAUTIFUL = 1062, BRILLIANT = 1063, CAMPANULE = 1064, CAPITAINE = 1065, CHANCEUSE = 1066, CHARMANTE = 1067, CLEMATITE = 1068, CLOCHETTE = 1069, CORIANDRE = 1070, CRACKLING = 1071, DESTROYER = 1072, EXCELLENT = 1073, FANTASTIC = 1074, FEATHERED = 1075, FRINGANTE = 1076, GALOPANTE = 1077, GINGEMBRE = 1078, HURRICANE = 1079, ICHIMONJI = 1080, IMPETUEUX = 1081, INCARNATE = 1082, LIGHTNING = 1083, MATSUKAZE = 1084, MEILLEURE = 1085, MENESTREL = 1086, MERCILESS = 1087, PENDRAGON = 1088, PRINCESSE = 1089, PRINTEMPS = 1090, PUISSANTE = 1091, QUADRILLE = 1092, ROSINANTE = 1093, RUTILANTE = 1094, SCHWARZER = 1095, SCHWARZES = 1096, SILBERNER = 1097, SILBERNES = 1098, SPARKLING = 1099, SPEEDSTER = 1100, TOURNESOL = 1101, TRANSIENT = 1102, TROTTEUSE = 1103, TURBULENT = 1104, TWINKLING = 1105, VAILLANTE = 1106, VALENTINE = 1107, VELOCIOUS = 1108, VERMEILLE = 1109, WONDERFUL = 1110, AMATSUKAZE = 1111, AUDACIEUSE = 1112, BENEVOLENT = 1113, BLISTERING = 1114, BRILLIANCE = 1115, BUCEPHALUS = 1116, CHALLENGER = 1117, EXCELLENTE = 1118, IMPETUEUSE = 1119, INVINCIBLE = 1120, MALEVOLENT = 1121, MILLENNIUM = 1122, TRANQUILLE = 1123, TURBULENTE = 1124, DESTRUCTION = 1125, FIRECRACKER = 1126, }
gpl-3.0
varunparkhe/Algorithm-Implementations
Hamming_Weight/Lua/Yonaba/numberlua.lua
115
13399
--[[ LUA MODULE bit.numberlua - Bitwise operations implemented in pure Lua as numbers, with Lua 5.2 'bit32' and (LuaJIT) LuaBitOp 'bit' compatibility interfaces. SYNOPSIS local bit = require 'bit.numberlua' print(bit.band(0xff00ff00, 0x00ff00ff)) --> 0xffffffff -- Interface providing strong Lua 5.2 'bit32' compatibility local bit32 = require 'bit.numberlua'.bit32 assert(bit32.band(-1) == 0xffffffff) -- Interface providing strong (LuaJIT) LuaBitOp 'bit' compatibility local bit = require 'bit.numberlua'.bit assert(bit.tobit(0xffffffff) == -1) DESCRIPTION This library implements bitwise operations entirely in Lua. This module is typically intended if for some reasons you don't want to or cannot install a popular C based bit library like BitOp 'bit' [1] (which comes pre-installed with LuaJIT) or 'bit32' (which comes pre-installed with Lua 5.2) but want a similar interface. This modules represents bit arrays as non-negative Lua numbers. [1] It can represent 32-bit bit arrays when Lua is compiled with lua_Number as double-precision IEEE 754 floating point. The module is nearly the most efficient it can be but may be a few times slower than the C based bit libraries and is orders or magnitude slower than LuaJIT bit operations, which compile to native code. Therefore, this library is inferior in performane to the other modules. The `xor` function in this module is based partly on Roberto Ierusalimschy's post in http://lua-users.org/lists/lua-l/2002-09/msg00134.html . The included BIT.bit32 and BIT.bit sublibraries aims to provide 100% compatibility with the Lua 5.2 "bit32" and (LuaJIT) LuaBitOp "bit" library. This compatbility is at the cost of some efficiency since inputted numbers are normalized and more general forms (e.g. multi-argument bitwise operators) are supported. STATUS WARNING: Not all corner cases have been tested and documented. Some attempt was made to make these similar to the Lua 5.2 [2] and LuaJit BitOp [3] libraries, but this is not fully tested and there are currently some differences. Addressing these differences may be improved in the future but it is not yet fully determined how to resolve these differences. The BIT.bit32 library passes the Lua 5.2 test suite (bitwise.lua) http://www.lua.org/tests/5.2/ . The BIT.bit library passes the LuaBitOp test suite (bittest.lua). However, these have not been tested on platforms with Lua compiled with 32-bit integer numbers. API BIT.tobit(x) --> z Similar to function in BitOp. BIT.tohex(x, n) Similar to function in BitOp. BIT.band(x, y) --> z Similar to function in Lua 5.2 and BitOp but requires two arguments. BIT.bor(x, y) --> z Similar to function in Lua 5.2 and BitOp but requires two arguments. BIT.bxor(x, y) --> z Similar to function in Lua 5.2 and BitOp but requires two arguments. BIT.bnot(x) --> z Similar to function in Lua 5.2 and BitOp. BIT.lshift(x, disp) --> z Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift), BIT.rshift(x, disp) --> z Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift), BIT.extract(x, field [, width]) --> z Similar to function in Lua 5.2. BIT.replace(x, v, field, width) --> z Similar to function in Lua 5.2. BIT.bswap(x) --> z Similar to function in Lua 5.2. BIT.rrotate(x, disp) --> z BIT.ror(x, disp) --> z Similar to function in Lua 5.2 and BitOp. BIT.lrotate(x, disp) --> z BIT.rol(x, disp) --> z Similar to function in Lua 5.2 and BitOp. BIT.arshift Similar to function in Lua 5.2 and BitOp. BIT.btest Similar to function in Lua 5.2 with requires two arguments. BIT.bit32 This table contains functions that aim to provide 100% compatibility with the Lua 5.2 "bit32" library. bit32.arshift (x, disp) --> z bit32.band (...) --> z bit32.bnot (x) --> z bit32.bor (...) --> z bit32.btest (...) --> true | false bit32.bxor (...) --> z bit32.extract (x, field [, width]) --> z bit32.replace (x, v, field [, width]) --> z bit32.lrotate (x, disp) --> z bit32.lshift (x, disp) --> z bit32.rrotate (x, disp) --> z bit32.rshift (x, disp) --> z BIT.bit This table contains functions that aim to provide 100% compatibility with the LuaBitOp "bit" library (from LuaJIT). bit.tobit(x) --> y bit.tohex(x [,n]) --> y bit.bnot(x) --> y bit.bor(x1 [,x2...]) --> y bit.band(x1 [,x2...]) --> y bit.bxor(x1 [,x2...]) --> y bit.lshift(x, n) --> y bit.rshift(x, n) --> y bit.arshift(x, n) --> y bit.rol(x, n) --> y bit.ror(x, n) --> y bit.bswap(x) --> y DEPENDENCIES None (other than Lua 5.1 or 5.2). DOWNLOAD/INSTALLATION If using LuaRocks: luarocks install lua-bit-numberlua Otherwise, download <https://github.com/davidm/lua-bit-numberlua/zipball/master>. Alternately, if using git: git clone git://github.com/davidm/lua-bit-numberlua.git cd lua-bit-numberlua Optionally unpack: ./util.mk or unpack and install in LuaRocks: ./util.mk install REFERENCES [1] http://lua-users.org/wiki/FloatingPoint [2] http://www.lua.org/manual/5.2/ [3] http://bitop.luajit.org/ LICENSE (c) 2008-2011 David Manura. Licensed under the same terms as Lua (MIT). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (end license) --]] local M = {_TYPE='module', _NAME='bit.numberlua', _VERSION='0.3.1.20120131'} local floor = math.floor local MOD = 2^32 local MODM = MOD-1 local function memoize(f) local mt = {} local t = setmetatable({}, mt) function mt:__index(k) local v = f(k); t[k] = v return v end return t end local function make_bitop_uncached(t, m) local function bitop(a, b) local res,p = 0,1 while a ~= 0 and b ~= 0 do local am, bm = a%m, b%m res = res + t[am][bm]*p a = (a - am) / m b = (b - bm) / m p = p*m end res = res + (a+b)*p return res end return bitop end local function make_bitop(t) local op1 = make_bitop_uncached(t,2^1) local op2 = memoize(function(a) return memoize(function(b) return op1(a, b) end) end) return make_bitop_uncached(op2, 2^(t.n or 1)) end -- ok? probably not if running on a 32-bit int Lua number type platform function M.tobit(x) return x % 2^32 end M.bxor = make_bitop {[0]={[0]=0,[1]=1},[1]={[0]=1,[1]=0}, n=4} local bxor = M.bxor function M.bnot(a) return MODM - a end local bnot = M.bnot function M.band(a,b) return ((a+b) - bxor(a,b))/2 end local band = M.band function M.bor(a,b) return MODM - band(MODM - a, MODM - b) end local bor = M.bor local lshift, rshift -- forward declare function M.rshift(a,disp) -- Lua5.2 insipred if disp < 0 then return lshift(a,-disp) end return floor(a % 2^32 / 2^disp) end rshift = M.rshift function M.lshift(a,disp) -- Lua5.2 inspired if disp < 0 then return rshift(a,-disp) end return (a * 2^disp) % 2^32 end lshift = M.lshift function M.tohex(x, n) -- BitOp style n = n or 8 local up if n <= 0 then if n == 0 then return '' end up = true n = - n end x = band(x, 16^n-1) return ('%0'..n..(up and 'X' or 'x')):format(x) end local tohex = M.tohex function M.extract(n, field, width) -- Lua5.2 inspired width = width or 1 return band(rshift(n, field), 2^width-1) end local extract = M.extract function M.replace(n, v, field, width) -- Lua5.2 inspired width = width or 1 local mask1 = 2^width-1 v = band(v, mask1) -- required by spec? local mask = bnot(lshift(mask1, field)) return band(n, mask) + lshift(v, field) end local replace = M.replace function M.bswap(x) -- BitOp style local a = band(x, 0xff); x = rshift(x, 8) local b = band(x, 0xff); x = rshift(x, 8) local c = band(x, 0xff); x = rshift(x, 8) local d = band(x, 0xff) return lshift(lshift(lshift(a, 8) + b, 8) + c, 8) + d end local bswap = M.bswap function M.rrotate(x, disp) -- Lua5.2 inspired disp = disp % 32 local low = band(x, 2^disp-1) return rshift(x, disp) + lshift(low, 32-disp) end local rrotate = M.rrotate function M.lrotate(x, disp) -- Lua5.2 inspired return rrotate(x, -disp) end local lrotate = M.lrotate M.rol = M.lrotate -- LuaOp inspired M.ror = M.rrotate -- LuaOp insipred function M.arshift(x, disp) -- Lua5.2 inspired local z = rshift(x, disp) if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end return z end local arshift = M.arshift function M.btest(x, y) -- Lua5.2 inspired return band(x, y) ~= 0 end -- -- Start Lua 5.2 "bit32" compat section. -- M.bit32 = {} -- Lua 5.2 'bit32' compatibility local function bit32_bnot(x) return (-1 - x) % MOD end M.bit32.bnot = bit32_bnot local function bit32_bxor(a, b, c, ...) local z if b then a = a % MOD b = b % MOD z = bxor(a, b) if c then z = bit32_bxor(z, c, ...) end return z elseif a then return a % MOD else return 0 end end M.bit32.bxor = bit32_bxor local function bit32_band(a, b, c, ...) local z if b then a = a % MOD b = b % MOD z = ((a+b) - bxor(a,b)) / 2 if c then z = bit32_band(z, c, ...) end return z elseif a then return a % MOD else return MODM end end M.bit32.band = bit32_band local function bit32_bor(a, b, c, ...) local z if b then a = a % MOD b = b % MOD z = MODM - band(MODM - a, MODM - b) if c then z = bit32_bor(z, c, ...) end return z elseif a then return a % MOD else return 0 end end M.bit32.bor = bit32_bor function M.bit32.btest(...) return bit32_band(...) ~= 0 end function M.bit32.lrotate(x, disp) return lrotate(x % MOD, disp) end function M.bit32.rrotate(x, disp) return rrotate(x % MOD, disp) end function M.bit32.lshift(x,disp) if disp > 31 or disp < -31 then return 0 end return lshift(x % MOD, disp) end function M.bit32.rshift(x,disp) if disp > 31 or disp < -31 then return 0 end return rshift(x % MOD, disp) end function M.bit32.arshift(x,disp) x = x % MOD if disp >= 0 then if disp > 31 then return (x >= 0x80000000) and MODM or 0 else local z = rshift(x, disp) if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end return z end else return lshift(x, -disp) end end function M.bit32.extract(x, field, ...) local width = ... or 1 if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end x = x % MOD return extract(x, field, ...) end function M.bit32.replace(x, v, field, ...) local width = ... or 1 if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end x = x % MOD v = v % MOD return replace(x, v, field, ...) end -- -- Start LuaBitOp "bit" compat section. -- M.bit = {} -- LuaBitOp "bit" compatibility function M.bit.tobit(x) x = x % MOD if x >= 0x80000000 then x = x - MOD end return x end local bit_tobit = M.bit.tobit function M.bit.tohex(x, ...) return tohex(x % MOD, ...) end function M.bit.bnot(x) return bit_tobit(bnot(x % MOD)) end local function bit_bor(a, b, c, ...) if c then return bit_bor(bit_bor(a, b), c, ...) elseif b then return bit_tobit(bor(a % MOD, b % MOD)) else return bit_tobit(a) end end M.bit.bor = bit_bor local function bit_band(a, b, c, ...) if c then return bit_band(bit_band(a, b), c, ...) elseif b then return bit_tobit(band(a % MOD, b % MOD)) else return bit_tobit(a) end end M.bit.band = bit_band local function bit_bxor(a, b, c, ...) if c then return bit_bxor(bit_bxor(a, b), c, ...) elseif b then return bit_tobit(bxor(a % MOD, b % MOD)) else return bit_tobit(a) end end M.bit.bxor = bit_bxor function M.bit.lshift(x, n) return bit_tobit(lshift(x % MOD, n % 32)) end function M.bit.rshift(x, n) return bit_tobit(rshift(x % MOD, n % 32)) end function M.bit.arshift(x, n) return bit_tobit(arshift(x % MOD, n % 32)) end function M.bit.rol(x, n) return bit_tobit(lrotate(x % MOD, n % 32)) end function M.bit.ror(x, n) return bit_tobit(rrotate(x % MOD, n % 32)) end function M.bit.bswap(x) return bit_tobit(bswap(x % MOD)) end return M
mit
dacrybabysuck/darkstar
scripts/zones/Upper_Jeuno/npcs/Glyke.lua
12
1041
----------------------------------- -- Area: Upper Jeuno -- NPC: Glyke -- Standard Merchant NPC ----------------------------------- local ID = require("scripts/zones/Upper_Jeuno/IDs") require("scripts/globals/shop") function onTrade(player,npc,trade) end function onTrigger(player,npc) local stock = { 4499, 92, -- Iron Bread 4408, 128, -- Tortilla 4356, 184, -- White Bread 4416, 1400, -- Pea Soup 4456, 2070, -- Boiled Crab 4437, 662, -- Roast Mutton 4406, 440, -- Baked Apple 4555, 1711, -- Windurst Salad 4559, 4585, -- Herb Quus 4422, 184, -- Orange Juice 4423, 276, -- Apple Juice 4442, 368, -- Pineapple Juice 4424, 1012, -- Mellon Juice 4441, 855, -- Grape Juice } player:showText(npc, ID.text.GLYKE_SHOP_DIALOG) dsp.shop.general(player, stock) end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
gpl-3.0