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
MkNiz/LOSS
classes/forms.lua
1
8740
--[CONTAINER] Container = Class{ -- pos - { x, y, w, h } -- padding - internal padding space, num or { top, bottom, left, right } -- margin - margin between elements within container, num or { top, bottom, left, right } -- flow - true or false: do elements "take up space"? -- flowDir - if flow true, do elements organize: left-right, right-left, top-bottom, bottom-top -- parent - parent element (i.e. container for container) init = function(self, pos, padding, margin, flow, flowDir, parent) -- Table containing this container's elements self.elements = {} if parent then self.x = pos[1] + parent.ccX self.y = pos[2] + parent.ccY else self.x, self.y = pos[1], pos[2] end self.w, self.h = pos[3], pos[4] self.pad = {} self.margin = {} self.pad.t, self.pad.b, self.pad.l, self.pad.r = 0,0,0,0 if padding then if type(padding) == "table" then self.pad.t = padding[1] or 0 self.pad.b = padding[2] or 0 self.pad.l = padding[3] or 0 self.pad.r = padding[4] or 0 elseif type(padding) == "number" then self.pad.t, self.pad.b, self.pad.l, self.pad.r = padding, padding, padding, padding else error("Container padding argument must be a number or a table of values.") end end if margin then if type(margin) == "table" then self.margin.t = margin[1] or 0 self.margin.b = margin[2] or 0 self.margin.l = margin[3] or 0 self.margin.r = margin[4] or 0 elseif type(margin) == "number" then self.margin.t, self.margin.b, self.margin.l, self.margin.r = margin, margin, margin, margin else error("Container margin argument must be a number or a table of values.") end end -- cXpn, cYpn - Modify flow calculations based on direction. -- Positive 1 for x = "left-right", Negative 1 for x = "right-left" -- Positive 1 for y = "top-bottom", Negative 1 for y = "bottom-top" self.cXpn, self.cYpn = 1, 1 -- cX, cY - X and Y coords of the "left" and "top" corners of padded area -- cW, cH - Width and height of padded area self.cX, self.cY = self.x + self.pad.l, self.y + self.pad.t self.cW, self.cH = self.w - (self.pad.l + self.pad.r), self.h - (self.pad.t + self.pad.b) -- ccX, ccY - Like cX/cY, but reflects the current state of the flow self.ccX, self.ccY = self.cX, self.cY self.flow = flow or true if self.flow then self.flowDir = flowDir or "left-right" -- Alter cX/cY & ccX/ccY for flow direction -- Alter cXpn/cYpn for flow direction -- "left-right" and "top-bottom" are defaults and therefore not included here if self.flowDir == "right-left" then self.cX = self.cX + self.cW self.ccX = self.cX self.cXpn = -1 elseif self.flowDir == "bottom-top" then self.cY = self.cY + self.cH self.ccY = self.cY self.cYpn = -1 end end -- cX2, cY2 - X and Y coords of the "right" and "bottom" corners of padded area self.cX2, self.cY2 = (self.cX + self.cW)*self.cXpn, (self.cY + self.cH)*self.cYpn end } function Container:draw() for k, element in ipairs(self.elements) do if element.drawn then element:draw() end end end -- Will run every hoverCheck() function for an element where "hovers" is true function Container:hoverScan(mx, my) for k, element in ipairs(self.elements) do if element.hovers then if element:hoverCheck(mx, my) then element.hovering = true return true else element.hovering = false end end end return false end -- Activates click function of any buttons in container that are clicked function Container:click(mx, my) for k, element in ipairs(self.elements) do if element:hoverCheck(mx, my) and element.clickable then element:click() end end end -- Adds a basic "clickable" element to the container function Container:addClickable(pos, activation, arguments) local x, y, w, h = pos[1], pos[2], pos[3], pos[4] local elm = self:plotFlow(x, y, w, h) self.elements[#self.elements+1] = Clickable({ elm.x, elm.y, w, h }, activation, arguments, self) end -- Adds a simple text button to the container function Container:addTextButton(pos, activation, arguments, text, color, textcolor) local x, y, w, h = pos[1], pos[2], pos[3], pos[4] local elm = self:plotFlow(x, y, w, h) self.elements[#self.elements+1] = TextButton({ elm.x, elm.y, w, h }, activation, arguments, self, text, color, textcolor) end -- function Container:plotFlow(x, y, w, h) local elm = {} if self.flow then if self.flowDir == "right-left" then elm.x = self.ccX - w - self.margin.r + x elm.y = self.ccY + y self.ccX = elm.x - self.margin.r elseif self.flowDir == "top-bottom" then elm.x = self.ccX + x elm.y = self.ccY + self.margin.t + y self.ccY = elm.y + h + self.margin.t elseif self.flowDir == "bottom-top" then elm.x = self.ccX + x elm.y = self.ccY - h - self.margin.b + y self.ccY = elm.y - self.margin.b else elm.x = self.ccX + self.margin.l + x elm.y = self.ccY + y self.ccX = elm.x + w + self.margin.l end else elm.x, elm.y = self.ccX+x, self.cY+y end return elm end function Container:checkClicks() for k, element in ipairs(self.elements) do if element.clickable then if element:hoverCheck(mx, my) then element:click() return true end end end return false end function Container:recalibrate(w1, h1, w2, h2, xVal, yVal) local wDiff, hDiff = w2-w1, h2-h1 self.x = self.x + wDiff self.y = self.y + hDiff for k, element in ipairs(self.elements) do if xVal then element.x = xVal else element.x = element.x + wDiff end if yVal then element.y = yVal else element.y = element.y + hDiff end end end --[CLICKABLE] Clickable = Class{ -- pos - { x, y, w, h } -- activation - function activated when clicked -- arguments - table of arguments sent to the activation function -- parent - parent element (i.e. container for clickable) init = function(self, pos, activation, arguments, parent) self.x, self.y, self.w, self.h = pos[1], pos[2], pos[3], pos[4] self.activation, self.arguments, self.parent = activation, arguments, parent self.hovers = true self.hovering = false self.drawn = true self.clickable = true self.hoverCursor = "hand" end } function Clickable:hoverCheck(mx, my) local x2, y2 = self.x+self.w, self.y+self.h if mx > self.x and mx < x2 and my > self.y and my < y2 then return true else return false end end function Clickable:draw() color("buttons") rekt("fill", self.x, self.y, self.w, self.h) color("borders") rekt("line", self.x, self.y, self.w, self.h) white() end function Clickable:click() self.activation(self.arguments) end --[TEXT BUTTON] TextButton = Class{ __includes = Clickable, -- text - Text displayed on button -- color - Optional color for button, {r, g, b, a} -- textcolor - Optional color for text, {r, g, b, a} init = function(self, pos, activation, arguments, parent, text, color, textcolor) Clickable.init(self, pos, activation, arguments, parent) self.text = text or "×" self.color, self.textcolor = color, textcolor end } function TextButton:draw() if self.color then sColor(unpack(self.color)) else color("buttons") end rekt("fill", self.x, self.y, self.w, self.h) if self.hovering and love.mouse.isDown(1) then color("shadows") rekt("fill", self.x, self.y, self.w, self.h) lyne( self.x+1, self.y+1, self.x+self.w-1, self.y+1 ) lyne( self.x+1, self.y+1, self.x+1, self.y+self.h-1 ) color("highlights") lyne( self.x+1, self.y+self.h-1, self.x+self.w-1, self.y+self.h-1) lyne( self.x+self.w-1, self.y+1, self.x+self.w-1, self.y+self.h-1) elseif self.hovering then color("highlights") rekt("fill", self.x, self.y, self.w, self.h) else color("highlights") lyne( self.x+1, self.y+1, self.x+self.w-1, self.y+1 ) lyne( self.x+1, self.y+1, self.x+1, self.y+self.h-1 ) color("shadows") lyne( self.x+1, self.y+self.h-1, self.x+self.w-1, self.y+self.h-1) lyne( self.x+self.w-1, self.y+1, self.x+self.w-1, self.y+self.h-1) end color("borders") rekt("line", self.x, self.y, self.w, self.h) if self.textcolor then sColor(unpack(self.textcolor)) else color("text") end pfStr(self.text, self.x, (self.y+((self.h/16-1)*8)), self.w, "center") white() end
mit
Mohammadrezar/DarkDiamond
TeleDiamond/libs/lua-redis.lua
580
35599
local redis = { _VERSION = 'redis-lua 2.0.4', _DESCRIPTION = 'A Lua client library for the redis key value storage system.', _COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri', } -- The following line is used for backwards compatibility in order to keep the `Redis` -- global module name. Using `Redis` is now deprecated so you should explicitly assign -- the module to a local variable when requiring it: `local redis = require('redis')`. Redis = redis local unpack = _G.unpack or table.unpack local network, request, response = {}, {}, {} local defaults = { host = '127.0.0.1', port = 6379, tcp_nodelay = true, path = nil } local function merge_defaults(parameters) if parameters == nil then parameters = {} end for k, v in pairs(defaults) do if parameters[k] == nil then parameters[k] = defaults[k] end end return parameters end local function parse_boolean(v) if v == '1' or v == 'true' or v == 'TRUE' then return true elseif v == '0' or v == 'false' or v == 'FALSE' then return false else return nil end end local function toboolean(value) return value == 1 end local function sort_request(client, command, key, params) --[[ params = { by = 'weight_*', get = 'object_*', limit = { 0, 10 }, sort = 'desc', alpha = true, } ]] local query = { key } if params then if params.by then table.insert(query, 'BY') table.insert(query, params.by) end if type(params.limit) == 'table' then -- TODO: check for lower and upper limits table.insert(query, 'LIMIT') table.insert(query, params.limit[1]) table.insert(query, params.limit[2]) end if params.get then if (type(params.get) == 'table') then for _, getarg in pairs(params.get) do table.insert(query, 'GET') table.insert(query, getarg) end else table.insert(query, 'GET') table.insert(query, params.get) end end if params.sort then table.insert(query, params.sort) end if params.alpha == true then table.insert(query, 'ALPHA') end if params.store then table.insert(query, 'STORE') table.insert(query, params.store) end end request.multibulk(client, command, query) end local function zset_range_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_byscore_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.limit then table.insert(opts, 'LIMIT') table.insert(opts, options.limit.offset or options.limit[1]) table.insert(opts, options.limit.count or options.limit[2]) end if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_reply(reply, command, ...) local args = {...} local opts = args[4] if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then local new_reply = { } for i = 1, #reply, 2 do table.insert(new_reply, { reply[i], reply[i + 1] }) end return new_reply else return reply end end local function zset_store_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.weights and type(options.weights) == 'table' then table.insert(opts, 'WEIGHTS') for _, weight in ipairs(options.weights) do table.insert(opts, weight) end end if options.aggregate then table.insert(opts, 'AGGREGATE') table.insert(opts, options.aggregate) end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function mset_filter_args(client, command, ...) local args, arguments = {...}, {} if (#args == 1 and type(args[1]) == 'table') then for k,v in pairs(args[1]) do table.insert(arguments, k) table.insert(arguments, v) end else arguments = args end request.multibulk(client, command, arguments) end local function hash_multi_request_builder(builder_callback) return function(client, command, ...) local args, arguments = {...}, { } if #args == 2 then table.insert(arguments, args[1]) for k, v in pairs(args[2]) do builder_callback(arguments, k, v) end else arguments = args end request.multibulk(client, command, arguments) end end local function parse_info(response) local info = {} local current = info response:gsub('([^\r\n]*)\r\n', function(kv) if kv == '' then return end local section = kv:match('^# (%w+)$') if section then current = {} info[section:lower()] = current return end local k,v = kv:match(('([^:]*):([^:]*)'):rep(1)) if k:match('db%d+') then current[k] = {} v:gsub(',', function(dbkv) local dbk,dbv = kv:match('([^:]*)=([^:]*)') current[k][dbk] = dbv end) else current[k] = v end end) return info end local function load_methods(proto, commands) local client = setmetatable ({}, getmetatable(proto)) for cmd, fn in pairs(commands) do if type(fn) ~= 'function' then redis.error('invalid type for command ' .. cmd .. '(must be a function)') end client[cmd] = fn end for i, v in pairs(proto) do client[i] = v end return client end local function create_client(proto, client_socket, commands) local client = load_methods(proto, commands) client.error = redis.error client.network = { socket = client_socket, read = network.read, write = network.write, } client.requests = { multibulk = request.multibulk, } return client end -- ############################################################################ function network.write(client, buffer) local _, err = client.network.socket:send(buffer) if err then client.error(err) end end function network.read(client, len) if len == nil then len = '*l' end local line, err = client.network.socket:receive(len) if not err then return line else client.error('connection error: ' .. err) end end -- ############################################################################ function response.read(client) local payload = client.network.read(client) local prefix, data = payload:sub(1, -#payload), payload:sub(2) -- status reply if prefix == '+' then if data == 'OK' then return true elseif data == 'QUEUED' then return { queued = true } else return data end -- error reply elseif prefix == '-' then return client.error('redis error: ' .. data) -- integer reply elseif prefix == ':' then local number = tonumber(data) if not number then if res == 'nil' then return nil end client.error('cannot parse '..res..' as a numeric response.') end return number -- bulk reply elseif prefix == '$' then local length = tonumber(data) if not length then client.error('cannot parse ' .. length .. ' as data length') end if length == -1 then return nil end local nextchunk = client.network.read(client, length + 2) return nextchunk:sub(1, -3) -- multibulk reply elseif prefix == '*' then local count = tonumber(data) if count == -1 then return nil end local list = {} if count > 0 then local reader = response.read for i = 1, count do list[i] = reader(client) end end return list -- unknown type of reply else return client.error('unknown response prefix: ' .. prefix) end end -- ############################################################################ function request.raw(client, buffer) local bufferType = type(buffer) if bufferType == 'table' then client.network.write(client, table.concat(buffer)) elseif bufferType == 'string' then client.network.write(client, buffer) else client.error('argument error: ' .. bufferType) end end function request.multibulk(client, command, ...) local args = {...} local argsn = #args local buffer = { true, true } if argsn == 1 and type(args[1]) == 'table' then argsn, args = #args[1], args[1] end buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n" buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n" local table_insert = table.insert for _, argument in pairs(args) do local s_argument = tostring(argument) table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n") end client.network.write(client, table.concat(buffer)) end -- ############################################################################ local function custom(command, send, parse) command = string.upper(command) return function(client, ...) send(client, command, ...) local reply = response.read(client) if type(reply) == 'table' and reply.queued then reply.parser = parse return reply else if parse then return parse(reply, command, ...) end return reply end end end local function command(command, opts) if opts == nil or type(opts) == 'function' then return custom(command, request.multibulk, opts) else return custom(command, opts.request or request.multibulk, opts.response) end end local define_command_impl = function(target, name, opts) local opts = opts or {} target[string.lower(name)] = custom( opts.command or string.upper(name), opts.request or request.multibulk, opts.response or nil ) end local undefine_command_impl = function(target, name) target[string.lower(name)] = nil end -- ############################################################################ local client_prototype = {} client_prototype.raw_cmd = function(client, buffer) request.raw(client, buffer .. "\r\n") return response.read(client) end -- obsolete client_prototype.define_command = function(client, name, opts) define_command_impl(client, name, opts) end -- obsolete client_prototype.undefine_command = function(client, name) undefine_command_impl(client, name) end client_prototype.quit = function(client) request.multibulk(client, 'QUIT') client.network.socket:shutdown() return true end client_prototype.shutdown = function(client) request.multibulk(client, 'SHUTDOWN') client.network.socket:shutdown() end -- Command pipelining client_prototype.pipeline = function(client, block) local requests, replies, parsers = {}, {}, {} local table_insert = table.insert local socket_write, socket_read = client.network.write, client.network.read client.network.write = function(_, buffer) table_insert(requests, buffer) end -- TODO: this hack is necessary to temporarily reuse the current -- request -> response handling implementation of redis-lua -- without further changes in the code, but it will surely -- disappear when the new command-definition infrastructure -- will finally be in place. client.network.read = function() return '+QUEUED' end local pipeline = setmetatable({}, { __index = function(env, name) local cmd = client[name] if not cmd then client.error('unknown redis command: ' .. name, 2) end return function(self, ...) local reply = cmd(client, ...) table_insert(parsers, #requests, reply.parser) return reply end end }) local success, retval = pcall(block, pipeline) client.network.write, client.network.read = socket_write, socket_read if not success then client.error(retval, 0) end client.network.write(client, table.concat(requests, '')) for i = 1, #requests do local reply, parser = response.read(client), parsers[i] if parser then reply = parser(reply) end table_insert(replies, i, reply) end return replies, #requests end -- Publish/Subscribe do local channels = function(channels) if type(channels) == 'string' then channels = { channels } end return channels end local subscribe = function(client, ...) request.multibulk(client, 'subscribe', ...) end local psubscribe = function(client, ...) request.multibulk(client, 'psubscribe', ...) end local unsubscribe = function(client, ...) request.multibulk(client, 'unsubscribe') end local punsubscribe = function(client, ...) request.multibulk(client, 'punsubscribe') end local consumer_loop = function(client) local aborting, subscriptions = false, 0 local abort = function() if not aborting then unsubscribe(client) punsubscribe(client) aborting = true end end return coroutine.wrap(function() while true do local message local response = response.read(client) if response[1] == 'pmessage' then message = { kind = response[1], pattern = response[2], channel = response[3], payload = response[4], } else message = { kind = response[1], channel = response[2], payload = response[3], } end if string.match(message.kind, '^p?subscribe$') then subscriptions = subscriptions + 1 end if string.match(message.kind, '^p?unsubscribe$') then subscriptions = subscriptions - 1 end if aborting and subscriptions == 0 then break end coroutine.yield(message, abort) end end) end client_prototype.pubsub = function(client, subscriptions) if type(subscriptions) == 'table' then if subscriptions.subscribe then subscribe(client, channels(subscriptions.subscribe)) end if subscriptions.psubscribe then psubscribe(client, channels(subscriptions.psubscribe)) end end return consumer_loop(client) end end -- Redis transactions (MULTI/EXEC) do local function identity(...) return ... end local emptytable = {} local function initialize_transaction(client, options, block, queued_parsers) local table_insert = table.insert local coro = coroutine.create(block) if options.watch then local watch_keys = {} for _, key in pairs(options.watch) do table_insert(watch_keys, key) end if #watch_keys > 0 then client:watch(unpack(watch_keys)) end end local transaction_client = setmetatable({}, {__index=client}) transaction_client.exec = function(...) client.error('cannot use EXEC inside a transaction block') end transaction_client.multi = function(...) coroutine.yield() end transaction_client.commands_queued = function() return #queued_parsers end assert(coroutine.resume(coro, transaction_client)) transaction_client.multi = nil transaction_client.discard = function(...) local reply = client:discard() for i, v in pairs(queued_parsers) do queued_parsers[i]=nil end coro = initialize_transaction(client, options, block, queued_parsers) return reply end transaction_client.watch = function(...) client.error('WATCH inside MULTI is not allowed') end setmetatable(transaction_client, { __index = function(t, k) local cmd = client[k] if type(cmd) == "function" then local function queuey(self, ...) local reply = cmd(client, ...) assert((reply or emptytable).queued == true, 'a QUEUED reply was expected') table_insert(queued_parsers, reply.parser or identity) return reply end t[k]=queuey return queuey else return cmd end end }) client:multi() return coro end local function transaction(client, options, coroutine_block, attempts) local queued_parsers, replies = {}, {} local retry = tonumber(attempts) or tonumber(options.retry) or 2 local coro = initialize_transaction(client, options, coroutine_block, queued_parsers) local success, retval if coroutine.status(coro) == 'suspended' then success, retval = coroutine.resume(coro) else -- do not fail if the coroutine has not been resumed (missing t:multi() with CAS) success, retval = true, 'empty transaction' end if #queued_parsers == 0 or not success then client:discard() assert(success, retval) return replies, 0 end local raw_replies = client:exec() if not raw_replies then if (retry or 0) <= 0 then client.error("MULTI/EXEC transaction aborted by the server") else --we're not quite done yet return transaction(client, options, coroutine_block, retry - 1) end end local table_insert = table.insert for i, parser in pairs(queued_parsers) do table_insert(replies, i, parser(raw_replies[i])) end return replies, #queued_parsers end client_prototype.transaction = function(client, arg1, arg2) local options, block if not arg2 then options, block = {}, arg1 elseif arg1 then --and arg2, implicitly options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2 else client.error("Invalid parameters for redis transaction.") end if not options.watch then watch_keys = { } for i, v in pairs(options) do if tonumber(i) then table.insert(watch_keys, v) options[i] = nil end end options.watch = watch_keys elseif not (type(options.watch) == 'table') then options.watch = { options.watch } end if not options.cas then local tx_block = block block = function(client, ...) client:multi() return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine. end end return transaction(client, options, block) end end -- MONITOR context do local monitor_loop = function(client) local monitoring = true -- Tricky since the payload format changed starting from Redis 2.6. local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$' local abort = function() monitoring = false end return coroutine.wrap(function() client:monitor() while monitoring do local message, matched local response = response.read(client) local ok = response:gsub(pattern, function(time, info, cmd, args) message = { timestamp = tonumber(time), client = info:match('%d+.%d+.%d+.%d+:%d+'), database = tonumber(info:match('%d+')) or 0, command = cmd, arguments = args:match('.+'), } matched = true end) if not matched then client.error('Unable to match MONITOR payload: '..response) end coroutine.yield(message, abort) end end) end client_prototype.monitor_messages = function(client) return monitor_loop(client) end end -- ############################################################################ local function connect_tcp(socket, parameters) local host, port = parameters.host, tonumber(parameters.port) local ok, err = socket:connect(host, port) if not ok then redis.error('could not connect to '..host..':'..port..' ['..err..']') end socket:setoption('tcp-nodelay', parameters.tcp_nodelay) return socket end local function connect_unix(socket, parameters) local ok, err = socket:connect(parameters.path) if not ok then redis.error('could not connect to '..parameters.path..' ['..err..']') end return socket end local function create_connection(parameters) if parameters.socket then return parameters.socket end local perform_connection, socket if parameters.scheme == 'unix' then perform_connection, socket = connect_unix, require('socket.unix') assert(socket, 'your build of LuaSocket does not support UNIX domain sockets') else if parameters.scheme then local scheme = parameters.scheme assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme) end perform_connection, socket = connect_tcp, require('socket').tcp end return perform_connection(socket(), parameters) end -- ############################################################################ function redis.error(message, level) error(message, (level or 1) + 1) end function redis.connect(...) local args, parameters = {...}, nil if #args == 1 then if type(args[1]) == 'table' then parameters = args[1] else local uri = require('socket.url') parameters = uri.parse(select(1, ...)) if parameters.scheme then if parameters.query then for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do if k == 'tcp_nodelay' or k == 'tcp-nodelay' then parameters.tcp_nodelay = parse_boolean(v) end end end else parameters.host = parameters.path end end elseif #args > 1 then local host, port = unpack(args) parameters = { host = host, port = port } end local commands = redis.commands or {} if type(commands) ~= 'table' then redis.error('invalid type for the commands table') end local socket = create_connection(merge_defaults(parameters)) local client = create_client(client_prototype, socket, commands) return client end function redis.command(cmd, opts) return command(cmd, opts) end -- obsolete function redis.define_command(name, opts) define_command_impl(redis.commands, name, opts) end -- obsolete function redis.undefine_command(name) undefine_command_impl(redis.commands, name) end -- ############################################################################ -- Commands defined in this table do not take the precedence over -- methods defined in the client prototype table. redis.commands = { -- commands operating on the key space exists = command('EXISTS', { response = toboolean }), del = command('DEL'), type = command('TYPE'), rename = command('RENAME'), renamenx = command('RENAMENX', { response = toboolean }), expire = command('EXPIRE', { response = toboolean }), pexpire = command('PEXPIRE', { -- >= 2.6 response = toboolean }), expireat = command('EXPIREAT', { response = toboolean }), pexpireat = command('PEXPIREAT', { -- >= 2.6 response = toboolean }), ttl = command('TTL'), pttl = command('PTTL'), -- >= 2.6 move = command('MOVE', { response = toboolean }), dbsize = command('DBSIZE'), persist = command('PERSIST', { -- >= 2.2 response = toboolean }), keys = command('KEYS', { response = function(response) if type(response) == 'string' then -- backwards compatibility path for Redis < 2.0 local keys = {} response:gsub('[^%s]+', function(key) table.insert(keys, key) end) response = keys end return response end }), randomkey = command('RANDOMKEY', { response = function(response) if response == '' then return nil else return response end end }), sort = command('SORT', { request = sort_request, }), -- commands operating on string values set = command('SET'), setnx = command('SETNX', { response = toboolean }), setex = command('SETEX'), -- >= 2.0 psetex = command('PSETEX'), -- >= 2.6 mset = command('MSET', { request = mset_filter_args }), msetnx = command('MSETNX', { request = mset_filter_args, response = toboolean }), get = command('GET'), mget = command('MGET'), getset = command('GETSET'), incr = command('INCR'), incrby = command('INCRBY'), incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), decr = command('DECR'), decrby = command('DECRBY'), append = command('APPEND'), -- >= 2.0 substr = command('SUBSTR'), -- >= 2.0 strlen = command('STRLEN'), -- >= 2.2 setrange = command('SETRANGE'), -- >= 2.2 getrange = command('GETRANGE'), -- >= 2.2 setbit = command('SETBIT'), -- >= 2.2 getbit = command('GETBIT'), -- >= 2.2 -- commands operating on lists rpush = command('RPUSH'), lpush = command('LPUSH'), llen = command('LLEN'), lrange = command('LRANGE'), ltrim = command('LTRIM'), lindex = command('LINDEX'), lset = command('LSET'), lrem = command('LREM'), lpop = command('LPOP'), rpop = command('RPOP'), rpoplpush = command('RPOPLPUSH'), blpop = command('BLPOP'), -- >= 2.0 brpop = command('BRPOP'), -- >= 2.0 rpushx = command('RPUSHX'), -- >= 2.2 lpushx = command('LPUSHX'), -- >= 2.2 linsert = command('LINSERT'), -- >= 2.2 brpoplpush = command('BRPOPLPUSH'), -- >= 2.2 -- commands operating on sets sadd = command('SADD'), srem = command('SREM'), spop = command('SPOP'), smove = command('SMOVE', { response = toboolean }), scard = command('SCARD'), sismember = command('SISMEMBER', { response = toboolean }), sinter = command('SINTER'), sinterstore = command('SINTERSTORE'), sunion = command('SUNION'), sunionstore = command('SUNIONSTORE'), sdiff = command('SDIFF'), sdiffstore = command('SDIFFSTORE'), smembers = command('SMEMBERS'), srandmember = command('SRANDMEMBER'), -- commands operating on sorted sets zadd = command('ZADD'), zincrby = command('ZINCRBY'), zrem = command('ZREM'), zrange = command('ZRANGE', { request = zset_range_request, response = zset_range_reply, }), zrevrange = command('ZREVRANGE', { request = zset_range_request, response = zset_range_reply, }), zrangebyscore = command('ZRANGEBYSCORE', { request = zset_range_byscore_request, response = zset_range_reply, }), zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2 request = zset_range_byscore_request, response = zset_range_reply, }), zunionstore = command('ZUNIONSTORE', { -- >= 2.0 request = zset_store_request }), zinterstore = command('ZINTERSTORE', { -- >= 2.0 request = zset_store_request }), zcount = command('ZCOUNT'), zcard = command('ZCARD'), zscore = command('ZSCORE'), zremrangebyscore = command('ZREMRANGEBYSCORE'), zrank = command('ZRANK'), -- >= 2.0 zrevrank = command('ZREVRANK'), -- >= 2.0 zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0 -- commands operating on hashes hset = command('HSET', { -- >= 2.0 response = toboolean }), hsetnx = command('HSETNX', { -- >= 2.0 response = toboolean }), hmset = command('HMSET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, k) table.insert(args, v) end), }), hincrby = command('HINCRBY'), -- >= 2.0 hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), hget = command('HGET'), -- >= 2.0 hmget = command('HMGET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, v) end), }), hdel = command('HDEL'), -- >= 2.0 hexists = command('HEXISTS', { -- >= 2.0 response = toboolean }), hlen = command('HLEN'), -- >= 2.0 hkeys = command('HKEYS'), -- >= 2.0 hvals = command('HVALS'), -- >= 2.0 hgetall = command('HGETALL', { -- >= 2.0 response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }), -- connection related commands ping = command('PING', { response = function(response) return response == 'PONG' end }), echo = command('ECHO'), auth = command('AUTH'), select = command('SELECT'), -- transactions multi = command('MULTI'), -- >= 2.0 exec = command('EXEC'), -- >= 2.0 discard = command('DISCARD'), -- >= 2.0 watch = command('WATCH'), -- >= 2.2 unwatch = command('UNWATCH'), -- >= 2.2 -- publish - subscribe subscribe = command('SUBSCRIBE'), -- >= 2.0 unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0 psubscribe = command('PSUBSCRIBE'), -- >= 2.0 punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0 publish = command('PUBLISH'), -- >= 2.0 -- redis scripting eval = command('EVAL'), -- >= 2.6 evalsha = command('EVALSHA'), -- >= 2.6 script = command('SCRIPT'), -- >= 2.6 -- remote server control commands bgrewriteaof = command('BGREWRITEAOF'), config = command('CONFIG', { -- >= 2.0 response = function(reply, command, ...) if (type(reply) == 'table') then local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end return reply end }), client = command('CLIENT'), -- >= 2.4 slaveof = command('SLAVEOF'), save = command('SAVE'), bgsave = command('BGSAVE'), lastsave = command('LASTSAVE'), flushdb = command('FLUSHDB'), flushall = command('FLUSHALL'), monitor = command('MONITOR'), time = command('TIME'), -- >= 2.6 slowlog = command('SLOWLOG', { -- >= 2.2.13 response = function(reply, command, ...) if (type(reply) == 'table') then local structured = { } for index, entry in ipairs(reply) do structured[index] = { id = tonumber(entry[1]), timestamp = tonumber(entry[2]), duration = tonumber(entry[3]), command = entry[4], } end return structured end return reply end }), info = command('INFO', { response = parse_info, }), } -- ############################################################################ return redis
agpl-3.0
Devul/DarkRP
gamemode/modules/fadmin/fadmin/playeractions/freeze/cl_init.lua
10
1858
FAdmin.StartHooks["Freeze"] = function() FAdmin.Messages.RegisterNotification{ name = "freeze", hasTarget = true, message = {"instigator", " froze ", "targets", " ", "extraInfo.1"}, readExtraInfo = function() local time = net.ReadUInt(16) return {time == 0 and FAdmin.PlayerActions.commonTimes[time] or string.format("for %s", FAdmin.PlayerActions.commonTimes[time] or (time .. " seconds"))} end } FAdmin.Messages.RegisterNotification{ name = "unfreeze", hasTarget = true, message = {"instigator", " unfroze ", "targets"}, } FAdmin.Access.AddPrivilege("Freeze", 2) FAdmin.Commands.AddCommand("freeze", nil, "<Player>") FAdmin.Commands.AddCommand("unfreeze", nil, "<Player>") FAdmin.ScoreBoard.Player:AddActionButton(function(ply) if ply:FAdmin_GetGlobal("FAdmin_frozen") then return "Unfreeze" end return "Freeze" end, function(ply) if ply:FAdmin_GetGlobal("FAdmin_frozen") then return "fadmin/icons/freeze", "fadmin/icons/disable" end return "fadmin/icons/freeze" end, Color(255, 130, 0, 255), function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "Freeze", ply) end, function(ply, button) if not ply:FAdmin_GetGlobal("FAdmin_frozen") then FAdmin.PlayerActions.addTimeMenu(function(secs) RunConsoleCommand("_FAdmin", "freeze", ply:UserID(), secs) button:SetImage2("fadmin/icons/disable") button:SetText("Unfreeze") button:GetParent():InvalidateLayout() end) else RunConsoleCommand("_FAdmin", "unfreeze", ply:UserID()) end button:SetImage2("null") button:SetText("Freeze") button:GetParent():InvalidateLayout() end) end
mit
thedraked/darkstar
scripts/zones/Al_Zahbi/npcs/Mihli_Aliapoh.lua
14
1047
----------------------------------- -- Area: Al Zahbi -- NPC: Mihli Aliapoh -- Type: Waterserpent General -- @zone 48 -- @pos -22.615 -7 78.907 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x010b); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
CCAAHH/1p
plugins/all.lua
1321
4661
do data = load_data(_config.moderation.data) 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) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_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 table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0
alirezanj1/AntiSpam
plugins/all.lua
1321
4661
do data = load_data(_config.moderation.data) 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) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_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 table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0
thedraked/darkstar
scripts/zones/Palborough_Mines/npcs/_3z7.lua
34
1087
----------------------------------- -- Elevator in Palborough -- Notes: Used to operate Elevator @3z0 ----------------------------------- package.loaded["scripts/zones/Palborough_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Palborough_Mines/TextIDs"); require("scripts/globals/status"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RunElevator(ELEVATOR_PALBOROUGH_MINES_LIFT); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
pevers/OpenRA
mods/d2k/maps/atreides-01b/atreides01b.lua
18
4800
HarkonnenReinforcements = { } HarkonnenReinforcements["Easy"] = { { "rifle", "rifle" } } HarkonnenReinforcements["Normal"] = { { "rifle", "rifle" }, { "rifle", "rifle", "rifle" }, { "rifle", "trike" }, } HarkonnenReinforcements["Hard"] = { { "rifle", "rifle" }, { "trike", "trike" }, { "rifle", "rifle", "rifle" }, { "rifle", "trike" }, { "trike", "trike" } } HarkonnenEntryWaypoints = { HarkonnenWaypoint1.Location, HarkonnenWaypoint2.Location, HarkonnenWaypoint3.Location, HarkonnenWaypoint4.Location } HarkonnenAttackDelay = DateTime.Seconds(30) HarkonnenAttackWaves = { } HarkonnenAttackWaves["Easy"] = 1 HarkonnenAttackWaves["Normal"] = 5 HarkonnenAttackWaves["Hard"] = 12 ToHarvest = { } ToHarvest["Easy"] = 2500 ToHarvest["Normal"] = 3000 ToHarvest["Hard"] = 3500 AtreidesReinforcements = { "rifle", "rifle", "rifle", "rifle" } AtreidesEntryPath = { AtreidesWaypoint.Location, AtreidesRally.Location } Messages = { "Build a concrete foundation before placing your buildings.", "Build a Wind Trap for power.", "Build a Refinery to collect Spice.", "Build a Silo to store additional Spice." } IdleHunt = function(actor) if not actor.IsDead then Trigger.OnIdle(actor, actor.Hunt) end end Tick = function() if HarkonnenArrived and harkonnen.HasNoRequiredUnits() then player.MarkCompletedObjective(KillHarkonnen) end if player.Resources > ToHarvest[Map.Difficulty] - 1 then player.MarkCompletedObjective(GatherSpice) end -- player has no Wind Trap if (player.PowerProvided <= 20 or player.PowerState ~= "Normal") and DateTime.GameTime % DateTime.Seconds(32) == 0 then HasPower = false Media.DisplayMessage(Messages[2], "Mentat") else HasPower = true end -- player has no Refinery and no Silos if HasPower and player.ResourceCapacity == 0 and DateTime.GameTime % DateTime.Seconds(32) == 0 then Media.DisplayMessage(Messages[3], "Mentat") end if HasPower and player.Resources > player.ResourceCapacity * 0.8 and DateTime.GameTime % DateTime.Seconds(32) == 0 then Media.DisplayMessage(Messages[4], "Mentat") end UserInterface.SetMissionText("Harvested resources: " .. player.Resources .. "/" .. ToHarvest[Map.Difficulty], player.Color) end WorldLoaded = function() player = Player.GetPlayer("Atreides") harkonnen = Player.GetPlayer("Harkonnen") InitObjectives() Trigger.OnRemovedFromWorld(AtreidesConyard, function() local refs = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(actor) return actor.Type == "refinery" end) if #refs == 0 then harkonnen.MarkCompletedObjective(KillAtreides) else Trigger.OnAllRemovedFromWorld(refs, function() harkonnen.MarkCompletedObjective(KillAtreides) end) end end) Media.DisplayMessage(Messages[1], "Mentat") Trigger.AfterDelay(DateTime.Seconds(25), function() Media.PlaySpeechNotification(player, "Reinforce") Reinforcements.Reinforce(player, AtreidesReinforcements, AtreidesEntryPath) end) WavesLeft = HarkonnenAttackWaves[Map.Difficulty] SendReinforcements() end SendReinforcements = function() local units = HarkonnenReinforcements[Map.Difficulty] local delay = Utils.RandomInteger(HarkonnenAttackDelay - DateTime.Seconds(2), HarkonnenAttackDelay) HarkonnenAttackDelay = HarkonnenAttackDelay - (#units * 3 - 3 - WavesLeft) * DateTime.Seconds(1) if HarkonnenAttackDelay < 0 then HarkonnenAttackDelay = 0 end Trigger.AfterDelay(delay, function() Reinforcements.Reinforce(harkonnen, Utils.Random(units), { Utils.Random(HarkonnenEntryWaypoints) }, 10, IdleHunt) WavesLeft = WavesLeft - 1 if WavesLeft == 0 then Trigger.AfterDelay(DateTime.Seconds(1), function() HarkonnenArrived = true end) else SendReinforcements() end end) end InitObjectives = function() Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) KillAtreides = harkonnen.AddPrimaryObjective("Kill all Atreides units.") GatherSpice = player.AddPrimaryObjective("Harvest " .. tostring(ToHarvest[Map.Difficulty]) .. " Solaris worth of Spice.") KillHarkonnen = player.AddSecondaryObjective("Eliminate all Harkonnen units and reinforcements\nin the area.") Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerLost(player, function() Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(player, "Lose") end) end) Trigger.OnPlayerWon(player, function() Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(player, "Win") end) end) end
gpl-3.0
thedraked/darkstar
scripts/zones/Abyssea-Konschtat/npcs/qm3.lua
10
1344
----------------------------------- -- Zone: Abyssea-Konschtat -- NPC: qm3 (???) -- Spawns Hexenpilz -- @pos ? ? ? 15 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(2908,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(16838837) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(16838837):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 2908); -- Inform payer what items they need. end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
horizonrz/DBTeam
bot/permissions.lua
43
1333
local sudos = { "plugins", "rank_admin", "bot", "lang_install", "set_lang", "tosupergroup", "gban_installer" } local admins = { "rank_mod", "gban", "ungban", "setrules", "setphoto", "creategroup", "setname", "addbots", "setlink", "rank_guest", "description", "export_gban" } local mods = { "whois", "kick", "add", "ban", "unban", "lockmember", "mute", "unmute", "admins", "members", "welcome", "mods", "flood", "commands", "lang", "settings", "mod_commands", "no_flood_ban", "muteall", "rules", "pre_process" } local function get_tag(plugin_tag) for v,tag in pairs(sudos) do if tag == plugin_tag then return 3 end end for v,tag in pairs(admins) do if tag == plugin_tag then return 2 end end for v,tag in pairs(mods) do if tag == plugin_tag then return 1 end end return 0 end local function user_num(user_id, chat_id) if new_is_sudo(user_id) then return 3 elseif is_admin(user_id) then return 2 elseif is_mod(chat_id, user_id) then return 1 else return 0 end end function permissions(user_id, chat_id, plugin_tag) local user_is = get_tag(plugin_tag) local user_n = user_num(user_id, chat_id) if user_n >= user_is then return true else return false end end
gpl-2.0
jhasse/wxFormBuilder
build/premake/4.3/src/base/validate.lua
70
2531
-- -- validate.lua -- Tests to validate the run-time environment before starting the action. -- Copyright (c) 2002-2009 Jason Perkins and the Premake project -- -- -- Performs a sanity check of all of the solutions and projects -- in the session to be sure they meet some minimum requirements. -- function premake.checkprojects() local action = premake.action.current() for sln in premake.solution.each() do -- every solution must have at least one project if (#sln.projects == 0) then return nil, "solution '" .. sln.name .. "' needs at least one project" end -- every solution must provide a list of configurations if (#sln.configurations == 0) then return nil, "solution '" .. sln.name .. "' needs configurations" end for prj in premake.solution.eachproject(sln) do -- every project must have a language if (not prj.language) then return nil, "project '" ..prj.name .. "' needs a language" end -- and the action must support it if (action.valid_languages) then if (not table.contains(action.valid_languages, prj.language)) then return nil, "the " .. action.shortname .. " action does not support " .. prj.language .. " projects" end end for cfg in premake.eachconfig(prj) do -- every config must have a kind if (not cfg.kind) then return nil, "project '" ..prj.name .. "' needs a kind in configuration '" .. cfg.name .. "'" end -- and the action must support it if (action.valid_kinds) then if (not table.contains(action.valid_kinds, cfg.kind)) then return nil, "the " .. action.shortname .. " action does not support " .. cfg.kind .. " projects" end end end -- some actions have custom validation logic if action.oncheckproject then action.oncheckproject(prj) end end end return true end -- -- Check the specified tools (/cc, /dotnet, etc.) against the current action -- to make sure they are compatible and supported. -- function premake.checktools() local action = premake.action.current() if (not action.valid_tools) then return true end for tool, values in pairs(action.valid_tools) do if (_OPTIONS[tool]) then if (not table.contains(values, _OPTIONS[tool])) then return nil, "the " .. action.shortname .. " action does not support /" .. tool .. "=" .. _OPTIONS[tool] .. " (yet)" end else _OPTIONS[tool] = values[1] end end return true end
gpl-2.0
mtroyka/Zero-K
LuaRules/Utilities/GetEffectiveWeaponRange.lua
10
5625
local function GetRangeModType(weaponDef) local modType = 0 --weapon targeting mod type if (weaponDef.type == "Cannon") or (weaponDef.type == "EmgCannon") or (weaponDef.type == "DGun" and weaponDef.gravityAffected) or (weaponDef.type == "AircraftBomb") then --Ballistic modType = 0 elseif (weaponDef.type == "LaserCannon" or weaponDef.type == "BeamLaser" or weaponDef.type == "Melee" or weaponDef.type == "Flame" or weaponDef.type == "LightningCannon" or (weaponDef.type == "DGun" and not weaponDef.gravityAffected)) then --Sphere modType = 1 elseif (weaponDef.type == "MissileLauncher" or weaponDef.type == "StarburstLauncher" or weaponDef.type == "TorpedoLauncher") then --Cylinder modType = 2 end return modType end local spGetGroundHeight = Spring.GetGroundHeight local cos45degree = math.cos(math.pi/4) --use test range of 45 degree for optimal launch local sin45degree = math.sin(math.pi/4) local function CalculateBallisticConstant(deltaV,myGravity,heightDiff) --determine maximum range & time local xVel = cos45degree*deltaV --horizontal portion local yVel = sin45degree*deltaV --vertical portion local t = nil local yDist = heightDiff local a = myGravity -- 0 = yVel*t - a*t*t/2 --this is the basic equation of motion for vertical motion, we set distance to 0 or yDist (this have 2 meaning: either is launching from ground or is hitting ground) then we find solution for time (t) using a quadratic solver -- 0 = (yVel)*t - (a/2)*t*t --^same equation as above rearranged to highlight time (t) local discriminant =(yVel^2 - 4*(-a/2)*(yDist))^0.5 local denominator = 2*(-a/2) local t1 = (-yVel + discriminant)/denominator ---formula for finding root for quadratic equation (quadratic solver). Ref: http://www.sosmath.com/algebra/quadraticeq/quadraformula/summary/summary.html local t2 = (-yVel - discriminant)/denominator xDist1 = xVel*t1 --distance travelled horizontally in "t" amount of time xDist2 = xVel*t2 local maxRange = nil if xDist1>= xDist2 then maxRange=xDist1 --maximum range t=t1 --flight time else maxRange=xDist2 t=t2 end return maxRange, t --return maximum range and flight time. end local reverseCompat = (Game.version:find('91.0') == 1) local function CalculateModdedMaxRange(heightDiff,weaponDef,modType) local customMaxRange = weaponDef.range local customHeightMod = weaponDef.heightMod local customCylinderTargeting = weaponDef.cylinderTargeting local customHeightBoost = weaponDef.heightBoostFactor local heightModded = (heightDiff)*customHeightMod local effectiveRange = 0 --equivalent to: GetRange2D(): if modType == 0 then --Ballistic local myGravity = (weaponDef.myGravity > 0 and weaponDef.myGravity*888.888888) or (Game.gravity) or 0 local deltaV = weaponDef.projectilespeed*30 local maxFlatRange = CalculateBallisticConstant(deltaV,myGravity,0) local scaleDown = customMaxRange/maxFlatRange --Example: UpdateRange() in Spring\rts\Sim\Weapons\Cannon.cpp local heightBoostFactor = customHeightBoost if heightBoostFactor < 0 and scaleDown > 0 then heightBoostFactor = (2 - scaleDown) / math.sqrt(scaleDown) --such that: heightBoostFactor == 1 when scaleDown == 1 end heightModded = heightModded*heightBoostFactor local moddedRange = CalculateBallisticConstant(deltaV,myGravity,heightModded) effectiveRange = moddedRange*scaleDown --Example: GetRange2D() in Spring\rts\Sim\Weapons\Cannon.cpp elseif modType == 1 then --SPHERE effectiveRange = math.sqrt(customMaxRange^2 - heightModded^2) --Pythagoras theorem. Example: GetRange2D() in Spring\rts\Sim\Weapons\Weapon.cpp elseif modType == 2 then --CYLINDER effectiveRange = customMaxRange - heightModded*customHeightMod --Example: GetRange2D() in Spring\rts\Sim\Weapons\StarburstLauncher.cpp --Note: for unknown reason we must "Minus the heightMod" instead of adding it. This is the opposite of what shown on the source-code, but ingame test suggest "Minus heightMod" and not adding. end --equivalent to: TestRange(): if reverseCompat and modType == 0 then customCylinderTargeting = 128 end if customCylinderTargeting >= 0.01 then --See Example: TestRange() in Spring\rts\Sim\Weapons\Weapon.cpp --STRICT CYLINDER if customCylinderTargeting * customMaxRange > math.abs(heightModded) then if modType == 0 then effectiveRange = math.min(effectiveRange,customMaxRange) --Ballistic is more complex, physically it have limited range when shooting upward else effectiveRange = customMaxRange --other weapon have no physic limit and should obey cylinder end else effectiveRange = 0 --out of Strict Cylinder bound end end return effectiveRange end --This function calculate effective range for unit with different target elevation. --Note: heightDiff is (unitY - targetY) --Note2: weaponNumOverride is defaulted to 1 if not specified function Spring.Utilities.GetEffectiveWeaponRange(unitDefID, heightDiff, weaponNumOverride) if not unitDefID or not UnitDefs[unitDefID] then return 0 end local weaponNumber = weaponNumOverride and math.modf(weaponNumOverride) or 1 heightDiff = heightDiff or 0 local weaponList = UnitDefs[unitDefID].weapons local effectiveMaxRange = 0 if #weaponList > 0 then if weaponNumber > #weaponList then Spring.Echo("Warning: No weapon no " .. weaponNumber .. " in unit's weapon list.") weaponNumber = 1 end local weaponDefID = weaponList[weaponNumber].weaponDef local weaponDef = WeaponDefs[weaponDefID] local modType = GetRangeModType(weaponDef) effectiveMaxRange = CalculateModdedMaxRange(heightDiff,weaponDef,modType) end return effectiveMaxRange end
gpl-2.0
mtroyka/Zero-K
units/chicken_spidermonkey.lua
3
6010
unitDef = { unitname = [[chicken_spidermonkey]], name = [[Spidermonkey]], description = [[All-Terrain Support]], acceleration = 0.36, brakeRate = 0.205, buildCostEnergy = 0, buildCostMetal = 0, builder = false, buildPic = [[chicken_spidermonkey.png]], buildTime = 500, canAttack = true, canGuard = true, canMove = true, canPatrol = true, category = [[LAND]], customParams = { description_fr = [[Lanceur de filet tout terrain]], description_de = [[Gelandegängige Luftabwehr]], helptext = [[The Spidermonkey is a very unusual support chicken. As the name suggests, it can climb walls, however it can also spin a silk line that slows and yanks enemies.]], helptext_fr = [[Le spidermonkey est une unit? de soutien tr?s inhabituelle parmis les poulets. Comme le nom l'indique il peut grimper les parois les plus escarp?es mais peut en plus projetter comme une fronde un filet pour bloquer au sol les unit?s a?riennes, ? la mani?re d'une araign?e attrappant des insectes.]], helptext_de = [[Der Spidermonkey ist ein sehr ungewöhnliches Chicken. Wie der Name verrät, kann er Wände hochklettern und schließlich auch wie eine Spinne per Netz seine Fliegen, bzw. Flugzeuge Luft fangen.]], }, explodeAs = [[NOWEAPON]], footprintX = 3, footprintZ = 3, iconType = [[spiderskirm]], idleAutoHeal = 20, idleTime = 300, leaveTracks = true, maxDamage = 1500, maxSlope = 72, maxVelocity = 2.2, maxWaterDepth = 22, minCloakDistance = 75, movementClass = [[ATKBOT3]], noAutoFire = false, noChaseCategory = [[TERRAFORM LAND SINK TURRET SHIP SATELLITE SWIM FLOAT SUB HOVER STUPIDTARGET MINE]], objectName = [[chicken_spidermonkey.s3o]], power = 500, seismicSignature = 4, selfDestructAs = [[NOWEAPON]], sfxtypes = { explosiongenerators = { [[custom:blood_spray]], [[custom:blood_explode]], [[custom:dirt]], }, }, sightDistance = 700, sonarDistance = 450, trackOffset = 0.5, trackStrength = 9, trackStretch = 1, trackType = [[ChickenTrackPointy]], trackWidth = 70, turnRate = 1200, upright = false, workerTime = 0, weapons = { { def = [[WEB]], badTargetCategory = [[UNARMED]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], mainDir = [[0 0 1]], maxAngleDif = 180, }, --{ -- def = [[SPORES]], -- badTargetCategory = [[SWIM LAND SHIP HOVER]], -- onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], --}, }, weaponDefs = { SPORES = { name = [[Spores]], areaOfEffect = 24, avoidFriendly = false, burst = 5, burstrate = 0.1, collideFriendly = false, craterBoost = 0, craterMult = 0, customParams = { light_radius = 0, }, damage = { default = 75, planes = [[150]], subs = 7.5, }, dance = 60, explosionGenerator = [[custom:NONE]], fireStarter = 0, fixedlauncher = 1, flightTime = 5, groundbounce = 1, heightmod = 0.5, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 2, model = [[chickeneggpink.s3o]], range = 600, reloadtime = 6, smokeTrail = true, soundstart = [[weapon/hiss]], startVelocity = 100, texture1 = [[]], texture2 = [[sporetrail]], tolerance = 10000, tracks = true, turnRate = 24000, turret = true, waterweapon = true, weaponAcceleration = 100, weaponType = [[MissileLauncher]], weaponVelocity = 500, wobble = 32000, }, WEB = { name = [[Web Weapon]], accuracy = 800, customParams = { impulse = [[-200]], timeslow_damagefactor = 1, timeslow_onlyslow = 1, timeslow_smartretarget = 0.33, }, craterBoost = 0, craterMult = 0, damage = { default = 30, subs = 0.75, }, dance = 150, explosionGenerator = [[custom:NONE]], fireStarter = 0, fixedlauncher = true, flightTime = 3, impactOnly = true, interceptedByShieldType = 2, range = 600, reloadtime = 0.1, smokeTrail = true, soundstart = [[chickens/web]], startVelocity = 600, texture2 = [[smoketrailthin]], tolerance = 63000, tracks = true, turnRate = 90000, turret = true, weaponAcceleration = 400, weaponType = [[MissileLauncher]], weaponVelocity = 2000, }, }, } return lowerkeys({ chicken_spidermonkey = unitDef })
gpl-2.0
cjp39/naev
ai/tpl/merchant.lua
1
2276
include("ai/include/basic.lua") -- Variables mem.enemy_close = 500 -- Distance enemy is too close for comfort -- Required control rate control_rate = 2 -- Required "control" function function control () task = ai.taskname() enemy = ai.getenemy() -- Runaway if enemy is near if task ~= "runaway" and enemy ~= nil and (ai.dist(enemy) < mem.enemy_close or ai.haslockon()) then if task ~= "none" then ai.poptask() end ai.pushtask("runaway",enemy) -- Try to jump when far enough away elseif task == "runaway" then target = ai.target() -- Check if should still run. if not ai.exists(target) then ai.poptask() return end dist = ai.dist( target ) if mem.attacked then -- Increment distress if mem.distressed == nil then mem.distressed = 10 -- Distresses more quickly at first else mem.distressed = mem.distressed + 1 end -- Check to see if should send distress signal. if mem.distressed > 10 then sos() mem.distressed = 1 end end -- See if another enemy is closer if enemy ~= nil and enemy ~= target then ai.poptask() ai.pushtask("runaway",enemy) end -- Try to jump. if dist > 400 then ai.hyperspace() end -- Find something to do elseif task == "none" then planet = ai.landplanet() -- planet must exist if planet == nil then ai.settimer(0, rnd.int(1000, 3000)) ai.pushtask("enterdelay") else mem.land = planet ai.pushtask("hyperspace") ai.pushtask("land") end end end -- Delays the ship when entering systems so that it doesn't leave right away function enterdelay () if ai.timeup(0) then ai.pushtask("hyperspace") end end function sos () end -- Required "attacked" function function attacked ( attacker ) mem.attacked = true if ai.taskname() ~= "runaway" then -- Sir Robin bravely ran away ai.pushtask("runaway", attacker) else -- run away from the new baddie ai.poptask() ai.pushtask("runaway", attacker) end end function create () end
gpl-3.0
thedraked/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Pettette.lua
14
1062
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Pettette -- Type: Standard NPC -- @zone 94 -- @pos 164.026 -0.001 -26.690 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0009); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
OpenNMT/OpenNMT
tools/tokenize.lua
4
2970
require('torch') require('onmt.init') local threads = require 'threads' local tokenizer = require('tools.utils.tokenizer') local cmd = onmt.utils.ExtendedCmdLine.new('tokenize.lua') tokenizer.declareOpts(cmd) cmd:text('') cmd:text('Other options') cmd:text('') cmd:option('-nparallel', 1, [[Number of parallel thread to run the tokenization]]) cmd:option('-batchsize', 1000, [[Size of each parallel batch - you should not change except if low memory]]) -- insert on the fly the option depending if there is a hook selected onmt.utils.HookManager.updateOpt(arg, cmd) onmt.utils.HookManager.declareOpts(cmd) local opt = cmd:parse(arg) local pool = threads.Threads( opt.nparallel, function(id) local HookManager = require('onmt.utils.HookManager') _G.separators = require('tools.utils.separators') _G.tokenizer = require('tools.utils.tokenizer') _G.BPE = require ('tools.utils.BPE') _G.hookManager = HookManager.new(opt, "thread "..id) if opt.bpe_model ~= '' then _G.bpe = _G.BPE.new(opt) end end ) pool:specific(true) local timer = torch.Timer() local idx = 0 while true do local batches_input = {} local batches_output = {} local cidx = 0 local line for i = 1, opt.nparallel do batches_input[i] = {} for _ = 1, opt.batchsize do line = io.read() if not line then break end cidx = cidx + 1 table.insert(batches_input[i], line) end if not line then break end end if cidx == 0 then break end for i = 1, #batches_input do pool:addjob( i, function() local output = {} local inputs = batches_input[i] -- preprocessing hook local pinputs = _G.hookManager:call("mpreprocess", opt, inputs) assert(pinputs ~= false) inputs = pinputs or inputs for b = 1,#inputs do local aline = inputs[b] local res local err local tokens res, err = pcall(function() tokens = _G.tokenizer.tokenize(opt, aline, _G.bpe) end) -- it can generate an exception if there are utf-8 issues in the text if not res then if string.find(err, "interrupted") then error("interrupted") else error("unicode error in line " .. idx+b*(i-1)*opt.batchsize .. ": " .. line .. '-' .. err) end end table.insert(output, table.concat(tokens, ' ')) end return output end, function(output) batches_output[i] = output end ) end pool:synchronize() -- output the tokenized and featurized string for i = 1, opt.nparallel do if not batches_output[i] then break end for b = 1, #batches_output[i] do io.write(batches_output[i][b] .. '\n') idx = idx + 1 end end if not line then break end end io.stderr:write(string.format('Tokenization completed in %0.3f seconds - %d sentences\n', timer:time().real, idx))
mit
ukoloff/rufus-lua-win
vendor/lua/lib/lua/logging/sql.lua
3
2625
------------------------------------------------------------------------------- -- Saves the logging information in a table using luasql -- -- @author Thiago Costa Ponte (thiago@ideais.com.br) -- -- @copyright 2004-2011 Kepler Project -- ------------------------------------------------------------------------------- require"logging" function logging.sql(params) params = params or {} params.tablename = params.tablename or "LogTable" params.logdatefield = params.logdatefield or "LogDate" params.loglevelfield = params.loglevelfield or "LogLevel" params.logmessagefield = params.logmessagefield or "LogMessage" if params.connectionfactory == nil or type(params.connectionfactory) ~= "function" then return nil, "No specified connection factory function" end local con, err if params.keepalive then con, err = params.connectionfactory() end return logging.new( function(self, level, message) if (not params.keepalive) or (con == nil) then con, err = params.connectionfactory() if not con then return nil, err end end local logDate = os.date("%Y-%m-%d %H:%M:%S") local insert = string.format("INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s')", params.tablename, params.logdatefield, params.loglevelfield, params.logmessagefield, logDate, level, string.gsub(message, "'", "''")) local ret, err = pcall(con.execute, con, insert) if not ret then con, err = params.connectionfactory() if not con then return nil, err end ret, err = con:execute(insert) if not ret then return nil, err end end if not params.keepalive then con:close() end return true end ) end return logging.sql
mit
SnabbCo/snabbswitch
lib/luajit/testsuite/test/lib/ffi/jit_struct.lua
6
4085
local ffi = require("ffi") ffi.cdef[[ typedef struct { int a, b, c; } jit_struct_foo_t; typedef struct { int a, b, c; } jit_struct_foo2_t; typedef struct { int a[10]; int b[10]; } jit_struct_sarr_t; typedef struct jit_struct_chain_t { struct jit_struct_chain_t *next; int v; } jit_struct_chain_t; ]] do --- iteration variable as field name local s = ffi.new("jit_struct_foo_t") for j,k in ipairs{ "a", "b", "c" } do for i=1,100 do s[k] = s[k] + j end end assert(s.a == 100) assert(s.b == 200) assert(s.c == 300) end do --- constant field names local s = ffi.new("jit_struct_foo_t") for i=1,100 do s.a = s.a + 1 s.b = s.b + 2 s.c = s.c + 3 end assert(s.a == 100) assert(s.b == 200) assert(s.c == 300) end do --- constants from structure local s = ffi.new("jit_struct_foo_t") local s2 = ffi.new("jit_struct_foo2_t", 1, 2, 3) for i=1,100 do s.a = s.a + s2.a s.b = s.b + s2.b s.c = s.c + s2.c end assert(s.a == 100) assert(s.b == 200) assert(s.c == 300) end do --- adding to array elements local s = ffi.new("jit_struct_sarr_t") for i=1,100 do s.a[5] = s.a[5] + 1 s.b[5] = s.b[5] + 2 end assert(s.a[5] == 100) assert(s.b[5] == 200) end do --- double indexing local s = ffi.new([[ struct { struct { int x; int b[10]; } a[100]; }]]) s.a[10].b[4] = 10 s.a[95].b[4] = 95 local x = 0 for i=1,100 do x = x + s.a[i-1].b[4] -- reassociate offsets for base and index end assert(x == 105) end do --- structurally identical local s1 = ffi.new("struct { int a; }") local s2 = ffi.new("struct { int a; }") local x = 0 for j=1,2 do for i=1,100 do s2.a = i s1.a = 1 x = x + s2.a -- cannot forward across aliasing store end if j == 1 then assert(x == 5050) s2 = s1 x = 0 else assert(x == 100) end end end do --- structurally different local s1 = ffi.new("struct { int a; }") local s2 = ffi.new("struct { char a; }") local x = 0 for j=1,2 do for i=1,100 do s2.a = i s1.a = 1 x = x + s2.a -- can forward across aliasing store end if j == 1 then assert(x == 5050) s2 = s1 -- this will cause a side trace x = 0 else assert(x == 100) end end end do --- union local s = ffi.new("union { uint8_t a; int8_t b; }") local x = 0 for i=1,200 do s.a = i x = x + s.b -- same offset, but must not alias (except if sign-extended) end assert(x == 1412) end do --- circular chain local s1 = ffi.new("jit_struct_chain_t") local s2 = ffi.new("jit_struct_chain_t") local s3 = ffi.new("jit_struct_chain_t") s1.next = s2 s2.next = s3 s3.next = s1 local p = s1 for i=1,99 do p.v = i p = p.next end assert(s1.v == 97) assert(s2.v == 98) assert(s3.v == 99) end do --- int struct initialiser local ct = ffi.typeof("struct { int a,b,c; }") local x,y,z = 0,0,0 for i=1,100 do local s = ct(i, i+1) x = x + s.a y = y + s.b z = z + s.c end assert(x == 5050) assert(y == 5150) assert(z == 0) end do --- double struct initialiser local ct = ffi.typeof("struct { double a,b,c; }") local x,y,z = 0,0,0 for i=1,100 do local s = ct(i, i+1) x = x + s.a y = y + s.b z = z + s.c end assert(x == 5050) assert(y == 5150) assert(z == 0) end do --- pointer / int struct initialiser local s1 = ffi.new("jit_struct_chain_t") local s for i=1,100 do s = ffi.new("jit_struct_chain_t", s1, i) end assert(tonumber(ffi.cast("int", s.next)) == tonumber(ffi.cast("int", ffi.cast("jit_struct_chain_t *", s1)))) assert(s.v == 100) end do --- unstable pointer/int type struct initialiser local ct = ffi.typeof("struct { int *p; int y; }") local s for i=1,200 do if i == 100 then ct = ffi.typeof("jit_struct_chain_t") end s = ct(nil, 10) end assert(s.v == 10) end do --- upvalued int box local s = ffi.new("struct { int x; }", 42) local function f() for i=1,100 do s.x = i assert(s.x == i) end end f() end
apache-2.0
mtroyka/Zero-K
LuaUI/Widgets/api_grabinput.lua
4
2524
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Grab Input", desc = "Implements grab input option", author = "GoogleFrog", date = "11 Novemember 2016", license = "GNU GPL, v2 or later", layer = 0, enabled = true, } end local ACTIVE_MESSAGE = "LobbyOverlayActive1" local INACTIVE_MESSAGE = "LobbyOverlayActive0" local lobbyOverlayActive = false -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Widget Options options_path = 'Settings/Interface/Mouse Cursor' options_order = { 'grabinput', 'lobbyDisables', } -- Radio buttons are intentionally absent from these options to allow hotkeys to -- toggle grabinput easily. options = { grabinput = { name = "Lock Cursor to Window", tooltip = "Prevents the cursor from leaving the Window/Screen", type = "bool", value = true, OnChange = function (self) if options.lobbyDisables.value and lobbyOverlayActive then Spring.SendCommands("grabinput 0") else Spring.SendCommands("grabinput " .. ((self.value and "1") or "0")) end end }, lobbyDisables = { name = "Lobby overlay disables lock", tooltip = "Disables input grabbing when the lobby overlay is visible.", type = "bool", value = true, noHotkey = false, OnChange = function (self) if self.value and lobbyOverlayActive then Spring.SendCommands("grabinput 1") else Spring.SendCommands("grabinput " .. ((options.grabinput.value and "1") or "0")) end end, noHotkey = true, }, } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Widget Interface function widget:Initialize() Spring.SendCommands("grabinput " .. ((options.grabinput.value and "1") or "0")) end function widget:Shutdown() -- For Chobby. Spring.SendCommands("grabinput 0") end function widget:RecvLuaMsg(msg) if msg == ACTIVE_MESSAGE then lobbyOverlayActive = true if options.lobbyDisables.value and options.grabinput.value then Spring.SendCommands("grabinput 0") end elseif msg == INACTIVE_MESSAGE then lobbyOverlayActive = false if options.lobbyDisables.value and options.grabinput.value then Spring.SendCommands("grabinput 1") end end end
gpl-2.0
thedraked/darkstar
scripts/zones/Port_San_dOria/npcs/Portaure.lua
17
1666
----------------------------------- -- Area: Port San d'Oria -- NPC: Portaure -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradePortaure") == 0) then player:messageSpecial(PORTAURE_DIALOG); player:setVar("FFR",player:getVar("FFR") - 1); player:setVar("tradePortaure",1); player:messageSpecial(FLYER_ACCEPTED); player:messageSpecial(FLYERS_HANDED,17 - player:getVar("FFR")); player:tradeComplete(); elseif (player:getVar("tradePortaure") ==1) then player:messageSpecial(FLYER_ALREADY); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x28b); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
kumpuu/factorio-helicopters
logic/heliPad.lua
1
2569
function getHeliPadIndexFromBaseEntity(ent) for i, v in ipairs(global.heliPads) do if v.baseEnt == ent then return i end end return nil end heliPad = { new = function(placementEnt) local obj = { valid = true, surface = placementEnt.surface, replacedTiles = {}, baseEnt = placementEnt.surface.create_entity { name = "heli-pad-entity", force = placementEnt.force, position = placementEnt.position, } } --game.players[1].print("calc: ".. tostring(placementEnt.position.y - heli_pad_sprite_y_shift).. " real pos: "..tostring(obj.baseEnt.position.y)) --game.players[1].print(tostring(placementEnt.position.x) .. "|" .. tostring(placementEnt.position.y)) local boundingBox = { left_top = {placementEnt.position.x - 3.5, placementEnt.position.y - 3.5}, right_bottom = {placementEnt.position.x + 3.5, placementEnt.position.y + 3.5} } local scorches = obj.surface.find_entities_filtered { area = boundingBox, type = "corpse", name = "small-scorchmark", } for k,v in pairs(scorches) do v.destroy() end local tiles = {} for i = -3, 3 do obj.replacedTiles[i] = {} for j = -3, 3 do table.insert(tiles, { name = "heli-pad-concrete", position = {x = placementEnt.position.x + i, y = placementEnt.position.y + j} }) local oldTile = obj.surface.get_tile(placementEnt.position.x + i, placementEnt.position.y + j) obj.replacedTiles[i][j] = { name = oldTile.name, position = oldTile.position } end end obj.surface.set_tiles(tiles, true) placementEnt.destroy() return setmetatable(obj, {__index = heliPad}) end, destroy = function(self) self.valid = false local restoredTiles = {} for i = -3, 3 do for j = -3, 3 do if self.surface.get_tile(self.baseEnt.position.x + i, self.baseEnt.position.y + j).name == "heli-pad-concrete" then self:migrateTile(self.replacedTiles[i][j]) table.insert(restoredTiles, self.replacedTiles[i][j]) end end end self.surface.set_tiles(restoredTiles, true) end, tile_migrations = { { {"grass", "grass-1"}, {"grass-medium", "grass-3"}, {"grass-dry", "grass-2"}, {"dirt", "dirt-3"}, {"dirt-dark", "dirt-6"}, {"sand", "sand-1"}, {"sand-dark", "sand-3"} }, }, migrateTile = function(self, tile) for i, curMigrationTable in ipairs(self.tile_migrations) do for k, curMigration in pairs(curMigrationTable) do if curMigration[1] == tile.name then tile.name = curMigration[2] break end end end end, }
mit
thedraked/darkstar
scripts/zones/LaLoff_Amphitheater/bcnms/ark_angels_1.lua
28
3110
----------------------------------- -- Area: LaLoff Amphitheater -- Name: Ark Angels 1 (Hume) ----------------------------------- package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil; ----------------------------------- require("scripts/zones/LaLoff_Amphitheater/TextIDs"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); ----------------------------------- -- Death cutscenes: -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); -- Hume -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); -- taru -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,2,0); -- mithra -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0); -- elvan -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,0); -- galka -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,5,0); -- divine might -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,6,0); -- skip ending cs -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:hasCompletedMission(ZILART,ARK_ANGELS)) then player:startEvent(0x7d01,instance:getEntrance(),instance:getFastestTime(),1,instance:getTimeInside(),180,0,1); -- winning CS (allow player to skip) else player:startEvent(0x7d01,instance:getEntrance(),instance:getFastestTime(),1,instance:getTimeInside(),180,0,0); -- winning CS (allow player to skip) end elseif (leavecode == 4) then player:startEvent(0x7d02, 0, 0, 0, 0, 0, instance:getEntrance(), 180); -- player lost end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); local AAKeyitems = (player:hasKeyItem(SHARD_OF_ARROGANCE) and player:hasKeyItem(SHARD_OF_COWARDICE) and player:hasKeyItem(SHARD_OF_ENVY) and player:hasKeyItem(SHARD_OF_RAGE)); if (csid == 0x7d01) then if (player:getCurrentMission(ZILART) == ARK_ANGELS and player:getVar("ZilartStatus") == 1) then player:addKeyItem(SHARD_OF_APATHY); player:messageSpecial(KEYITEM_OBTAINED,SHARD_OF_APATHY); if (AAKeyitems == true) then player:completeMission(ZILART,ARK_ANGELS); player:addMission(ZILART,THE_SEALED_SHRINE); player:setVar("ZilartStatus",0); end end end end;
gpl-3.0
rjeli/luvit
bench/http-cluster/app.lua
14
1034
--[[ Copyright 2014 The Luvit Authors. 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. --]] -- This file represents the high-level logic of the clustered app. return function (req) -- p(req) -- print("Writing response headers") local body = string.format("%s %s\n", req.method, req.path) local res = { code = 200, { "Server", "Luvit" }, { "Content-Type", "text/plain" }, { "Content-Length", #body }, } if req.keepAlive then res[#res + 1] = { "Connection", "Keep-Alive" } end return res, body end
apache-2.0
thedraked/darkstar
scripts/globals/items/strip_of_sheep_jerky.lua
18
1379
----------------------------------------- -- ID: 4518 -- Item: strip_of_sheep_jerky -- Food Effect: 60Min, All Races ----------------------------------------- -- Strength 3 -- Intelligence -1 -- Attack % 22 -- Attack Cap 35 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,4518); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 3); target:addMod(MOD_INT, -1); target:addMod(MOD_FOOD_ATTP, 22); target:addMod(MOD_FOOD_ATT_CAP, 35); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 3); target:delMod(MOD_INT, -1); target:delMod(MOD_FOOD_ATTP, 22); target:delMod(MOD_FOOD_ATT_CAP, 35); end;
gpl-3.0
thedraked/darkstar
scripts/zones/Quicksand_Caves/TextIDs.lua
7
1486
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6384; -- Obtained: <item> GIL_OBTAINED = 6385; -- Obtained <number> gil KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem> FISHING_MESSAGE_OFFSET = 7204; -- You can't fish here. HOMEPOINT_SET = 11419; -- Home point set! -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7311; -- You unlock the chest! CHEST_FAIL = 7312; -- Fails to open the chest. CHEST_TRAP = 7313; -- The chest was trapped! CHEST_WEAK = 7314; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7315; -- The chest was a mimic! CHEST_MOOGLE = 7316; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7317; -- The chest was but an illusion... CHEST_LOCKED = 7318; -- The chest appears to be locked. -- Other dialog NOTHING_OUT_OF_ORDINARY = 6398; -- There is nothing out of the ordinary here. SENSE_OF_FOREBODING = 6399; -- You are suddenly overcome with a sense of foreboding... DOOR_FIRMLY_SHUT = 7319; -- The door is firmly shut. POOL_OF_WATER = 7351; -- It is a pool of water. YOU_FIND_NOTHING = 7354; -- You find nothing. SOMETHING_IS_BURIED = 7359; -- Something is buried in this fallen pillar. -- conquest Base CONQUEST_BASE = 7045; -- Tallying conquest results...
gpl-3.0
mtroyka/Zero-K
scripts/corrad.lua
16
2147
include "constants.lua" local base = piece 'base' local ground = piece 'ground' local head = piece 'head' local smokePiece = {head} local SCANNER_PERIOD = 1000 local on = false --[[ local function TargetingLaser() while on do Turn(emit1, x_axis, math.rad(-50)) Turn(emit2, x_axis, math.rad(-40)) Turn(emit3, x_axis, math.rad(-20)) Turn(emit4, x_axis, math.rad(-5)) EmitSfx(emit1, 2048) EmitSfx(emit2, 2048) EmitSfx(emit3, 2048) EmitSfx(emit4, 2048) Sleep(20) Turn(emit1, x_axis, math.rad(-30)) Turn(emit2, x_axis, math.rad(-10)) Turn(emit3, x_axis, math.rad(10)) Turn(emit4, x_axis, math.rad(30)) EmitSfx(emit1, 2048) EmitSfx(emit2, 2048) EmitSfx(emit3, 2048) EmitSfx(emit4, 2048) Sleep(20) Turn(emit1, x_axis, math.rad(5)) Turn(emit2, x_axis, math.rad(20)) Turn(emit3, x_axis, math.rad(40)) Turn(emit4, x_axis, math.rad(50)) EmitSfx(emit1, 2048) EmitSfx(emit2, 2048) EmitSfx(emit3, 2048) EmitSfx(emit4, 2048) Sleep(20) end end ]] local index = 0 local function ScannerLoop() while true do while (not on) or Spring.GetUnitIsStunned(unitID) do Sleep(300) end EmitSfx(head, 4096) index = index + 1 if index == 5 then index = 0 EmitSfx(head, 1024) end Sleep(SCANNER_PERIOD) end end function script.Create() StartThread(SmokeUnit, smokePiece) --StartThread(ScannerLoop) local cmd = Spring.FindUnitCmdDesc(unitID, CMD.ATTACK) if cmd then Spring.RemoveUnitCmdDesc(unitID, cmd) end end function script.Activate() Spin(head, y_axis, math.rad(60)) on = true end function script.Deactivate() StopSpin(head, y_axis) on = false end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity <= .25 then Explode(ground, sfxNone) Explode(head, sfxFall + sfxExplode) return 1 elseif severity <= .50 then Explode(ground, sfxNone) Explode(head, sfxFall + sfxExplode) return 1 elseif severity <= .99 then corpsetype = 2 Explode(ground, sfxNone) Explode(head, sfxFall + sfxExplode) return 2 else Explode(ground, sfxNone) Explode(head, sfxFall + sfxExplode) return 2 end end
gpl-2.0
thedraked/darkstar
scripts/zones/Inner_Horutoto_Ruins/npcs/_5cc.lua
14
1067
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: _5cc (Gate of Ice) -- @pos -228 0 99 192 ----------------------------------- package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Inner_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(DOOR_FIRMLY_CLOSED); return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
thedraked/darkstar
scripts/globals/items/plate_of_coeurl_sautee.lua
18
1759
----------------------------------------- -- ID: 4548 -- Item: plate_of_coeurl_sautee -- Food Effect: 180Min, All Races ----------------------------------------- -- Strength 5 -- Agility 1 -- Intelligence -2 -- Attack % 20 -- Attack Cap 75 -- Ranged ATT % 20 -- Ranged ATT Cap 75 -- Stun Resist 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4548); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 5); target:addMod(MOD_AGI, 1); target:addMod(MOD_INT, -2); target:addMod(MOD_FOOD_ATTP, 20); target:addMod(MOD_FOOD_ATT_CAP, 75); target:addMod(MOD_FOOD_RATTP, 20); target:addMod(MOD_FOOD_RATT_CAP, 75); target:addMod(MOD_STUNRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 5); target:delMod(MOD_AGI, 1); target:delMod(MOD_INT, -2); target:delMod(MOD_FOOD_ATTP, 20); target:delMod(MOD_FOOD_ATT_CAP, 75); target:delMod(MOD_FOOD_RATTP, 20); target:delMod(MOD_FOOD_RATT_CAP, 75); target:delMod(MOD_STUNRES, 5); end;
gpl-3.0
thedraked/darkstar
scripts/globals/spells/valor_minuet.lua
27
1497
----------------------------------------- -- Spell: Valor Minuet -- Grants Attack bonus to all allies. ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 5 + math.floor((sLvl+iLvl) / 8); if (power >= 16) then power = 16; end local iBoost = caster:getMod(MOD_MINUET_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); if (iBoost > 0) then power = power + 1 + (iBoost-1)*4; end power = power + caster:getMerit(MERIT_MINUET_EFFECT); if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_MINUET,power,0,duration,caster:getID(), 0, 1)) then spell:setMsg(75); end return EFFECT_MINUET; end;
gpl-3.0
pevers/OpenRA
mods/cnc/maps/gdi04b/gdi04b.lua
29
5792
BhndTrigger = { CPos.New(39, 21), CPos.New(40, 21), CPos.New(41, 21) } Atk1Trigger = { CPos.New(35, 37) } Atk2Trigger = { CPos.New(9, 44), CPos.New(10, 44), CPos.New(11, 44), CPos.New(12, 44), CPos.New(13, 44) } AutoTrigger = { CPos.New(5, 30), CPos.New(6, 30), CPos.New(7, 30), CPos.New(8, 30), CPos.New(9, 30), CPos.New(10, 30), CPos.New(11, 30), CPos.New(12, 30), CPos.New(13, 30) } GDIHeliTrigger = { CPos.New(11, 11), CPos.New(11, 12), CPos.New(11, 13), CPos.New(11, 14), CPos.New(11, 15), CPos.New(12, 15), CPos.New(13, 15), CPos.New(14, 15), CPos.New(15, 15), CPos.New(16, 15) } Hunters = { Hunter1, Hunter2, Hunter3, Hunter4, Hunter5 } NodxUnits = { "e1", "e1", "e3", "e3" } AutoUnits = { "e1", "e1", "e1", "e3", "e3" } KillsUntilReinforcements = 12 GDIReinforcements = { "e2", "e2", "e2", "e2", "e2" } GDIReinforcementsWaypoints = { GDIReinforcementsEntry.Location, GDIReinforcementsWP1.Location } NodHeli = { { HeliEntry.Location, NodHeliLZ.Location }, { "e1", "e1", "e3", "e3" } } SendHeli = function(heli) units = Reinforcements.ReinforceWithTransport(nod, "tran", heli[2], heli[1], { heli[1][1] }) Utils.Do(units[2], function(actor) actor.Hunt() Trigger.OnIdle(actor, actor.Hunt) Trigger.OnKilled(actor, KillCounter) end) end SendGDIReinforcements = function() Media.PlaySpeechNotification(gdi, "Reinforce") Reinforcements.ReinforceWithTransport(gdi, "apc", GDIReinforcements, GDIReinforcementsWaypoints, nil, function(apc, team) table.insert(team, apc) Trigger.OnAllKilled(team, function() Trigger.AfterDelay(DateTime.Seconds(5), SendGDIReinforcements) end) Utils.Do(team, function(unit) unit.Stance = "Defend" end) end) end Build = function(unitTypes, repeats, func) if HandOfNod.IsDead then return end local innerFunc = function(units) Utils.Do(units, func) if repeats then Trigger.OnAllKilled(units, function() Build(unitTypes, repeats, func) end) end end if not HandOfNod.Build(unitTypes, innerFunc) then Trigger.AfterDelay(DateTime.Seconds(5), function() Build(unitTypes, repeats, func) end) end end BuildNod1 = function() Build(NodxUnits, false, function(actor) Trigger.OnKilled(actor, KillCounter) actor.Patrol({ NodPatrol1.Location, NodPatrol2.Location, NodPatrol3.Location, NodPatrol4.Location }, false) Trigger.OnIdle(actor, actor.Hunt) end) end BuildNod2 = function() Build(NodxUnits, false, function(actor) Trigger.OnKilled(actor, KillCounter) actor.Patrol({ NodPatrol1.Location, NodPatrol2.Location }, false) Trigger.OnIdle(actor, actor.Hunt) end) end BuildAuto = function() Build(AutoUnits, true, function(actor) Trigger.OnKilled(actor, KillCounter) Trigger.OnIdle(actor, actor.Hunt) end) end ReinforcementsSent = false kills = 0 KillCounter = function() kills = kills + 1 end Tick = function() nod.Cash = 1000 if not ReinforcementsSent and kills >= KillsUntilReinforcements then ReinforcementsSent = true gdi.MarkCompletedObjective(reinforcementsObjective) SendGDIReinforcements() end if gdi.HasNoRequiredUnits() then Trigger.AfterDelay(DateTime.Seconds(1), function() gdi.MarkFailedObjective(gdiObjective) end) end end SetupWorld = function() Utils.Do(nod.GetGroundAttackers(), function(unit) Trigger.OnKilled(unit, KillCounter) end) Utils.Do(gdi.GetGroundAttackers(), function(unit) unit.Stance = "Defend" end) Utils.Do(Hunters, function(actor) actor.Hunt() end) Trigger.OnRemovedFromWorld(crate, function() gdi.MarkCompletedObjective(gdiObjective) end) end WorldLoaded = function() gdi = Player.GetPlayer("GDI") nod = Player.GetPlayer("Nod") Trigger.OnObjectiveAdded(gdi, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(gdi, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(gdi, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerWon(gdi, function() Media.PlaySpeechNotification(gdi, "Win") end) Trigger.OnPlayerLost(gdi, function() Media.PlaySpeechNotification(gdi, "Lose") end) gdiObjective = gdi.AddPrimaryObjective("Retrieve the crate with the stolen rods.") reinforcementsObjective = gdi.AddSecondaryObjective("Eliminate " .. KillsUntilReinforcements .. " Nod units for reinforcements.") nod.AddPrimaryObjective("Defend against the GDI forces.") SetupWorld() bhndTrigger = false Trigger.OnExitedFootprint(BhndTrigger, function(a, id) if not bhndTrigger and a.Owner == gdi then bhndTrigger = true Trigger.RemoveFootprintTrigger(id) SendHeli(NodHeli) end end) atk1Trigger = false Trigger.OnExitedFootprint(Atk1Trigger, function(a, id) if not atk1Trigger and a.Owner == gdi then atk1Trigger = true Trigger.RemoveFootprintTrigger(id) BuildNod1() end end) atk2Trigger = false Trigger.OnEnteredFootprint(Atk2Trigger, function(a, id) if not atk2Trigger and a.Owner == gdi then atk2Trigger = true Trigger.RemoveFootprintTrigger(id) BuildNod2() end end) autoTrigger = false Trigger.OnEnteredFootprint(AutoTrigger, function(a, id) if not autoTrigger and a.Owner == gdi then autoTrigger = true Trigger.RemoveFootprintTrigger(id) BuildAuto() Trigger.AfterDelay(DateTime.Seconds(4), function() tank.Hunt() end) end end) gdiHeliTrigger = false Trigger.OnEnteredFootprint(GDIHeliTrigger, function(a, id) if not gdiHeliTrigger and a.Owner == gdi then gdiHeliTrigger = true Trigger.RemoveFootprintTrigger(id) Reinforcements.ReinforceWithTransport(gdi, "tran", nil, { HeliEntry.Location, GDIHeliLZ.Location }) end end) Camera.Position = GDIReinforcementsWP1.CenterPosition end
gpl-3.0
filug/nodemcu-firmware
lua_modules/bh1750/bh1750.lua
89
1372
-- *************************************************************************** -- BH1750 module for ESP8266 with nodeMCU -- BH1750 compatible tested 2015-1-22 -- -- Written by xiaohu -- -- MIT license, http://opensource.org/licenses/MIT -- *************************************************************************** local moduleName = ... local M = {} _G[moduleName] = M --I2C slave address of GY-30 local GY_30_address = 0x23 -- i2c interface ID local id = 0 --LUX local l --CMD local CMD = 0x10 local init = false --Make it more faster local i2c = i2c function M.init(sda, scl) i2c.setup(id, sda, scl, i2c.SLOW) --print("i2c ok..") init = true end local function read_data(ADDR, commands, length) i2c.start(id) i2c.address(id, ADDR, i2c.TRANSMITTER) i2c.write(id, commands) i2c.stop(id) i2c.start(id) i2c.address(id, ADDR,i2c.RECEIVER) tmr.delay(200000) c = i2c.read(id, length) i2c.stop(id) return c end local function read_lux() dataT = read_data(GY_30_address, CMD, 2) --Make it more faster UT = dataT:byte(1) * 256 + dataT:byte(2) l = (UT*1000/12) return(l) end function M.read() if (not init) then print("init() must be called before read.") else read_lux() end end function M.getlux() return l end return M
mit
mason-larobina/luakit
tests/async/test_clib_luakit.lua
4
4241
--- Test luakit clib functionality. -- -- @copyright 2012 Mason Larobina <mason.larobina@gmail.com> local assert = require "luassert" local test = require "tests.lib" local T = {} T.test_luakit = function () assert.is_table(luakit) -- Check metatable local mt = getmetatable(luakit) assert.is_function(mt.__index, "luakit mt missing __index") end T.test_luakit_index = function () local funcprops = { "exec", "quit", "save_file", "spawn", "spawn_sync", "time", "uri_decode", "uri_encode", "idle_add", "idle_remove" } for _, p in ipairs(funcprops) do assert.is_function(luakit[p], "Missing/invalid function: luakit."..p) end local strprops = { "cache_dir", "config_dir", "data_dir", "execpath", "confpath", "install_path", "version" } for _, p in ipairs(strprops) do assert.is_string(luakit[p], "Missing/invalid property: luakit."..p) end local boolprops = { "dev_paths", "verbose", "nounique" } for _, p in ipairs(boolprops) do assert.is_boolean(luakit[p], "Missing/invalid property: luakit."..p) end assert.is_number(luakit.time(), "Invalid: luakit.time()") end T.test_webkit_version = function () assert.is_match("^%d+%.%d+%.%d+$", luakit.webkit_version, "Invalid format: luakit.webkit_version") assert.is_match("^%d+%.%d+$", luakit.webkit_user_agent_version, "Invalid format: luakit.webkit_user_agent_version") end T.test_windows_table = function () assert.is_table(luakit.windows, "Missing/invalid luakit.windows table.") local baseline = #luakit.windows assert.is_number(baseline, "Invalid number of windows") local win = widget{type="window"} assert.is_equal(baseline+1, #luakit.windows, "luakit.windows not tracking opened windows.") win:destroy() assert.is_equal(baseline, #luakit.windows, "luakit.windows not tracking closed windows.") end T.test_invalid_prop = function () assert.is_nil(luakit.invalid_property) end T.test_idle_add_del = function () local f = function () end assert.is_false(luakit.idle_remove(f), "Function can't be removed before it's been added.") for _ = 1,5 do luakit.idle_add(f) end for _ = 1,5 do assert.is_true(luakit.idle_remove(f), "Error removing callback.") end assert.is_false(luakit.idle_remove(f), "idle_remove removed incorrect number of callbacks.") end T.test_register_scheme = function () assert.has_error(function () luakit.register_scheme("") end) assert.has_error(function () luakit.register_scheme("http") end) assert.has_error(function () luakit.register_scheme("https") end) assert.has_error(function () luakit.register_scheme("ABC") end) assert.has_error(function () luakit.register_scheme(" ") end) luakit.register_scheme("test-scheme-name") luakit.register_scheme("a-.++...--8970d-d-") end T.test_website_data = function () local _, minor = luakit.webkit_version:match("^(%d+)%.(%d+)%.") if tonumber(minor) < 16 then return end local wd = luakit.website_data assert.is_table(wd) assert.is_function(wd.fetch) assert.has_error(function () wd.fetch("") end) assert.has_error(function () wd.fetch({}) end) assert.has_error(function () wd.remove("") end) assert.has_error(function () wd.remove({}) end) assert.has_error(function () wd.remove({"all"}) end) local v = widget{type="webview"} coroutine.wrap(function () assert(not wd.fetch({"all"})["Local files"]) test.continue() end)() test.wait(1000) v.uri = "file:///" test.wait_for_view(v) coroutine.wrap(function () assert(wd.fetch({"all"})["Local files"]) wd.remove({"all"}, "Local files") assert(not wd.fetch({"all"})["Local files"]) test.continue() end)() test.wait() v:destroy() end T.test_luakit_install_paths = function () local paths = assert(luakit.install_paths) assert.equal(paths.install_dir, luakit.install_path) for _, k in ipairs {"install_dir", "config_dir", "doc_dir", "man_dir", "pixmap_dir", "app_dir"} do assert(type(paths[k]) == "string") end end return T -- vim: et:sw=4:ts=8:sts=4:tw=80
gpl-3.0
thedraked/darkstar
scripts/zones/Kazham/npcs/Vah_Keshura.lua
17
1073
----------------------------------- -- Area: Kazham -- NPC: Vah Keshura -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("BathedInScent") == 1) then player:startEvent(0x00BB); -- scent from Blue Rafflesias else player:startEvent(0x007C); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
joyhuang-game/OpenRA
mods/ra/maps/soviet-05/AI.lua
26
4192
IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end IdlingUnits = function() local lazyUnits = Map.ActorsInBox(NWIdlePoint.CenterPosition, Map.BottomRight, function(actor) return actor.HasProperty("Hunt") and (actor.Owner == GoodGuy or actor.Owner == Greece) end) Utils.Do(lazyUnits, function(unit) Trigger.OnDamaged(unit, function() Trigger.ClearAll(unit) Trigger.AfterDelay(0, function() IdleHunt(unit) end) end) end) end BaseBuildings = { { "powr", CVec.New(3, -2), 300 }, { "tent", CVec.New(0, 4), 400 }, { "hbox", CVec.New(3, 6), 600 }, { "proc", CVec.New(4, 2), 1400 }, { "powr", CVec.New(5, -3), 300 }, { "weap", CVec.New(-5, 3), 2000 }, { "hbox", CVec.New(-6, 5), 600 }, { "gun", CVec.New(0, 8), 600 }, { "gun", CVec.New(-4, 7), 600 }, { "powr", CVec.New(-4, -3), 300 }, { "proc", CVec.New(-9, 1), 1400 }, { "powr", CVec.New(-8, -2), 300 }, { "silo", CVec.New(6, 0), 150 }, { "agun", CVec.New(-3, 0), 800 }, { "powr", CVec.New(-6, -2), 300 }, { "agun", CVec.New(4, 1), 800 }, { "gun", CVec.New(-9, 5), 600 }, { "gun", CVec.New(-2, -3), 600 }, { "powr", CVec.New(4, 6), 300 }, { "gun", CVec.New(3, -6), 600 }, { "hbox", CVec.New(3, -4), 600 }, { "gun", CVec.New(2, 3), 600 } } BuildBase = function() if not CheckForCYard() then return end for i,v in ipairs(BaseBuildings) do if not v[4] then BuildBuilding(v) return end end Trigger.AfterDelay(DateTime.Seconds(5), BuildBase) end BuildBuilding = function(building) Trigger.AfterDelay(Actor.BuildTime(building[1]), function() local actor = Actor.Create(building[1], true, { Owner = GoodGuy, Location = MCVDeploy.Location + building[2] }) GoodGuy.Cash = GoodGuy.Cash - building[3] building[4] = true Trigger.OnKilled(actor, function() building[4] = false end) Trigger.OnDamaged(actor, function(building) if building.Owner == GoodGuy and building.Health < building.MaxHealth * 3/4 then building.StartBuildingRepairs() end end) Trigger.AfterDelay(DateTime.Seconds(1), BuildBase) end) end ProduceInfantry = function() if Barr.IsDead then return end local delay = Utils.RandomInteger(DateTime.Seconds(3), DateTime.Seconds(9)) local toBuild = { Utils.Random(AlliedInfantryTypes) } Greece.Build(toBuild, function(unit) GreeceInfAttack[#GreeceInfAttack + 1] = unit[1] if #GreeceInfAttack >= 7 then SendUnits(GreeceInfAttack, InfantryWaypoints) GreeceInfAttack = { } Trigger.AfterDelay(DateTime.Minutes(2), ProduceInfantry) else Trigger.AfterDelay(delay, ProduceInfantry) end end) end ProduceShips = function() if Shipyard.IsDead then return end Greece.Build( {"dd"}, function(unit) Ships[#Ships + 1] = unit[1] if #Ships >= 2 then SendUnits(Ships, ShipWaypoints) Ships = { } Trigger.AfterDelay(DateTime.Minutes(6), ProduceShips) else Trigger.AfterDelay(Actor.BuildTime("dd"), ProduceShips) end end) end ProduceInfantryGG = function() if not BaseBuildings[2][4] then return end local delay = Utils.RandomInteger(DateTime.Seconds(3), DateTime.Seconds(9)) local toBuild = { Utils.Random(AlliedInfantryTypes) } GoodGuy.Build(toBuild, function(unit) GGInfAttack[#GGInfAttack + 1] = unit[1] if #GGInfAttack >= 10 then SendUnits(GGInfAttack, InfantryGGWaypoints) GGInfAttack = { } Trigger.AfterDelay(DateTime.Minutes(2), ProduceInfantryGG) else Trigger.AfterDelay(delay, ProduceInfantryGG) end end) end ProduceTanksGG = function() if not BaseBuildings[6][4] then return end local delay = Utils.RandomInteger(DateTime.Seconds(12), DateTime.Seconds(17)) local toBuild = { Utils.Random(AlliedTankTypes) } GoodGuy.Build(toBuild, function(unit) TankAttackGG[#TankAttackGG + 1] = unit[1] if #TankAttackGG >= 6 then SendUnits(TankAttackGG, TanksGGWaypoints) TankAttackGG = { } Trigger.AfterDelay(DateTime.Minutes(3), ProduceTanksGG) else Trigger.AfterDelay(delay, ProduceTanksGG) end end) end SendUnits = function(units, waypoints) Utils.Do(units, function(unit) if not unit.IsDead then Utils.Do(waypoints, function(waypoint) unit.AttackMove(waypoint.Location) end) unit.Hunt() end end) end
gpl-3.0
thedraked/darkstar
scripts/zones/Bastok_Mines/npcs/Mariadok.lua
59
1037
----------------------------------- -- Area: Bastok Mines -- NPC: Mariadok -- Type: Weather Reporter ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0002,0,0,0,0,0,0,0,VanadielTime()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
thedraked/darkstar
scripts/globals/abilities/pets/gust_breath.lua
29
1334
--------------------------------------------------- -- Gust Breath --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/ability"); --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0; end; function onUseAbility(pet, target, skill, action) local master = pet:getMaster() ---------- Deep Breathing ---------- -- 0 for none -- 1 for first merit -- 0.25 for each merit after the first -- TODO: 0.1 per merit for augmented AF2 (10663 *w/ augment*) local deep = 1; if (pet:hasStatusEffect(EFFECT_MAGIC_ATK_BOOST) == true) then deep = deep + 1 + (master:getMerit(MERIT_DEEP_BREATHING)-1)*0.25; pet:delStatusEffect(EFFECT_MAGIC_ATK_BOOST); end local gear = master:getMod(MOD_WYVERN_BREATH)/256; -- Master gear that enhances breath local dmgmod = MobBreathMove(pet, target, 0.185, pet:getMainLvl()*15, ELE_WIND); -- Works out to (hp/6) + 15, as desired dmgmod = (dmgmod * (1+gear))*deep; pet:setTP(0) local dmg = AbilityFinalAdjustments(dmgmod,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end
gpl-3.0
SnabbCo/snabbswitch
src/program/snabbvmx/query/query.lua
9
4331
module(..., package.seeall) local counter = require("core.counter") local ffi = require("ffi") local lib = require("core.lib") local ipv4 = require("lib.protocol.ipv4") local ethernet = require("lib.protocol.ethernet") local lwutil = require("apps.lwaftr.lwutil") local shm = require("core.shm") local keys, file_exists = lwutil.keys, lwutil.file_exists local macaddress_t = ffi.typeof[[ struct { uint8_t ether[6]; } ]] local function show_usage (code) print(require("program.snabbvmx.query.README_inc")) main.exit(code) end local function sort (t) table.sort(t) return t end local function parse_args (raw_args) local handlers = {} function handlers.h() show_usage(0) end local args = lib.dogetopt(raw_args, handlers, "h", { help="h" }) if #args > 0 then show_usage(1) end end local function read_counters (tree, app_name) local ret = {} local cnt, cnt_path, value local counters_path = "/" .. tree .. "/" .. app_name .. "/" local counters = shm.children(counters_path) for _, name in ipairs(counters) do cnt_path = counters_path .. name if string.match(cnt_path, ".counter") then cnt = counter.open(cnt_path, 'readonly') value = tonumber(counter.read(cnt)) name = name:gsub(".counter$", "") ret[name] = value end end return ret end local function print_next_hop (pid, name) local next_hop_mac = "/" .. pid .. "/" .. name if file_exists(shm.root .. next_hop_mac) then local nh = shm.open(next_hop_mac, macaddress_t, "readonly") print((" <%s>%s</%s>"):format(name, ethernet:ntop(nh.ether), name)) end end local function print_monitor (pid) local path = "/" .. pid .. "/v4v6_mirror" if file_exists(shm.root .. path) then local ipv4_address = shm.open(path, "struct { uint32_t ipv4; }", "readonly") print((" <%s>%s</%s>"):format("monitor", ipv4:ntop(ipv4_address), "monitor")) end end local function print_counters (pid, dir) local apps_path = "/" .. pid .. "/" .. dir local apps print((" <%s>"):format(dir)) if dir == "engine" then -- Open, read and print whatever counters are in that directory. local counters = read_counters(pid, dir) for _, name in ipairs(sort(keys(counters))) do local value = counters[name] print((" <%s>%d</%s>"):format(name, value, name)) end else apps = shm.children(apps_path) for _, app_name in ipairs(apps) do local sanitized_name = string.gsub(app_name, "[ >:]", "-") if (string.find(sanitized_name, "^[0-9]")) then sanitized_name = "_" .. sanitized_name end print((" <%s>"):format(sanitized_name)) -- Open, read and print whatever counters are in that directory. local counters = read_counters(pid .. "/" .. dir, app_name) for _, name in ipairs(sort(keys(counters))) do local value = counters[name] print((" <%s>%d</%s>"):format(name, value, name)) end print((" </%s>"):format(sanitized_name)) end end print((" </%s>"):format(dir)) end local function transpose (t) local ret = {} for k, v in pairs(t) do ret[v] = k end return ret end function run (raw_args) parse_args(raw_args) print("<snabb>") local pids = {} local pids_name = {} local named_programs = transpose(engine.enumerate_named_programs()) for _, pid in ipairs(shm.children("/")) do if shm.exists("/"..pid.."/name") then local instance_id_name = named_programs[tonumber(pid)] local instance_id = instance_id_name and instance_id_name:match("(%d+)") if instance_id then pids[instance_id] = pid pids_name[instance_id] = instance_id_name end end end for _, instance_id in ipairs(sort(keys(pids))) do local pid = pids[instance_id] print(" <instance>") print((" <id>%d</id>"):format(instance_id)) print((" <name>%s</name>"):format(pids_name[instance_id])) print((" <pid>%d</pid>"):format(pid)) print_next_hop(pid, "next_hop_mac_v4") print_next_hop(pid, "next_hop_mac_v6") print_monitor(pid) print_counters(pid, "engine") print_counters(pid, "pci") print_counters(pid, "apps") print_counters(pid, "links") print(" </instance>") end print("</snabb>") end
apache-2.0
nicholas-leonard/dp
objectid.lua
7
1062
------------------------------------------------------------------------ --[[ ObjectID ]]-- -- An identifier than can be used to save files, objects, etc. -- Provides a unique name. ------------------------------------------------------------------------ local ObjectID = torch.class("dp.ObjectID") ObjectID.isObjectID = true function ObjectID:__init(name, parent) self._parent = parent self._name = name end function ObjectID:toList() local obj_list = {} if self._parent then obj_list = self._parent:toList() end table.insert(obj_list, self._name) return obj_list end function ObjectID:toString(seperator) seperator = seperator or ':' local obj_string = '' if self._parent then obj_string = self._parent:toString() .. seperator end return obj_string .. self._name end function ObjectID:toPath() return self:toString('/') end function ObjectID:name() return self._name end function ObjectID:create(name) return dp.ObjectID(name, self) end function ObjectID:parent() return self._parent end
bsd-3-clause
gowadbd/gowad
plugins/s_type.lua
2
1610
--[[ _____ ____ ____ ___ _____ |_ _| _ \ | __ ) / _ \_ _| | | | |_) | | _ \| | | || | | | | __/ | |_) | |_| || | |_| |_| |____/ \___/ |_| KASPER TP (BY @kasper_dev) _ __ _ ____ ____ _____ ____ _____ ____ | |/ / / \ / ___|| _ \| ____| _ \ |_ _| _ \ | ' / / _ \ \___ \| |_) | _| | |_) | | | | |_) | | . \ / ___ \ ___) | __/| |___| _ < | | | __/ |_|\_\/_/ \_\____/|_| |_____|_| \_\ |_| |_| --]] local function run(msg, matches, callback, extra) local data = load_data(_config.moderation.data) local group_type = data[tostring(msg.to.id)]['group_type'] if matches[1] and is_sudo(msg) then data[tostring(msg.to.id)]['group_type'] = matches[1] save_data(_config.moderation.data, data) return ' '..matches[1] end if not is_owner(msg) then return '' end end return { patterns = { "^[#!/]type (.*)$", "^كول (.*)$", }, run = run } --[[ _____ ____ ____ ___ _____ |_ _| _ \ | __ ) / _ \_ _| | | | |_) | | _ \| | | || | | | | __/ | |_) | |_| || | |_| |_| |____/ \___/ |_| KASPER TP (BY @kasper_dev) _ __ _ ____ ____ _____ ____ _____ ____ | |/ / / \ / ___|| _ \| ____| _ \ |_ _| _ \ | ' / / _ \ \___ \| |_) | _| | |_) | | | | |_) | | . \ / ___ \ ___) | __/| |___| _ < | | | __/ |_|\_\/_/ \_\____/|_| |_____|_| \_\ |_| |_| --]]
gpl-2.0
latenitefilms/hammerspoon
extensions/ipc/ipc.lua
3
22359
--- === hs.ipc === --- --- Provides Hammerspoon with the ability to create both local and remote message ports for inter-process communication. --- --- The most common use of this module is to provide support for the command line tool `hs` which can be added to your terminal shell environment with [hs.ipc.cliInstall](#cliInstall). The command line tool will not work unless the `hs.ipc` module is loaded first, so it is recommended that you add `require("hs.ipc")` to your Hammerspoon `init.lua` file (usually located at ~/.hammerspoon/init.lua) so that it is always available when Hammerspoon is running. --- --- This module is based heavily on code from Mjolnir by [Steven Degutis](https://github.com/sdegutis/). local USERDATA_TAG = "hs.ipc" local module = require("hs.libipc") local timer = require("hs.timer") local settings = require("hs.settings") local log = require("hs.logger").new(USERDATA_TAG, (settings.get(USERDATA_TAG .. ".logLevel") or "warning")) local json = require("hs.json") local fnutils = require("hs.fnutils") -- private variables and methods ----------------------------------------- local MSG_ID = { REGISTER = 100, -- register an instance with the v2 cli UNREGISTER = 200, -- unregister an instance with the v2 cli LEGACYCHK = 900, -- query to test if we are the v2 ipc or not (v1 will ignore the id and evaluate) COMMAND = 500, -- a command from the user from a v2 cli QUERY = 501, -- an internal query from the v2 cli LEGACY = 0, -- v1 cli/ipc only used the 0 msgID ERROR = -1, -- result was an error OUTPUT = 1, -- print output RETURN = 2, -- result CONSOLE = 3, -- cloned console output } local originalPrint = print local printReplacement = function(...) originalPrint(...) for _,v in pairs(module.__registeredCLIInstances) do if v._cli.console and v.print and not v._cli.quietMode then -- v.print(...) -- make it more obvious what is console output versus the command line's local things = table.pack(...) local stdout = (things.n > 0) and tostring(things[1]) or "" for i = 2, things.n do stdout = stdout .. "\t" .. tostring(things[i]) end v._cli.remote:sendMessage(stdout .. "\n", MSG_ID.CONSOLE) end end end print = printReplacement -- luacheck: ignore local originalReload = hs.reload local reloadReplacement = function(...) hs._reloadTriggered = true return originalReload(...) end hs.reload = reloadReplacement -- Public interface ------------------------------------------------------ --- hs.ipc.cliColors([colors]) -> table --- Function --- Get or set the terminal escape codes used to produce colorized output in the `hs` command line tool --- --- Parameters: --- * colors - an optional table or explicit nil specifying the colors to use when colorizing output for the command line tool. If you specify an explicit nil, the colors will revert to their defaults. If you specify a table it must contain one or more of the following keys with the terminal key sequence as a string for the value: --- * initial - this color is used for the initial tagline when starting the command line tool and for output to the Hammerspoon console that is redirected to the instance. Defaults to "\27[35m" (foreground magenta). --- * input - this color is used for input typed in by the user into the cli instance. Defaults to "\27[33m" (foreground yellow). --- * output - this color is used for output generated by the commands executed within the instance and the results returned. Defaults to "\27[36m" (foreground cyan). --- * error - this color is used for lua errors generated by the commands executed within the instance. Defaults to "\27[31m" (foreground red). --- --- Returns: --- * a table describing the colors used when colorizing output in the `hs` command line tool. --- --- Notes: --- * For a brief intro into terminal colors, you can visit a web site like this one [http://jafrog.com/2013/11/23/colors-in-terminal.html](http://jafrog.com/2013/11/23/colors-in-terminal.html) --- * Lua doesn't support octal escapes in it's strings, so use `\x1b` or `\27` to indicate the `escape` character e.g. `ipc.cliSetColors{ initial = "", input = "\27[33m", output = "\27[38;5;11m" }` --- --- * Changes made with this function are saved with `hs.settings` with the following labels and will persist through a reload or restart of Hammerspoon: "ipc.cli.color_initial", "ipc.cli.color_input", "ipc.cli.color_output", and "ipc.cli.color_error" module.cliColors = function(...) local args = table.pack(...) if args.n > 0 then if type(args[1]) == "nil" then settings.clear("ipc.cli.color_initial") settings.clear("ipc.cli.color_input") settings.clear("ipc.cli.color_output") settings.clear("ipc.cli.color_error") else local colors = args[1] if colors.initial then settings.set("ipc.cli.color_initial", colors.initial) end if colors.input then settings.set("ipc.cli.color_input", colors.input) end if colors.output then settings.set("ipc.cli.color_output", colors.output) end if colors.error then settings.set("ipc.cli.color_error", colors.error) end end end local colors = {} colors.initial = settings.get("ipc.cli.color_initial") or "\27[35m" ; colors.input = settings.get("ipc.cli.color_input") or "\27[33m" ; colors.output = settings.get("ipc.cli.color_output") or "\27[36m" ; colors.error = settings.get("ipc.cli.color_error") or "\27[31m" ; return setmetatable(colors, { __tostring = function(self) local res = "" for k,v in fnutils.sortByKeys(self) do res = res .. string.format("%-7s = %q\n", k, v) end return res end, }) end --- hs.ipc.cliGetColors() -> table --- Deprecated --- See [hs.ipc.cliColors](#cliColors). local seenDeprecatedGetColors = false module.cliGetColors = function() if not seenDeprecatedGetColors then seenDeprecatedGetColors = true log.w("hs.ipc.cliGetColors is deprecated and may be removed in the future. Please use hs.ipc.cliColors instead.") end return module.cliColors() end --- hs.ipc.cliSetColors(table) -> table --- Deprecated --- See [hs.ipc.cliColors](#cliColors). local seenDeprecatedSetColors = false module.cliSetColors = function(colors) if not seenDeprecatedSetColors then seenDeprecatedSetColors = true log.w("hs.ipc.cliSetColors is deprecated and may be removed in the future. Please use hs.ipc.cliColors instead.") end return module.cliColors(colors) end --- hs.ipc.cliResetColors() --- Deprecated --- See [hs.ipc.cliColors](#cliColors). local seenDeprecatedResetColors = false module.cliResetColors = function() if not seenDeprecatedResetColors then seenDeprecatedResetColors = true log.w("hs.ipc.cliResetColors is deprecated and may be removed in the future. Please use hs.ipc.cliColors instead.") end return module.cliColors(nil) end --- hs.ipc.cliSaveHistory([state]) -> boolean --- Function --- Get or set whether or not the command line tool saves a history of the commands you type. --- --- Parameters: --- * state - an optional boolean (default false) specifying whether or not a history of the commands you type into the command line tool should be saved between sessions. --- --- Returns: --- * the current, possibly changed, value --- --- Notes: --- * If this is enabled, your history is saved in `hs.configDir .. ".cli.history"`, which is usually "~/.hammerspoon/.cli.history". --- * If you have multiple invocations of the command line tool running at the same time, only the history of the last one cleanly exited is saved; this is a limitation of the readline wrapper Apple has provided for libedit and at present no workaround is known. --- --- * Changes made with this function are saved with `hs.settings` with the label "ipc.cli.saveHistory" and will persist through a reload or restart of Hammerspoon. module.cliSaveHistory = function(...) local args = table.pack(...) if args.n > 0 then settings.set("ipc.cli.saveHistory", args[1] and true or nil) end return settings.get("ipc.cli.saveHistory") or false end --- hs.ipc.cliSaveHistorySize([size]) -> number --- Function --- Get or set whether the maximum number of commands saved when command line tool history saving is enabled. --- --- Parameters: --- * size - an optional integer (default 1000) specifying the maximum number of commands to save when [hs.ipc.cliSaveHistory](#cliSaveHistory) is set to true. --- --- Returns: --- * the current, possibly changed, value --- --- Notes: --- * When [hs.ipc.cliSaveHistory](#cliSaveHistory) is enabled, your history is saved in `hs.configDir .. ".cli.history"`, which is usually "~/.hammerspoon/.cli.history". --- * If you have multiple invocations of the command line tool running at the same time, only the history of the last one cleanly exited is saved; this is a limitation of the readline wrapper Apple has provided for libedit and at present no workaround is known. --- --- * Changes made with this function are saved with `hs.settings` with the label "ipc.cli.historyLimit" and will persist through a reload or restart of Hammerspoon. module.cliSaveHistorySize = function(...) local args = table.pack(...) if args.n > 0 then settings.set("ipc.cli.historyLimit", math.tointeger(args[1]) or nil) end return settings.get("ipc.cli.historyLimit") or 1000 end --- hs.ipc.cliStatus([path][,silent]) -> bool --- Function --- Gets the status of the `hs` command line tool --- --- Parameters: --- * path - An optional string containing a path to look for the `hs` tool. Defaults to `/usr/local` --- * silent - An optional boolean indicating whether or not to print errors to the Hammerspoon Console --- --- Returns: --- * A boolean, true if the `hs` command line tool is correctly installed, otherwise false module.cliStatus = function(p, s) local path = p or "/usr/local" local mod_path = hs.processInfo["frameworksPath"] local resource_path = hs.processInfo["resourcePath"] local frameworks_path = hs.processInfo["frameworksPath"] local silent = s or false local bin_file = os.execute("[ -f \""..path.."/bin/hs\" ]") local man_file = os.execute("[ -f \""..path.."/share/man/man1/hs.1\" ]") local bin_link = os.execute("[ -L \""..path.."/bin/hs\" ]") local man_link = os.execute("[ -L \""..path.."/share/man/man1/hs.1\" ]") local bin_ours = os.execute("[ \""..path.."/bin/hs\" -ef \""..frameworks_path.."/hs/hs\" ]") local man_ours = os.execute("[ \""..path.."/share/man/man1/hs.1\" -ef \""..resource_path.."/man/hs.man\" ]") local result = bin_file and man_file and bin_link and man_link and bin_ours and man_ours or false local broken = false if not bin_ours and bin_file then if not silent then print([[cli installation problem: 'hs' is not ours.]]) end broken = true end if not man_ours and man_file then if not silent then print([[cli installation problem: 'hs.1' is not ours.]]) end broken = true end if bin_file and not bin_link then if not silent then print([[cli installation problem: 'hs' is an independant file won't be updated when Hammerspoon is.]]) end broken = true end if not bin_file and bin_link then if not silent then print([[cli installation problem: 'hs' is a dangling link.]]) end broken = true end if man_file and not man_link then if not silent then print([[cli installation problem: man page for 'hs.1' is an independant file and won't be updated when Hammerspoon is.]]) end broken = true end if not man_file and man_link then if not silent then print([[cli installation problem: man page for 'hs.1' is a dangling link.]]) end broken = true end if ((bin_file and bin_link) and not (man_file and man_link)) or ((man_file and man_link) and not (bin_file and bin_link)) then if not silent then print([[cli installation problem: incomplete installation of 'hs' and 'hs.1'.]]) end broken = true end return broken and "broken" or result end --- hs.ipc.cliInstall([path][,silent]) -> bool --- Function --- Installs the `hs` command line tool --- --- Parameters: --- * path - An optional string containing a path to install the tool in. Defaults to `/usr/local` --- * silent - An optional boolean indicating whether or not to print errors to the Hammerspoon Console --- --- Returns: --- * A boolean, true if the tool was successfully installed, otherwise false --- --- Notes: --- * If this function fails, it is likely that you have some old/broken symlinks. You can use `hs.ipc.cliUninstall()` to forcibly tidy them up --- * You may need to pre-create `/usr/local/bin` and `/usr/local/share/man/man1` in a terminal using sudo, and adjust permissions so your login user can write to them module.cliInstall = function(p, s) local path = p or "/usr/local" local silent = s or false if module.cliStatus(path, true) == false then local mod_path = hs.processInfo["frameworksPath"] local resource_path = hs.processInfo["resourcePath"] os.execute("ln -s \""..mod_path.."/hs/hs\" \""..path.."/bin/\"") os.execute("ln -s \""..resource_path.."/man/hs.man\" \""..path.."/share/man/man1/hs.1\"") end return module.cliStatus(path, silent) end --- hs.ipc.cliUninstall([path][,silent]) -> bool --- Function --- Uninstalls the `hs` command line tool --- --- Parameters: --- * path - An optional string containing a path to remove the tool from. Defaults to `/usr/local` --- * silent - An optional boolean indicating whether or not to print errors to the Hammerspoon Console --- --- Returns: --- * A boolean, true if the tool was successfully removed, otherwise false --- --- Notes: --- * This function used to be very conservative and refuse to remove symlinks it wasn't sure about, but now it will unconditionally remove whatever it finds at `path/bin/hs` and `path/share/man/man1/hs.1`. This is more likely to be useful in situations where this command is actually needed (please open an Issue on GitHub if you disagree!) module.cliUninstall = function(p, s) local path = p or "/usr/local" local silent = s or false os.execute("rm \""..path.."/bin/hs\"") os.execute("rm \""..path.."/share/man/man1/hs.1\"") return not module.cliStatus(path, silent) end module.__registeredCLIInstances = {} -- cleanup in case someone goes away without saying goodbye module.__registeredInstanceCleanup = timer.doEvery(60, function() for k, v in pairs(module.__registeredCLIInstances) do if v._cli.remote and not v._cli.remote:isValid() then log.df("pruning %s; message port is no longer valid", k) v._cli.remote:delete() module.__registeredCLIInstances[k] = nil elseif not v._cli.remote then module.__registeredCLIInstances[k] = nil end end end) module.__defaultHandler = function(_, msgID, msg) if msgID == MSG_ID.LEGACYCHK then -- the message sent will be a mathematical equation; the original ipc will evaluate it because it ignored -- the msgid. We send back a version string instead return "version:2.0a" elseif msgID == MSG_ID.REGISTER then -- registering a new instance local instanceID, arguments = msg:match("^([%w-]+)\0(.*)$") if not instanceID then instanceID, arguments = msg, nil end local scriptArguments = nil local quietMode = false local console = "none" if arguments then arguments = json.decode(arguments) scriptArguments = {} local seenSeparator = false for i, v in ipairs(arguments) do if i > 1 and (v == "--" or v:match("^~") or v:match("^%.?/")) then seenSeparator = true end if seenSeparator then table.insert(scriptArguments, v) else if v == "-q" then quietMode = true end if v == "-C" then console = "mirror" end if v == "-P" then console = "legacy" end end end if #scriptArguments == 0 then scriptArguments = arguments end end log.df("registering %s", instanceID) module.__registeredCLIInstances[instanceID] = setmetatable({ _cli = { remote = module.remotePort(instanceID), console = console, _args = arguments, args = scriptArguments, quietMode = quietMode, }, print = function(...) local parent = module.__registeredCLIInstances[instanceID]._cli if parent.quietMode then return end local things = table.pack(...) local stdout = (things.n > 0) and tostring(things[1]) or "" for i = 2, things.n do stdout = stdout .. "\t" .. tostring(things[i]) end module.__registeredCLIInstances[instanceID]._cli.remote:sendMessage(stdout .. "\n", MSG_ID.OUTPUT) if type(parent.console) == "nil" then originalPrint(...) end end, }, { __index = _G, __newindex = function(_, key, value) _G[key] = value end, }) elseif msgID == MSG_ID.UNREGISTER then -- unregistering an instance log.df("unregistering %s", msg) module.__registeredCLIInstances[msg]._cli.remote:delete() module.__registeredCLIInstances[msg] = nil elseif msgID == MSG_ID.COMMAND or msgID == MSG_ID.QUERY then local instanceID, code = msg:match("^([%w-]*)\0(.*)$") -- print(msg, instanceID, code) if instanceID then if hs._consoleInputPreparser then if type(hs._consoleInputPreparser) == "function" then local status, code2 = pcall(hs._consoleInputPreparser, code) if status then code = code2 else hs.luaSkinLog.ef("console preparse error: %s", code2) end else hs.luaSkinLog.e("console preparser must be a function or nil") end end local fnEnv = module.__registeredCLIInstances[instanceID] local fn, err = load("return " .. code, "return " .. code, "bt", fnEnv) if not fn then fn, err = load(code, code, "bt", fnEnv) end local results = fn and table.pack(pcall(fn)) or { false, err, n = 2 } local str = (results.n > 1) and tostring(results[2]) or "" for i = 3, results.n do str = str .. "\t" .. tostring(results[i]) end if #str > 0 then str = str .. "\n" end if msgID == MSG_ID.COMMAND then if not hs._reloadTriggered then fnEnv._cli.remote:sendMessage(str, results[1] and MSG_ID.RETURN or MSG_ID.ERROR) end return results[1] and "ok" or "error" else return str end else log.ef("unexpected message received: %s", msg) end elseif msgID == MSG_ID.LEGACY then log.df("in legacy handler") local _, str = (msg:sub(1,1) == "r"), msg:sub(2) if hs._consoleInputPreparser then if type(hs._consoleInputPreparser) == "function" then local status, s2 = pcall(hs._consoleInputPreparser, str) if status then str = s2 else hs.luaSkinLog.ef("console preparse error: %s", s2) end else hs.luaSkinLog.e("console preparser must be a function or nil") end end local originalprint = print local fakestdout = "" print = function(...) -- luacheck: ignore originalprint(...) local things = table.pack(...) for i = 1, things.n do if i > 1 then fakestdout = fakestdout .. "\t" end fakestdout = fakestdout .. tostring(things[i]) end fakestdout = fakestdout .. "\n" end -- local fn = raw and rawhandler or module.handler local fn = function(ss) local fn, err = load("return " .. ss) if not fn then fn, err = load(ss) end if fn then return fn() else return err end end local results = table.pack(pcall(function() return fn(str) end)) str = "" for i = 2, results.n do if i > 2 then str = str .. "\t" end str = str .. tostring(results[i]) end print = originalprint -- luacheck: ignore return fakestdout .. str else log.ef("unexpected message id received: %d, %s", msgID, msg) end end module.__default = module.localPort("Hammerspoon", module.__defaultHandler) -- Return Module Object -------------------------------------------------- return setmetatable(module, { __index = function(self, key) if key == "handler" then log.e("Setting a specialized handler is no longer supported in hs.ipc. Use `hs.ipc.localPort` to setup your own message port for handling custom requests.") return nil else return rawget(self, key) -- probably not necessary, but... end end, __newindex = function(self, key, value) if key == "handler" then log.e("Setting a specialized handler is no longer supported in hs.ipc. Use `hs.ipc.localPort` to setup your own message port for handling custom requests.") else rawset(self, key, value) end end, })
mit
thedraked/darkstar
scripts/globals/items/puk_egg.lua
18
1158
----------------------------------------- -- ID: 5569 -- Item: puk_egg -- Food Effect: 5Min, All Races ----------------------------------------- -- Health 6 -- Magic 6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5569); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 6); target:addMod(MOD_MP, 6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 6); target:delMod(MOD_MP, 6); end;
gpl-3.0
lyzardiar/RETools
PublicTools/bin/tools/bin/ios/x86_64/jit/v.lua
78
5755
---------------------------------------------------------------------------- -- Verbose mode of the LuaJIT compiler. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module shows verbose information about the progress of the -- JIT compiler. It prints one line for each generated trace. This module -- is useful to see which code has been compiled or where the compiler -- punts and falls back to the interpreter. -- -- Example usage: -- -- luajit -jv -e "for i=1,1000 do for j=1,1000 do end end" -- luajit -jv=myapp.out myapp.lua -- -- Default output is to stderr. To redirect the output to a file, pass a -- filename as an argument (use '-' for stdout) or set the environment -- variable LUAJIT_VERBOSEFILE. The file is overwritten every time the -- module is started. -- -- The output from the first example should look like this: -- -- [TRACE 1 (command line):1 loop] -- [TRACE 2 (1/3) (command line):1 -> 1] -- -- The first number in each line is the internal trace number. Next are -- the file name ('(command line)') and the line number (':1') where the -- trace has started. Side traces also show the parent trace number and -- the exit number where they are attached to in parentheses ('(1/3)'). -- An arrow at the end shows where the trace links to ('-> 1'), unless -- it loops to itself. -- -- In this case the inner loop gets hot and is traced first, generating -- a root trace. Then the last exit from the 1st trace gets hot, too, -- and triggers generation of the 2nd trace. The side trace follows the -- path along the outer loop and *around* the inner loop, back to its -- start, and then links to the 1st trace. Yes, this may seem unusual, -- if you know how traditional compilers work. Trace compilers are full -- of surprises like this -- have fun! :-) -- -- Aborted traces are shown like this: -- -- [TRACE --- foo.lua:44 -- leaving loop in root trace at foo:lua:50] -- -- Don't worry -- trace aborts are quite common, even in programs which -- can be fully compiled. The compiler may retry several times until it -- finds a suitable trace. -- -- Of course this doesn't work with features that are not-yet-implemented -- (NYI error messages). The VM simply falls back to the interpreter. This -- may not matter at all if the particular trace is not very high up in -- the CPU usage profile. Oh, and the interpreter is quite fast, too. -- -- Also check out the -jdump module, which prints all the gory details. -- ------------------------------------------------------------------------------ -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local jutil = require("jit.util") local vmdef = require("jit.vmdef") local funcinfo, traceinfo = jutil.funcinfo, jutil.traceinfo local type, format = type, string.format local stdout, stderr = io.stdout, io.stderr -- Active flag and output file handle. local active, out ------------------------------------------------------------------------------ local startloc, startex local function fmtfunc(func, pc) local fi = funcinfo(func, pc) if fi.loc then return fi.loc elseif fi.ffid then return vmdef.ffnames[fi.ffid] elseif fi.addr then return format("C:%x", fi.addr) else return "(?)" end end -- Format trace error message. local function fmterr(err, info) if type(err) == "number" then if type(info) == "function" then info = fmtfunc(info) end err = format(vmdef.traceerr[err], info) end return err end -- Dump trace states. local function dump_trace(what, tr, func, pc, otr, oex) if what == "start" then startloc = fmtfunc(func, pc) startex = otr and "("..otr.."/"..oex..") " or "" else if what == "abort" then local loc = fmtfunc(func, pc) if loc ~= startloc then out:write(format("[TRACE --- %s%s -- %s at %s]\n", startex, startloc, fmterr(otr, oex), loc)) else out:write(format("[TRACE --- %s%s -- %s]\n", startex, startloc, fmterr(otr, oex))) end elseif what == "stop" then local info = traceinfo(tr) local link, ltype = info.link, info.linktype if ltype == "interpreter" then out:write(format("[TRACE %3s %s%s -- fallback to interpreter]\n", tr, startex, startloc)) elseif ltype == "stitch" then out:write(format("[TRACE %3s %s%s %s %s]\n", tr, startex, startloc, ltype, fmtfunc(func, pc))) elseif link == tr or link == 0 then out:write(format("[TRACE %3s %s%s %s]\n", tr, startex, startloc, ltype)) elseif ltype == "root" then out:write(format("[TRACE %3s %s%s -> %d]\n", tr, startex, startloc, link)) else out:write(format("[TRACE %3s %s%s -> %d %s]\n", tr, startex, startloc, link, ltype)) end else out:write(format("[TRACE %s]\n", what)) end out:flush() end end ------------------------------------------------------------------------------ -- Detach dump handlers. local function dumpoff() if active then active = false jit.attach(dump_trace) if out and out ~= stdout and out ~= stderr then out:close() end out = nil end end -- Open the output file and attach dump handlers. local function dumpon(outfile) if active then dumpoff() end if not outfile then outfile = os.getenv("LUAJIT_VERBOSEFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stderr end jit.attach(dump_trace, "trace") active = true end -- Public module functions. return { on = dumpon, off = dumpoff, start = dumpon -- For -j command line option. }
mit
brimworks/zile
src/buffer.lua
1
10218
-- Buffer-oriented functions -- -- Copyright (c) 2010-2011 Free Software Foundation, Inc. -- -- This file is part of GNU Zile. -- -- GNU Zile 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, or (at your option) -- any later version. -- -- GNU Zile 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 GNU Zile; see the file COPYING. If not, write to the -- Free Software Foundation, Fifth Floor, 51 Franklin Street, Boston, -- MA 02111-1301, USA. -- The buffer list buffers = {} buffer_name_history = history_new () -- Allocate a new buffer, set the default local variable values, and -- insert it into the buffer list. -- The allocation of the first empty line is done here to simplify -- the code. function buffer_new () local bp = {} -- Allocate point. bp.pt = point_new () -- Allocate a line. bp.pt.p = line_new () bp.pt.p.text = "" -- Allocate the limit marker. bp.lines = line_new () bp.lines.prev = bp.pt.p bp.lines.next = bp.pt.p bp.pt.p.prev = bp.lines bp.pt.p.next = bp.lines bp.last_line = 0 -- Allocate markers list. bp.markers = {} -- Set default EOL string. bp.eol = coding_eol_lf -- Set directory. bp.dir = posix.getcwd () or "" -- Insert into buffer list. table.insert (buffers, bp) init_buffer (bp) return bp end -- Initialise a buffer function init_buffer (bp) if get_variable_bool ("auto-fill-mode") then bp.autofill = true end end -- Get filename, or buffer name if nil. function get_buffer_filename_or_name (bp) return bp.filename or bp.name end function activate_mark () cur_bp.mark_active = true end function deactivate_mark () cur_bp.mark_active = false end function delete_region (rp) local m = point_marker () if warn_if_readonly_buffer () then return false end goto_point (rp.start) undo_save (UNDO_REPLACE_BLOCK, rp.start, rp.size, 0) undo_nosave = true for i = rp.size, 1, -1 do delete_char () end undo_nosave = false cur_bp.pt = table.clone (m.pt) unchain_marker (m) return true end function calculate_buffer_size (bp) local lp = bp.lines.next local size = 0 if lp == bp.lines then return 0 end while true do size = size + #lp.text lp = lp.next if lp == bp.lines then break end size = size + 1 end return size end -- Return a safe tab width for the given buffer. function tab_width (bp) return math.max (get_variable_number_bp (bp, "tab-width"), 1) end -- Copy a region of text into a string. function copy_text_block (pt, size) local lp = pt.p local s = string.sub (lp.text, pt.o + 1) .. "\n" lp = lp.next while #s < size do s = s .. lp.text .. "\n" lp = lp.next end return string.sub (s, 1, size) end function in_region (lineno, x, rp) if lineno < rp.start.n or lineno > rp.finish.n then return false elseif rp.start.n == rp.finish.n then return x >= rp.start.o and x < rp.finish.o elseif lineno == rp.start.n then return x >= rp.start.o elseif lineno == rp.finish.n then return x < rp.finish.o else return true end return false end local function warn_if_no_mark () if not cur_bp.mark then minibuf_error ("The mark is not set now") return true elseif not cur_bp.mark_active and get_variable_bool ("transient-mark-mode") then minibuf_error ("The mark is not active now") return true end return false end function region_new () return {} end -- Calculate the region size between point and mark and set the -- region. function calculate_the_region (rp) if warn_if_no_mark () then return false end if cmp_point (cur_bp.pt, cur_bp.mark.pt) < 0 then -- Point is before mark. rp.start = table.clone (cur_bp.pt) rp.finish = table.clone (cur_bp.mark.pt) else -- Mark is before point. rp.start = table.clone (cur_bp.mark.pt) rp.finish = table.clone (cur_bp.pt) end local size = rp.finish.o - rp.start.o local lp = rp.start.p while lp ~= rp.finish.p do size = size + #lp.text + 1 lp = lp.next end rp.size = size return true end -- Switch to the specified buffer. function switch_to_buffer (bp) assert (cur_wp.bp == cur_bp) -- The buffer is the current buffer; return safely. if cur_bp == bp then return end -- Set current buffer. cur_bp = bp cur_wp.bp = cur_bp -- Move the buffer to head. for i = 1, #buffers do if buffers[i] == bp then table.remove (buffers, i) table.insert (buffers, bp) break end end -- Change to buffer's default directory posix.chdir (bp.dir) thisflag.need_resync = true end -- Create a buffer name using the file name. local function make_buffer_name (filename) local s = posix.basename (filename) if not find_buffer (s) then return s else local i = 2 while true do local name = string.format ("%s<%ld>", s, i) if not find_buffer (name) then return name end i = i + 1 end end end -- Search for a buffer named `name'. function find_buffer (name) for _, bp in ipairs (buffers) do if bp.name == name then return bp end end end -- Set a new filename, and from it a name, for the buffer. function set_buffer_names (bp, filename) if filename[1] ~= '/' then filename = posix.getcwd () .. "/" .. filename bp.filename = filename else bp.filename = filename end bp.name = make_buffer_name (filename) end -- Remove the specified buffer from the buffer list. -- Recreate the scratch buffer when required. function kill_buffer (kill_bp) -- Search for windows displaying the buffer to kill. for _, wp in ipairs (windows) do if wp.bp == kill_bp then wp.topdelta = 0 wp.saved_pt = nil end end -- Remove the buffer from the buffer list. local next_bp = buffers[#buffers] for i = 1, #buffers do if buffers[i] == kill_bp then table.remove (buffers, i) next_bp = buffers[i > 1 and i - 1 or #buffers] if cur_bp == kill_bp then cur_bp = next_bp end break end end -- If no buffers left, recreate scratch buffer and point windows at -- it. if #buffers == 0 then table.insert (buffers, create_scratch_buffer ()) cur_bp = buffers[1] for _, wp in ipairs (windows) do wp.bp = cur_bp end end -- Resync windows that need it. for _, wp in ipairs (windows) do if wp.bp == kill_bp then wp.bp = next_bp resync_redisplay (wp) end end end -- Set the specified buffer's temporary flag and move the buffer -- to the end of the buffer list. function set_temporary_buffer (bp) bp.temporary = true for i = 1, #buffers do if buffers[i] == bp then table.remove (buffers, i) break end end table.insert (buffers, 1, bp) end -- Print an error message into the echo area and return true -- if the current buffer is readonly; otherwise return false. function warn_if_readonly_buffer () if cur_bp.readonly then minibuf_error (string.format ("Buffer is readonly: %s", cur_bp.name)) return true end return false end function activate_mark () cur_bp.mark_active = true end function deactivate_mark () cur_bp.mark_active = false end -- Check if the buffer has been modified. If so, asks the user if -- he/she wants to save the changes. If the response is positive, return -- true, else false. function check_modified_buffer (bp) if bp.modified and not bp.nosave then while true do local ans = minibuf_read_yesno (string.format ("Buffer %s modified; kill anyway? (yes or no) ", bp.name)) if ans == nil then execute_function ("keyboard-quit") return false elseif not ans then return false end break end end return true end Defun ("kill-buffer", {"string"}, [[ Kill buffer BUFFER. With a nil argument, kill the current buffer. ]], true, function (buffer) local ok = leT if not buffer then local cp = make_buffer_completion () buffer = minibuf_read (string.format ("Kill buffer (default %s): ", cur_bp.name), "", cp, buffer_name_history) if not buffer then ok = execute_function ("keyboard-quit") end end local bp if buffer and buffer ~= "" then bp = find_buffer (buffer) if not bp then minibuf_error (string.format ("Buffer `%s' not found", buffer)) ok = leNIL end else bp = cur_bp end if ok == leT then if not check_modified_buffer (bp) then ok = leNIL else kill_buffer (bp) end end return ok end ) local function buffer_next (this_bp) for i, bp in ipairs (buffers) do if bp == this_bp then if i > 1 then return buffers[i - 1] else return buffers[#buffers] end break end end end Defun ("switch-to-buffer", {"string"}, [[ Select buffer @i{buffer} in the current window. ]], true, function (buffer) local ok = leT local bp = buffer_next (cur_bp) if not buffer then local cp = make_buffer_completion () buffer = minibuf_read (string.format ("Switch to buffer (default %s): ", bp.name), "", cp, buffer_name_history) if not buffer then ok = execute_function ("keyboard-quit") end end if ok == leT then if buffer and buffer ~= "" then bp = find_buffer (buffer) if not bp then bp = buffer_new () bp.name = buffer bp.needname = true bp.nosave = true end end switch_to_buffer (bp) end return ok end ) function create_scratch_buffer () local bp = buffer_new () bp.name = "*scratch*" bp.needname = true bp.temporary = true bp.nosave = true return bp end
gpl-3.0
mtroyka/Zero-K
LuaUI/Widgets/chili/simple examples/Widgets/gui_chiligui.lua
18
2737
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "chiliGUI", desc = "hot GUI Framework", author = "jK & quantum", date = "WIP", license = "GPLv2", layer = 1000, enabled = true -- loaded by default? } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local Chili = VFS.Include(LUAUI_DIRNAME.."Widgets/chiligui/chiligui.lua") -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local screen0 = Chili.Screen:New{} local th --//= Chili.TextureHandler local tk = Chili.TaskHandler -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --// Export Widget Globals WG.Chili = Chili WG.Chili.Screen0 = screen0 -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:DrawScreen() if (not th) then th = Chili.TextureHandler th.Initialize() end th.Update() gl.PushMatrix() local vsx,vsy = gl.GetViewSizes() gl.Translate(0,vsy,0) gl.Scale(1,-1,1) screen0:Draw() gl.PopMatrix() end function widget:Update() --th.Update() tk.Update() end function widget:IsAbove(x,y) if screen0:IsAbove(x,y) then return true end end local mods = {} function widget:MousePress(x,y,button) local alt, ctrl, meta, shift = Spring.GetModKeyState() mods.alt=alt; mods.ctrl=ctrl; mods.meta=meta; mods.shift=shift; if screen0:MouseDown(x,y,button,mods) then return true end end function widget:MouseRelease(x,y,button) local alt, ctrl, meta, shift = Spring.GetModKeyState() mods.alt=alt; mods.ctrl=ctrl; mods.meta=meta; mods.shift=shift; if screen0:MouseUp(x,y,button,mods) then return true end end function widget:MouseMove(x,y,dx,dy,button) local alt, ctrl, meta, shift = Spring.GetModKeyState() mods.alt=alt; mods.ctrl=ctrl; mods.meta=meta; mods.shift=shift; if screen0:MouseMove(x,y,dx,dy,button,mods) then return true end end function widget:MouseWheel(up,value) local x,y = Spring.GetMouseState() local alt, ctrl, meta, shift = Spring.GetModKeyState() mods.alt=alt; mods.ctrl=ctrl; mods.meta=meta; mods.shift=shift; if screen0:MouseWheel(x,y,up,value,mods) then return true end end
gpl-2.0
kumpuu/factorio-helicopters
prototypes/style/style.lua
1
3234
--[[data.raw["gui-style"].default["heli-listbox_button"] = { type = "button_style", parent = "button", font = "default-bold", align = "left", scalable = true, --maximal_height = 33, minimal_height = 33, --maximal_width = 33, minimal_width = 33, left_click_sound = { { filename = "__core__/sound/list-box-click.ogg", volume = 1 } }, default_font_color={r=1, g=1, b=1}, default_graphical_set = { type = "composition", filename = "__Helicopters__/graphics/gui/black.png", priority = "extra-high-no-scale", position = {0, 0} }, hovered_font_color={r=1, g=1, b=1}, hovered_graphical_set = { type = "composition", filename = "__Helicopters__/graphics/gui/grey.png", priority = "extra-high-no-scale", corner_size = {0, 0}, position = {0, 0} }, clicked_font_color = {r=0, g=0, b=0}, clicked_graphical_set = { type = "composition", filename = "__Helicopters__/graphics/gui/orange.png", priority = "extra-high-no-scale", corner_size = {0, 0}, position = {0, 0} }, } --]] data.raw["gui-style"].default["heli-listbox_button"] = { type = "button_style", parent = "button", font = "default-bold", --maximal_height = 33, minimal_height = 33, --maximal_width = 33, minimal_width = 33, --top_padding = 0, --bottom_padding = 0, --right_padding = 0, --left_padding = 0, left_click_sound = { { filename = "__core__/sound/gui-click.ogg", volume = 1 } }, right_click_sound = { { filename = "__core__/sound/gui-click.ogg", volume = 1 } } } function makeButtonStyle(width, height, image, padding) padding = padding or {} return { type = "button_style", parent = "button", scalable = true, width = width, height = height, top_padding = padding.top or 0, right_padding = padding.right or 0, bottom_padding = padding.bottom or 0, left_padding = padding.left or 0, default_graphical_set = { filename = image, priority = "extra-high-no-scale", width = width, height = height, priority = "extra-high-no-scale", }, hovered_graphical_set = { filename = image, priority = "extra-high-no-scale", width = width, height = height, position = {width, y = 0}, priority = "extra-high-no-scale", }, clicked_graphical_set = { filename = image, priority = "extra-high-no-scale", width = width, height = height, position = {width * 2, 0}, priority = "extra-high-no-scale", }, } end data.raw["gui-style"].default["heli-clear_text_button"] = makeButtonStyle(15, 15, "__Helicopters__/graphics/icons/clear-text.png", {top = 4}) data.raw["gui-style"].default["heli-speaker_on_button"] = makeButtonStyle(15, 15, "__Helicopters__/graphics/icons/speaker_on.png") data.raw["gui-style"].default["heli-speaker_off_button"] = makeButtonStyle(15, 15, "__Helicopters__/graphics/icons/speaker_off.png")
mit
thedraked/darkstar
scripts/globals/items/persikos.lua
18
1174
----------------------------------------- -- ID: 4274 -- Item: persikos -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility -7 -- Intelligence 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4274); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, -7); target:addMod(MOD_INT, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, -7); target:delMod(MOD_INT, 5); end;
gpl-3.0
dmolina/my-config
awesome/.config/awesome/themes/multicolor/theme.lua
4
4294
--[[ Multicolor Awesome WM config 2.0 github.com/copycat-killer --]] theme = {} theme.confdir = os.getenv("HOME") .. "/.config/awesome/themes/multicolor" theme.wallpaper = theme.confdir .. "/wall.png" theme.font = "Terminus 8" --theme.taglist_font = theme.menu_bg_normal = "#000000" theme.menu_bg_focus = "#000000" theme.bg_normal = "#000000" theme.bg_focus = "#000000" theme.bg_urgent = "#000000" theme.fg_normal = "#aaaaaa" theme.fg_focus = "#ff8c00" theme.fg_urgent = "#af1d18" theme.fg_minimize = "#ffffff" theme.fg_black = "#424242" theme.fg_red = "#ce5666" theme.fg_green = "#80a673" theme.fg_yellow = "#ffaf5f" theme.fg_blue = "#7788af" theme.fg_magenta = "#94738c" theme.fg_cyan = "#778baf" theme.fg_white = "#aaaaaa" theme.fg_blu = "#8ebdde" theme.border_width = "1" theme.border_normal = "#1c2022" theme.border_focus = "#606060" theme.border_marked = "#3ca4d8" theme.menu_width = "110" theme.menu_border_width = "0" theme.menu_fg_normal = "#aaaaaa" theme.menu_fg_focus = "#ff8c00" theme.menu_bg_normal = "#050505dd" theme.menu_bg_focus = "#050505dd" theme.submenu_icon = theme.confdir .. "/icons/submenu.png" theme.widget_temp = theme.confdir .. "/icons/temp.png" theme.widget_uptime = theme.confdir .. "/icons/ac.png" theme.widget_cpu = theme.confdir .. "/icons/cpu.png" theme.widget_weather = theme.confdir .. "/icons/dish.png" theme.widget_fs = theme.confdir .. "/icons/fs.png" theme.widget_mem = theme.confdir .. "/icons/mem.png" theme.widget_fs = theme.confdir .. "/icons/fs.png" theme.widget_note = theme.confdir .. "/icons/note.png" theme.widget_note_on = theme.confdir .. "/icons/note_on.png" theme.widget_netdown = theme.confdir .. "/icons/net_down.png" theme.widget_netup = theme.confdir .. "/icons/net_up.png" theme.widget_mail = theme.confdir .. "/icons/mail.png" theme.widget_batt = theme.confdir .. "/icons/bat.png" theme.widget_clock = theme.confdir .. "/icons/clock.png" theme.widget_vol = theme.confdir .. "/icons/spkr.png" theme.taglist_squares_sel = theme.confdir .. "/icons/square_a.png" theme.taglist_squares_unsel = theme.confdir .. "/icons/square_b.png" theme.tasklist_disable_icon = true theme.tasklist_floating = "" theme.tasklist_maximized_horizontal = "" theme.tasklist_maximized_vertical = "" theme.layout_tile = theme.confdir .. "/icons/tile.png" theme.layout_tilegaps = theme.confdir .. "/icons/tilegaps.png" theme.layout_tileleft = theme.confdir .. "/icons/tileleft.png" theme.layout_tilebottom = theme.confdir .. "/icons/tilebottom.png" theme.layout_tiletop = theme.confdir .. "/icons/tiletop.png" theme.layout_fairv = theme.confdir .. "/icons/fairv.png" theme.layout_fairh = theme.confdir .. "/icons/fairh.png" theme.layout_spiral = theme.confdir .. "/icons/spiral.png" theme.layout_dwindle = theme.confdir .. "/icons/dwindle.png" theme.layout_max = theme.confdir .. "/icons/max.png" theme.layout_fullscreen = theme.confdir .. "/icons/fullscreen.png" theme.layout_magnifier = theme.confdir .. "/icons/magnifier.png" theme.layout_floating = theme.confdir .. "/icons/floating.png" return theme
gpl-3.0
thedraked/darkstar
scripts/zones/Metalworks/npcs/Ayame.lua
14
2996
----------------------------------- -- Area: Metalworks -- NPC: Ayame -- Involved in Missions -- Starts and Finishes Quest: True Strength -- @pos 133 -19 34 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(BASTOK,TRUE_STRENGTH) == QUEST_ACCEPTED) then if (trade:hasItemQty(1100,1) and trade:getItemCount() == 1) then -- Trade Xalmo Feather player:startEvent(0x02ed); -- Finish Quest "True Strength" end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local trueStrength = player:getQuestStatus(BASTOK,TRUE_STRENGTH); local WildcatBastok = player:getVar("WildcatBastok"); if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,9) == false) then player:startEvent(0x03a7); elseif (player:getCurrentMission(BASTOK) == THE_CRYSTAL_LINE and player:hasKeyItem(C_L_REPORTS)) then player:startEvent(0x02c8); elseif (trueStrength == QUEST_AVAILABLE and player:getMainJob() == JOBS.MNK and player:getMainLvl() >= 50) then player:startEvent(0x02ec); -- Start Quest "True Strength" else player:startEvent(0x02bd); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x02c8) then finishMissionTimeline(player,1,csid,option); elseif (csid == 0x02ec) then player:addQuest(BASTOK,TRUE_STRENGTH); elseif (csid == 0x02ed) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14215); -- Temple Hose else player:tradeComplete(); player:addTitle(PARAGON_OF_MONK_EXCELLENCE); player:addItem(14215); player:messageSpecial(ITEM_OBTAINED,14215); -- Temple Hose player:addFame(BASTOK,AF3_FAME); player:completeQuest(BASTOK,TRUE_STRENGTH); end elseif (csid == 0x03a7) then player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",9,true); end end;
gpl-3.0
X-Coder/wire
lua/entities/gmod_wire_gimbal.lua
10
2231
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Gimbal" ENT.WireDebugName = "Gimbal" if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:GetPhysicsObject():EnableGravity(false) self.Inputs = WireLib.CreateInputs(self,{"On", "X", "Y", "Z", "Target [VECTOR]", "Direction [VECTOR]", "Angle [ANGLE]"}) self.XYZ = Vector() end function ENT:TriggerInput(name,value) if name == "On" then self.On = value ~= 0 else self.TargetPos = nil self.TargetDir = nil self.TargetAng = nil if name == "X" then self.XYZ.x = value self.TargetPos = self.XYZ elseif name == "Y" then self.XYZ.y = value self.TargetPos = self.XYZ elseif name == "Z" then self.XYZ.z = value self.TargetPos = self.XYZ elseif name == "Target" then self.XYZ = Vector(value.x, value.y, value.z) self.TargetPos = self.XYZ elseif name == "Direction" then self.TargetDir = value elseif name == "Angle" then self.TargetAng = value end end self:ShowOutput() return true end function ENT:Think() if self.On then local ang if self.TargetPos then ang = (self.TargetPos - self:GetPos()):Angle() elseif self.TargetDir then ang = self.TargetDir:Angle() elseif self.TargetAng then ang = self.TargetAng end if ang then self:SetAngles(ang + Angle(90,0,0)) end -- TODO: Put an option in the CPanel for Angle(90,0,0), and other useful directions self:GetPhysicsObject():Wake() end self:NextThink(CurTime()) return true end function ENT:ShowOutput() if not self.On then self:SetOverlayText("Off") elseif self.TargetPos then self:SetOverlayText(string.format("Aiming towards (%.2f, %.2f, %.2f)", self.XYZ.x, self.XYZ.y, self.XYZ.z)) elseif self.TargetDir then self:SetOverlayText(string.format("Aiming (%.4f, %.4f, %.4f)", self.TargetDir.x, self.TargetDir.y, self.TargetDir.z)) elseif self.TargetAng then self:SetOverlayText(string.format("Aiming (%.1f, %.1f, %.1f)", self.TargetAng.pitch, self.TargetAng.yaw, self.TargetAng.roll)) end end duplicator.RegisterEntityClass("gmod_wire_gimbal", WireLib.MakeWireEnt, "Data")
gpl-3.0
thedraked/darkstar
scripts/globals/items/serving_of_herb_crawler_eggs.lua
18
1526
----------------------------------------- -- ID: 4552 -- Item: serving_of_herb_crawler_eggs -- Food Effect: 180Min, All Races ----------------------------------------- -- Health % 6 -- Health Cap 80 -- Magic 10 -- Agility 3 -- Vitality -1 -- Evasion 8 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4552); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 6); target:addMod(MOD_FOOD_HP_CAP, 80); target:addMod(MOD_MP, 10); target:addMod(MOD_AGI, 3); target:addMod(MOD_VIT, -1); target:addMod(MOD_EVA, 8); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 6); target:delMod(MOD_FOOD_HP_CAP, 80); target:delMod(MOD_MP, 10); target:delMod(MOD_AGI, 3); target:delMod(MOD_VIT, -1); target:delMod(MOD_EVA, 8); end;
gpl-3.0
thedraked/darkstar
scripts/globals/items/dish_of_spaghetti_melanzane_+1.lua
17
1375
----------------------------------------- -- ID: 5214 -- Item: dish_of_spaghetti_melanzane_+1 -- Food Effect: 1Hr, All Races ----------------------------------------- -- HP % 25 (cap 105) -- Vitality 2 -- Store TP 4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5214); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 25); target:addMod(MOD_FOOD_HP_CAP, 105); target:addMod(MOD_VIT, 2); target:addMod(MOD_STORETP, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 25); target:delMod(MOD_FOOD_HP_CAP, 105); target:delMod(MOD_VIT, 2); target:delMod(MOD_STORETP, 4); end;
gpl-3.0
mtroyka/Zero-K
units/corcrw.lua
3
8848
unitDef = { unitname = [[corcrw]], name = [[Krow]], description = [[Flying Fortress]], acceleration = 0.09, activateWhenBuilt = true, airStrafe = 0, bankingAllowed = false, brakeRate = 0.04, buildCostEnergy = 4500, buildCostMetal = 4500, builder = false, buildPic = [[CORCRW.png]], buildTime = 4500, canAttack = true, canFly = true, canGuard = true, canMove = true, canPatrol = true, canstop = [[1]], canSubmerge = false, category = [[GUNSHIP]], collide = true, collisionVolumeOffsets = [[0 0 5]], collisionVolumeScales = [[86 22 86]], collisionVolumeType = [[cylY]], corpse = [[DEAD]], cruiseAlt = 120, customParams = { description_fr = [[Forteresse Volante]], description_de = [[Schwebendes Bollwerk]], helptext = [[The Krow may be expensive and ponderous, but its incredible armor allows it do fly into all but the thickest anti-air defenses and engage enemies with its three laser cannons. Best of all, it can drop a large spread of carpet bombs that devastates anything under it.]], helptext_fr = [[La Forteresse Volante est l'ADAV le plus solide jamais construit, est ?quip?e de nombreuses tourelles laser, elle est capable de riposter dans toutes les directions et d'encaisser des d?g?ts importants. Id?al pour un appuyer un assaut lourd ou monopiler l'Anti-Air pendant une attaque a?rienne.]], helptext_de = [[Der Krow scheint teuer und schwerfällig, aber seine unglaubliche Panzerung erlaubt ihm auch durch die größe Flugabwehr zu kommen und alles abzuholzen, was in Sichtweite seiner drei Laserkanonen kommt. Er kann sogar feindliche Jäger vom Himmel holen.]], modelradius = [[10]], }, explodeAs = [[LARGE_BUILDINGEX]], floater = true, footprintX = 5, footprintZ = 5, hoverAttack = true, iconType = [[supergunship]], idleAutoHeal = 5, idleTime = 1800, maneuverleashlength = [[500]], maxDamage = 16000, maxVelocity = 3.3, minCloakDistance = 150, noAutoFire = false, noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE SUB]], objectName = [[krow.s3o]], script = [[corcrw.lua]], seismicSignature = 0, selfDestructAs = [[LARGE_BUILDINGEX]], sfxtypes = { explosiongenerators = { [[custom:BEAMWEAPON_MUZZLE_RED]], [[custom:BEAMWEAPON_MUZZLE_RED]], }, }, sightDistance = 633, turnRate = 250, upright = true, workerTime = 0, weapons = { { def = [[KROWLASER]], mainDir = [[0.38 0.1 0.2]], maxAngleDif = 180, badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, { def = [[KROWLASER]], mainDir = [[-0.38 0.1 0.2]], maxAngleDif = 180, badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, { def = [[SPECIALTRIGGER]], mainDir = [[0 0 1]], maxAngleDif = 360, }, { def = [[KROWLASER]], mainDir = [[0 0.1 -0.38]], maxAngleDif = 180, badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, { --def = [[LIGHTNING]], def = [[CLUSTERBOMB]], --def = [[TIMEDISTORT]], }, }, weaponDefs = { KROWLASER = { name = [[Laserbeam]], areaOfEffect = 8, avoidFeature = false, canattackground = true, collideFriendly = false, coreThickness = 0.5, craterBoost = 0, craterMult = 0, customParams = { light_camera_height = 1800, light_radius = 160, }, damage = { default = 37.8, subs = 1.8, }, duration = 0.02, explosionGenerator = [[custom:BEAMWEAPON_HIT_RED]], fireStarter = 50, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, range = 450, reloadtime = 0.2, rgbColor = [[1 0 0]], soundHit = [[weapon/laser/lasercannon_hit]], soundStart = [[weapon/laser/heavylaser_fire2]], soundStartVolume = 0.7, soundTrigger = true, thickness = 3.25, tolerance = 10000, turret = true, weaponType = [[LaserCannon]], weaponVelocity = 2300, }, SPECIALTRIGGER = { name = [[FakeWeapon]], commandFire = true, cylinderTargeting = 1, craterBoost = 0, craterMult = 0, damage = { default = -0.001, planes = -0.001, subs = -0.001, }, explosionGenerator = [[custom:NONE]], impactOnly = true, impulseBoost = 0, impulseFactor = 1, interceptedByShieldType = 0, range = 200, reloadtime = 30, size = 0, targetborder = 1, tolerance = 20000, turret = true, waterWeapon = true, weaponType = [[Cannon]], weaponVelocity = 600, }, TIMEDISTORT = { name = [[Time Distortion Field]], areaOfEffect = 600, burst = 100, burstRate = 0.1, craterBoost = 0, craterMult = 0, damage = { default = 100, }, edgeeffectiveness = 0.75, explosionGenerator = [[custom:riotball_dark]], explosionSpeed = 3, impulseBoost = 1, impulseFactor = -2, interceptedByShieldType = 1, myGravity = 10, noSelfDamage = true, range = 300, reloadtime = 30, soundHitVolume = 1, turret = true, weaponType = [[Cannon]], weaponVelocity = 230, }, CLUSTERBOMB = { name = [[Cluster Bomb]], accuracy = 200, areaOfEffect = 128, burst = 75, burstRate = 0.3, commandFire = true, craterBoost = 1, craterMult = 2, damage = { default = 250, planes = 250, subs = 12.5, }, explosionGenerator = [[custom:MEDMISSILE_EXPLOSION]], fireStarter = 180, impulseBoost = 0, impulseFactor = 0.2, interceptedByShieldType = 2, model = [[wep_b_fabby.s3o]], range = 10, reloadtime = 30, -- if you change this redo the value in oneclick_weapon_defs EMPIRICALLY smokeTrail = true, soundHit = [[explosion/ex_med6]], soundHitVolume = 8, soundStart = [[weapon/cannon/mini_cannon]], soundStartVolume = 2, sprayangle = 14400, turret = true, weaponType = [[Cannon]], weaponVelocity = 400, }, }, featureDefs = { DEAD = { blocking = true, collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[80 30 80]], collisionVolumeType = [[ellipsoid]], featureDead = [[HEAP]], footprintX = 5, footprintZ = 5, object = [[krow_dead.s3o]], }, HEAP = { blocking = false, footprintX = 4, footprintZ = 4, object = [[debris4x4a.s3o]], }, }, } return lowerkeys({ corcrw = unitDef })
gpl-2.0
thedraked/darkstar
scripts/zones/Southern_San_dOria/npcs/Machielle.lua
17
1881
----------------------------------- -- Area: Southern San d'Oria -- NPC: Machielle -- Only sells when Bastok controls Norvallen Region ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Southern_San_dOria/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == 1) then if (trade:hasItemQty(532,1) == true and trade:getItemCount() == 1) then player:messageSpecial(FLYER_REFUSED); end else onHalloweenTrade(player,trade,npc); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local RegionOwner = GetRegionOwner(NORVALLEN); if (RegionOwner ~= NATION_SANDORIA) then player:showText(npc,MACHIELLE_CLOSED_DIALOG); else player:showText(npc,MACHIELLE_OPEN_DIALOG); local stock = {0x02b0,18, --Arrowwood Log 0x026d,25, --Crying Mustard 0x026a,25, --Blue Peas 0x02ba,88} --Ash Log showShop(player,SANDORIA,stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
128technology/protobuf_dissector
modules/generic/proto.lua
1
2070
---------------------------------------- -- -- Copyright (c) 2015, 128 Technology, Inc. -- -- author: Hadriel Kaplan <hadriel@128technology.com> -- -- This code is licensed under the MIT license. -- -- Version: 1.0 -- ------------------------------------------ -- prevent wireshark loading this file as a plugin if not _G['protbuf_dissector'] then return end local Prefs = require "prefs" local PacketDecoder = require "generic.packet" local Decoder = require "back_end.decoder" local GenericDecoder = require "generic.decoder" local Fixed32Decoder = require "generic.fixed32" local Fixed64Decoder = require "generic.fixed64" local VarintDecoder = require "generic.varint" local GroupDecoder = require "generic.group" local BytesDecoder = require "generic.bytes" local GenericProtoFields = require "generic.proto_fields" local GenericExperts = require "generic.experts" -------------------------------------------------------------------------------- -- our module table that we return to the caller of this script local GenericProto = {} GenericProto.proto = Proto.new("Protobuf", "Google Protobuf Format") local pfields = GenericProtoFields:getFields() -- register the ProtoFields and Experts GenericProto.proto.fields = pfields GenericProto.proto.experts = GenericExperts:getFields() -- create the Preferences Prefs:create(GenericProto.proto) GenericDecoder:register("FIXED32", Fixed32Decoder.new(pfields.FIXED32)) GenericDecoder:register("FIXED64", Fixed64Decoder.new(pfields.FIXED64)) GenericDecoder:register("VARINT", VarintDecoder.new(pfields.VARINT)) GenericDecoder:register("START_GROUP", GroupDecoder.new(pfields.GROUP)) GenericDecoder:register("LENGTH_DELIMITED", BytesDecoder.new(pfields.LENGTH_BYTES)) local packet_decoder = PacketDecoder.new(GenericProto.proto) function GenericProto.proto.dissector(tvbuf, pktinfo, root) return Decoder.new(tvbuf, pktinfo, root):decode(packet_decoder) end DissectorTable.get("udp.port"):add(0, GenericProto.proto) return GenericProto
mit
thedraked/darkstar
scripts/globals/items/leremieu_salad.lua
18
1674
----------------------------------------- -- ID: 5185 -- Item: leremieu_salad -- Food Effect: 240Min, All Races ----------------------------------------- -- Health 20 -- Magic 20 -- Dexterity 4 -- Agility 4 -- Vitality 6 -- Charisma 4 -- Defense % 25 -- Defense Cap 160 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5185); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_MP, 20); target:addMod(MOD_DEX, 4); target:addMod(MOD_AGI, 4); target:addMod(MOD_VIT, 6); target:addMod(MOD_CHR, 4); target:addMod(MOD_FOOD_DEFP, 25); target:addMod(MOD_FOOD_DEF_CAP, 160); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_MP, 20); target:delMod(MOD_DEX, 4); target:delMod(MOD_AGI, 4); target:delMod(MOD_VIT, 6); target:delMod(MOD_CHR, 4); target:delMod(MOD_FOOD_DEFP, 25); target:delMod(MOD_FOOD_DEF_CAP, 160); end;
gpl-3.0
thedraked/darkstar
scripts/zones/Stellar_Fulcrum/mobs/Kam_lanaut.lua
23
1461
----------------------------------- -- Area: Stellar Fulcrum -- MOB: Kam'lanaut -- Zilart Mission 8 BCNM Fight ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/globals/magic"); local blades = {823, 826, 828, 825, 824, 827}; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) local changeTime = mob:getLocalVar("changeTime"); local element = mob:getLocalVar("element"); if (changeTime == 0) then mob:setLocalVar("changeTime",math.random(1,3)*15) return; end if (mob:getBattleTime() >= changeTime) then local newelement = element; while (newelement == element) do newelement = math.random(1,6); end if (element ~= 0) then mob:delMod(absorbMod[element], 100); end mob:useMobAbility(blades[newelement]); mob:addMod(absorbMod[newelement], 100); mob:setLocalVar("changeTime", mob:getBattleTime() + math.random(1,3)*15); mob:setLocalVar("element", newelement); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) player:addTitle(DESTROYER_OF_ANTIQUITY); end;
gpl-3.0
thedraked/darkstar
scripts/zones/Bastok_Mines/npcs/Explorer_Moogle.lua
17
1731
----------------------------------- -- Area: Bastok Mines -- NPC: Explorer Moogle -- ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/teleports"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) accept = 0; event = 0x0249; if (player:getGil() < 300) then accept = 1; end if (player:getMainLvl() < EXPLORER_MOOGLE_LEVELCAP) then event = event + 1; end player:startEvent(event,player:getZoneID(),0,accept); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local price = 300; if (csid == 0x0249) then if (option == 1 and player:delGil(price)) then toExplorerMoogle(player,231); elseif (option == 2 and player:delGil(price)) then toExplorerMoogle(player,234); elseif (option == 3 and player:delGil(price)) then toExplorerMoogle(player,240); elseif (option == 4 and player:delGil(price)) then toExplorerMoogle(player,248); elseif (option == 5 and player:delGil(price)) then toExplorerMoogle(player,249); end end end;
gpl-3.0
thedraked/darkstar
scripts/zones/Abyssea-Konschtat/npcs/Cavernous_Maw.lua
29
1200
----------------------------------- -- Area: Abyssea - Konschatat -- NPC: Cavernous Maw -- @pos 159.943 -72.109 -839.986 15 -- Teleports Players to Konschatat Highlands ----------------------------------- package.loaded["scripts/zones/Abyssea-Konschtat/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Abyssea-Konschtat/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00C8); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00C8 and option == 1) then player:setPos(91,-68,-582,237,108); end end;
gpl-3.0
NPLPackages/main
script/ide/gui_helper.lua
1
25576
--[[ Title: GUI helper functions for ParaEngine Author(s): LiXizhi, WangTian Date: 2005/10 desc: To enable helper call: ------------------------------------------------------ NPL.load("(gl)script/ide/gui_helper.lua"); ------------------------------------------------------ ]] if(_guihelper==nil) then _guihelper={} end local math_floor = math.floor NPL.load("(gl)script/ide/MessageBox.lua"); NPL.load("(gl)script/ide/ButtonStyles.lua"); NPL.load("(gl)script/ide/System/Core/Color.lua"); local Color = commonlib.gettable("System.Core.Color"); -- deprecated: use Color.ConvertColorToRGBAString instead -- @param color: a string of "#FFFFFF" or "255 255 255 0" -- @return: return a string of "255 255 255 0". the alpha part may be omitted. function _guihelper.ConvertColorToRGBAString(color) if(color and string.find(color, "#")~=nil) then color = string.gsub(string.gsub(color, "#", ""), "(%x%x)", function (h) return tonumber(h, 16).." " end); end return color; end local getcolor = _guihelper.ConvertColorToRGBAString; -- get the last UI object position. This function is usually used when in a mouse click event callback script. -- return x, y, width, height. all of them may be nil. function _guihelper.GetLastUIObjectPos() local ui_obj = ParaUI.GetUIObject(id); if(ui_obj:IsValid()) then return ui_obj:GetAbsPosition(); end end -- return true if the given ui object is clipped by any of its parent container. -- (just in case of a scrollable container) -- @param margin: default to 0.2 of uiobject width. max allowed clipping width function _guihelper.IsUIObjectClipped(uiobject, margin) if(uiobject) then local x, y, width, height = uiobject:GetAbsPosition(); margin = margin or 0.2; local margin_width = 5 if(margin < 1) then margin_width = math.max(5, math.floor(width*margin)) else margin_width = margin_width; end local parent = uiobject.parent; while (parent and parent:IsValid()) do local px, py, pwidth, pheight = parent:GetAbsPosition(); px = px - margin_width; py = py - margin_width; pwidth = pwidth + margin_width*2; pheight = pheight + margin_width*2; if(px <= x and py <= y and (px+pwidth) >= (x+width) and (py+pheight)>=(y+height)) then parent = parent.parent; else return true; end end end end --[[ Set all texture layers of an UI object to the specifed color if UIobject is nil or is an invalid UI object, this function does nothing. e.g. _guihelper.SetUIColor(uiobject, "255 0 0"); or _guihelper.SetUIColor(uiobject, "255 0 0 128"); ]] function _guihelper.SetUIColor(uiobject, color) if(uiobject~=nil and uiobject:IsValid())then color = getcolor(color); uiobject:SetCurrentState("highlight"); uiobject.color=color; uiobject:SetCurrentState("pressed"); uiobject.color=color; uiobject:SetCurrentState("disabled"); uiobject.color=color; uiobject:SetCurrentState("normal"); uiobject.color=color; end end -- set color mask. -- @param color: it can be "255 255 255", "#FFFFFF", "255 255 255 100", alpha is supported. function _guihelper.SetColorMask(uiobject, color) if(uiobject and color)then uiobject.colormask = getcolor(color); end end -- set the text font color of a UI control. -- @param color: it can be "255 255 255", "#FFFFFF", "255 255 255 100", alpha is supported. function _guihelper.SetFontColor(uiobject, color) if(uiobject~=nil and uiobject:IsValid())then color = getcolor(color); uiobject:SetCurrentState("highlight"); uiobject:GetFont("text").color = color; uiobject:SetCurrentState("disabled"); uiobject:GetFont("text").color = color; uiobject:SetCurrentState("normal"); uiobject:GetFont("text").color = color; end end -- set the text font color of a UI control. -- @param color: it can be "255 255 255", "#FFFFFF", "255 255 255 100", alpha is supported. -- @param color_highlight: nil or the highlighted color function _guihelper.SetButtonFontColor(uiobject, color, color_highlight) if(uiobject~=nil and uiobject:IsValid())then color = getcolor(color); color_highlight = getcolor(color_highlight); uiobject:SetCurrentState("highlight"); uiobject:GetFont("text").color = color_highlight or color; uiobject:SetCurrentState("disabled"); uiobject:GetFont("text").color = color; uiobject:SetCurrentState("pressed"); uiobject:GetFont("text").color = color; uiobject:SetCurrentState("normal"); uiobject:GetFont("text").color = color; end end -- set the text font color of a UI control. -- @param color: it can be "255 255 255", "#FFFFFF", "255 255 255 100", alpha is supported. function _guihelper.SetButtonTextColor(uiobject, color) if(uiobject~=nil and uiobject:IsValid())then color = getcolor(color); uiobject:SetCurrentState("highlight"); uiobject:GetFont("text").color = color; uiobject:SetCurrentState("pressed"); uiobject:GetFont("text").color=color; uiobject:SetCurrentState("normal"); uiobject:GetFont("text").color = color; uiobject:SetCurrentState("disabled"); uiobject:GetFont("text").color = color; end end local default_font_str = "default"; -- set the default font. -- @param font_name: default font string, such as "System;12". If default, it will be the default one. function _guihelper.SetDefaultFont(font_name) default_font_str = font_name or "default"; end local font_objects = {}; -- get the cached invisible text font GUIText object -- @param fontName: if nil, default to default_font_str function _guihelper.GetTextObjectByFont(fontName) fontName = fontName or default_font_str local obj = font_objects[fontName]; if(obj and obj:IsValid()) then return obj; else local _parent = ParaUI.GetUIObject("_fonts_"); if(_parent:IsValid() == false) then _parent = ParaUI.CreateUIObject("container","_fonts_", "_lt",-100,-20,200,15); _parent.visible = false; _parent.enabled = false; _parent:AttachToRoot(); end local _this = _parent:GetChild(fontName); if(not _this:IsValid()) then _this = ParaUI.CreateUIObject("editbox",fontName, "_lt",0,0,800,22); _this.visible = false; if(fontName ~= "default") then _this.font = fontName; end _this:GetFont("text").format = 1+256; -- center and no clip -- _this:GetFont("text").format = 32+256; -- left top single line and no clip _parent:AddChild(_this); font_objects[fontName] = _this; return font_objects[fontName]; end end end local textWidthCache = {}; local function GetTextWidthCache(fontName) local cache = textWidthCache[fontName or ""] if(cache) then return cache else cache = commonlib.ArrayMap:new(); textWidthCache[fontName or ""] = cache; return cache; end end -- get the width of text of a given font. It internally cache the font object and UI object on first call. -- @param text: text for which to determine the width -- @param fontName: font name, such as "System;12". If nil, it will use the default font of text control. -- @return the width of text of a given font function _guihelper.GetTextWidth(text, fontName) if(not text or text=="") then return 0 end local cache = GetTextWidthCache(fontName) local item = cache:get(text) local curTime = commonlib.TimerManager.GetCurrentTime(); if(item) then item[2] = curTime return item[1]; else local _this = _guihelper.GetTextObjectByFont(fontName); _this.text = text; width = _this:GetTextLineSize(); cache:push(text, {width, curTime}); if(cache:size() > 500) then cache:valueSort(function(a, b) return a[2] >= b[2] end) cache:resize(300) end return width; end end -- Automatically trim additional text so that the text can be displayed inside a given width -- e.g. a commonly used pattern is like below: -- local displayText = _guihelper.AutoTrimTextByWidth(text, maxTextWidth) -- if(displayText == text) then -- _this.text = text -- else -- _this.text = string.sub(displayText, 1, string.len(displayText)-3).."..."; -- end -- @param text: currently it only works for english letters. TODO: for utf8 text, we can first convert to unicode and then back. -- @param maxWidth: the max width in pixel. -- @param fontName: font name, such as "System;12". If nil, it will use the default font of text control. -- @return the text which may be trimed function _guihelper.AutoTrimTextByWidth(text, maxWidth, fontName) if(not text or text=="") then return "" end local nSize = #(text); local width = _guihelper.GetTextWidth(text,fontName); if(width < maxWidth) then return text end -- Initialise numbers local iStart,iEnd,iMid = 1,nSize, nSize -- modified binary search while (iStart <= iEnd) do -- calculate middle iMid = math_floor( (iStart+iEnd)/2 ); -- get compare value local value2 = _guihelper.GetTextWidth(string.sub(text, 1, iMid),fontName); if(value2 >= maxWidth) then iEnd = iMid - 1; else iStart = iMid + 1; end end return string.sub(text, 1, iMid) end -- trim UTF8 text by width -- @param text: UTF8 string. -- @param maxWidth: the max width in pixel. -- @param fontName: font name, such as "System;12". If nil, it will use the default font of text control. -- return the trimmed text and the remaining text function _guihelper.TrimUtf8TextByWidth(text, maxWidth, fontName) if(not text or text=="") then return "" end local width = _guihelper.GetTextWidth(text,fontName); if(width < maxWidth) then return text end -- Initialise numbers local nSize = ParaMisc.GetUnicodeCharNum(text); local iStart,iEnd,iMid = 1,nSize, nSize -- modified binary search while (iStart <= iEnd) do -- calculate middle iMid = math_floor( (iStart+iEnd)/2 ); -- get compare value local value2 = _guihelper.GetTextWidth(ParaMisc.UniSubString(text, 1, iMid),fontName); if(value2 >= maxWidth) then iEnd = iMid - 1; iMid = iEnd; else iStart = iMid + 1; end end local leftText = ParaMisc.UniSubString(text, 1, iMid); local rightText = ParaMisc.UniSubString(text, iMid+1, -1); if(iMid > 1 and iMid < nSize) then -- preventing word break of english letters. local leftword = leftText:match("%w+$"); local rightword = rightText:match("^%w+"); if(leftword and rightword and leftword~=leftText) then leftText = string.sub(leftText, 1, -(#leftword+1)); rightText = leftword..rightText; end end return leftText, rightText; end -- @param uiobject uiobject such as button -- @param format: 0 for left alignment; 1 for horizontal center alignment; 4 for vertical center aligntment; 5 for both vertical and horizontal; -- 32 for single-lined left top alignment, 36 for single-lined vertical center alignment -- DT_TOP 0x00000000 -- DT_LEFT 0x00000000 -- DT_CENTER 0x00000001 -- DT_RIGHT 0x00000002 -- DT_VCENTER 0x00000004 -- DT_BOTTOM 0x00000008 -- DT_SINGLELINE 0x00000020 -- DT_WORDBREAK 0x00000010 -- DT_NOCLIP 0x00000100 -- DT_EXTERNALLEADING 0x00000200 -- @param fontName: if nil, it default to "text", can also be "selected_text" for editbox function _guihelper.SetUIFontFormat(uiobject, format, fontName) if(uiobject~=nil and uiobject:IsValid())then fontName = fontName or "text"; uiobject:SetCurrentState("highlight"); uiobject:GetFont(fontName).format=format; uiobject:SetCurrentState("pressed"); uiobject:GetFont(fontName).format=format; uiobject:SetCurrentState("disabled"); uiobject:GetFont(fontName).format=format; uiobject:SetCurrentState("normal"); uiobject:GetFont(fontName).format=format; end end -- @deprecated -- @param r, g, b, a: each in [0,255] function _guihelper.RGBA_TO_DWORD(r, g, b, a) return Color.RGBA_TO_DWORD(r, g, b, a); end -- @deprecated -- convert from color string to dwColor -- if alpha is not provided. the returned wColor will also not contain alpha. -- @param color: can be "#FFFFFF" or "#FFFFFF00" with alpha function _guihelper.ColorStr_TO_DWORD(color) return Color.ColorStr_TO_DWORD(color); end -- @deprecated -- @param r, g, b, a: each in [0,255] -- @return r, g, b, a: each in [0,255] function _guihelper.DWORD_TO_RGBA(w) return Color.DWORD_TO_RGBA(w); end --[[ set the text of a ui control by its name. @param objName:name of the object @param newText: string of the new text. ]] function _guihelper.SafeSetText(objName, newText) local temp = ParaUI.GetUIObject(objName); if(temp:IsValid()==true) then temp.text = newText; end end --[[ get the text of a ui control as a number. return nil if invalid. @param objName:name of the object @return: number or nil ]] function _guihelper.SafeGetNumber(objName) local temp = ParaUI.GetUIObject(objName); if(temp:IsValid()==true) then return tonumber(temp.text); end return nil; end --[[ get the text of a ui control as a number. return nil if invalid. @param objName:name of the object, such as {"name1", "name2"} @return: number or nil ]] function _guihelper.SafeGetText(objName) local temp = ParaUI.GetUIObject(objName); if(temp:IsValid()==true) then return temp.text; end return nil; end --[[ @param objList: an array of button names. @param selectedName: name of the selected button. If nil, nothing will be selected. @param color: color used for highlighting the checked button. @param checked_bg, unchecked_bg: can be nil or the texture of the checked and unchecked state. ]] function _guihelper.CheckRadioButtons(objList, selectedName, color, checked_bg, unchecked_bg) if(color == nil) then color = "255 255 255"; end local texture; local key, objName; for key, objName in pairs(objList) do local temp = ParaUI.GetUIObject(objName); if(temp:IsValid()==true) then if(temp.name == selectedName) then if(checked_bg~=nil) then temp.background = checked_bg; end if(temp:HasLayer("background")) then -- for vista style buttons, we will only change the background layer temp:SetActiveLayer("background"); temp:SetCurrentState("highlight"); temp.color=color; temp:SetCurrentState("pressed"); temp.color=color; temp:SetCurrentState("normal"); temp.color=color; temp:SetActiveLayer("artwork"); else temp:SetCurrentState("highlight"); temp.color=color; temp:SetCurrentState("pressed"); temp.color=color; temp:SetCurrentState("normal"); temp.color=color; end else if(unchecked_bg~=nil) then temp.background = unchecked_bg; end if(temp:HasLayer("background")) then -- for vista style buttons, we will only change the background layer temp:SetActiveLayer("background"); temp:SetCurrentState("highlight"); temp.color="255 255 255"; temp:SetCurrentState("pressed"); temp.color="160 160 160"; temp:SetCurrentState("normal"); temp.color="0 0 0 0"; temp:SetActiveLayer("artwork"); else temp:SetCurrentState("highlight"); temp.color="255 255 255"; temp:SetCurrentState("pressed"); temp.color="160 160 160"; temp:SetCurrentState("normal"); temp.color="200 200 200"; end end end end end -- NOTE: --WangTian: change background for group of buttons --[[ @param objList: an array of button names. @param selectedName: name of the selected button. If nil, nothing will be selected. @param color: color used for highlighting the checked button. @param checked_bg, unchecked_bg: can be nil or the texture of the checked and unchecked state. ]] function _guihelper.CheckRadioButtons2(objList, selectedName, color, checked_bg, unchecked_bg) if(color == nil) then color = "255 255 255"; end local texture; local key, objName; for key, objName in pairs(objList) do local temp = ParaUI.GetUIObject(objName); if(temp:IsValid()==true) then if(temp.name == selectedName) then if(temp:HasLayer("background")) then temp:SetActiveLayer("background"); if(checked_bg~=nil) then -- for vista style buttons, we will only change the background layer temp:SetCurrentState("highlight"); temp.color="255 255 255"; temp:SetCurrentState("pressed"); temp.color="160 160 160"; temp:SetCurrentState("normal"); temp.color="200 200 200"; end temp:SetActiveLayer("artwork"); end else if(temp:HasLayer("background")) then temp:SetActiveLayer("background"); if(unchecked_bg~=nil) then --temp.background = unchecked_bg; -- for vista style buttons, we will only change the background layer temp:SetCurrentState("highlight"); temp.color="255 255 255"; temp:SetCurrentState("pressed"); temp.color="160 160 160"; temp:SetCurrentState("normal"); temp.color="200 200 200"; end temp:SetActiveLayer("artwork"); end end end end end --[[ @param objList: an array <index, button names>, such as {[1] = "name1", [2] ="name2",} @param nSelectedIndex: index of the selected button. If nil, nothing will be selected. @param color: color used for highlighting the checked button. @param checked_bg, unchecked_bg: can be nil or the texture of the checked and unchecked state. ]] function _guihelper.CheckRadioButtonsByIndex(objList, nSelectedIndex, color, checked_bg, unchecked_bg) if(color == nil) then color = "255 255 255"; end local texture; local index, objName; for index, objName in ipairs(objList) do local temp = ParaUI.GetUIObject(objName); if(temp:IsValid()==true) then if(index == nSelectedIndex) then if(checked_bg~=nil) then temp.background = checked_bg; end if(temp:HasLayer("background")) then -- for vista style buttons, we will only change the background layer temp:SetActiveLayer("background"); temp:SetCurrentState("highlight"); temp.color=color; temp:SetCurrentState("pressed"); temp.color=color; temp:SetActiveLayer("artwork"); temp:SetCurrentState("normal"); temp.color=color; else temp:SetCurrentState("highlight"); temp.color=color; temp:SetCurrentState("pressed"); temp.color=color; temp:SetCurrentState("normal"); temp.color=color; end else if(checked_bg~=nil) then temp.background = unchecked_bg; end if(temp:HasLayer("background")) then -- for vista style buttons, we will only change the background layer temp:SetActiveLayer("background"); temp:SetCurrentState("highlight"); temp.color="255 255 255"; temp:SetCurrentState("pressed"); temp.color="160 160 160"; temp:SetCurrentState("normal"); temp.color="0 0 0 0"; temp:SetActiveLayer("artwork"); else temp:SetCurrentState("highlight"); temp.color="255 255 255"; temp:SetCurrentState("pressed"); temp.color="160 160 160"; temp:SetCurrentState("normal"); temp.color="200 200 200"; end end end end end --[[ for all objects in objList, only the selectedName is made visible. @param objList: an array of button names, such as {"name1", "name2"} @param selectedName: name of the selected button. If nil, nothing will be selected. ]] function _guihelper.SwitchVizGroup(objList, selectedName) local key, objName; for key, objName in pairs(objList) do local temp = ParaUI.GetUIObject(objName); if(temp:IsValid()==true) then if(temp.name == selectedName) then temp.visible = true; else temp.visible = false; end end end end --[[ for all objects in objList, only the selectedName is made visible. @param objList: an array <index, button names>, such as {[1] = "name1", [2] ="name2",} @param nSelectedIndex: index of the selected button. If nil, nothing will be selected. ]] function _guihelper.SwitchVizGroupByIndex(objList, nSelectedIndex) local index, objName; for index, objName in ipairs(objList) do local temp = ParaUI.GetUIObject(objName); if(temp:IsValid()==true) then if(index == nSelectedIndex) then temp.visible = true; else temp.visible = false; end end end end --[[this is a message handler for placeholder buttons,etc. it will display the name of control, the texture file path, etc in the messagebox @param ctrlName: control name @param comments: if not nil, it is additional text that will be displayed. ]] function _guihelper.OnClick(ctrlName, comments) local temp = ParaUI.GetUIObject(ctrlName); if(temp:IsValid()==true) then local text = string.format("name: %s\r\nbg: %s\r\n", ctrlName, temp.background); if(comments~=nil)then text = text..comments.."\r\n"; end _guihelper.MessageBox(text); else _guihelper.MessageBox(ctrlName.." control not found\r\n"); end end -- print out the table structure -- @param t: table to print -- @param filename: the file name to print out the table function _guihelper.PrintTableStructure(t, filename) NPL.load("(gl)script/kids/3DMapSystem_Misc.lua"); Map3DSystem.Misc.SaveTableToFile(t, filename); end -- print out the ui object structure -- @param obj: ui object to print -- @param filename: the file name to print out the ui object function _guihelper.PrintUIObjectStructure(obj, filename) local function portToTable(obj, t) local function getObjInfo(obj) return obj.type.." @ "..obj.x.." "..obj.y.." "..obj.width.." "..obj.height; end if(obj.type == "container") then t[obj.name] = {}; local nCount = obj:GetChildCount(); for i = 0, nCount - 1 do local _ui = obj:GetChildAt(i); portToTable(_ui, t[obj.name]); end else t[obj.name] = getObjInfo(obj); end end local t = {}; portToTable(obj, t); _guihelper.PrintTableStructure(t, filename); end -- set the container enabled, this will iterately set the enabled attribute in the UI object child container -- @param bEnabled: true or false function _guihelper.SetContainerEnabled(obj, bEnabled) if(obj:IsValid() == true) then if(obj.type == "container") then local nCount = obj:GetChildCount(); for i = 0, nCount - 1 do local _ui = obj:GetChildAt(i); _guihelper.SetContainerEnabled(_ui, bEnabled) end obj.enabled = bEnabled; else obj.enabled = bEnabled; end end end local align_translator = { ["_lb"] = function(x, y, width, height, screen_width, screen_height) return x, screen_height+y, width, height; end, ["_ct"] = function(x, y, width, height, screen_width, screen_height) return x + screen_width / 2, y + screen_height/2, width, height; end, ["_ctt"] = function(x, y, width, height, screen_width, screen_height) return x + screen_width / 2, y, width, height; end, ["_ctb"] = function(x, y, width, height, screen_width, screen_height) return x + screen_width / 2, screen_height-y-height, width, height; end, ["_ctl"] = function(x, y, width, height, screen_width, screen_height) return x, y + screen_height/2, width, height; end, ["_ctr"] = function(x, y, width, height, screen_width, screen_height) return screen_width - width - x, y + screen_height/2, width, height; end, ["_rt"] = function(x, y, width, height, screen_width, screen_height) return screen_width + x, y, width, height; end, ["_rb"] = function(x, y, width, height, screen_width, screen_height) return screen_width + x, screen_height + y, width, height; end, ["_mt"] = function(x, y, width, height, screen_width, screen_height) return x, y, screen_width - width - x, height; end, ["_mb"] = function(x, y, width, height, screen_width, screen_height) return x, screen_height-y-height, screen_width - width - x, height; end, ["_ml"] = function(x, y, width, height, screen_width, screen_height) return x, y, width, screen_height-height-y; end, ["_mr"] = function(x, y, width, height, screen_width, screen_height) return screen_width - width - x, y, width, screen_height-height-y; end, ["_fi"] = function(x, y, width, height, screen_width, screen_height) return x, y, screen_width - width - x, screen_height-height-y; end, } --translate from ParaUI alignment to left top alignment based on the current screen resolution. -- @param screen_width, screen_height: the current screen resolution. if nil, it will be refreshed using current screen resolution. function _guihelper.NormalizeAlignment(alignment, x, y, width, height, screen_width, screen_height) local func = align_translator[alignment or "_lt"]; if(func) then if(not screen_width) then if(Map3DSystem.ScreenResolution) then screen_width, screen_height = Map3DSystem.ScreenResolution.screen_width, Map3DSystem.ScreenResolution.screen_height else local _; _, _, screen_width, screen_height = ParaUI.GetUIObject("root"):GetAbsPosition(); end end x, y, width, height = func(x, y, width, height, screen_width, screen_height); end return x, y, width, height, screen_width, screen_height; end local states = {[1] = "highlight", [2] = "pressed", [3] = "disabled", [4] = "normal"}; -- update control bar for containers, etc. function _guihelper.UpdateScrollBar(_this, scrollbar_track, scrollbar_upleft, scrollbar_downright, scrollbar_thumb) for i = 1, 4 do _this:SetCurrentState(states[i]); if(scrollbar_track) then texture=_this:GetTexture("track"); texture.texture = scrollbar_track; end if(scrollbar_upleft) then texture=_this:GetTexture("up_left"); texture.texture = scrollbar_upleft; end if(scrollbar_downright) then texture=_this:GetTexture("down_right"); texture.texture = scrollbar_downright; end if(scrollbar_thumb) then texture=_this:GetTexture("thumb"); texture.texture = scrollbar_thumb; end end end
gpl-2.0
thedraked/darkstar
scripts/zones/Bhaflau_Thickets/npcs/qm1.lua
30
1349
----------------------------------- -- Area: Bhaflau Thickets -- NPC: ??? (Spawn Lividroot Amooshah(ZNM T2)) -- @pos 334 -10 184 52 ----------------------------------- package.loaded["scripts/zones/Bhaflau_Thickets/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Bhaflau_Thickets/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local mobID = 16990473; if (trade:hasItemQty(2578,1) and trade:getItemCount() == 1) then -- Trade Oily Blood if (GetMobAction(mobID) == ACTION_NONE) then player:tradeComplete(); SpawnMob(mobID):updateClaim(player); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_HAPPENS); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
thedraked/darkstar
scripts/zones/Riverne-Site_A01/npcs/Spatial_Displacement.lua
17
3365
----------------------------------- -- Area: Riverne Site #A01 -- NPC: Spacial Displacement ----------------------------------- ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local id = npc:getID(); local base = 16900334; -- (First Spacial Displacement in NPC_LIST) if (id == base) then player:startEvent(0x2); elseif (id == base+1) then player:startEvent(0x3); elseif (id == base+2) then player:startEvent(0x4); elseif (id == base+7) then player:startEvent(0x7); elseif (id == base+8) then player:startEvent(0x8); elseif (id == base+9) then player:startEvent(0x9); elseif (id == base+10) then player:startEvent(0x0A); elseif (id == base+11) then player:startEvent(0xB); elseif (id == base+12) then player:startEvent(0xC); elseif (id == base+13) then player:startEvent(0xD); elseif (id == base+14) then player:startEvent(0xE); elseif (id == base+15) then player:startEvent(0xF); elseif (id == base+16) then player:startEvent(0x10); elseif (id == base+18) then player:startEvent(0x12); elseif (id == base+20) then player:startEvent(0x14); elseif (id == base+21) then player:startEvent(0x15); elseif (id == base+22) then player:startEvent(0x16); elseif (id == base+23) then player:startEvent(0x17); elseif (id == base+24) then player:startEvent(0x18); elseif (id == base+25) then player:startEvent(0x19); elseif (id == base+26) then player:startEvent(0x1A); elseif (id == base+27) then player:startEvent(0x1b); elseif (id == base+28) then player:startEvent(0x1C); elseif (id == base+29) then player:startEvent(0x1d); elseif (id == base+30) then player:startEvent(0x1E); elseif (id == base+31) then player:startEvent(0x1F); elseif (id == base+33) then player:startEvent(0x21); elseif (id == base+34) then player:startEvent(0x22); elseif (id == base+35) then player:startEvent(0x23); elseif (id == base+36) then player:startEvent(0x24); elseif (id == base+37) then player:startEvent(0x25); elseif (id == base+38) then player:startEvent(0x26); elseif (id == base+39) then player:startEvent(0x27); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x23 and option == 1) then player:setPos(12.527,0.345,-539.602,127,31); -- to Monarch Linn (Retail confirmed) elseif (csid == 0x0A and option == 1) then player:setPos(-538.526,-29.5,359.219,255,25); -- back to Misareaux Coast (Retail confirmed) end; end;
gpl-3.0
thedraked/darkstar
scripts/zones/Xarcabard/npcs/Tememe_WW.lua
14
3321
----------------------------------- -- Area: Xarcabard -- NPC: Tememe, W.W. -- Type: Border Conquest Guards -- @pos -133.678 -22.517 112.224 112 ----------------------------------- package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Xarcabard/TextIDs"); local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = VALDEAUNIA; local csid = 0x7ff6; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
sharklinux/shark
samples/bpf/net_skb_recv.lua
2
1188
#!/usr/bin/env shark local bpf = require("bpf") bpf.cdef[[ #include <linux/skbuff.h> #include <linux/netdevice.h> #include <uapi/linux/bpf.h> #include "bpf_helpers.h" #define _(P) ({typeof(P) val = 0; bpf_probe_read(&val, sizeof(val), &P); val;}) SEC("kprobe/__netif_receive_skb_core") int bpf_prog1(struct pt_regs *ctx) { /* attaches to kprobe netif_receive_skb, * looks for packets on loobpack device and prints them */ char devname[IFNAMSIZ] = {}; struct net_device *dev; struct sk_buff *skb; int len; /* non-portable! works for the given kernel only */ skb = (struct sk_buff *) ctx->di; dev = _(skb->dev); len = _(skb->len); bpf_probe_read(devname, sizeof(devname), dev->name); if (devname[0] == 'l' && devname[1] == 'o') { char fmt[] = "skb %p len %d\n"; /* using bpf_trace_printk() for DEBUG ONLY */ bpf_trace_printk(fmt, sizeof(fmt), skb, len); } return 0; } ]] os.execute("taskset 1 ping -c5 localhost >/dev/null &") for line in io.lines("/sys/kernel/debug/tracing/trace_pipe") do print(line) end
lgpl-2.1
telergybot/1984joorge
plugins/owners.lua
284
12473
local function lock_group_namemod(msg, data, target) 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_namemod(msg, data, target) 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 local function lock_group_floodmod(msg, data, target) 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_floodmod(msg, data, target) 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 local function lock_group_membermod(msg, data, target) 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_membermod(msg, data, target) 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 local function unlock_group_photomod(msg, data, target) 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 show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) 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']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end 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.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) 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 run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) 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] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
master041/tele-master-asli
plugins/boobs.lua
731
1601
do -- Recursive function local function getRandomButts(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.obutts.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt <= 3 then print('Cannot get that butts, trying another one...') return getRandomButts(attempt) end return 'http://media.obutts.ru/' .. data.preview end local function getRandomBoobs(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.oboobs.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt < 10 then print('Cannot get that boobs, trying another one...') return getRandomBoobs(attempt) end return 'http://media.oboobs.ru/' .. data.preview end local function run(msg, matches) local url = nil if matches[1] == "!boobs" then url = getRandomBoobs() end if matches[1] == "!butts" then url = getRandomButts() end if url ~= nil then local receiver = get_receiver(msg) send_photo_from_url(receiver, url) else return 'Error getting boobs/butts for you, please try again later.' end end return { description = "Gets a random boobs or butts pic", usage = { "!boobs: Get a boobs NSFW image. 🔞", "!butts: Get a butts NSFW image. 🔞" }, patterns = { "^!boobs$", "^!butts$" }, run = run } end
gpl-2.0
thedraked/darkstar
scripts/globals/homepoint.lua
4
17850
require("scripts/globals/settings"); local homepoints = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25, 26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50, 51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75, 76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100, 101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116}; --paramNum bit x y z rotation zone cost homepoints[0] = { 1, 1, -85.554, 1, -64.554, 45, 230, 500}; -- Southern San d'Oria #1 homepoints[1] = { 1, 2, 44.1, 2, -34.5, 170, 230, 500}; -- Southern San d'Oria #2 homepoints[2] = { 1, 3, 140.5, -2, 121, 0, 230, 500}; -- Southern San d'Oria #3 homepoints[3] = { 1, 4, -178, 4, 71, 0, 231, 500}; -- Northern San d'Oria #1 homepoints[4] = { 1, 5, 10, -0.2, 95, 0, 231, 500}; -- Northern San d'Oria #2 homepoints[5] = { 1, 6, 70, -0.2, 10, 0, 231, 500}; -- Northern San d'Oria #3 homepoints[6] = { 1, 7, -38, -4, -63, 0, 232, 500}; -- Port San d'Oria #1 homepoints[7] = { 1, 8, 48, -12, -105, 0, 232, 500}; -- Port San d'Oria #2 homepoints[8] = { 1, 9, -6, -13, -150, 0, 232, 500}; -- Port San d'Oria #3 homepoints[9] = { 1, 10, 39, 0, -43, 0, 234, 500}; -- Bastok Mines #1 homepoints[10] = { 1, 11, 118, 1, -58, 0, 234, 500}; -- Bastok Mines #2 homepoints[11] = { 1, 12, -293, -10, -102, 0, 235, 500}; -- Bastok Markets #1 homepoints[12] = { 1, 13, -328, -12, -33, 0, 235, 500}; -- Bastok Markets #2 homepoints[13] = { 1, 14, -189, -8, 26, 0, 235, 500}; -- Bastok Markets #3 homepoints[14] = { 1, 15, 58.85, 7.499, -27.790, 0, 236, 500}; -- Port Bastok #1 homepoints[15] = { 1, 16, 42, 8.5, -244, 0, 236, 500}; -- Port Bastok #2 homepoints[16] = { 1, 17, 46, -14, -19, 0, 237, 500}; -- Metalworks #1 homepoints[17] = { 1, 18, -32, -5, 132, 0, 238, 500}; -- Windurst Waters #1 homepoints[18] = { 1, 19, 138.5, 0, -14, 0, 238, 500}; -- Windurst Waters #2 homepoints[19] = { 1, 20, -72, -5, 125, 0, 239, 500}; -- Windurst Walls #1 homepoints[20] = { 1, 21, -212, 0, -99, 0, 239, 500}; -- Windurst Walls #2 homepoints[21] = { 1, 22, 31, -6.5, -40, 0, 239, 500}; -- Windurst Walls #3 homepoints[22] = { 1, 23, -188, -4, 101, 0, 240, 500}; -- Port Windurst #1 homepoints[23] = { 1, 24, -207, -8, 210, 0, 240, 500}; -- Port Windurst #2 homepoints[24] = { 1, 25, 180, -12, 226, 0, 240, 500}; -- Port Windurst #3 homepoints[25] = { 1, 26, 9, -2, 0, 0, 241, 500}; -- Windurst Woods #1 homepoints[26] = { 1, 27, 107, -5, -56, 0, 241, 500}; -- Windurst Woods #2 homepoints[27] = { 1, 28, -92, -5, 62, 0, 241, 500}; -- Windurst Woods #3 homepoints[28] = { 1, 29, 74, -7, -139, 0, 241, 500}; -- Windurst Woods #4 homepoints[29] = { 1, 30, -6, 3, 0, 0, 243, 500}; -- Ru'Lude Gardens #1 homepoints[30] = { 1, 31, 53, 9, -57, 0, 243, 500}; -- Ru'Lude Gardens #2 homepoints[31] = { 1, 32, -67, 6, -25, 1, 243, 500}; -- Ru'Lude Gardens #3 homepoints[32] = { 2, 1, -99, 0, 167, 0, 244, 500}; -- Upper Jeuno #1 homepoints[33] = { 2, 2, 32, -1, -44, 0, 244, 500}; -- Upper Jeuno #2 homepoints[34] = { 2, 3, -52, 1, 16, 0, 244, 500}; -- Upper Jeuno #3 homepoints[35] = { 2, 4, -99, 0, -183, 0, 245, 500}; -- Lower Jeuno #1 homepoints[36] = { 2, 5, 18, -1, 54, 0, 245, 500}; -- Lower Jeuno #2 homepoints[37] = { 2, 6, 37, 0, 9, 0, 246, 500}; -- Port Jeuno #1 homepoints[38] = { 2, 7, -155, -1, -4, 0, 246, 500}; -- Port Jeuno #2 homepoints[39] = { 2, 8, 78, -13, -94, 0, 250, 500}; -- Kazham #1 homepoints[40] = { 2, 9, -13, -15, 87, 0, 249, 500}; -- Mhaura #1 homepoints[41] = { 2, 10, -27, 0, -47, 0, 252, 500}; -- Norg #1 homepoints[42] = { 2, 11, -29, 0, -76, 0, 247, 500}; -- Rabao #1 homepoints[43] = { 2, 12, 36, -11, 35, 0, 248, 500}; -- Selbina #1 homepoints[44] = { 2, 13, -84, 4, -32, 128, 256, 500}; -- Western Adoulin #1 homepoints[45] = { 2, 14, -51, 0, 59, 128, 257, 500}; -- Eastern Adoulin #1 homepoints[46] = { 2, 15, -107, 3, 295, 128, 261, 1000}; -- Ceizak Battlegrounds #1 homepoints[47] = { 2, 16, -193, -0.5, -252, 128, 262, 1000}; -- Foret de Hennetiel #1 homepoints[48] = { 2, 17, -415, -63.2, 409, 106, 265, 1000}; -- Morimar Basalt Fields #1 homepoints[49] = { 2, 18, -420, 0, -62, 64, 263, 1000}; -- Yorcia Weald #1 homepoints[50] = { 2, 19, -23, 0, 174, 0, 266, 1000}; -- Marjami Ravine #1 homepoints[51] = { 2, 20, 210, 20.299, 315, 192, 267, 1000}; -- Kamihr Drifts #1 homepoints[52] = { 2, 21, 434, -40, 171, 0, 142, 1000}; -- Yughott Grotto #1 homepoints[53] = { 2, 22, 109, -38, -147, 0, 143, 1000}; -- Palborough Mines #1 homepoints[54] = { 2, 23, -132, -3, -303, 0, 145, 1000}; -- Giddeus #1 homepoints[55] = { 2, 24, 243, -24, 62, 0, 204, 1000}; -- Fei'Yin #1 homepoints[56] = { 2, 25, -984, 17, -289, 0, 208, 1000}; -- Quicksand Caves #1 homepoints[57] = { 2, 26, -80, 46, 62, 0, 160, 1000}; -- Den of Rancor #1 homepoints[58] = { 2, 27, -554, -70, 66, 0, 162, 1000}; -- Castle Zvahl Keep #1 homepoints[59] = { 2, 28, 5, -42, 526, 0, 130, 1000}; -- Ru'Aun Gardens #1 homepoints[60] = { 2, 29, -499, -42, 167, 0, 130, 1000}; -- Ru'Aun Gardens #2 homepoints[61] = { 2, 30, -312, -42, -422, 0, 130, 1000}; -- Ru'Aun Gardens #3 homepoints[62] = { 2, 31, 500, -42, 158, 0, 130, 1000}; -- Ru'Aun Gardens #4 homepoints[63] = { 2, 32, 305, -42, -427, 0, 130, 1000}; -- Ru'Aun Gardens #5 homepoints[64] = { 3, 1, -1, -27, 107, 0, 26, 500}; -- Tavnazian Safehold #1 homepoints[65] = { 3, 2, -21, 0, -21, 0, 50, 500}; -- Aht Urhgan Whitegate #1 homepoints[66] = { 3, 3, -20, 0, -25, 0, 53, 500}; -- Nashmau #1 -- homepoints[67] = { 3, 4, 0, 0, 0, 0, 48, 500}; -- Al Zahbi #1 // Doesn't exist related to BG Wiki homepoints[68] = { 3, 5, -85, 1, -66, 0, 80, 500}; -- Southern San d'Oria [S] #1 homepoints[69] = { 3, 6, -293, -10, -102, 0, 87, 500}; -- Bastok Markets [S] #1 homepoints[70] = { 3, 7, -32, -5, 131, 0, 94, 500}; -- Windurst Waters [S] #1 homepoints[71] = { 3, 8, -365, -176.5, -36, 0, 158, 1000}; -- Upper Delkfutt's Tower #1 homepoints[72] = { 3, 9, -13, 48, 61, 0, 178, 1000}; -- The Shrine of Ru'Avitau #1 homepoints[73] = { 3, 10, 0, 0, 0, 0, 29, 1000}; -- Riverne - Site #B01 #1 homepoints[74] = { 3, 11, -98, -10, -493, 192, 52, 1000}; -- Bhaflau Thickets #1 homepoints[75] = { 3, 12, -449, 13, -497, 0, 79, 1000}; -- Caedarva Mire #1 homepoints[76] = { 3, 13, 64, -196, 181, 0, 5, 1000}; -- Uleguerand Range #1 homepoints[77] = { 3, 14, 380, 23, -62, 0, 5, 1000}; -- Uleguerand Range #2 homepoints[78] = { 3, 15, 424, -32, 221, 0, 5, 1000}; -- Uleguerand Range #3 homepoints[79] = { 3, 16, 64, -96, 461, 0, 5, 1000}; -- Uleguerand Range #4 homepoints[80] = { 3, 17, -220, -1, -62, 0, 5, 1000}; -- Uleguerand Range #5 homepoints[81] = { 3, 18, -200, -10, 342, 0, 7, 1000}; -- Attohwa Chasm #1 homepoints[82] = { 3, 19, -58, 40, 14, 64, 9, 1000}; -- Pso'Xja #1 homepoints[83] = { 3, 20, 445, 27, -22, 0, 12, 1000}; -- Newton Movalpolos #1 homepoints[84] = { 3, 21, 189, 0, 362, 0, 30, 1000}; -- Riveren - Site #A01 #1 // Location not verified from retail homepoints[85] = { 3, 22, 7, 0, 709, 192, 33, 1000}; -- Al'Taieu #1 homepoints[86] = { 3, 23, -532, 0, 447, 128, 33, 1000}; -- Al'Taieu #2 homepoints[87] = { 3, 24, 569, 0, 410, 192, 33, 1000}; -- Al'Taieu #3 homepoints[88] = { 3, 25, -12, 0, -288, 192, 34, 1000}; -- Grand Palace of Hu'Xzoi #1 homepoints[89] = { 3, 26, -426, 0, 368, 224, 35, 1000}; -- The Garden of Ru'Hmet #1 homepoints[90] = { 3, 27, -540.844, -4.000, 70.809, 74, 61, 1000}; -- Mount Zhayolm #1 // No valid location homepoints[91] = { 3, 28, -303, -8, 526, 0, 113, 1000}; -- Cape Terrigan #1 homepoints[92] = { 3, 29, 88, -15, -217, 0, 153, 1000}; -- The Boyahda Tree #1 homepoints[93] = { 3, 30, 182, 34, -62, 223, 160, 1000}; -- Den of Rancor #2 homepoints[94] = { 3, 31, 102, 0, 269, 191, 204, 1000}; -- Fei'Yin #2 homepoints[95] = { 3, 32, -63, 50, 81, 192, 205, 1000}; -- Ifrit's Cauldron #1 homepoints[96] = { 4, 1, 573, 9, -500, 0, 208, 1000}; -- Quicksand Caves #2 homepoints[97] = { 4, 2, -165, -1, 12, 65, 230, 500}; -- Southern San d'Oria #4 homepoints[98] = { 4, 3, -132, 12, 194, 170, 231, 500}; -- Northern San d'Oria #4 homepoints[99] = { 4, 4, 87, 7, 1, 0, 234, 500}; -- Bastok Mines #3 homepoints[100] = { 4, 5, -192, -6, -69, 0, 235, 500}; -- Bastok Markets #4 homepoints[101] = { 4, 6, -127, -6, 8, 206, 236, 500}; -- Port Bastok #3 homepoints[102] = { 4, 7, -76, 2, 3, 124, 237, 500}; -- Metalworks #2 homepoints[103] = { 4, 8, 5, -4, -175, 130, 238, 500}; -- Windurst Waters #3 homepoints[104] = { 4, 9, -65, -5, 54, 127, 252, 500}; -- Norg #2 homepoints[105] = { 4, 10, -21, 8, 110, 64, 247, 500}; -- Rabao #2 homepoints[106] = { 4, 11, 130, 0, -16, 0, 50, 500}; -- Aht Urhgan Whitegate #2 homepoints[107] = { 4, 12, -108, -6, 108, 192, 50, 500}; -- Aht Urhgan Whitegate #3 homepoints[108] = { 4, 13, -99, 0, -68, 0, 50, 500}; -- Aht Urhgan Whitegate #4 homepoints[109] = { 4, 14, 32, 0, -164, 32, 256, 500}; -- Western Adoulin #2 homepoints[110] = { 4, 15, -51, 0, -96, 96, 257, 500}; -- Eastern Adoulin #2 homepoints[111] = { 4, 16, 223, -13, -254, 0, 137, 1000}; -- Xarcabard [S] #1 homepoints[112] = { 4, 17, 5.539, -0.434, 8.133, 73, 281, 1000}; -- Leafallia #1 // on your right when you enter. homepoints[113] = { 4, 18, 66, -70, -554, 128, 155, 1000}; -- *Castle Zvahl Keep [S] #1 // same location as in the present homepoints[114] = { 4, 19, -65, -17.5, 563, 224, 25, 1000}; -- Misareaux Coast #1 homepoints[115] = { 4, 20, -212, -21, 93, 64, 126, 500}; -- Qufim Island #1 -- homepoints[116] = { 4, 21, 0, 0, 0, 0, 276, 1000}; -- Inner Ra'Kaznar #1 // next to the Sinister Reign NPC and Ra'Kaznar Turris local freeHpTeleGroups = { 1, 2, 3, 4, 5, 6, 7, 8}; freeHpTeleGroups[1] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 97, 98}; --San d'Oria freeHpTeleGroups[2] = { 9, 10, 11, 12 ,13, 14, 15, 16, 99, 100, 101, 102}; -- Bastok freeHpTeleGroups[3] = { 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 ,27 ,28, 103}; -- Windurst freeHpTeleGroups[4] = { 29, 30, 31, 32, 33, 34, 35, 36, 37, 38}; -- Jueno freeHpTeleGroups[5] = { 65, 106, 107, 108}; -- Aht Urghan freeHpTeleGroups[6] = { 44, 45, 109, 110}; -- Adoulin freeHpTeleGroups[7] = { 41, 104}; -- Norg freeHpTeleGroups[8] = { 42, 105}; -- Rabao function homepointMenu( player, csid, hpIndex) if ( HOMEPOINT_HEAL == 1) then player:addHP(player:getMaxHP()); player:addMP(player:getMaxMP()); end if ( HOMEPOINT_TELEPORT == 1) then if ( homepoints[hpIndex] == nil) then return; end -- Check for valid hpIndex player:setLocalVar("currentHpIndex", hpIndex + 1); local HpTeleportMask1 = bit.bor( bit.lshift( player:getVar("HpTeleportMask1a"), 16), player:getVar("HpTeleportMask1b")); local HpTeleportMask2 = bit.bor( bit.lshift( player:getVar("HpTeleportMask2a"), 16), player:getVar("HpTeleportMask2b")); local HpTeleportMask3 = bit.bor( bit.lshift( player:getVar("HpTeleportMask3a"), 16), player:getVar("HpTeleportMask3b")); local HpTeleportMask4 = bit.bor( bit.lshift( player:getVar("HpTeleportMask4a"), 16), player:getVar("HpTeleportMask4b")); -- Register new homepoint? local newHp = 0; if ( homepoints[hpIndex][1] == 1) then if ( bit.rshift( bit.lshift( HpTeleportMask1, 32 - homepoints[hpIndex][2]), 31) == 0) then newHp = 0x10000; -- This value causes the "You have registered a new home point!" dialog to display -- Update the homepoint teleport mask with the new location HpTeleportMask1 = bit.bor( HpTeleportMask1, bit.lshift( 1, homepoints[hpIndex][2] - 1)); -- Save new mask to database player:setVar("HpTeleportMask1a", bit.rshift( HpTeleportMask1, 16)); player:setVar("HpTeleportMask1b", bit.rshift( bit.lshift( HpTeleportMask1, 16), 16)); end elseif ( homepoints[hpIndex][1] == 2) then if ( bit.rshift( bit.lshift( HpTeleportMask2, 32 - homepoints[hpIndex][2]), 31) == 0) then newHp = 0x10000; HpTeleportMask2 = bit.bor( HpTeleportMask2, bit.lshift( 1, homepoints[hpIndex][2] - 1)); player:setVar("HpTeleportMask2a", bit.rshift( HpTeleportMask2, 16)); player:setVar("HpTeleportMask2b", bit.rshift( bit.lshift( HpTeleportMask2, 16), 16)); end elseif ( homepoints[hpIndex][1] == 3) then if ( bit.rshift( bit.lshift( HpTeleportMask3, 32 - homepoints[hpIndex][2]), 31) == 0) then newHp = 0x10000; HpTeleportMask3 = bit.bor( HpTeleportMask3, bit.lshift( 1, homepoints[hpIndex][2] - 1)); player:setVar("HpTeleportMask3a", bit.rshift( HpTeleportMask3, 16)); player:setVar("HpTeleportMask3b", bit.rshift( bit.lshift( HpTeleportMask3, 16), 16)); end elseif ( homepoints[hpIndex][1] == 4) then if ( bit.rshift( bit.lshift( HpTeleportMask4, 32 - homepoints[hpIndex][2]), 31) == 0) then newHp = 0x10000; HpTeleportMask4 = bit.bor( HpTeleportMask4, bit.lshift( 1, homepoints[hpIndex][2] - 1)); player:setVar("HpTeleportMask4a", bit.rshift( HpTeleportMask4, 16)); player:setVar("HpTeleportMask4b", bit.rshift( bit.lshift( HpTeleportMask4, 16), 16)); end end player:startEvent( csid, 0, HpTeleportMask1, HpTeleportMask2, HpTeleportMask3, HpTeleportMask4, player:getGil(), 4095, hpIndex + newHp); else player:PrintToPlayer( "Home point teleports are currently disabled on this server."); player:startEvent( csid, 0, 0, 0, 0, 0, player:getGil(), 4095, hpIndex); end end; function hpTeleport( player, option) if ( option == 2 or option > 0x10000 and option < 0x7F0003) then local hpIndex = bit.rshift( option, 16); -- Calculate hpIndex based on option selected local teleportCost = homepoints[hpIndex][8]; if ( freeHpTeleport( player, hpIndex)) then teleportCost = 0; end player:delGil(teleportCost); player:setLocalVar("currentHpIndex", 0); player:setPos( homepoints[hpIndex][3], homepoints[hpIndex][4], homepoints[hpIndex][5], homepoints[hpIndex][6], homepoints[hpIndex][7]); end end; function freeHpTeleport( player, hpIndex) local currentHpIndex = player:getLocalVar("currentHpIndex") - 1; for x = 1, 20 do if ( freeHpTeleGroups[x] ~= nil) then for y = 1, 20 do if ( freeHpTeleGroups[x][y] ~= nil) then if ( freeHpTeleGroups[x][y] == currentHpIndex) then for z = 1, 20 do if ( freeHpTeleGroups[x][z] ~= nil) then if ( freeHpTeleGroups[x][z] == hpIndex) then return true; end else break; end end end else break; end end else break; end end return false; end;
gpl-3.0
alalazo/wesnoth
data/lua/wml/role.lua
2
2840
local helper = wesnoth.require "helper" local utils = wesnoth.require "wml-utils" function wesnoth.wml_actions.role(cfg) -- role= and type= are handled differently than in other tags, -- so we need to remove them from the filter local role = cfg.role local filter = helper.shallow_literal(cfg) if role == nil then helper.wml_error("missing role= in [role]") end local types = {} if cfg.type then for value in utils.split(cfg.type) do table.insert(types, utils.trim(value)) end end filter.role, filter.type = nil, nil local search_map, search_recall, reassign = true, true, true if cfg.search_recall_list == "only" then search_map = false elseif cfg.search_recall_list ~= nil then search_recall = not not cfg.search_recall_list end if cfg.reassign ~= nil then reassign = not not cfg.reassign end -- pre-build a new [recall] from the [auto_recall] -- copy only recall-specific attributes, no SUF at all -- the SUF will be id= which we will add in a moment -- keep this in sync with the C++ recall function!!! local recall = nil local child = helper.get_child(cfg, "auto_recall") if child ~= nil then if helper.get_nth_child(cfg, "auto_recall", 2) ~= nil then wesnoth.log("debug", "More than one [auto_recall] found within [role]", true) end local original = helper.shallow_literal(child) recall = {} recall.x = original.x recall.y = original.y recall.show = original.show recall.fire_event = original.fire_event recall.check_passability = original.check_passability end if not reassign then if search_map then local unit = wesnoth.get_units{role=role}[1] if unit then return end end if recall and search_recall then local unit = wesnoth.get_recall_units{role=role}[1] if unit then recall.id = unit.id wesnoth.wml_actions.recall(recall) return end end end if search_map then -- first attempt to match units on the map local i = 1 repeat -- give precedence based on the order specified in type= if #types > 0 then filter.type = types[i] end local unit = wesnoth.get_units(filter)[1] if unit then unit.role = role return end i = i + 1 until #types == 0 or i > #types end if search_recall then -- then try to match units on the recall lists i = 1 repeat if #types > 0 then filter.type = types[i] end local unit = wesnoth.get_recall_units(filter)[1] if unit then unit.role = role if recall then recall.id = unit.id wesnoth.wml_actions.recall(recall) end return end i = i + 1 until #types == 0 or i > #types end -- no matching unit found, try the [else] tags for else_child in helper.child_range(cfg, "else") do local action = utils.handle_event_commands(else_child, "conditional") if action ~= "none" then return end end end
gpl-2.0
thedraked/darkstar
scripts/globals/items/holy_maul_+1.lua
41
1077
----------------------------------------- -- ID: 17114 -- Item: Holy Maul +1 -- Additional Effect: Light Damage ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 10; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(7,21); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_LIGHT, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHT,0); dmg = adjustForTarget(target,dmg,ELE_LIGHT); dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg); local message = MSGBASIC_ADD_EFFECT_DMG; if (dmg < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_LIGHT_DAMAGE,message,dmg; end end;
gpl-3.0
thedraked/darkstar
scripts/zones/Dynamis-Jeuno/Zone.lua
21
2379
----------------------------------- -- -- Zone: Dynamis-Jeuno -- ----------------------------------- package.loaded["scripts/zones/Dynamis-Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Dynamis-Jeuno/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaJeuno]UniqueID")) then if (player:isBcnmsFull() == 1) then if (player:hasStatusEffect(EFFECT_DYNAMIS, 0) == false) then inst = player:addPlayerToDynamis(1283); if (inst == 1) then player:bcnmEnter(1283); else cs = 0; end else player:bcnmEnter(1283); end else inst = player:bcnmRegister(1283); if (inst == 1) then player:bcnmEnter(1283); else cs = 0; end end else cs = 0; end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0) then player:setPos(48.930,10.002,-71.032,195,0xF3); end end;
gpl-3.0
mtroyka/Zero-K
scripts/spideraa.lua
11
4807
include "spider_walking.lua" include "constants.lua" -------------------------------------------------------------------------------- -- pieces -------------------------------------------------------------------------------- local base = piece 'base' local turret = piece 'turret' local barrel = piece 'barrel' local flare = piece 'flare' local leg1 = piece 'leg1' -- back right local leg2 = piece 'leg2' -- middle right local leg3 = piece 'leg3' -- front right local leg4 = piece 'leg4' -- back left local leg5 = piece 'leg5' -- middle left local leg6 = piece 'leg6' -- front left local smokePiece = {base, turret} -------------------------------------------------------------------------------- -- constants -------------------------------------------------------------------------------- -- Signal definitions local SIG_WALK = 1 local SIG_AIM = 2 local PERIOD = 0.17 local sleepTime = PERIOD*1000 local legRaiseAngle = math.rad(30) local legRaiseSpeed = legRaiseAngle/PERIOD local legLowerSpeed = legRaiseAngle/PERIOD local legForwardAngle = math.rad(20) local legForwardTheta = math.rad(45) local legForwardOffset = 0 local legForwardSpeed = legForwardAngle/PERIOD local legMiddleAngle = math.rad(20) local legMiddleTheta = 0 local legMiddleOffset = 0 local legMiddleSpeed = legMiddleAngle/PERIOD local legBackwardAngle = math.rad(20) local legBackwardTheta = -math.rad(45) local legBackwardOffset = 0 local legBackwardSpeed = legBackwardAngle/PERIOD local restore_delay = 3000 -- four-stroke hexapedal walkscript local function Walk() Signal(SIG_WALK) SetSignalMask(SIG_WALK) while true do walk(leg1, leg2, leg3, leg4, leg5, leg6, legRaiseAngle, legRaiseSpeed, legLowerSpeed, legForwardAngle, legForwardOffset, legForwardSpeed, legForwardTheta, legMiddleAngle, legMiddleOffset, legMiddleSpeed, legMiddleTheta, legBackwardAngle, legBackwardOffset, legBackwardSpeed, legBackwardTheta, sleepTime) end end local function RestoreLegs() Signal(SIG_WALK) SetSignalMask(SIG_WALK) restoreLegs(leg1, leg2, leg3, leg4, leg5, leg6, legRaiseSpeed, legForwardSpeed, legMiddleSpeed,legBackwardSpeed) end function script.Create() StartThread(SmokeUnit, smokePiece) end function script.StartMoving() StartThread(Walk) end function script.StopMoving() StartThread(RestoreLegs) end local function RestoreAfterDelay() Sleep(restore_delay) Turn(turret, y_axis, 0, math.rad(90)) Turn(barrel, x_axis, 0, math.rad(90)) end function script.AimWeapon(num, heading, pitch) Signal(SIG_AIM) SetSignalMask(SIG_AIM) Turn(turret, y_axis, heading, math.rad(450)) Turn(barrel, x_axis, math.max(-pitch - math.rad(15), -math.rad(90)), math.rad(180)) WaitForTurn(turret, y_axis) WaitForTurn(barrel, x_axis) StartThread(RestoreAfterDelay) return true end function script.AimFromWeapon(num) return turret end function script.BlockShot(num, targetID) if Spring.ValidUnitID(targetID) then local distMult = (Spring.GetUnitSeparation(unitID, targetID) or 0)/1000 return GG.OverkillPrevention_CheckBlock(unitID, targetID, 220.1, 75 * distMult) end return false end function script.QueryWeapon(num) return flare end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity <= .25 then Explode(barrel, sfxNone) Explode(base, sfxNone) Explode(leg1, sfxNone) Explode(leg2, sfxNone) Explode(leg3, sfxNone) Explode(leg4, sfxNone) Explode(leg5, sfxNone) Explode(leg6, sfxNone) Explode(turret, sfxNone) return 1 elseif severity <= .50 then Explode(barrel, sfxFall) Explode(base, sfxNone) Explode(leg1, sfxFall) Explode(leg2, sfxFall) Explode(leg3, sfxFall) Explode(leg4, sfxFall) Explode(leg5, sfxFall) Explode(leg6, sfxFall) Explode(turret, sfxShatter) return 1 elseif severity <= .99 then Explode(barrel, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(base, sfxNone) Explode(leg1, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg2, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg3, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg4, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg5, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg6, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(turret, sfxShatter) return 2 else Explode(barrel, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(base, sfxNone) Explode(leg1, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg2, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg3, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg4, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg5, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(leg6, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(turret, sfxShatter + sfxExplode) return 2 end end
gpl-2.0
Devul/DarkRP
gamemode/libraries/disjointset.lua
11
1972
/*--------------------------------------------------------------------------- Disjoint-set forest implementation Inspired by the book Introduction To Algorithms (third edition) by FPtje Atheos Running time per operation (Union/FindSet): O(a(n)) where a is the inverse of the Ackermann function. ---------------------------------------------------------------------------*/ local pairs = pairs local setmetatable = setmetatable local string = string local table = table local tostring = tostring module("disjoint") local metatable -- Make a singleton set. Parent parameter is optional, must be a disjoint-set as well. function MakeSet(x, parent) local set = {} set.value = x set.rank = 0 set.parent = parent or set setmetatable(set, metatable) return set end local function Link(x, y) if x == y then return x end -- Union by rank if x.rank > y.rank then y.parent = x return x end x.parent = y if x.rank == y.rank then y.rank = y.rank + 1 end return y end -- Apply the union operation between two sets. function Union(x, y) return Link(FindSet(x), FindSet(y)) end function FindSet(x) local parent = x local listParents -- Go up the tree to find the parent while parent ~= parent.parent do parent = parent.parent listParents = listParents or {} table.insert(listParents, parent) end -- Path compression, update all parents to refer to the top parent if listParents then for k,v in pairs(listParents) do v.parent = parent end end return parent end function Disconnect(x) x.parent = x return x end metatable = { __tostring = function(self) return string.format("Disjoint-Set [value: %s][Rank: %s][Parent: %s]", tostring(self.value), self.rank, tostring(self.parent.value)) end, __metatable = true, -- restrict access to metatable __add = Union }
mit
thedraked/darkstar
scripts/zones/Port_San_dOria/npcs/Ambleon.lua
14
1059
----------------------------------- -- Area: Port San d'Oria -- NPC: Ambleon -- Type: NPC World Pass Dealer -- @zone 232 -- @pos 71.622 -17 -137.134 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x02c6); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
NPLPackages/main
script/ide/System/Encoding/base64.lua
1
2740
--[[ Title: base64 Author(s): LiXizhi Desc: Use Lib: ------------------------------------------------------- NPL.load("(gl)script/ide/System/Encoding/base64.lua"); local Encoding = commonlib.gettable("System.Encoding"); assert(Encoding.base64("hello world")=="aGVsbG8gd29ybGQ="); assert(Encoding.unbase64("aGVsbG8gd29ybGQ=")=="hello world"); ------------------------------------------------------- ]] NPL.load("(gl)script/ide/math/bit.lua"); local Encoding = commonlib.gettable("System.Encoding"); -- encoding function Encoding.base64(data) return ParaMisc.base64(data) end -- decoding function Encoding.unbase64(data) return ParaMisc.unbase64(data) end if(not ParaMisc.base64 or not ParaMisc.unbase64) then log("warning: C++ version of base64 or unbase64 not available. Default to script implementation. \n"); local string_char = string.char; local bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; local endings = { '', '==', '=' }; local function enc1(x) local r,b='',x:byte() for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end return r; end local function enc2(x) if (#x < 6) then return '' end local c=0 for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end return bytes:sub(c+1, c+1); end -- encoding function Encoding.base64(data) return ((data:gsub('.', enc1)..'0000'):gsub('%d%d%d?%d?%d?%d?', enc2)..endings[#data%3+1]) end local ibytes = { ['A'] = 00, ['B'] = 01, ['C'] = 02, ['D'] = 03, ['E'] = 04, ['F'] = 05, ['G'] = 06, ['H'] = 07, ['I'] = 08, ['J'] = 09, ['K'] = 10, ['L'] = 11, ['M'] = 12, ['N'] = 13, ['O'] = 14, ['P'] = 15, ['Q'] = 16, ['R'] = 17, ['S'] = 18, ['T'] = 19, ['U'] = 20, ['V'] = 21, ['W'] = 22, ['X'] = 23, ['Y'] = 24, ['Z'] = 25, ['a'] = 26, ['b'] = 27, ['c'] = 28, ['d'] = 29, ['e'] = 30, ['f'] = 31, ['g'] = 32, ['h'] = 33, ['i'] = 34, ['j'] = 35, ['k'] = 36, ['l'] = 37, ['m'] = 38, ['n'] = 39, ['o'] = 40, ['p'] = 41, ['q'] = 42, ['r'] = 43, ['s'] = 44, ['t'] = 45, ['u'] = 46, ['v'] = 47, ['w'] = 48, ['x'] = 49, ['y'] = 50, ['z'] = 51, ['0'] = 52, ['1'] = 53, ['2'] = 54, ['3'] = 55, ['4'] = 56, ['5'] = 57, ['6'] = 58, ['7'] = 59, ['8'] = 60, ['9'] = 61, ['+'] = 62, ['/'] = 63, ['='] = 64 } local function dec1(x) if (x == '=') then return '' end local r,f='', ibytes[x]; for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end return r; end local function dec2(x) if (#x ~= 8) then return '' end local c=0 for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end return string_char(c) end -- decoding function Encoding.unbase64(data) data = data:gsub('[^'..bytes..'=]', '') return (data:gsub('.', dec1):gsub('%d%d%d?%d?%d?%d?%d?%d?', dec2)) end end
gpl-2.0
thedraked/darkstar
scripts/globals/mobskills/Necrobane.lua
43
1075
--------------------------------------------- -- Necrobane --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if(mob:getFamily() == 316) then local mobSkin = mob:getModelId(); if (mobSkin == 1839) then return 0; else return 1; end end if(mob:getFamily() == 91) then local mobSkin = mob:getModelId(); if (mobSkin == 1840) then return 0; else return 1; end end return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded); target:delHP(dmg); MobStatusEffectMove(mob, target, EFFECT_CURSE_I, 1, 0, 60); return dmg; end;
gpl-3.0
thedraked/darkstar
scripts/zones/Kazham/npcs/Mamerie.lua
17
1410
----------------------------------- -- Area: Kazham -- NPC: Mamerie -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,MAMERIE_SHOP_DIALOG); stock = {0x11C1,62, -- Gysahl Greens 0x0348,7, -- Chocobo Feather 0x4278,11, -- Pet Food Alpha Biscuit 0x4279,82, -- Pet Food Beta Biscuit 0x45C4,82, -- Carrot Broth 0x45C6,695, -- Bug Broth 0x45C8,126, -- Herbal Broth 0x45CA,695, -- Carrion Broth 0x13D1,50784} -- Scroll of Chocobo Mazurka showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
mtroyka/Zero-K
units/shiparty.lua
2
3415
unitDef = { unitname = [[shiparty]], name = [[Ronin]], description = [[Cruiser (Artillery)]], acceleration = 0.0417, activateWhenBuilt = true, brakeRate = 0.142, buildCostEnergy = 850, buildCostMetal = 850, builder = false, buildPic = [[shiparty.png]], buildTime = 850, canAttack = true, canMove = true, category = [[SHIP]], collisionVolumeOffsets = [[0 1 3]], collisionVolumeScales = [[32 32 132]], collisionVolumeType = [[cylZ]], corpse = [[DEAD]], customParams = { helptext = [[This Cruiser packs a powerful, long-range artillery cannon, useful for bombarding fixed emplacements and shore targets. Beware of aircraft, submarines and raider ships.]], --extradrawrange = 200, modelradius = [[55]], turnatfullspeed = [[1]], }, explodeAs = [[BIG_UNITEX]], floater = true, footprintX = 4, footprintZ = 4, iconType = [[shiparty]], idleAutoHeal = 5, idleTime = 1800, losEmitHeight = 25, maxDamage = 3000, maxVelocity = 1.7, minCloakDistance = 75, minWaterDepth = 10, movementClass = [[BOAT4]], noChaseCategory = [[TERRAFORM FIXEDWING GUNSHIP TOOFAST]], objectName = [[shiparty.s3o]], script = [[shiparty.lua]], seismicSignature = 4, selfDestructAs = [[BIG_UNITEX]], sightDistance = 660, sonarDistance = 660, turninplace = 0, turnRate = 350, waterline = 0, weapons = { { def = [[PLASMA]], badTargetCategory = [[GUNSHIP]], onlyTargetCategory = [[SWIM LAND SHIP SINK TURRET FLOAT GUNSHIP HOVER]], }, }, weaponDefs = { PLASMA = { name = [[Plasma Cannon]], areaOfEffect = 96, avoidFeature = false, avoidGround = false, craterBoost = 1, craterMult = 2, damage = { default = 601.1, planes = 601.1, subs = 30, }, explosionGenerator = [[custom:PLASMA_HIT_96]], impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, myGravity = 0.1, projectiles = 1, range = 1200, reloadtime = 4, soundHit = [[weapon/cannon/cannon_hit2]], soundStart = [[weapon/cannon/heavy_cannon]], turret = true, weaponType = [[Cannon]], weaponVelocity = 400, }, }, featureDefs = { DEAD = { blocking = false, featureDead = [[HEAP]], footprintX = 4, footprintZ = 4, object = [[shiparty_dead.s3o]], }, HEAP = { blocking = false, footprintX = 4, footprintZ = 4, object = [[debris4x4b.s3o]], }, }, } return lowerkeys({ shiparty = unitDef })
gpl-2.0
thedraked/darkstar
scripts/zones/Nashmau/npcs/Fhe_Maksojha.lua
14
2276
----------------------------------- -- Area: Nashmau -- NPC: Fhe Maksojha -- Type: Standard NPC -- @pos 19.084 -7 71.287 53 ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Nashmau/TextIDs"); ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local notmeanttobe = player:getQuestStatus(AHT_URHGAN,NOT_MEANT_TO_BE); local notMeantToBeProg = player:getVar("notmeanttobeCS"); if (notmeanttobe == QUEST_AVAILABLE) then player:startEvent(0x0125); elseif (notMeantToBeProg == 1) then player:startEvent(0x0127); elseif (notMeantToBeProg == 2) then player:startEvent(0x0126); elseif (notMeantToBeProg == 3) then player:startEvent(0x0128); elseif (notMeantToBeProg == 5) then player:startEvent(0x0129); elseif (notmeanttobe == QUEST_COMPLETED) then player:startEvent(0x012a); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0125) then player:setVar("notmeanttobeCS",1); player:addQuest(AHT_URHGAN,NOT_MEANT_TO_BE); elseif (csid == 0x0126) then player:setVar("notmeanttobeCS",3); elseif (csid == 0x0129) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINEDX,2187,3); else player:setVar("notmeanttobeCS",0); player:addItem(2187,3); player:messageSpecial(ITEM_OBTAINEDX,2187,3); player:completeQuest(AHT_URHGAN,NOT_MEANT_TO_BE); end end end;
gpl-3.0
thedraked/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Gavrie.lua
17
1534
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Gavrie -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,GAVRIE_SHOP_DIALOG); stock = {0x1036,2595, -- Eye Drops 0x1034,316, -- Antidote 0x1037,800, -- Echo Drops 0x1010,910, -- Potion 0x1020,4832, -- Ether 0x103B,3360, -- Remedy 0x119D,12, -- Distilled Water 0x492B,50, -- Automaton Oil 0x492C,250, -- Automaton Oil +1 0x492D,500, -- Automaton Oil +2 0x4AF1,1000} -- Automaton Oil +3 showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
thedraked/darkstar
scripts/zones/Dynamis-Valkurm/Zone.lua
7
2472
----------------------------------- -- -- Zone: Dynamis-Valkurm -- ----------------------------------- package.loaded["scripts/zones/Dynamis-Valkurm/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Dynamis-Valkurm/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaValkurm]UniqueID")) then if (player:isBcnmsFull() == 1) then if (player:hasStatusEffect(EFFECT_DYNAMIS, 0) == false) then inst = player:addPlayerToDynamis(1286); if (inst == 1) then player:bcnmEnter(1286); else cs = 0x0065; end else player:bcnmEnter(1286); end else inst = player:bcnmRegister(1286); if (inst == 1) then player:bcnmEnter(1286); else cs = 0x0065; end end else cs = 0x0065; end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0065) then player:setPos(117,-9,132,162,103); end end;
gpl-3.0
X-Coder/wire
lua/entities/gmod_wire_sensor.lua
10
6626
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Beacon Sensor" ENT.WireDebugName = "Beacon Sensor" if CLIENT then return end -- No more client local MODEL = Model( "models/props_lab/huladoll.mdl" ) function ENT:Initialize() self:SetModel( MODEL ) self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = Wire_CreateInputs(self, { "Target" }) self.Outputs = Wire_CreateOutputs(self, { "Out" }) end function ENT:Setup(xyz_mode, outdist, outbrng, gpscord, direction_vector, direction_normalized, target_velocity, velocity_normalized) if !xyz_mode and !outdist and !outbrng and !gpscord and !direction_vector and !target_velocity then outdist = true end self.xyz_mode = xyz_mode self.PrevOutput = nil self.Value = 0 self.outdist = outdist self.outbrng = outbrng self.gpscord = gpscord self.direction_vector = direction_vector self.direction_normalized = direction_normalized self.target_velocity = target_velocity self.velocity_normalized = velocity_normalized local onames = {} if (outdist) then table.insert(onames, "Distance") end if (xyz_mode) then table.insert(onames, "X") table.insert(onames, "Y") table.insert(onames, "Z") end if (outbrng) then table.insert(onames, "Bearing") table.insert(onames, "Elevation") end if (gpscord) then table.insert(onames, "World_X") table.insert(onames, "World_Y") table.insert(onames, "World_Z") end if (direction_vector) then table.insert(onames, "Direction_X") table.insert(onames, "Direction_Y") table.insert(onames, "Direction_Z") end if (target_velocity) then table.insert(onames, "Velocity_X") table.insert(onames, "Velocity_Y") table.insert(onames, "Velocity_Z") end Wire_AdjustOutputs(self, onames) self:TriggerOutputs(0, Angle(0, 0, 0),Vector(0, 0, 0),Vector(0, 0, 0),Vector(0, 0, 0),Vector(0,0,0)) self:ShowOutput() end function ENT:Think() self.BaseClass.Think(self) if not IsValid(self.ToSense) or not self.ToSense.GetBeaconPos then return end if (self.Active) then local dist = 0 local distc = Vector(0,0,0); local brng = Angle(0,0,0); local velo = Vector(0,0,0); local gpscords = Vector(0,0,0); local dirvec = Vector(0,0,0); local MyPos = self:GetPos() //local BeaconPos = self.Inputs["Target"].Src:GetBeaconPos(self) local BeaconPos = self.ToSense:GetBeaconPos(self) or MyPos if (self.outdist) then dist = (BeaconPos-MyPos):Length() end if (self.xyz_mode) then local DeltaPos = self:WorldToLocal(BeaconPos) distc = Vector(-DeltaPos.y,DeltaPos.x,DeltaPos.z) end if (self.outbrng) then local DeltaPos = self:WorldToLocal(BeaconPos) brng = DeltaPos:Angle() end if (self.gpscord) then gpscords = BeaconPos end if (self.direction_vector) then dirvec = BeaconPos - MyPos; if(self.direction_normalized) then dirvec:Normalize() end; end; if (self.target_velocity) then velo = self.ToSense:GetBeaconVelocity(self); if(self.velocity_normalized) then velo:Normalize() end; end self:TriggerOutputs(dist, brng, distc, gpscords,dirvec,velo) self:ShowOutput() self:NextThink(CurTime()+0.04) return true end end function ENT:ShowOutput() local txt = "" if (self.outdist) then txt = string.format("%s\nDistance = %.3f", txt, self.Outputs.Distance.Value) end if (self.xyz_mode) then txt = string.format("%s\nOffset = %.3f, %.3f, %.3f", txt, self.Outputs.X.Value, self.Outputs.Y.Value, self.Outputs.Z.Value) end if (self.outbrng) then txt = string.format("%s\nBearing = %.3f, %.3f", txt, self.Outputs.Bearing.Value, self.Outputs.Elevation.Value) end if (self.gpscord) then txt = string.format("%s\nWorldPos = %.3f, %.3f, %.3f", txt, self.Outputs.World_X.Value, self.Outputs.World_Y.Value, self.Outputs.World_Z.Value) end if (self.direction_vector) then txt = string.format("%s\nDirectionVector = %.3f, %.3f, %.3f", txt, self.Outputs.Direction_X.Value, self.Outputs.Direction_Y.Value, self.Outputs.Direction_Z.Value) end if (self.target_velocity) then txt = string.format("%s\nTargetVelocity = %.3f, %.3f, %.3f", txt, self.Outputs.Velocity_X.Value, self.Outputs.Velocity_Y.Value, self.Outputs.Velocity_Z.Value) end self:SetOverlayText(string.Right(txt,#txt-1)) -- Cut off the first \n end function ENT:TriggerOutputs(dist, brng, distc, gpscords,dirvec,velo) if (self.outdist) then Wire_TriggerOutput(self, "Distance", dist) end if (self.xyz_mode) then Wire_TriggerOutput(self, "X", distc.x) Wire_TriggerOutput(self, "Y", distc.y) Wire_TriggerOutput(self, "Z", distc.z) end if (self.gpscord) then Wire_TriggerOutput(self, "World_X", gpscords.x) Wire_TriggerOutput(self, "World_Y", gpscords.y) Wire_TriggerOutput(self, "World_Z", gpscords.z) end if (self.outbrng) then local pitch = brng.p local yaw = brng.y if (pitch > 180) then pitch = pitch - 360 end if (yaw > 180) then yaw = yaw - 360 end Wire_TriggerOutput(self, "Bearing", -yaw) Wire_TriggerOutput(self, "Elevation", -pitch) end if(self.direction_vector) then Wire_TriggerOutput(self, "Direction_X", dirvec.x) Wire_TriggerOutput(self, "Direction_Y", dirvec.y) Wire_TriggerOutput(self, "Direction_Z", dirvec.z) end if(self.target_velocity) then Wire_TriggerOutput(self, "Velocity_X", velo.x) Wire_TriggerOutput(self, "Velocity_Y", velo.y) Wire_TriggerOutput(self, "Velocity_Z", velo.z) end end function ENT:TriggerInput(iname, value) if (iname == "Target") and ( self.ToSense != self.Inputs.Target.Src ) then self:LinkEnt(self.Inputs.Target.Src) end end function ENT:LinkEnt(beacon) if IsValid(beacon) and beacon.GetBeaconPos then self.ToSense = beacon self.Active = true WireLib.SendMarks(self, {beacon}) return true else self:UnlinkEnt() return false, "Must link to ent that outputs BeaconPos" end end function ENT:UnlinkEnt(ent) self.ToSense = nil self.Active = false WireLib.SendMarks(self, {}) return true end duplicator.RegisterEntityClass("gmod_wire_sensor", WireLib.MakeWireEnt, "Data", "xyz_mode", "outdist", "outbrng", "gpscord", "direction_vector", "direction_normalized", "target_velocity", "velocity_normalized") function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} if IsValid(self.ToSense) then info.to_sense = self.ToSense:EntIndex() end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) self:LinkEnt(GetEntByID(info.to_sense)) end
gpl-3.0
mtroyka/Zero-K
LuaRules/Gadgets/unit_jumpjet_pilot_2.lua
11
4195
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if (not gadgetHandler:IsSyncedCode()) then return false end function gadget:GetInfo() return { name = "Jumpjet Pilot 2014", desc = "Steers leapers 2014", author = "xponen, quantum (code from Jumpjet Pilot but use Spring pathing)", date = "January 28, 2014", license = "GNU GPL, v2 or later", layer = 0, enabled = false -- loaded by default? } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- include("LuaRules/Configs/customcmds.h.lua") VFS.Include("LuaRules/Utilities/isTargetReachable.lua") local spRequestPath = Spring.RequestPath local leaperDefID = UnitDefNames.chicken_leaper.id local gridSize = math.floor(350/2) local leapersCommand local noRecursion = false gridSize = tonumber(UnitDefNames["chicken_leaper"].customParams.jump_range) function Dist(x,y,z, x2, y2, z2) local xd = x2-x local yd = y2-y local zd = z2-z return math.sqrt(xd*xd + yd*yd + zd*zd) end function gadget:AllowCommand_GetWantedCommand() return true end function gadget:AllowCommand_GetWantedUnitDefID() return {[leaperDefID] = true} end function gadget:AllowCommand(unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOptions, cmdTag, synced) if noRecursion then return true end if unitDefID == leaperDefID and (cmdID == CMD.MOVE or cmdID == CMD.FIGHT) then local startX, startZ, startY if cmdOptions.shift then -- queue, use last queue position local queue = Spring.GetCommandQueue(unitID, -1) for i=#queue, 1, -1 do if #(queue[i].params) == 3 then -- todo: be less lazy startX,startY, startZ = queue[i].params[1], queue[i].params[2], queue[i].params[3] break end end end if not startX or not startZ then startX, startY, startZ = Spring.GetUnitPosition(unitID) end if (Spring.GetUnitIsDead(unitID)) then return false; end local waypoints local moveID = UnitDefs[unitDefID].moveDef.id if moveID then --unit has compatible moveID? local minimumGoalDist = 8 local result, lastwaypoint result, lastwaypoint, waypoints = Spring.Utilities.IsTargetReachable( moveID,startX,startY,startZ,cmdParams[1],cmdParams[2],cmdParams[3],minimumGoalDist) end if waypoints then --we have waypoint to destination? leapersCommand = leapersCommand or {} leapersCommand[unitID] = {} if not cmdOptions.shift then leapersCommand[unitID][1] = {CMD.STOP, {}, {}} end local d = 0 local way1,way2,way3 = startX,startY,startZ local idx = #leapersCommand[unitID]+1 for i=1, #waypoints do --sum all distance in waypoints d = d + Dist(way1,way2,way3, waypoints[i][1],waypoints[i][2],waypoints[i][3]) way1,way2,way3 = waypoints[i][1],waypoints[i][2],waypoints[i][3] if d >= gridSize then leapersCommand[unitID][idx] = {CMD_JUMP, {waypoints[i][1],waypoints[i][2],waypoints[i][3]}, {"shift"}} idx = idx + 1 leapersCommand[unitID][idx] = {CMD.FIGHT, {waypoints[i][1],waypoints[i][2],waypoints[i][3]}, {"shift"}} idx = idx + 1 d = 0 end end leapersCommand[unitID][idx] = {CMD_JUMP, {way1, way2, way3}, {"shift"}} idx = idx + 1 leapersCommand[unitID][idx] = {CMD.FIGHT, {way1, way2, way3}, {"shift"}} idx = idx + 1 leapersCommand[unitID][idx] = {CMD_JUMP, {cmdParams[1], cmdParams[2], cmdParams[3]}, {"shift"}} else -- if the computed path shows "no path found" (false), abort leapersCommand = leapersCommand or {} leapersCommand[unitID] = {[1]={CMD.STOP, {}, cmdOptions.shift and {"shift"} or {}}} return false; end return false -- reject original command, we're handling it end return true -- other order end function gadget:GameFrame(frame) if leapersCommand then noRecursion = true for unitID,ordersArray in pairs(leapersCommand) do if not Spring.GetUnitIsDead(unitID) then Spring.GiveOrderArrayToUnitArray({unitID},ordersArray) end end noRecursion = false leapersCommand = nil end end
gpl-2.0
thedraked/darkstar
scripts/zones/Upper_Jeuno/npcs/Monberaux.lua
14
5908
----------------------------------- -- Area: Upper Jeuno -- NPC: Monberaux -- Starts and Finishes Quest: The Lost Cardian (finish), The kind cardian (start) -- Involved in Quests: Save the Clock Tower -- @pos -43 0 -1 244 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(555,1) == true and trade:getItemCount() == 1) then a = player:getVar("saveTheClockTowerNPCz1"); -- NPC Part1 if (a == 0 or (a ~= 4 and a ~= 5 and a ~= 6 and a ~= 12 and a ~= 20 and a ~= 7 and a ~= 28 and a ~= 13 and a ~= 22 and a ~= 14 and a ~= 21 and a ~= 15 and a ~= 23 and a ~= 29 and a ~= 30 and a ~= 31)) then player:startEvent(0x005b,10 - player:getVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TheLostCardien = player:getQuestStatus(JEUNO,THE_LOST_CARDIAN); local CooksPride = player:getQuestStatus(JEUNO,COOK_S_PRIDE); -- COP mission 1-1 if (player:getCurrentMission(COP) == THE_RITES_OF_LIFE and player:getVar("PromathiaStatus") == 1) then player:startEvent(0x000a);--10 -- COP mission 1-2 elseif (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x0009);--9 -- COP mission 3-5 elseif (player:getCurrentMission(COP) == DARKNESS_NAMED and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x0052);-- 82 elseif (player:getCurrentMission(COP) == DARKNESS_NAMED and player:getVar("PromathiaStatus") == 3) then player:startEvent(0x004B); --75 elseif (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 2) then player:startEvent(0x004A); --74 elseif (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 4) then player:startEvent(0x0006); elseif (CooksPride == QUEST_COMPLETED and TheLostCardien == QUEST_AVAILABLE and player:getVar("theLostCardianVar") == 2) then player:startEvent(0x0021); -- Long CS & Finish Quest "The Lost Cardian" 33 elseif (CooksPride == QUEST_COMPLETED and TheLostCardien == QUEST_AVAILABLE and player:getVar("theLostCardianVar") == 3) then player:startEvent(0x0022); -- Shot CS & Finish Quest "The Lost Cardian" 34 elseif (TheLostCardien == QUEST_COMPLETED and player:getQuestStatus(JEUNO,THE_KIND_CARDIAN) == QUEST_ACCEPTED) then player:startEvent(0x0020); -- 32 else player:startEvent(0x001c); -- Standard dialog 28 end end; --Door:Infirmary 2 ++ --Door:Infirmary 10 ++ --Door:Infirmary 207 ++ --Door:Infirmary 82 ++ --Door:Infirmary 10059 nonCOP --Door:Infirmary 10060 nonCOP --Door:Infirmary 10205 nonCOP --Door:Infirmary 10061 nonCOP --Door:Infirmary 10062 nonCOP --Door:Infirmary 10207 nonCOP --Door:Infirmary 33 ++ --Door:Infirmary 34 ++ --Door:Infirmary 2 ++ --Door:Infirmary 82 ++ --Door:Infirmary 75 ++ --Door:Infirmary 10060 nonCOP --Door:Infirmary 10205 nonCOP --Tenzen 10011 --Tenzen 10012 ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0006) then player:setVar("COP_Tenzen_s_Path",5); elseif (csid == 0x004a) then player:setVar("COP_Tenzen_s_Path",3); player:addKeyItem(ENVELOPE_FROM_MONBERAUX); player:messageSpecial(KEYITEM_OBTAINED,ENVELOPE_FROM_MONBERAUX); elseif (csid == 0x000a) then player:setVar("PromathiaStatus",0); player:addKeyItem(MYSTERIOUS_AMULET_DRAINED); player:completeMission(COP,THE_RITES_OF_LIFE); player:addMission(COP,BELOW_THE_ARKS); -- start the mission 1-2 player:startEvent(0x00cf); --207 elseif (csid == 0x0052) then player:setVar("PromathiaStatus",1); elseif (csid == 0x004B) then player:setVar("PromathiaStatus",0); player:completeMission(COP,DARKNESS_NAMED); player:addMission(COP,SHELTERING_DOUBT); elseif (csid == 0x005b) then player:setVar("saveTheClockTowerVar",player:getVar("saveTheClockTowerVar") + 1); player:setVar("saveTheClockTowerNPCz1",player:getVar("saveTheClockTowerNPCz1") + 4); elseif (csid == 0x0021 and option == 0 or csid == 0x0022 and option == 0) then player:addTitle(TWOS_COMPANY); player:setVar("theLostCardianVar",0); player:addGil(GIL_RATE*2100); player:messageSpecial(GIL_OBTAINED,GIL_RATE*2100); player:addKeyItem(TWO_OF_SWORDS); player:messageSpecial(KEYITEM_OBTAINED,TWO_OF_SWORDS); -- Two of Swords (Key Item) player:addFame(JEUNO,30); player:completeQuest(JEUNO,THE_LOST_CARDIAN); player:addQuest(JEUNO,THE_KIND_CARDIAN); -- Start next quest "THE_KING_CARDIAN" elseif (csid == 0x0021 and option == 1) then player:setVar("theLostCardianVar",3); end end;
gpl-3.0
NPLPackages/main
script/sqlite/lunit.lua
1
18237
--[[ use the lib: ------------------------------------------------------------ NPL.load("(gl)script/sqlite/lunit.lua"); ------------------------------------------------------------ ]] --[[-------------------------------------------------------------------------- This file is part of lunit 0.4pre (alpha). For Details about lunit look at: http://www.nessie.de/mroth/lunit/ Author: Michael Roth <mroth@nessie.de> Copyright (c) 2004 Michael Roth <mroth@nessie.de> 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. --]]-------------------------------------------------------------------------- ----------------------- -- Intialize package -- ----------------------- local P = { } lunit = P -- Import local type = type local print = print local ipairs = ipairs local pairs = pairs local string = string local table = table local pcall = pcall local xpcall = xpcall local traceback = debug.traceback local error = error local setmetatable = setmetatable local rawset = rawset local orig_assert = assert local getfenv = getfenv local setfenv = setfenv local tostring = tostring -- Start package scope setfenv(1, P) -------------------------------- -- Private data and functions -- -------------------------------- local run_testcase local do_assert, check_msg local stats = { } local testcases = { } local stats_inc, tc_mt -------------------------- -- Type check functions -- -------------------------- function is_nil(x) return type(x) == "nil" end function is_boolean(x) return type(x) == "boolean" end function is_number(x) return type(x) == "number" end function is_string(x) return type(x) == "string" end function is_table(x) return type(x) == "table" end function is_function(x) return type(x) == "function" end function is_thread(x) return type(x) == "thread" end function is_userdata(x) return type(x) == "userdata" end ---------------------- -- Assert functions -- ---------------------- function assert(assertion, msg) stats_inc("assertions") check_msg("assert", msg) do_assert(not not assertion, "assertion failed (was: "..tostring(assertion)..")", msg) -- (convert assertion to bool) return assertion end function assert_fail(msg) stats_inc("assertions") check_msg("assert_fail", msg) do_assert(false, "failure", msg) end function assert_true(actual, msg) stats_inc("assertions") check_msg("assert_true", msg) do_assert(is_boolean(actual), "true expected but was a "..type(actual), msg) do_assert(actual == true, "true expected but was false", msg) return actual end function assert_false(actual, msg) stats_inc("assertions") check_msg("assert_false", msg) do_assert(is_boolean(actual), "false expected but was a "..type(actual), msg) do_assert(actual == false, "false expected but was true", msg) return actual end function assert_equal(expected, actual, msg) stats_inc("assertions") check_msg("assert_equal", msg) do_assert(expected == actual, "expected '"..tostring(expected).."' but was '"..tostring(actual).."'", msg) return actual end function assert_not_equal(unexpected, actual, msg) stats_inc("assertions") check_msg("assert_not_equal", msg) do_assert(unexpected ~= actual, "'"..tostring(expected).."' not expected but was one", msg) return actual end function assert_match(pattern, actual, msg) stats_inc("assertions") check_msg("assert_match", msg) do_assert(is_string(pattern), "assert_match expects the pattern as a string") do_assert(is_string(actual), "expected a string to match pattern '"..pattern.."' but was a '"..type(actual).."'", msg) do_assert(not not string.find(actual, pattern), "expected '"..actual.."' to match pattern '"..pattern.."' but doesn't", msg) return actual end function assert_not_match(pattern, actual, msg) stats_inc("assertions") check_msg("assert_not_match", msg) do_assert(is_string(actual), "expected a string to not match pattern '"..pattern.."' but was a '"..type(actual).."'", msg) do_assert(string.find(actual, pattern) == nil, "expected '"..actual.."' to not match pattern '"..pattern.."' but it does", msg) return actual end function assert_nil(actual, msg) stats_inc("assertions") check_msg("assert_nil", msg) do_assert(is_nil(actual), "nil expected but was a "..type(actual), msg) return actual end function assert_not_nil(actual, msg) stats_inc("assertions") check_msg("assert_not_nil", msg) do_assert(not is_nil(actual), "nil not expected but was one", msg) return actual end function assert_boolean(actual, msg) stats_inc("assertions") check_msg("assert_boolean", msg) do_assert(is_boolean(actual), "boolean expected but was a "..type(actual), msg) return actual end function assert_not_boolean(actual, msg) stats_inc("assertions") check_msg("assert_not_boolean", msg) do_assert(not is_boolean(actual), "boolean not expected but was one", msg) return actual end function assert_number(actual, msg) stats_inc("assertions") check_msg("assert_number", msg) do_assert(is_number(actual), "number expected but was a "..type(actual), msg) return actual end function assert_not_number(actual, msg) stats_inc("assertions") check_msg("assert_not_number", msg) do_assert(not is_number(actual), "number not expected but was one", msg) return actual end function assert_string(actual, msg) stats_inc("assertions") check_msg("assert_string", msg) do_assert(is_string(actual), "string expected but was a "..type(actual), msg) return actual end function assert_not_string(actual, msg) stats_inc("assertions") check_msg("assert_not_string", msg) do_assert(not is_string(actual), "string not expected but was one", msg) return actual end function assert_table(actual, msg) stats_inc("assertions") check_msg("assert_table", msg) do_assert(is_table(actual), "table expected but was a "..type(actual), msg) return actual end function assert_not_table(actual, msg) stats_inc("assertions") check_msg("assert_not_table", msg) do_assert(not is_table(actual), "table not expected but was one", msg) return actual end function assert_function(actual, msg) stats_inc("assertions") check_msg("assert_function", msg) do_assert(is_function(actual), "function expected but was a "..type(actual), msg) return actual end function assert_not_function(actual, msg) stats_inc("assertions") check_msg("assert_not_function", msg) do_assert(not is_function(actual), "function not expected but was one", msg) return actual end function assert_thread(actual, msg) stats_inc("assertions") check_msg("assert_thread", msg) do_assert(is_thread(actual), "thread expected but was a "..type(actual), msg) return actual end function assert_not_thread(actual, msg) stats_inc("assertions") check_msg("assert_not_thread", msg) do_assert(not is_thread(actual), "thread not expected but was one", msg) return actual end function assert_userdata(actual, msg) stats_inc("assertions") check_msg("assert_userdata", msg) do_assert(is_userdata(actual), "userdata expected but was a "..type(actual), msg) return actual end function assert_not_userdata(actual, msg) stats_inc("assertions") check_msg("assert_not_userdata", msg) do_assert(not is_userdata(actual), "userdata not expected but was one", msg) return actual end function assert_error(msg, func) stats_inc("assertions") if is_nil(func) then func, msg = msg, nil end check_msg("assert_error", msg) do_assert(is_function(func), "assert_error expects a function as the last argument but it was a "..type(func)) local ok, errmsg = pcall(func) do_assert(ok == false, "error expected but no error occurred", msg) end function assert_pass(msg, func) stats_inc("assertions") if is_nil(func) then func, msg = msg, nil end check_msg("assert_pass", msg) do_assert(is_function(func), "assert_pass expects a function as the last argument but it was a "..type(func)) local ok, errmsg = pcall(func) if not ok then do_assert(ok == true, "no error expected but error was: "..errmsg, msg) end end ----------------------------------------------------------- -- Assert implementation that assumes it was called from -- -- lunit code which was called directly from user code. -- ----------------------------------------------------------- function do_assert(assertion, base_msg, user_msg) orig_assert(is_boolean(assertion)) orig_assert(is_string(base_msg)) orig_assert(is_string(user_msg) or is_nil(user_msg)) if not assertion then if user_msg then error(base_msg..": "..user_msg, 3) else error(base_msg.."!", 3) end end end ------------------------------------------- -- Checks the msg argument in assert_xxx -- ------------------------------------------- function check_msg(name, msg) orig_assert(is_string(name)) if not (is_nil(msg) or is_string(msg)) then error("lunit."..name.."() expects the optional message as a string but it was a "..type(msg).."!" ,3) end end ------------------------------------- -- Creates a new TestCase 'Object' -- ------------------------------------- function TestCase(name) do_assert(is_string(name), "lunit.TestCase() needs a string as an argument") local tc = { __lunit_name = name; __lunit_setup = nil; __lunit_tests = { }; __lunit_teardown = nil; } setmetatable(tc, tc_mt) table.insert(testcases, tc) return tc end tc_mt = { __newindex = function(tc, key, value) rawset(tc, key, value) if is_string(key) and is_function(value) then local name = string.lower(key) if string.find(name, "^test") or string.find(name, "test$") then table.insert(tc.__lunit_tests, key) elseif name == "setup" then tc.__lunit_setup = value elseif name == "teardown" then tc.__lunit_teardown = value end end end } ----------------------------------------- -- Wrap Functions in a TestCase object -- ----------------------------------------- function wrap(name, ...) local arg = {...}; if is_function(name) then table.insert(arg, 1, name) name = "Anonymous Testcase" end local tc = TestCase(name) for index, test in ipairs(arg) do tc["Test #"..index] = test end return tc end ---------------------------------- -- Runs the complete Test Suite -- ---------------------------------- function run() --------------------------- -- Initialize statistics -- --------------------------- stats.testcases = 0 -- Total number of Test Cases stats.tests = 0 -- Total number of all Tests in all Test Cases stats.run = 0 -- Number of Tests run stats.notrun = 0 -- Number of Tests not run stats.failed = 0 -- Number of Tests failed stats.warnings = 0 -- Number of Warnings (teardown) stats.errors = 0 -- Number of Errors (setup) stats.passed = 0 -- Number of Test passed stats.assertions = 0 -- Number of all assertions made in all Test in all Test Cases -------------------------------- -- Count Test Cases and Tests -- -------------------------------- stats.testcases = table.getn(testcases) for _, tc in ipairs(testcases) do stats_inc("tests" , table.getn(tc.__lunit_tests)) end ------------------ -- Print Header -- ------------------ print() print("#### Test Suite with "..stats.tests.." Tests in "..stats.testcases.." Test Cases loaded.") ------------------------ -- Run all Test Cases -- ------------------------ for _, tc in ipairs(testcases) do run_testcase(tc) end ------------------ -- Print Footer -- ------------------ print() print("#### Test Suite finished.") local msg_assertions = stats.assertions.." Assertions checked. " local msg_passed = stats.passed == stats.tests and "All Tests passed" or stats.passed.." Tests passed" local msg_failed = stats.failed > 0 and ", "..stats.failed.." failed" or "" local msg_run = stats.notrun > 0 and ", "..stats.notrun.." not run" or "" local msg_warn = stats.warnings > 0 and ", "..stats.warnings.." warnings" or "" print() print(msg_assertions..msg_passed..msg_failed..msg_run..msg_warn.."!") ----------------- -- Return code -- ----------------- if stats.passed == stats.tests then return 0 else return 1 end end ----------------------------- -- Runs a single Test Case -- ----------------------------- function run_testcase(tc) orig_assert(is_table(tc)) orig_assert(is_table(tc.__lunit_tests)) orig_assert(is_string(tc.__lunit_name)) orig_assert(is_nil(tc.__lunit_setup) or is_function(tc.__lunit_setup)) orig_assert(is_nil(tc.__lunit_teardown) or is_function(tc.__lunit_teardown)) ---------------------------------- -- Protected call to a function -- ---------------------------------- local function call(errprefix, func) orig_assert(is_string(errprefix)) orig_assert(is_function(func)) local ok, errmsg = xpcall(function() func(tc) end, traceback) if not ok then print() print(errprefix..": "..errmsg) end return ok end ------------------------------------ -- Calls setup() on the Test Case -- ------------------------------------ local function setup(testname) if tc.__lunit_setup then return call("ERROR: "..testname..": setup() failed", tc.__lunit_setup) else return true end end ------------------------------------------ -- Calls a single Test on the Test Case -- ------------------------------------------ local function run(testname) orig_assert(is_string(testname)) orig_assert(is_function(tc[testname])) local ok = call("FAIL: "..testname, tc[testname]) if not ok then stats_inc("failed") else stats_inc("passed") end return ok end --------------------------------------- -- Calls teardown() on the Test Case -- --------------------------------------- local function teardown(testname) if tc.__lunit_teardown then if not call("WARNING: "..testname..": teardown() failed", tc.__lunit_teardown) then stats_inc("warnings") end end end --------------------------------- -- Run all Tests on a TestCase -- --------------------------------- print() print("#### Running '"..tc.__lunit_name.."' ("..table.getn(tc.__lunit_tests).." Tests)...") for _, testname in ipairs(tc.__lunit_tests) do if setup(testname) then run(testname) stats_inc("run") teardown(testname) else print("WARN: Skipping '"..testname.."'...") stats_inc("notrun") end end end --------------------- -- Import function -- --------------------- function import(name) do_assert(is_string(name), "lunit.import() expects a single string as argument") local user_env = getfenv(2) -------------------------------------------------- -- Installs a specific function in the user env -- -------------------------------------------------- local function install(funcname) user_env[funcname] = P[funcname] end ---------------------------------------------------------- -- Install functions matching a pattern in the user env -- ---------------------------------------------------------- local function install_pattern(pattern) for funcname, _ in pairs(P) do if string.find(funcname, pattern) then install(funcname) end end end ------------------------------------------------------------ -- Installs assert() and all assert_xxx() in the user env -- ------------------------------------------------------------ local function install_asserts() install_pattern("^assert.*") end ------------------------------------------- -- Installs all is_xxx() in the user env -- ------------------------------------------- local function install_tests() install_pattern("^is_.+") end if name == "asserts" or name == "assertions" then install_asserts() elseif name == "tests" or name == "checks" then install_tests() elseif name == "all" then install_asserts() install_tests() install("TestCase") elseif string.find(name, "^assert.*") and P[name] then install(name) elseif string.find(name, "^is_.+") and P[name] then install(name) elseif name == "TestCase" then install("TestCase") else error("luniit.import(): invalid function '"..name.."' to import", 2) end end -------------------------------------------------- -- Installs a private environment on the caller -- -------------------------------------------------- function setprivfenv() local new_env = { } local new_env_mt = { __index = getfenv(2) } setmetatable(new_env, new_env_mt) setfenv(2, new_env) end -------------------------------------------------- -- Increments a counter in the statistics table -- -------------------------------------------------- function stats_inc(varname, value) orig_assert(is_table(stats)) orig_assert(is_string(varname)) orig_assert(is_nil(value) or is_number(value)) if not stats[varname] then return end stats[varname] = stats[varname] + (value or 1) end
gpl-2.0
rjeli/luvit
tests/test-instanceof.lua
14
1312
--[[ Copyright 2014 The Luvit Authors. 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 core = require("core") local Object = core.Object local Emitter = core.Emitter local instanceof = core.instanceof require('tap')(function (test) test("test instanceof", function() local o = Object:new() local e = Emitter:new() assert(instanceof(o, Object)) assert(not instanceof(o, Emitter)) assert(instanceof(e, Emitter)) assert(instanceof(e, Object)) assert(not instanceof({}, Object)) assert(not instanceof(2, Object)) assert(not instanceof('a', Object)) assert(not instanceof(function() end, Object)) -- Caveats: We would like to these to be false, but we could not. assert(instanceof(Object, Object)) assert(instanceof(Emitter, Object)) end) end)
apache-2.0
SnabbCo/snabbswitch
lib/ljsyscall/syscall/freebsd/constants.lua
6
31735
-- tables of constants for NetBSD local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string, select = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string, select local abi = require "syscall.abi" local h = require "syscall.helpers" local bit = require "syscall.bit" local octal, multiflags, charflags, swapflags, strflag, atflag, modeflags = h.octal, h.multiflags, h.charflags, h.swapflags, h.strflag, h.atflag, h.modeflags local version = require "syscall.freebsd.version".version local ffi = require "ffi" local function charp(n) return ffi.cast("char *", n) end local c = {} c.errornames = require "syscall.freebsd.errors" c.STD = strflag { IN_FILENO = 0, OUT_FILENO = 1, ERR_FILENO = 2, IN = 0, OUT = 1, ERR = 2, } c.PATH_MAX = 1024 c.E = strflag { PERM = 1, NOENT = 2, SRCH = 3, INTR = 4, IO = 5, NXIO = 6, ["2BIG"] = 7, NOEXEC = 8, BADF = 9, CHILD = 10, DEADLK = 11, NOMEM = 12, ACCES = 13, FAULT = 14, NOTBLK = 15, BUSY = 16, EXIST = 17, XDEV = 18, NODEV = 19, NOTDIR = 20, ISDIR = 21, INVAL = 22, NFILE = 23, MFILE = 24, NOTTY = 25, TXTBSY = 26, FBIG = 27, NOSPC = 28, SPIPE = 29, ROFS = 30, MLINK = 31, PIPE = 32, DOM = 33, RANGE = 34, AGAIN = 35, INPROGRESS = 36, ALREADY = 37, NOTSOCK = 38, DESTADDRREQ = 39, MSGSIZE = 40, PROTOTYPE = 41, NOPROTOOPT = 42, PROTONOSUPPORT= 43, SOCKTNOSUPPORT= 44, OPNOTSUPP = 45, PFNOSUPPORT = 46, AFNOSUPPORT = 47, ADDRINUSE = 48, ADDRNOTAVAIL = 49, NETDOWN = 50, NETUNREACH = 51, NETRESET = 52, CONNABORTED = 53, CONNRESET = 54, NOBUFS = 55, ISCONN = 56, NOTCONN = 57, SHUTDOWN = 58, TOOMANYREFS = 59, TIMEDOUT = 60, CONNREFUSED = 61, LOOP = 62, NAMETOOLONG = 63, HOSTDOWN = 64, HOSTUNREACH = 65, NOTEMPTY = 66, PROCLIM = 67, USERS = 68, DQUOT = 69, STALE = 70, REMOTE = 71, BADRPC = 72, BADRPC = 72, RPCMISMATCH = 73, PROGUNAVAIL = 74, PROGMISMATCH = 75, PROCUNAVAIL = 76, NOLCK = 77, NOSYS = 78, FTYPE = 79, AUTH = 80, NEEDAUTH = 81, IDRM = 82, NOMSG = 83, OVERFLOW = 84, CANCELED = 85, ILSEQ = 86, NOATTR = 87, DOOFUS = 88, BADMSG = 89, MULTIHOP = 90, NOLINK = 91, PROTO = 92, NOTCAPABLE = 93, CAPMODE = 94, } if version >= 10 then c.E.NOTRECOVERABLE= 95 c.E.OWNERDEAD = 96 end -- alternate names c.EALIAS = { WOULDBLOCK = c.E.AGAIN, } c.AF = strflag { UNSPEC = 0, LOCAL = 1, INET = 2, IMPLINK = 3, PUP = 4, CHAOS = 5, NETBIOS = 6, ISO = 7, ECMA = 8, DATAKIT = 9, CCITT = 10, SNA = 11, DECNET = 12, DLI = 13, LAT = 14, HYLINK = 15, APPLETALK = 16, ROUTE = 17, LINK = 18, -- #define pseudo_AF_XTP 19 COIP = 20, CNT = 21, -- #define pseudo_AF_RTIP 22 IPX = 23, SIP = 24, -- pseudo_AF_PIP 25 ISDN = 26, -- pseudo_AF_KEY 27 INET6 = 28, NATM = 29, ATM = 30, -- pseudo_AF_HDRCMPLT 31 NETGRAPH = 32, SLOW = 33, SCLUSTER = 34, ARP = 35, BLUETOOTH = 36, IEEE80211 = 37, } c.AF.UNIX = c.AF.LOCAL c.AF.OSI = c.AF.ISO c.AF.E164 = c.AF.ISDN if version >= 10 then c.AF.INET_SDP = 40 c.AF.INET6_SDP = 42 end c.O = multiflags { RDONLY = 0x0000, WRONLY = 0x0001, RDWR = 0x0002, ACCMODE = 0x0003, NONBLOCK = 0x0004, APPEND = 0x0008, SHLOCK = 0x0010, EXLOCK = 0x0020, ASYNC = 0x0040, FSYNC = 0x0080, SYNC = 0x0080, NOFOLLOW = 0x0100, CREAT = 0x0200, TRUNC = 0x0400, EXCL = 0x0800, NOCTTY = 0x8000, DIRECT = 0x00010000, DIRECTORY = 0x00020000, EXEC = 0x00040000, TTY_INIT = 0x00080000, CLOEXEC = 0x00100000, } -- for pipe2, selected flags from c.O c.OPIPE = multiflags { NONBLOCK = 0x0004, CLOEXEC = 0x00100000, } -- sigaction, note renamed SIGACT from SIG_ c.SIGACT = strflag { ERR = -1, DFL = 0, IGN = 1, HOLD = 3, } c.SIGEV = strflag { NONE = 0, SIGNAL = 1, THREAD = 2, KEVENT = 3, THREAD_ID = 4, } c.SIG = strflag { HUP = 1, INT = 2, QUIT = 3, ILL = 4, TRAP = 5, ABRT = 6, EMT = 7, FPE = 8, KILL = 9, BUS = 10, SEGV = 11, SYS = 12, PIPE = 13, ALRM = 14, TERM = 15, URG = 16, STOP = 17, TSTP = 18, CONT = 19, CHLD = 20, TTIN = 21, TTOU = 22, IO = 23, XCPU = 24, XFSZ = 25, VTALRM = 26, PROF = 27, WINCH = 28, INFO = 29, USR1 = 30, USR2 = 31, THR = 32, } if version >=10 then c.SIG.LIBRT = 33 end c.SIG.LWP = c.SIG.THR c.EXIT = strflag { SUCCESS = 0, FAILURE = 1, } c.OK = charflags { F = 0, X = 0x01, W = 0x02, R = 0x04, } c.MODE = modeflags { SUID = octal('04000'), SGID = octal('02000'), STXT = octal('01000'), RWXU = octal('00700'), RUSR = octal('00400'), WUSR = octal('00200'), XUSR = octal('00100'), RWXG = octal('00070'), RGRP = octal('00040'), WGRP = octal('00020'), XGRP = octal('00010'), RWXO = octal('00007'), ROTH = octal('00004'), WOTH = octal('00002'), XOTH = octal('00001'), } c.SEEK = strflag { SET = 0, CUR = 1, END = 2, DATA = 3, HOLE = 4, } c.SOCK = multiflags { STREAM = 1, DGRAM = 2, RAW = 3, RDM = 4, SEQPACKET = 5, } if version >= 10 then c.SOCK.CLOEXEC = 0x10000000 c.SOCK.NONBLOCK = 0x20000000 end c.SOL = strflag { SOCKET = 0xffff, } c.POLL = multiflags { IN = 0x0001, PRI = 0x0002, OUT = 0x0004, RDNORM = 0x0040, RDBAND = 0x0080, WRBAND = 0x0100, INIGNEOF = 0x2000, ERR = 0x0008, HUP = 0x0010, NVAL = 0x0020, } c.POLL.WRNORM = c.POLL.OUT c.POLL.STANDARD = c.POLL["IN,PRI,OUT,RDNORM,RDBAND,WRBAND,ERR,HUP,NVAL"] c.AT_FDCWD = atflag { FDCWD = -100, } c.AT = multiflags { EACCESS = 0x100, SYMLINK_NOFOLLOW = 0x200, SYMLINK_FOLLOW = 0x400, REMOVEDIR = 0x800, } c.S_I = modeflags { FMT = octal('0170000'), FWHT = octal('0160000'), FSOCK = octal('0140000'), FLNK = octal('0120000'), FREG = octal('0100000'), FBLK = octal('0060000'), FDIR = octal('0040000'), FCHR = octal('0020000'), FIFO = octal('0010000'), SUID = octal('0004000'), SGID = octal('0002000'), SVTX = octal('0001000'), STXT = octal('0001000'), RWXU = octal('00700'), RUSR = octal('00400'), WUSR = octal('00200'), XUSR = octal('00100'), RWXG = octal('00070'), RGRP = octal('00040'), WGRP = octal('00020'), XGRP = octal('00010'), RWXO = octal('00007'), ROTH = octal('00004'), WOTH = octal('00002'), XOTH = octal('00001'), } c.S_I.READ = c.S_I.RUSR c.S_I.WRITE = c.S_I.WUSR c.S_I.EXEC = c.S_I.XUSR c.PROT = multiflags { NONE = 0x0, READ = 0x1, WRITE = 0x2, EXEC = 0x4, } c.MAP = multiflags { SHARED = 0x0001, PRIVATE = 0x0002, FILE = 0x0000, FIXED = 0x0010, RENAME = 0x0020, NORESERVE = 0x0040, RESERVED0080 = 0x0080, RESERVED0100 = 0x0100, HASSEMAPHORE = 0x0200, STACK = 0x0400, NOSYNC = 0x0800, ANON = 0x1000, NOCORE = 0x00020000, -- TODO add aligned maps in } if abi.abi64 and version >= 10 then c.MAP["32BIT"] = 0x00080000 end c.MCL = strflag { CURRENT = 0x01, FUTURE = 0x02, } -- flags to `msync'. - note was MS_ renamed to MSYNC_ c.MSYNC = multiflags { SYNC = 0x0000, ASYNC = 0x0001, INVALIDATE = 0x0002, } c.MADV = strflag { NORMAL = 0, RANDOM = 1, SEQUENTIAL = 2, WILLNEED = 3, DONTNEED = 4, FREE = 5, NOSYNC = 6, AUTOSYNC = 7, NOCORE = 8, CORE = 9, PROTECT = 10, } c.IPPROTO = strflag { IP = 0, HOPOPTS = 0, ICMP = 1, IGMP = 2, GGP = 3, IPV4 = 4, IPIP = 4, TCP = 6, ST = 7, EGP = 8, PIGP = 9, RCCMON = 10, NVPII = 11, PUP = 12, ARGUS = 13, EMCON = 14, XNET = 15, CHAOS = 16, UDP = 17, MUX = 18, MEAS = 19, HMP = 20, PRM = 21, IDP = 22, TRUNK1 = 23, TRUNK2 = 24, LEAF1 = 25, LEAF2 = 26, RDP = 27, IRTP = 28, TP = 29, BLT = 30, NSP = 31, INP = 32, SEP = 33, ["3PC"] = 34, IDPR = 35, XTP = 36, DDP = 37, CMTP = 38, TPXX = 39, IL = 40, IPV6 = 41, SDRP = 42, ROUTING = 43, FRAGMENT = 44, IDRP = 45, RSVP = 46, GRE = 47, MHRP = 48, BHA = 49, ESP = 50, AH = 51, INLSP = 52, SWIPE = 53, NHRP = 54, MOBILE = 55, TLSP = 56, SKIP = 57, ICMPV6 = 58, NONE = 59, DSTOPTS = 60, AHIP = 61, CFTP = 62, HELLO = 63, SATEXPAK = 64, KRYPTOLAN = 65, RVD = 66, IPPC = 67, ADFS = 68, SATMON = 69, VISA = 70, IPCV = 71, CPNX = 72, CPHB = 73, WSN = 74, PVP = 75, BRSATMON = 76, ND = 77, WBMON = 78, WBEXPAK = 79, EON = 80, VMTP = 81, SVMTP = 82, VINES = 83, TTP = 84, IGP = 85, DGP = 86, TCF = 87, IGRP = 88, OSPFIGP = 89, SRPC = 90, LARP = 91, MTP = 92, AX25 = 93, IPEIP = 94, MICP = 95, SCCSP = 96, ETHERIP = 97, ENCAP = 98, APES = 99, GMTP = 100, IPCOMP = 108, SCTP = 132, MH = 135, PIM = 103, CARP = 112, PGM = 113, MPLS = 137, PFSYNC = 240, RAW = 255, } c.SCM = multiflags { RIGHTS = 0x01, TIMESTAMP = 0x02, CREDS = 0x03, BINTIME = 0x04, } c.F = strflag { DUPFD = 0, GETFD = 1, SETFD = 2, GETFL = 3, SETFL = 4, GETOWN = 5, SETOWN = 6, OGETLK = 7, OSETLK = 8, OSETLKW = 9, DUP2FD = 10, GETLK = 11, SETLK = 12, SETLKW = 13, SETLK_REMOTE= 14, READAHEAD = 15, RDAHEAD = 16, DUPFD_CLOEXEC= 17, DUP2FD_CLOEXEC= 18, } c.FD = multiflags { CLOEXEC = 1, } -- note changed from F_ to FCNTL_LOCK c.FCNTL_LOCK = strflag { RDLCK = 1, UNLCK = 2, WRLCK = 3, UNLCKSYS = 4, CANCEL = 5, } -- lockf, changed from F_ to LOCKF_ c.LOCKF = strflag { ULOCK = 0, LOCK = 1, TLOCK = 2, TEST = 3, } -- for flock (2) c.LOCK = multiflags { SH = 0x01, EX = 0x02, NB = 0x04, UN = 0x08, } c.W = multiflags { NOHANG = 1, UNTRACED = 2, CONTINUED = 4, NOWAIT = 8, EXITED = 16, TRAPPED = 32, LINUXCLONE = 0x80000000, } c.W.STOPPED = c.W.UNTRACED -- waitpid and wait4 pid c.WAIT = strflag { ANY = -1, MYPGRP = 0, } c.MSG = multiflags { OOB = 0x1, PEEK = 0x2, DONTROUTE = 0x4, EOR = 0x8, TRUNC = 0x10, CTRUNC = 0x20, WAITALL = 0x40, DONTWAIT = 0x80, EOF = 0x100, NOTIFICATION = 0x2000, NBIO = 0x4000, COMPAT = 0x8000, NOSIGNAL = 0x20000, } if version >= 10 then c.MSG.CMSG_CLOEXEC = 0x40000 end c.PC = strflag { LINK_MAX = 1, MAX_CANON = 2, MAX_INPUT = 3, NAME_MAX = 4, PATH_MAX = 5, PIPE_BUF = 6, CHOWN_RESTRICTED = 7, NO_TRUNC = 8, VDISABLE = 9, ALLOC_SIZE_MIN = 10, FILESIZEBITS = 12, REC_INCR_XFER_SIZE= 14, REC_MAX_XFER_SIZE = 15, REC_MIN_XFER_SIZE = 16, REC_XFER_ALIGN = 17, SYMLINK_MAX = 18, MIN_HOLE_SIZE = 21, ASYNC_IO = 53, PRIO_IO = 54, SYNC_IO = 55, ACL_EXTENDED = 59, ACL_PATH_MAX = 60, CAP_PRESENT = 61, INF_PRESENT = 62, MAC_PRESENT = 63, ACL_NFS4 = 64, } -- getpriority, setpriority flags c.PRIO = strflag { PROCESS = 0, PGRP = 1, USER = 2, MIN = -20, -- TODO useful to have for other OSs MAX = 20, } c.RUSAGE = strflag { SELF = 0, CHILDREN = -1, THREAD = 1, } c.SOMAXCONN = 128 c.SO = strflag { DEBUG = 0x0001, ACCEPTCONN = 0x0002, REUSEADDR = 0x0004, KEEPALIVE = 0x0008, DONTROUTE = 0x0010, BROADCAST = 0x0020, USELOOPBACK = 0x0040, LINGER = 0x0080, OOBINLINE = 0x0100, REUSEPORT = 0x0200, TIMESTAMP = 0x0400, NOSIGPIPE = 0x0800, ACCEPTFILTER = 0x1000, BINTIME = 0x2000, NO_OFFLOAD = 0x4000, NO_DDP = 0x8000, SNDBUF = 0x1001, RCVBUF = 0x1002, SNDLOWAT = 0x1003, RCVLOWAT = 0x1004, SNDTIMEO = 0x1005, RCVTIMEO = 0x1006, ERROR = 0x1007, TYPE = 0x1008, LABEL = 0x1009, PEERLABEL = 0x1010, LISTENQLIMIT = 0x1011, LISTENQLEN = 0x1012, LISTENINCQLEN= 0x1013, SETFIB = 0x1014, USER_COOKIE = 0x1015, PROTOCOL = 0x1016, } c.SO.PROTOTYPE = c.SO.PROTOCOL c.DT = strflag { UNKNOWN = 0, FIFO = 1, CHR = 2, DIR = 4, BLK = 6, REG = 8, LNK = 10, SOCK = 12, WHT = 14, } c.IP = strflag { OPTIONS = 1, HDRINCL = 2, TOS = 3, TTL = 4, RECVOPTS = 5, RECVRETOPTS = 6, RECVDSTADDR = 7, RETOPTS = 8, MULTICAST_IF = 9, MULTICAST_TTL = 10, MULTICAST_LOOP = 11, ADD_MEMBERSHIP = 12, DROP_MEMBERSHIP = 13, MULTICAST_VIF = 14, RSVP_ON = 15, RSVP_OFF = 16, RSVP_VIF_ON = 17, RSVP_VIF_OFF = 18, PORTRANGE = 19, RECVIF = 20, IPSEC_POLICY = 21, FAITH = 22, ONESBCAST = 23, BINDANY = 24, FW_TABLE_ADD = 40, FW_TABLE_DEL = 41, FW_TABLE_FLUSH = 42, FW_TABLE_GETSIZE = 43, FW_TABLE_LIST = 44, FW3 = 48, DUMMYNET3 = 49, FW_ADD = 50, FW_DEL = 51, FW_FLUSH = 52, FW_ZERO = 53, FW_GET = 54, FW_RESETLOG = 55, FW_NAT_CFG = 56, FW_NAT_DEL = 57, FW_NAT_GET_CONFIG = 58, FW_NAT_GET_LOG = 59, DUMMYNET_CONFIGURE = 60, DUMMYNET_DEL = 61, DUMMYNET_FLUSH = 62, DUMMYNET_GET = 64, RECVTTL = 65, MINTTL = 66, DONTFRAG = 67, RECVTOS = 68, ADD_SOURCE_MEMBERSHIP = 70, DROP_SOURCE_MEMBERSHIP = 71, BLOCK_SOURCE = 72, UNBLOCK_SOURCE = 73, } c.IP.SENDSRCADDR = c.IP.RECVDSTADDR -- Baud rates just the identity function other than EXTA, EXTB c.B = strflag { EXTA = 19200, EXTB = 38400, } c.CC = strflag { VEOF = 0, VEOL = 1, VEOL2 = 2, VERASE = 3, VWERASE = 4, VKILL = 5, VREPRINT = 6, VINTR = 8, VQUIT = 9, VSUSP = 10, VDSUSP = 11, VSTART = 12, VSTOP = 13, VLNEXT = 14, VDISCARD = 15, VMIN = 16, VTIME = 17, VSTATUS = 18, } c.IFLAG = multiflags { IGNBRK = 0x00000001, BRKINT = 0x00000002, IGNPAR = 0x00000004, PARMRK = 0x00000008, INPCK = 0x00000010, ISTRIP = 0x00000020, INLCR = 0x00000040, IGNCR = 0x00000080, ICRNL = 0x00000100, IXON = 0x00000200, IXOFF = 0x00000400, IXANY = 0x00000800, IMAXBEL = 0x00002000, } c.OFLAG = multiflags { OPOST = 0x00000001, ONLCR = 0x00000002, OXTABS = 0x00000004, ONOEOT = 0x00000008, OCRNL = 0x00000010, ONOCR = 0x00000020, ONLRET = 0x00000040, } c.CFLAG = multiflags { CIGNORE = 0x00000001, CSIZE = 0x00000300, CS5 = 0x00000000, CS6 = 0x00000100, CS7 = 0x00000200, CS8 = 0x00000300, CSTOPB = 0x00000400, CREAD = 0x00000800, PARENB = 0x00001000, PARODD = 0x00002000, HUPCL = 0x00004000, CLOCAL = 0x00008000, CCTS_OFLOW = 0x00010000, CRTS_IFLOW = 0x00020000, CDTR_IFLOW = 0x00040000, CDSR_OFLOW = 0x00080000, CCAR_OFLOW = 0x00100000, } c.CFLAG.CRTSCTS = c.CFLAG.CCTS_OFLOW + c.CFLAG.CRTS_IFLOW c.LFLAG = multiflags { ECHOKE = 0x00000001, ECHOE = 0x00000002, ECHOK = 0x00000004, ECHO = 0x00000008, ECHONL = 0x00000010, ECHOPRT = 0x00000020, ECHOCTL = 0x00000040, ISIG = 0x00000080, ICANON = 0x00000100, ALTWERASE = 0x00000200, IEXTEN = 0x00000400, EXTPROC = 0x00000800, TOSTOP = 0x00400000, FLUSHO = 0x00800000, NOKERNINFO = 0x02000000, PENDIN = 0x20000000, NOFLSH = 0x80000000, } c.TCSA = multiflags { -- this is another odd one, where you can have one flag plus SOFT NOW = 0, DRAIN = 1, FLUSH = 2, SOFT = 0x10, } -- tcflush(), renamed from TC to TCFLUSH c.TCFLUSH = strflag { IFLUSH = 1, OFLUSH = 2, IOFLUSH = 3, } -- termios - tcflow() and TCXONC use these. renamed from TC to TCFLOW c.TCFLOW = strflag { OOFF = 1, OON = 2, IOFF = 3, ION = 4, } -- for chflags and stat. note these have no prefix c.CHFLAGS = multiflags { UF_NODUMP = 0x00000001, UF_IMMUTABLE = 0x00000002, UF_APPEND = 0x00000004, UF_OPAQUE = 0x00000008, UF_NOUNLINK = 0x00000010, SF_ARCHIVED = 0x00010000, SF_IMMUTABLE = 0x00020000, SF_APPEND = 0x00040000, SF_NOUNLINK = 0x00100000, SF_SNAPSHOT = 0x00200000, } c.CHFLAGS.IMMUTABLE = c.CHFLAGS.UF_IMMUTABLE + c.CHFLAGS.SF_IMMUTABLE c.CHFLAGS.APPEND = c.CHFLAGS.UF_APPEND + c.CHFLAGS.SF_APPEND c.CHFLAGS.OPAQUE = c.CHFLAGS.UF_OPAQUE c.CHFLAGS.NOUNLINK = c.CHFLAGS.UF_NOUNLINK + c.CHFLAGS.SF_NOUNLINK if version >=10 then c.CHFLAGS.UF_SYSTEM = 0x00000080 c.CHFLAGS.UF_SPARSE = 0x00000100 c.CHFLAGS.UF_OFFLINE = 0x00000200 c.CHFLAGS.UF_REPARSE = 0x00000400 c.CHFLAGS.UF_ARCHIVE = 0x00000800 c.CHFLAGS.UF_READONLY = 0x00001000 c.CHFLAGS.UF_HIDDEN = 0x00008000 end c.TCP = strflag { NODELAY = 1, MAXSEG = 2, NOPUSH = 4, NOOPT = 8, MD5SIG = 16, INFO = 32, CONGESTION = 64, KEEPINIT = 128, KEEPIDLE = 256, KEEPINTVL = 512, KEEPCNT = 1024, } c.RB = multiflags { AUTOBOOT = 0, ASKNAME = 0x001, SINGLE = 0x002, NOSYNC = 0x004, HALT = 0x008, INITNAME = 0x010, DFLTROOT = 0x020, KDB = 0x040, RDONLY = 0x080, DUMP = 0x100, MINIROOT = 0x200, VERBOSE = 0x800, SERIAL = 0x1000, CDROM = 0x2000, POWEROFF = 0x4000, GDB = 0x8000, MUTE = 0x10000, SELFTEST = 0x20000, RESERVED1 = 0x40000, RESERVED2 = 0x80000, PAUSE = 0x100000, MULTIPLE = 0x20000000, BOOTINFO = 0x80000000, } -- kqueue c.EV = multiflags { ADD = 0x0001, DELETE = 0x0002, ENABLE = 0x0004, DISABLE = 0x0008, ONESHOT = 0x0010, CLEAR = 0x0020, RECEIPT = 0x0040, DISPATCH = 0x0080, SYSFLAGS = 0xF000, FLAG1 = 0x2000, EOF = 0x8000, ERROR = 0x4000, } if version >= 10 then c.EV.DROP = 0x1000 end c.EVFILT = strflag { READ = -1, WRITE = -2, AIO = -3, VNODE = -4, PROC = -5, SIGNAL = -6, TIMER = -7, FS = -9, LIO = -10, USER = -11, SYSCOUNT = 11, } c.NOTE = multiflags { -- user FFNOP = 0x00000000, FFAND = 0x40000000, FFOR = 0x80000000, FFCOPY = 0xc0000000, FFCTRLMASK = 0xc0000000, FFLAGSMASK = 0x00ffffff, TRIGGER = 0x01000000, -- read and write LOWAT = 0x0001, -- vnode DELETE = 0x0001, WRITE = 0x0002, EXTEND = 0x0004, ATTRIB = 0x0008, LINK = 0x0010, RENAME = 0x0020, REVOKE = 0x0040, -- proc EXIT = 0x80000000, FORK = 0x40000000, EXEC = 0x20000000, PCTRLMASK = 0xf0000000, PDATAMASK = 0x000fffff, TRACK = 0x00000001, TRACKERR = 0x00000002, CHILD = 0x00000004, } c.SHM = strflag { ANON = charp(1), } c.PD = multiflags { DAEMON = 0x00000001, } c.ITIMER = strflag { REAL = 0, VIRTUAL = 1, PROF = 2, } c.SA = multiflags { ONSTACK = 0x0001, RESTART = 0x0002, RESETHAND = 0x0004, NOCLDSTOP = 0x0008, NODEFER = 0x0010, NOCLDWAIT = 0x0020, SIGINFO = 0x0040, } -- ipv6 sockopts c.IPV6 = strflag { SOCKOPT_RESERVED1 = 3, UNICAST_HOPS = 4, MULTICAST_IF = 9, MULTICAST_HOPS = 10, MULTICAST_LOOP = 11, JOIN_GROUP = 12, LEAVE_GROUP = 13, PORTRANGE = 14, --ICMP6_FILTER = 18, -- not namespaced as IPV6 CHECKSUM = 26, V6ONLY = 27, IPSEC_POLICY = 28, FAITH = 29, RTHDRDSTOPTS = 35, RECVPKTINFO = 36, RECVHOPLIMIT = 37, RECVRTHDR = 38, RECVHOPOPTS = 39, RECVDSTOPTS = 40, USE_MIN_MTU = 42, RECVPATHMTU = 43, PATHMTU = 44, PKTINFO = 46, HOPLIMIT = 47, NEXTHOP = 48, HOPOPTS = 49, DSTOPTS = 50, RTHDR = 51, RECVTCLASS = 57, TCLASS = 61, DONTFRAG = 62, } c.CLOCK = strflag { REALTIME = 0, VIRTUAL = 1, PROF = 2, MONOTONIC = 4, UPTIME = 5, UPTIME_PRECISE = 7, UPTIME_FAST = 8, REALTIME_PRECISE = 9, REALTIME_FAST = 10, MONOTONIC_PRECISE = 11, MONOTONIC_FAST = 12, SECOND = 13, THREAD_CPUTIME_ID = 14, PROCESS_CPUTIME_ID = 15, } c.EXTATTR_NAMESPACE = strflag { EMPTY = 0x00000000, USER = 0x00000001, SYSTEM = 0x00000002, } -- TODO mount flag is an int, so ULL is odd, but these are flags too... -- TODO many flags missing, plus FreeBSD has a lot more mount complexities c.MNT = strflag { RDONLY = 0x0000000000000001ULL, SYNCHRONOUS = 0x0000000000000002ULL, NOEXEC = 0x0000000000000004ULL, NOSUID = 0x0000000000000008ULL, NFS4ACLS = 0x0000000000000010ULL, UNION = 0x0000000000000020ULL, ASYNC = 0x0000000000000040ULL, SUIDDIR = 0x0000000000100000ULL, SOFTDEP = 0x0000000000200000ULL, NOSYMFOLLOW = 0x0000000000400000ULL, GJOURNAL = 0x0000000002000000ULL, MULTILABEL = 0x0000000004000000ULL, ACLS = 0x0000000008000000ULL, NOATIME = 0x0000000010000000ULL, NOCLUSTERR = 0x0000000040000000ULL, NOCLUSTERW = 0x0000000080000000ULL, SUJ = 0x0000000100000000ULL, FORCE = 0x0000000000080000ULL, } c.CTL = strflag { UNSPEC = 0, KERN = 1, VM = 2, VFS = 3, NET = 4, DEBUG = 5, HW = 6, MACHDEP = 7, USER = 8, P1003_1B = 9, MAXID = 10, } c.KERN = strflag { OSTYPE = 1, OSRELEASE = 2, OSREV = 3, VERSION = 4, MAXVNODES = 5, MAXPROC = 6, MAXFILES = 7, ARGMAX = 8, SECURELVL = 9, HOSTNAME = 10, HOSTID = 11, CLOCKRATE = 12, VNODE = 13, PROC = 14, FILE = 15, PROF = 16, POSIX1 = 17, NGROUPS = 18, JOB_CONTROL = 19, SAVED_IDS = 20, BOOTTIME = 21, NISDOMAINNAME = 22, UPDATEINTERVAL = 23, OSRELDATE = 24, NTP_PLL = 25, BOOTFILE = 26, MAXFILESPERPROC = 27, MAXPROCPERUID = 28, DUMPDEV = 29, IPC = 30, DUMMY = 31, PS_STRINGS = 32, USRSTACK = 33, LOGSIGEXIT = 34, IOV_MAX = 35, HOSTUUID = 36, ARND = 37, MAXID = 38, } if version >= 10 then -- not supporting on freebsd 9 as different ABI, recommend upgrade to use local function CAPRIGHT(idx, b) return bit.bor64(bit.lshift64(1, 57 + idx), b) end c.CAP = multiflags {} -- index 0 c.CAP.READ = CAPRIGHT(0, 0x0000000000000001ULL) c.CAP.WRITE = CAPRIGHT(0, 0x0000000000000002ULL) c.CAP.SEEK_TELL = CAPRIGHT(0, 0x0000000000000004ULL) c.CAP.SEEK = bit.bor64(c.CAP.SEEK_TELL, 0x0000000000000008ULL) c.CAP.PREAD = bit.bor64(c.CAP.SEEK, c.CAP.READ) c.CAP.PWRITE = bit.bor64(c.CAP.SEEK, c.CAP.WRITE) c.CAP.MMAP = CAPRIGHT(0, 0x0000000000000010ULL) c.CAP.MMAP_R = bit.bor64(c.CAP.MMAP, c.CAP.SEEK, c.CAP.READ) c.CAP.MMAP_W = bit.bor64(c.CAP.MMAP, c.CAP.SEEK, c.CAP.WRITE) c.CAP.MMAP_X = bit.bor64(c.CAP.MMAP, c.CAP.SEEK, 0x0000000000000020ULL) c.CAP.MMAP_RW = bit.bor64(c.CAP.MMAP_R, c.CAP.MMAP_W) c.CAP.MMAP_RX = bit.bor64(c.CAP.MMAP_R, c.CAP.MMAP_X) c.CAP.MMAP_WX = bit.bor64(c.CAP.MMAP_W, c.CAP.MMAP_X) c.CAP.MMAP_RWX = bit.bor64(c.CAP.MMAP_R, c.CAP.MMAP_W, c.CAP.MMAP_X) c.CAP.CREATE = CAPRIGHT(0, 0x0000000000000040ULL) c.CAP.FEXECVE = CAPRIGHT(0, 0x0000000000000080ULL) c.CAP.FSYNC = CAPRIGHT(0, 0x0000000000000100ULL) c.CAP.FTRUNCATE = CAPRIGHT(0, 0x0000000000000200ULL) c.CAP.LOOKUP = CAPRIGHT(0, 0x0000000000000400ULL) c.CAP.FCHDIR = CAPRIGHT(0, 0x0000000000000800ULL) c.CAP.FCHFLAGS = CAPRIGHT(0, 0x0000000000001000ULL) c.CAP.CHFLAGSAT = bit.bor64(c.CAP.FCHFLAGS, c.CAP.LOOKUP) c.CAP.FCHMOD = CAPRIGHT(0, 0x0000000000002000ULL) c.CAP.FCHMODAT = bit.bor64(c.CAP.FCHMOD, c.CAP.LOOKUP) c.CAP.FCHOWN = CAPRIGHT(0, 0x0000000000004000ULL) c.CAP.FCHOWNAT = bit.bor64(c.CAP.FCHOWN, c.CAP.LOOKUP) c.CAP.FCNTL = CAPRIGHT(0, 0x0000000000008000ULL) c.CAP.FLOCK = CAPRIGHT(0, 0x0000000000010000ULL) c.CAP.FPATHCONF = CAPRIGHT(0, 0x0000000000020000ULL) c.CAP.FSCK = CAPRIGHT(0, 0x0000000000040000ULL) c.CAP.FSTAT = CAPRIGHT(0, 0x0000000000080000ULL) c.CAP.FSTATAT = bit.bor64(c.CAP.FSTAT, c.CAP.LOOKUP) c.CAP.FSTATFS = CAPRIGHT(0, 0x0000000000100000ULL) c.CAP.FUTIMES = CAPRIGHT(0, 0x0000000000200000ULL) c.CAP.FUTIMESAT = bit.bor64(c.CAP.FUTIMES, c.CAP.LOOKUP) c.CAP.LINKAT = bit.bor64(c.CAP.LOOKUP, 0x0000000000400000ULL) c.CAP.MKDIRAT = bit.bor64(c.CAP.LOOKUP, 0x0000000000800000ULL) c.CAP.MKFIFOAT = bit.bor64(c.CAP.LOOKUP, 0x0000000001000000ULL) c.CAP.MKNODAT = bit.bor64(c.CAP.LOOKUP, 0x0000000002000000ULL) c.CAP.RENAMEAT = bit.bor64(c.CAP.LOOKUP, 0x0000000004000000ULL) c.CAP.SYMLINKAT = bit.bor64(c.CAP.LOOKUP, 0x0000000008000000ULL) c.CAP.UNLINKAT = bit.bor64(c.CAP.LOOKUP, 0x0000000010000000ULL) c.CAP.ACCEPT = CAPRIGHT(0, 0x0000000020000000ULL) c.CAP.BIND = CAPRIGHT(0, 0x0000000040000000ULL) c.CAP.CONNECT = CAPRIGHT(0, 0x0000000080000000ULL) c.CAP.GETPEERNAME = CAPRIGHT(0, 0x0000000100000000ULL) c.CAP.GETSOCKNAME = CAPRIGHT(0, 0x0000000200000000ULL) c.CAP.GETSOCKOPT = CAPRIGHT(0, 0x0000000400000000ULL) c.CAP.LISTEN = CAPRIGHT(0, 0x0000000800000000ULL) c.CAP.PEELOFF = CAPRIGHT(0, 0x0000001000000000ULL) c.CAP.RECV = c.CAP.READ c.CAP.SEND = c.CAP.WRITE c.CAP.SETSOCKOPT = CAPRIGHT(0, 0x0000002000000000ULL) c.CAP.SHUTDOWN = CAPRIGHT(0, 0x0000004000000000ULL) c.CAP.BINDAT = bit.bor64(c.CAP.LOOKUP, 0x0000008000000000ULL) c.CAP.CONNECTAT = bit.bor64(c.CAP.LOOKUP, 0x0000010000000000ULL) c.CAP.SOCK_CLIENT = bit.bor64(c.CAP.CONNECT, c.CAP.GETPEERNAME, c.CAP.GETSOCKNAME, c.CAP.GETSOCKOPT, c.CAP.PEELOFF, c.CAP.RECV, c.CAP.SEND, c.CAP.SETSOCKOPT, c.CAP.SHUTDOWN) c.CAP.SOCK_SERVER = bit.bor64(c.CAP.ACCEPT, c.CAP.BIND, c.CAP.GETPEERNAME, c.CAP.GETSOCKNAME, c.CAP.GETSOCKOPT, c.CAP.LISTEN, c.CAP.PEELOFF, c.CAP.RECV, c.CAP.SEND, c.CAP.SETSOCKOPT, c.CAP.SHUTDOWN) c.CAP.ALL0 = CAPRIGHT(0, 0x0000007FFFFFFFFFULL) c.CAP.UNUSED0_40 = CAPRIGHT(0, 0x0000008000000000ULL) c.CAP_UNUSED0_57 = CAPRIGHT(0, 0x0100000000000000ULL) -- index 1 c.CAP.MAC_GET = CAPRIGHT(1, 0x0000000000000001ULL) c.CAP.MAC_SET = CAPRIGHT(1, 0x0000000000000002ULL) c.CAP.SEM_GETVALUE = CAPRIGHT(1, 0x0000000000000004ULL) c.CAP.SEM_POST = CAPRIGHT(1, 0x0000000000000008ULL) c.CAP.SEM_WAIT = CAPRIGHT(1, 0x0000000000000010ULL) c.CAP.EVENT = CAPRIGHT(1, 0x0000000000000020ULL) c.CAP.KQUEUE_EVENT = CAPRIGHT(1, 0x0000000000000040ULL) c.CAP.IOCTL = CAPRIGHT(1, 0x0000000000000080ULL) c.CAP.TTYHOOK = CAPRIGHT(1, 0x0000000000000100ULL) c.CAP.PDGETPID = CAPRIGHT(1, 0x0000000000000200ULL) c.CAP.PDWAIT = CAPRIGHT(1, 0x0000000000000400ULL) c.CAP.PDKILL = CAPRIGHT(1, 0x0000000000000800ULL) c.CAP.EXTATTR_DELETE = CAPRIGHT(1, 0x0000000000001000ULL) c.CAP.EXTATTR_GET = CAPRIGHT(1, 0x0000000000002000ULL) c.CAP.EXTATTR_LIST = CAPRIGHT(1, 0x0000000000004000ULL) c.CAP.EXTATTR_SET = CAPRIGHT(1, 0x0000000000008000ULL) c.CAP_ACL_CHECK = CAPRIGHT(1, 0x0000000000010000ULL) c.CAP_ACL_DELETE = CAPRIGHT(1, 0x0000000000020000ULL) c.CAP_ACL_GET = CAPRIGHT(1, 0x0000000000040000ULL) c.CAP_ACL_SET = CAPRIGHT(1, 0x0000000000080000ULL) c.CAP_KQUEUE_CHANGE = CAPRIGHT(1, 0x0000000000100000ULL) c.CAP_KQUEUE = bit.bor64(c.CAP.KQUEUE_EVENT, c.CAP.KQUEUE_CHANGE) c.CAP_ALL1 = CAPRIGHT(1, 0x00000000001FFFFFULL) c.CAP_UNUSED1_22 = CAPRIGHT(1, 0x0000000000200000ULL) c.CAP_UNUSED1_57 = CAPRIGHT(1, 0x0100000000000000ULL) c.CAP_FCNTL = multiflags { GETFL = bit.lshift(1, c.F.GETFL), SETFL = bit.lshift(1, c.F.SETFL), GETOWN = bit.lshift(1, c.F.GETOWN), SETOWN = bit.lshift(1, c.F.SETOWN), } c.CAP_FCNTL.ALL = bit.bor(c.CAP_FCNTL.GETFL, c.CAP_FCNTL.SETFL, c.CAP_FCNTL.GETOWN, c.CAP_FCNTL.SETOWN) c.CAP_IOCTLS = multiflags { ALL = h.longmax, } c.CAP_RIGHTS_VERSION = 0 -- we do not understand others end -- freebsd >= 10 if version >= 11 then -- for utimensat c.UTIME = strflag { NOW = -1, OMIT = -2, } end return c
apache-2.0
alalazo/wesnoth
data/ai/micro_ais/cas/ca_hunter.lua
2
8201
local H = wesnoth.require "helper" local W = H.set_wml_action_metatable {} local AH = wesnoth.require "ai/lua/ai_helper.lua" local MAIUV = wesnoth.require "ai/micro_ais/micro_ai_unit_variables.lua" local M = wesnoth.map local function hunter_attack_weakest_adj_enemy(ai, hunter) -- Attack the enemy with the fewest hitpoints adjacent to 'hunter', if there is one -- Returns status of the attack: -- 'attacked': if a unit was attacked -- 'killed': if a unit was killed -- 'no_attack': if no unit was attacked if (hunter.attacks_left == 0) then return 'no_attack' end local min_hp, target = 9e99 for xa,ya in H.adjacent_tiles(hunter.x, hunter.y) do local enemy = wesnoth.get_unit(xa, ya) if AH.is_attackable_enemy(enemy) then if (enemy.hitpoints < min_hp) then min_hp, target = enemy.hitpoints, enemy end end end if target then AH.checked_attack(ai, hunter, target) if target and target.valid then return 'attacked' else return 'killed' end end return 'no_attack' end local function get_hunter(cfg) local filter = H.get_child(cfg, "filter") or { id = cfg.id } local hunter = AH.get_units_with_moves { side = wesnoth.current.side, { "and", filter } }[1] return hunter end local ca_hunter = {} function ca_hunter:evaluation(cfg) if get_hunter(cfg) then return cfg.ca_score end return 0 end function ca_hunter:execution(cfg) -- Hunter does a random wander in area given by @cfg.hunting_ground until it finds -- and kills an enemy unit, then retreats to position given by @cfg.home_x/y -- for @cfg.rest_turns turns, or until fully healed local hunter = get_hunter(cfg) local hunter_vars = MAIUV.get_mai_unit_variables(hunter, cfg.ai_id) -- If hunting_status is not set for the hunter -> default behavior -> random wander if (not hunter_vars.hunting_status) then -- Hunter gets a new goal if none exist or on any move with 10% random chance local rand = math.random(10) if (not hunter_vars.goal_x) or (rand == 1) then -- 'locs' includes border hexes, but that does not matter here locs = AH.get_passable_locations((H.get_child(cfg, "filter_location") or {}), hunter) local rand = math.random(#locs) hunter_vars.goal_x, hunter_vars.goal_y = locs[rand][1], locs[rand][2] MAIUV.set_mai_unit_variables(hunter, cfg.ai_id, hunter_vars) end local reach_map = AH.get_reachable_unocc(hunter) -- Now find the one of these hexes that is closest to the goal local max_rating, best_hex = -9e99 reach_map:iter( function(x, y, v) -- Distance from goal is first rating local rating = -M.distance_between(x, y, hunter_vars.goal_x, hunter_vars.goal_y) -- Huge rating bonus if this is next to an enemy local enemy_hp = 500 for xa,ya in H.adjacent_tiles(x, y) do local enemy = wesnoth.get_unit(xa, ya) if AH.is_attackable_enemy(enemy) then if (enemy.hitpoints < enemy_hp) then enemy_hp = enemy.hitpoints end end end rating = rating + 500 - enemy_hp -- prefer attack on weakest enemy if (rating > max_rating) then max_rating, best_hex = rating, { x, y } end end) if (best_hex[1] ~= hunter.x) or (best_hex[2] ~= hunter.y) then AH.checked_move(ai, hunter, best_hex[1], best_hex[2]) -- partial move only if (not hunter) or (not hunter.valid) then return end else -- If hunter did not move, we need to stop it (also delete the goal) AH.checked_stopunit_moves(ai, hunter) if (not hunter) or (not hunter.valid) then return end hunter_vars.goal_x, hunter_vars.goal_y = nil, nil MAIUV.set_mai_unit_variables(hunter, cfg.ai_id, hunter_vars) end -- If this gets the hunter to the goal, we delete the goal if (hunter.x == hunter_vars.goal_x) and (hunter.y == hunter_vars.goal_y) then hunter_vars.goal_x, hunter_vars.goal_y = nil, nil MAIUV.set_mai_unit_variables(hunter, cfg.ai_id, hunter_vars) end -- Finally, if the hunter ended up next to enemies, attack the weakest of those local attack_status = hunter_attack_weakest_adj_enemy(ai, hunter) -- If the enemy was killed, hunter returns home if hunter and hunter.valid and (attack_status == 'killed') then hunter_vars.goal_x, hunter_vars.goal_y = nil, nil hunter_vars.hunting_status = 'returning' MAIUV.set_mai_unit_variables(hunter, cfg.ai_id, hunter_vars) if cfg.show_messages then W.message { speaker = hunter.id, message = 'Now that I have eaten, I will go back home.' } end end return end -- If we got here, this means the hunter is either returning, or resting if (hunter_vars.hunting_status == 'returning') then goto_x, goto_y = wesnoth.find_vacant_tile(cfg.home_x, cfg.home_y, hunter) local next_hop = AH.next_hop(hunter, goto_x, goto_y) if next_hop then AH.movefull_stopunit(ai, hunter, next_hop) if (not hunter) or (not hunter.valid) then return end -- If there's an enemy on the 'home' hex and we got right next to it, attack that enemy if (M.distance_between(cfg.home_x, cfg.home_y, hunter.x, hunter.y) == 1) then local enemy = wesnoth.get_unit(cfg.home_x, cfg.home_y) if AH.is_attackable_enemy(enemy) then if cfg.show_messages then W.message { speaker = hunter.id, message = 'Get out of my home!' } end AH.checked_attack(ai, hunter, enemy) if (not hunter) or (not hunter.valid) then return end end end end -- We also attack the weakest adjacent enemy, if still possible hunter_attack_weakest_adj_enemy(ai, hunter) if (not hunter) or (not hunter.valid) then return end -- If the hunter got home, start the resting counter if (hunter.x == cfg.home_x) and (hunter.y == cfg.home_y) then hunter_vars.hunting_status = 'resting' hunter_vars.resting_until = wesnoth.current.turn + (cfg.rest_turns or 3) MAIUV.set_mai_unit_variables(hunter, cfg.ai_id, hunter_vars) if cfg.show_messages then W.message { speaker = hunter.id, message = 'I made it home - resting now until the end of Turn ' .. hunter_vars.resting_until .. ' or until fully healed.' } end end return end -- If we got here, the only remaining action should be resting if (hunter_vars.hunting_status == 'resting') then AH.checked_stopunit_moves(ai, hunter) if (not hunter) or (not hunter.valid) then return end -- We also attack the weakest adjacent enemy hunter_attack_weakest_adj_enemy(ai, hunter) if (not hunter) or (not hunter.valid) then return end -- If this is the last turn of resting, we remove the status and turn variable if (hunter.hitpoints >= hunter.max_hitpoints) and (hunter_vars.resting_until <= wesnoth.current.turn) then hunter_vars.hunting_status = nil hunter_vars.resting_until = nil MAIUV.set_mai_unit_variables(hunter, cfg.ai_id, hunter_vars) if cfg.show_messages then W.message { speaker = hunter.id, message = 'I am done resting. It is time to go hunting again next turn.' } end end return end -- In principle we should never get here, but just in case something got changed in WML: -- Reset variable, so that hunter goes hunting on next turn hunter_vars.hunting_status = nil MAIUV.set_mai_unit_variables(hunter, cfg.ai_id, hunter_vars) end return ca_hunter
gpl-2.0
thedraked/darkstar
scripts/zones/Pashhow_Marshlands/npcs/Beastmen_s_Banner.lua
14
1037
----------------------------------- -- Area: Pashhow Marshlands -- NPC: Beastmen_s_Banner -- @pos -172.764 25.119 93.640 109 ----------------------------------- package.loaded["scripts/zones/Pashhow_Marshlands/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Pashhow_Marshlands/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(BEASTMEN_BANNER); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end;
gpl-3.0
thedraked/darkstar
scripts/zones/Western_Altepa_Desert/npcs/relic.lua
14
1892
----------------------------------- -- Area: Western Altepa Desert -- NPC: <this space intentionally left blank> -- @pos -152 -16 20 125 ----------------------------------- package.loaded["scripts/zones/Western_Altepa_Desert/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Western_Altepa_Desert/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece if (player:getVar("RELIC_IN_PROGRESS") == 18287 and trade:getItemCount() == 4 and trade:hasItemQty(18287,1) and trade:hasItemQty(1575,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1451,1)) then player:startEvent(205,18288); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 205) then if (player:getFreeSlotsCount() < 2) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18288); player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1450); else player:tradeComplete(); player:addItem(18288); player:addItem(1450,30); player:messageSpecial(ITEM_OBTAINED,18288); player:messageSpecial(ITEMS_OBTAINED,1450,30); player:setVar("RELIC_IN_PROGRESS",0); end end end;
gpl-3.0
thedraked/darkstar
scripts/globals/items/kusamochi_+1.lua
35
2086
----------------------------------------- -- ID: 6263 -- Item: kusamochi+1 -- Food Effect: 60 Min, All Races ----------------------------------------- -- HP + 30 (Pet & Master) -- Vitality + 4 (Pet & Master) -- Attack + 21% Cap: 77 (Pet & Master) Pet Cap: 120 -- Ranged Attack + 21% Cap: 77 (Pet & Master) Pet Cap: 120 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD)) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,6263); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 30) target:addMod(MOD_VIT, 4) target:addMod(MOD_FOOD_ATTP, 21) target:addMod(MOD_FOOD_ATT_CAP, 77) target:addMod(MOD_FOOD_RATTP, 16) target:addMod(MOD_FOOD_RATT_CAP, 77) target:addPetMod(MOD_HP, 30) target:addPetMod(MOD_VIT, 4) target:addPetMod(MOD_FOOD_ATTP, 21) target:addPetMod(MOD_FOOD_ATT_CAP, 120) target:addPetMod(MOD_FOOD_RATTP, 21) target:addPetMod(MOD_FOOD_RATT_CAP, 120) end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 30) target:delMod(MOD_VIT, 4) target:delMod(MOD_FOOD_ATTP, 21) target:delMod(MOD_FOOD_ATT_CAP, 77) target:delMod(MOD_FOOD_RATTP, 16) target:delMod(MOD_FOOD_RATT_CAP, 77) target:delPetMod(MOD_HP, 30) target:delPetMod(MOD_VIT, 4) target:delPetMod(MOD_FOOD_ATTP, 21) target:delPetMod(MOD_FOOD_ATT_CAP, 120) target:delPetMod(MOD_FOOD_RATTP, 21) target:delPetMod(MOD_FOOD_RATT_CAP, 120) end;
gpl-3.0
thedraked/darkstar
scripts/zones/Northern_San_dOria/npcs/Taulenne.lua
16
5134
----------------------------------- -- Area: Northern San d'Oria -- NPC: Taulenne -- Armor Storage NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; package.loaded["scripts/globals/armorstorage"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/armorstorage"); require("scripts/globals/settings"); require("scripts/globals/quests"); local Deposit = 0x0304; local Withdrawl = 0x0305; local ArraySize = #StorageArray; local G1 = 0; local G2 = 0; local G3 = 0; local G4 = 0; local G5 = 0; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end for SetId = 1,ArraySize,11 do local TradeCount = trade:getItemCount(); local T1 = trade:hasItemQty(StorageArray[SetId + 5],1); if (T1 == true) then if (player:hasKeyItem(StorageArray[SetId + 10]) == false) then if (TradeCount == StorageArray[SetId + 3]) then local T2 = trade:hasItemQty(StorageArray[SetId + 4],1); local T3 = trade:hasItemQty(StorageArray[SetId + 6],1); local T4 = trade:hasItemQty(StorageArray[SetId + 7],1); local T5 = trade:hasItemQty(StorageArray[SetId + 8],1); if (StorageArray[SetId + 4] == 0) then T2 = true; end if (StorageArray[SetId + 6] == 0) then T3 = true; end if (StorageArray[SetId + 7] == 0) then T4 = true; end if (StorageArray[SetId + 8] == 0) then T5 = true; end if (T2 == true and T3 == true and T4 == true and T5 == true) then player:startEvent(Deposit,0,0,0,0,0,StorageArray[SetId + 9]); player:addKeyItem(StorageArray[SetId + 10]); player:messageSpecial(KEYITEM_OBTAINED,StorageArray[SetId + 10]); break; end end end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local CurrGil = player:getGil(); for KeyItem = 11,ArraySize,11 do if player:hasKeyItem(StorageArray[KeyItem]) then if StorageArray[KeyItem - 9] == 1 then G1 = G1 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 2 then G2 = G2 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 3 then G3 = G3 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 4 then G4 = G4 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 6 then G5 = G5 + StorageArray[KeyItem - 8]; end end end player:startEvent(Withdrawl,G1,G2,G3,G4,CurrGil,G5); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) if (csid == Withdrawl) then player:updateEvent( StorageArray[option * 11 - 6], StorageArray[option * 11 - 5], StorageArray[option * 11 - 4], StorageArray[option * 11 - 3], StorageArray[option * 11 - 2], StorageArray[option * 11 - 1]); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == Withdrawl) then if (option > 0 and option <= StorageArray[ArraySize] - 10) then if (player:getFreeSlotsCount() >= StorageArray[option * 11 - 7]) then for Item = 2,6,1 do if (StorageArray[option * 11 - Item] > 0) then player:addItem(StorageArray[option * 11 - Item],1); player:messageSpecial(ITEM_OBTAINED,StorageArray[option * 11 - Item]); end end player:delKeyItem(StorageArray[option * 11]); player:setGil(player:getGil() - StorageArray[option * 11 - 1]); else for Item = 2,6,1 do if (StorageArray[option * 11 - Item] > 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,StorageArray[option * 11 - Item]); end end end end end if (csid == Deposit) then player:tradeComplete(); end end;
gpl-3.0
thedraked/darkstar
scripts/zones/La_Theine_Plateau/npcs/Dimensional_Portal.lua
17
1389
----------------------------------- -- Area: La Theine Plateau -- NPC: Dimensional Portal ----------------------------------- package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/La_Theine_Plateau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) > THE_WARRIOR_S_PATH) or (DIMENSIONAL_PORTAL_UNLOCK == true) then player:startEvent(0x00CC); else player:messageSpecial(ALREADY_OBTAINED_TELE+1); -- Telepoint Disappeared end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00CC and option == 1) then player:setPos(25.299,-2.799,579,193,33); -- To AlTaieu {R} end end;
gpl-3.0
thedraked/darkstar
scripts/zones/Windurst_Waters/npcs/Naiko-Paneiko.lua
25
3850
----------------------------------- -- Area: Windurst Waters -- NPC: Naiko-Paneiko -- Involved In Quest: Making Headlines, Riding on the Clouds -- @zone 238 -- @pos -246 -5 -308 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_4") == 2) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_4",0); player:tradeComplete(); player:addKeyItem(SPIRITED_STONE); player:messageSpecial(KEYITEM_OBTAINED,SPIRITED_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) function testflag(set,flag) return (set % (2*flag) >= flag) end MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES); if (MakingHeadlines == 0) then player:startEvent(0x0299); -- Quest Start elseif (MakingHeadlines == 1) then prog = player:getVar("QuestMakingHeadlines_var"); -- Variable to track if player has talked to 4 NPCs and a door -- 1 = Kyume -- 2 = Yujuju -- 4 = Hiwom -- 8 = Umumu -- 16 = Mahogany Door if (testflag(tonumber(prog),1) == false or testflag(tonumber(prog),2) == false or testflag(tonumber(prog),4) == false or testflag(tonumber(prog),8) == false) then rand = math.random(1,2); if (rand == 1) then player:startEvent(0x029a); -- Quest Reminder 1 else player:startEvent(0x029f); -- Quest Reminder 2 end elseif (testflag(tonumber(prog),8) == true and testflag(tonumber(prog),16) == false) then player:startEvent(0x02a1); -- Advises to validate story elseif (prog == 31) then rand = math.random(1,2); if (rand == 1) then player:startEvent(0x02a2); -- Quest finish 1 elseif (scoop == 4 and door == 1) then player:startEvent(0x029e); -- Quest finish 2 end end else player:startEvent(0x0297); -- Standard conversation end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0299) then player:addQuest(WINDURST,MAKING_HEADLINES); elseif (csid == 0x029e or csid == 0x02a2) then player:addTitle(EDITORS_HATCHET_MAN); player:addGil(GIL_RATE*560); player:messageSpecial(GIL_OBTAINED,GIL_RATE*560); player:delKeyItem(WINDURST_WOODS_SCOOP); player:delKeyItem(WINDURST_WALLS_SCOOP); player:delKeyItem(WINDURST_WATERS_SCOOP); player:delKeyItem(PORT_WINDURST_SCOOP); player:setVar("QuestMakingHeadlines_var",0); player:addFame(WINDURST,30); player:completeQuest(WINDURST,MAKING_HEADLINES); end end;
gpl-3.0
thedraked/darkstar
scripts/globals/mobskills/Fulmination.lua
27
1503
--------------------------------------------- -- Fulmination -- -- Description: Deals heavy magical damage in an area of effect. Additional effect: Paralysis + Stun -- Type: Magical -- Utsusemi/Blink absorb: Wipes Shadows -- Range: 30 yalms --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if(mob:getFamily() == 316) then local mobSkin = mob:getModelId(); if (mobSkin == 1805) then return 0; else return 1; end end local family = mob:getFamily(); local mobhp = mob:getHPP(); local result = 1 if (family == 168 and mobhp <= 35) then -- Khimera < 35% result = 0; elseif (family == 315 and mobhp <= 50) then -- Tyger < 50% result = 0; end return result; end; function onMobWeaponSkill(target, mob, skill) -- TODO: Hits all players near Khimaira, not just alliance. local dmgmod = 3; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg() * 4,ELE_LIGHTNING,dmgmod,TP_MAB_BONUS,1); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_THUNDER,MOBPARAM_WIPE_SHADOWS); MobStatusEffectMove(mob,target,EFFECT_PARALYSIS, 40, 0, 60); MobStatusEffectMove(mob,target,EFFECT_STUN, 1, 0, 4); target:delHP(dmg); return dmg; end;
gpl-3.0
Alittlemurkling/Noct
awesome/freedesktop/menu.lua
8
3706
-- Grab environment local utils = require("freedesktop.utils") local io = io local string = string local table = table local os = os local ipairs = ipairs local pairs = pairs module("freedesktop.menu") all_menu_dirs = { '/usr/share/applications/', '/usr/local/share/applications/', '~/.local/share/applications/' } show_generic_name = false --- Create menus for applications -- @param menu_dirs A list of application directories (optional). -- @return A prepared menu w/ categories function new(arg) -- the categories and their synonyms where shamelessly copied from lxpanel -- source code. local programs = {} local config = arg or {} programs['AudioVideo'] = {} programs['Development'] = {} programs['Education'] = {} programs['Game'] = {} programs['Graphics'] = {} programs['Network'] = {} programs['Office'] = {} programs['Settings'] = {} programs['System'] = {} programs['Utility'] = {} programs['Other'] = {} for i, dir in ipairs(config.menu_dirs or all_menu_dirs) do local entries = utils.parse_desktop_files({dir = dir}) for j, program in ipairs(entries) do -- check whether to include in the menu if program.show and program.Name and program.cmdline then if show_generic_name and program.GenericName then program.Name = program.Name .. ' (' .. program.GenericName .. ')' end local target_category = nil if program.categories then for _, category in ipairs(program.categories) do if programs[category] then target_category = category break end end end if not target_category then target_category = 'Other' end if target_category then table.insert(programs[target_category], { program.Name, program.cmdline, program.icon_path }) end end end end -- sort each submenu alphabetically case insensitive for k, v in pairs(programs) do table.sort(v, function(a, b) return a[1]:lower() < b[1]:lower() end) end local menu = { { "Accessories", programs["Utility"], utils.lookup_icon({ icon = 'applications-accessories' }) }, { "Development", programs["Development"], utils.lookup_icon({ icon = 'applications-development' }) }, { "Education", programs["Education"], utils.lookup_icon({ icon = 'applications-science' }) }, { "Games", programs["Game"], utils.lookup_icon({ icon = 'applications-games' }) }, { "Graphics", programs["Graphics"], utils.lookup_icon({ icon = 'applications-graphics' }) }, { "Internet", programs["Network"], utils.lookup_icon({ icon = 'applications-internet' }) }, { "Multimedia", programs["AudioVideo"], utils.lookup_icon({ icon = 'applications-multimedia' }) }, { "Office", programs["Office"], utils.lookup_icon({ icon = 'applications-office' }) }, { "Other", programs["Other"], utils.lookup_icon({ icon = 'applications-other' }) }, { "Settings", programs["Settings"], utils.lookup_icon({ icon = 'preferences-desktop' }) }, { "System Tools", programs["System"], utils.lookup_icon({ icon = 'applications-system' }) }, } -- Removing empty entries from menu local cleanedMenu = {} for index, item in ipairs(menu) do itemTester = item[2] if itemTester[1] then table.insert(cleanedMenu, item) end end return cleanedMenu end
gpl-3.0
mtroyka/Zero-K
effects/mary_sue.lua
25
5718
-- mary_sue_fireball1 -- mary_sue_fireball3 -- mary_sue -- mary_sue_fireball2 return { ["mary_sue_fireball1"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[1 1 1 0.01 0 0 0 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 10, particlelifespread = 0, particlesize = 15, particlesizespread = 0, particlespeed = 1, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[exp02_1]], }, }, }, ["mary_sue_fireball3"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 10, particlelifespread = 0, particlesize = 15, particlesizespread = 0, particlespeed = 1, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[exp02_3]], }, }, }, ["mary_sue"] = { frame1 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:MARY_SUE_FIREBALL1]], pos = [[0, 0, 0]], }, }, frame2 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 6.6, explosiongenerator = [[custom:MARY_SUE_FIREBALL2]], pos = [[0, 6.6, 0]], }, }, frame3 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 13.2, explosiongenerator = [[custom:MARY_SUE_FIREBALL3]], pos = [[0, 13.2, 0]], }, }, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.9, flashsize = 25, ttl = 6, color = { [1] = 1, [2] = 0.69999998807907, [3] = 0.69999998807907, }, }, pikes = { air = true, class = [[explspike]], count = 15, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.2, color = [[1.0,0.7,0]], dir = [[-15 r30,-15 r30,-15 r30]], length = 15, width = 5, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 2, ground = true, water = true, properties = { airdrag = 0.97, alwaysvisible = true, colormap = [[1 1 0 0.01 1 0.7 0.5 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 20, particlelife = 7.5, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 3, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["mary_sue_fireball2"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 10, particlelifespread = 0, particlesize = 15, particlesizespread = 0, particlespeed = 1, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[exp02_2]], }, }, }, }
gpl-2.0
thedraked/darkstar
scripts/zones/Windurst_Woods/npcs/Nalta.lua
14
1046
----------------------------------- -- Area: Windurst Woods -- NPC: Nalta -- Type: Conquest Troupe -- @zone 241 -- @pos 19.140 1 -51.297 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0036); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
mohammadclashclash/dark98
plugins/ingroup.lua
202
31524
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) 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']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] 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.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators 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 get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators 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_namemod(msg, data, target) if not is_momod(msg) then return "For moderators 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 local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" 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_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" 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 local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators 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_membermod(msg, data, target) if not is_momod(msg) then return "For moderators 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 local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators 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 set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators 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 local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted.') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..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 == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, 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 help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name if success == -1 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' then print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'rem' then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local receiver = 'user#id'..msg.action.user.id local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return false end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id) send_large_msg(receiver, rules) end if matches[1] == 'chat_del_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 savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(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, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and matches[2] then if not is_owner(msg) then return "Only owner can promote" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end if matches[1] == 'newlink' then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == 'setowner' then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'help' then if not is_momod(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() 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 end return { patterns = { "^[!/](add)$", "^[!/](rem)$", "^[!/](rules)$", "^[!/](about)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](promote) (.*)$", "^[!/](help)$", "^[!/](clean) (.*)$", "^[!/](demote) (.*)$", "^[!/](set) ([^%s]+) (.*)$", "^[!/](lock) (.*)$", "^[!/](setowner) (%d+)$", "^[!/](owner)$", "^[!/](res) (.*)$", "^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/](unlock) (.*)$", "^[!/](setflood) (%d+)$", "^[!/](settings)$", "^[!/](modlist)$", "^[!/](newlink)$", "^[!/](link)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
latenitefilms/hammerspoon
extensions/doc/hsdocs/init.lua
4
30798
--- === hs.doc.hsdocs === --- --- Manage the internal documentation web server. --- --- This module provides functions for managing the Hammerspoon built-in documentation web server. Currently, this is the same documentation available in the Dash docset for Hammerspoon, but does not require third party software for viewing. --- --- Future enhancements to this module under consideration include: --- * Support for third-party modules to add to the documentation set at run-time --- * Markdown/HTML based tutorials and How-To examples --- * Documentation for the LuaSkin Objective-C Framework --- * Lua Reference documentation --- --- The intent of this sub-module is to provide as close a rendering of the same documentation available at the Hammerspoon Github site and Dash documentation as possible in a manner suitable for run-time modification so module developers can test out documentation additions without requiring a complete recompilation of the Hammerspoon source. As always, the most current and official documentation can be found at https://www.hammerspoon.org and in the official Hammerspoon Dash docset. local module = {} -- private variables and methods ----------------------------------------- local USERDATA_TAG = "hs.doc.hsdocs" local settings = require"hs.settings" local image = require"hs.image" local webview = require"hs.webview" local doc = require"hs.doc" local watchable = require"hs.watchable" local timer = require"hs.timer" local host = require"hs.host" local hotkey = require"hs.hotkey" local documentRoot = package.searchpath("hs.hsdocs", package.path):match("^(/.*/).*%.lua$") local osVersion = host.operatingSystemVersion() local toolbarImages = { prevArrow = image.imageFromASCII(".......\n" .. "..3....\n" .. ".......\n" .. "41....1\n" .. ".......\n" .. "..5....\n" .. ".......", { { strokeColor = { white = .5 } }, { strokeColor = { white = .5 }, fillColor = { alpha = 0.0 }, shouldClose = false }, {}, }), nextArrow = image.imageFromASCII(".......\n" .. "....3..\n" .. ".......\n" .. "1....14\n" .. ".......\n" .. "....5..\n" .. ".......", { { strokeColor = { white = .5 } }, { strokeColor = { white = .5 }, fillColor = { alpha = 0.0 }, shouldClose = false }, {} }), lightMode = image.imageFromASCII("1.........2\n" .. "...........\n" .. "...........\n" .. ".....b.....\n" .. "...........\n" .. "...........\n" .. "....e.f....\n" .. "...........\n" .. "...a...c...\n" .. "...........\n" .. "4.........3", { { strokeColor = { white = .5 }, fillColor = { alpha = 0.0 } }, { strokeColor = { white = .5 }, fillColor = { alpha = 0.0 }, shouldClose = false }, { strokeColor = { white = .5 } }, {} }), darkMode = image.imageFromASCII("1.........2\n" .. "...........\n" .. "...........\n" .. ".....b.....\n" .. "...........\n" .. "...........\n" .. "....e.f....\n" .. "...........\n" .. "...a...c...\n" .. "...........\n" .. "4.........3", { { strokeColor = { white = .75 }, fillColor = { alpha = 0.5 } }, { strokeColor = { white = .75 }, fillColor = { alpha = 0.0 }, shouldClose = false }, { strokeColor = { white = .75 } }, {} }), followMode = image.imageFromASCII("2.........3\n" .. "...........\n" .. ".....g.....\n" .. "...........\n" .. "1...f.h...4\n" .. "6...b.c...9\n" .. "...........\n" .. "...a...d...\n" .. "...........\n" .. "7.........8", { { strokeColor = { white = .5 }, fillColor = { alpha = 0.0 }, shouldClose = false }, { strokeColor = { white = .75 }, fillColor = { alpha = 0.5 }, shouldClose = false }, { strokeColor = { white = .75 }, fillColor = { alpha = 0.0 }, shouldClose = false }, { strokeColor = { white = .5 }, fillColor = { alpha = 0.0 }, shouldClose = true }, {} }), noTrackWindow = image.imageFromASCII("1.........2\n" .. "4.........3\n" .. "6.........7\n" .. "...........\n" .. "...........\n" .. "...........\n" .. "...........\n" .. "...........\n" .. "...........\n" .. "9.........8", { { strokeColor = { white = .5 }, fillColor = { alpha = 0.25 }, shouldClose = false }, { strokeColor = { white = .5 }, fillColor = { alpha = 0.0 }}, {} }), trackWindow = image.imageFromASCII("1.......2..\n" .. "4.......3..\n" .. "6.......7.c\n" .. "...........\n" .. "...........\n" .. "...........\n" .. "...........\n" .. "9.......8..\n" .. "...........\n" .. "..a.......b", { { strokeColor = { white = .5 }, fillColor = { alpha = 0.25 }, shouldClose = false }, { strokeColor = { white = .5 }, fillColor = { alpha = 0.0 }}, { strokeColor = { white = .6 }, fillColor = { alpha = 0.0 }, shouldClose = false}, {} }), index = image.imageFromName("statusicon"), help = image.imageFromName(image.systemImageNames.RevealFreestandingTemplate), } local frameTracker = function(cmd, wv, opt) if cmd == "frameChange" and settings.get("_documentationServer.trackBrowserFrameChanges") then settings.set("_documentationServer.browserFrame", opt) elseif cmd == "focusChange" then if module._modalKeys then if opt then module._modalKeys:enter() else module._modalKeys:exit() end end elseif cmd == "close" then if module._modalKeys then module._modalKeys:exit() end end end local updateToolbarIcons = function(toolbar, browser) local historyList = browser:historyList() if historyList.current > 1 then toolbar:modifyItem{ id = "prev", enable = true } else toolbar:modifyItem{ id = "prev", enable = false } end if historyList.current < #historyList then toolbar:modifyItem{ id = "next", enable = true } else toolbar:modifyItem{ id = "next", enable = false } end local mode = module.browserDarkMode() if type(mode) == "nil" then toolbar:modifyItem{ id = "mode", image = toolbarImages.followMode } elseif type(mode) == "boolean" then toolbar:modifyItem{ id = "mode", image = mode and toolbarImages.darkMode or toolbarImages.lightMode } elseif type(mode) == "number" then toolbar:modifyItem{ id = "mode", image = (mode > 50) and toolbarImages.darkMode or toolbarImages.lightMode } end toolbar:modifyItem{ id = "track", image = module.trackBrowserFrame() and toolbarImages.trackWindow or toolbarImages.noTrackWindow } end local makeModuleListForMenu = function() local searchList = {} for i,v in ipairs(doc._jsonForModules) do table.insert(searchList, v.name) end for i,v in ipairs(doc._jsonForSpoons) do table.insert(searchList, "spoon." .. v.name) end table.sort(searchList, function(a, b) return a:lower() < b:lower() end) return searchList end local makeToolbar = function(browser) local toolbar = webview.toolbar.new("hsBrowserToolbar", { { id = "index", label = "Index", image = toolbarImages.index, tooltip = "Display documentation index", }, { id = "navigation", label = "Navigation", groupMembers = { "prev", "next" }, }, { id = "prev", tooltip = "Display previously viewed page in history", image = toolbarImages.prevArrow, enable = false, allowedAlone = false, }, { id = "next", tooltip = "Display next viewed page in history", image = toolbarImages.nextArrow, enable = false, allowedAlone = false, }, { id = "search", tooltip = "Search for a Hammerspoon function or method by name", searchfield = true, searchWidth = 250, searchPredefinedSearches = makeModuleListForMenu(), searchPredefinedMenuTitle = false, searchReleaseFocusOnCallback = true, fn = function(t, w, i, text) if text ~= "" then w:url("http://localhost:" .. tostring(module._server:port()) .. "/module.lp/" .. text) end end, }, { id = "NSToolbarFlexibleSpaceItem" }, { id = "mode", tooltip = "Toggle display mode between System/Dark/Light", image = toolbarImages.followMode, }, { id = "track", tooltip = "Toggle window frame tracking", image = toolbarImages.noTrackWindow, }, { id = "NSToolbarSpaceItem" }, { id = "help", tooltip = "Display Browser Help", image = toolbarImages.help, fn = function(t, w, i) w:evaluateJavaScript("toggleHelp()") end, } }):canCustomize(true) :displayMode("icon") :sizeMode("small") :autosaves(true) :setCallback(function(t, w, i) if i == "prev" then w:goBack() elseif i == "next" then w:goForward() elseif i == "index" then w:url("http://localhost:" .. tostring(module._server:port()) .. "/") elseif i == "mode" then local mode = module.browserDarkMode() if type(mode) == "nil" then module.browserDarkMode(true) elseif type(mode) == "boolean" then if mode then module.browserDarkMode(false) else module.browserDarkMode(nil) end elseif type(mode) == "number" then if mode < 50 then module.browserDarkMode(false) else module.browserDarkMode(true) end else -- shouldn't be possible, but... module.browserDarkMode(nil) end -- w:reload() local current = module.browserDarkMode() if type(current) == "nil" then current = (host.interfaceStyle() == "Dark") end w:evaluateJavaScript("setInvertLevel(" .. (current and "100" or "0") .. ")") module._browser:darkMode(current) elseif i == "track" then local track = module.trackBrowserFrame() if track then module.browserFrame(nil) end module.trackBrowserFrame(not track) else hs.luaSkinLog.wf("%s browser callback received %s and has no handler", USERDATA_TAG, i) end updateToolbarIcons(t, w) end) updateToolbarIcons(toolbar, browser) return toolbar end local defineHotkeys = function() local hk = hotkey.modal.new() hk:bind({"cmd"}, "f", nil, function() module._browser:evaluateJavaScript("toggleFind()") end) hk:bind({"cmd"}, "l", nil, function() if module._browser:attachedToolbar() then module._browser:attachedToolbar():selectSearchField() end end) hk:bind({"cmd"}, "r", nil, function() module._browser:evaluateJavaScript("window.location.reload(true)") end) hk:bind({}, "escape", nil, function() module._browser:evaluateJavaScript([[ document.getElementById("helpStuff").style.display == "block" ]], function(ans1) if ans1 then module._browser:evaluateJavaScript("toggleHelp()") end module._browser:evaluateJavaScript([[ document.getElementById("searcher").style.display == "block" ]], function(ans2) if ans2 then module._browser:evaluateJavaScript("toggleFind()") end if not ans1 and not ans2 then module._browser:hide() hk:exit() end end) end) end) hk:bind({"cmd"}, "g", nil, function() module._browser:evaluateJavaScript([[ document.getElementById("searcher").style.display == "block" ]], function(ans) if ans then module._browser:evaluateJavaScript("searchForText(0)") end end) end) hk:bind({"cmd", "shift"}, "g", nil, function() module._browser:evaluateJavaScript([[ document.getElementById("searcher").style.display == "block" ]], function(ans) if ans then module._browser:evaluateJavaScript("searchForText(1)") end end) end) -- because these would interfere with the search field, we let Javascript handle these, see search.lp -- hk:bind({}, "return", nil, function() end) -- hk:bind({"shift"}, "return", nil, function() end) return hk end local makeBrowser = function() local screen = require"hs.screen" local mainScreenFrame = screen:primaryScreen():frame() local browserFrame = settings.get("_documentationServer.browserFrame") if not (browserFrame and browserFrame.x and browserFrame.y and browserFrame.h and browserFrame.w) then browserFrame = { x = mainScreenFrame.x + 10, y = mainScreenFrame.y + 32, h = mainScreenFrame.h - 42, w = 800 } end local options = { developerExtrasEnabled = true, } if (osVersion["major"] == 10 and osVersion["minor"] > 10) then options.privateBrowsing = true options.applicationName = "Hammerspoon/" .. hs.processInfo.version end -- not used anymore, but just in case, I'm leaving the skeleton here... -- local ucc = webview.usercontent.new("hsdocs"):setCallback(function(obj) ---- if obj.body == "message" then ---- else -- print("~~ hsdocs unexpected ucc callback: ", require("hs.inspect")(obj)) ---- end -- end) -- local browser = webview.new(browserFrame, options, ucc):windowStyle(1+2+4+8) local browser = webview.new(browserFrame, options):windowStyle(1+2+4+8) :allowTextEntry(true) :allowGestures(true) :windowCallback(frameTracker) :navigationCallback(function(a, w, n, e) if e then hs.luaSkinLog.ef("%s browser navigation for %s error:%s", USERDATA_TAG, a, e.localizedDescription) return true end if a == "didFinishNavigation" then updateToolbarIcons(w:attachedToolbar(), w) end end) module._modalKeys = defineHotkeys() browser:attachedToolbar(makeToolbar(browser)) return browser end -- Public interface ------------------------------------------------------ module._moduleListChanges = watchable.watch("hs.doc", "changeCount", function(w, p, k, o, n) if module._browser then module._browser:attachedToolbar():modifyItem{ id = "search", searchPredefinedSearches = makeModuleListForMenu(), } end end) --- hs.doc.hsdocs.interface([interface]) -> currentValue --- Function --- Get or set the network interface that the Hammerspoon documentation web server will be served on --- --- Parameters: --- * interface - an optional string, or nil, specifying the network interface the Hammerspoon documentation web server will be served on. An explicit nil specifies that the web server should listen on all active interfaces for the machine. Defaults to "localhost". --- --- Returns: --- * the current, possibly new, value --- --- Notes: --- * See `hs.httpserver.setInterface` for a description of valid values that can be specified as the `interface` argument to this function. --- * A change to the interface can only occur when the documentation server is not running. If the server is currently active when you call this function with an argument, the server will be temporarily stopped and then restarted after the interface has been changed. --- --- * Changes made with this function are saved with `hs.settings` with the label "_documentationServer.interface" and will persist through a reload or restart of Hammerspoon. module.interface = function(...) local args = table.pack(...) if args.n > 0 then local newValue, needRestart = args[1], false if newValue == nil or type(newValue) == "string" then if module._server then needRestart = true module.stop() end if newValue == nil then settings.set("_documentationServer.interface", true) else settings.set("_documentationServer.interface", newValue) end if needRestart then module.start() end else error("interface must be nil or a string", 2) end end local current = settings.get("_documentationServer.interface") or "localhost" if current == true then return nil -- since nil has no meaning to settings, we use this boolean value as a placeholder else return current end end --- hs.doc.hsdocs.port([value]) -> currentValue --- Function --- Get or set the Hammerspoon documentation server HTTP port. --- --- Parameters: --- * value - an optional number specifying the port for the Hammerspoon documentation web server --- --- Returns: --- * the current, possibly new, value --- --- Notes: --- * The default port number is 12345. --- --- * Changes made with this function are saved with `hs.settings` with the label "_documentationServer.serverPort" and will persist through a reload or restart of Hammerspoon. module.port = function(...) local args = table.pack(...) local value = args[1] if args.n == 1 and (type(value) == "number" or type(value) == "nil") then if module._server then module._server:port(value or 12345) end settings.set("_documentationServer.serverPort", value) end return settings.get("_documentationServer.serverPort") or 12345 end --- hs.doc.hsdocs.start() -> `hs.doc.hsdocs` --- Function --- Start the Hammerspoon internal documentation web server. --- --- Parameters: --- * None --- --- Returns: --- * the table representing the `hs.doc.hsdocs` module --- --- Notes: --- * This function is automatically called, if necessary, when [hs.doc.hsdocs.help](#help) is invoked. --- * The documentation web server can be viewed from a web browser by visiting "http://localhost:port" where `port` is the port the server is running on, 12345 by default -- see [hs.doc.hsdocs.port](#port). module.start = function() if module._server then error("documentation server already running") else module._server = require"hs.httpserver.hsminweb".new(documentRoot) module._server:port(module.port()) :name("Hammerspoon Documentation") :bonjour(true) :luaTemplateExtension("lp") :interface(module.interface()) :directoryIndex{ "index.html", "index.lp", }:start() module._server._logBadTranslations = true module._server._logPageErrorTranslations = true module._server._allowRenderTranslations = true end return module end --- hs.doc.hsdocs.stop() -> `hs.doc.hsdocs` --- Function --- Stop the Hammerspoon internal documentation web server. --- --- Parameters: --- * None --- --- Returns: --- * the table representing the `hs.doc.hsdocs` module module.stop = function() if not module._server then error("documentation server not running") else module._server:stop() module._server = nil end return module end --- hs.doc.hsdocs.help([identifier]) -> nil --- Function --- Display the documentation for the specified Hammerspoon function, or the Table of Contents for the Hammerspoon documentation in a built-in mini browser. --- --- Parameters: --- * an optional string specifying a Hammerspoon module, function, or method to display documentation for. If you leave out this parameter, the table of contents for the Hammerspoon built-in documentation is displayed instead. --- --- Returns: --- * None module.help = function(target) if not module._server then module.start() end local targetURL = "http://localhost:" .. tostring(module._server:port()) .. "/" if type(target) == "string" then targetURL = targetURL .. "module.lp/" .. target elseif type(target) == "table" and target.__path then targetURL = targetURL .. "module.lp/" .. target.__path end if webview and not settings.get("_documentationServer.forceExternalBrowser") then module._browser = module._browser or makeBrowser() module._browser:url(targetURL):show() else local targetApp = settings.get("_documentationServer.forceExternalBrowser") local urlevent = require"hs.urlevent" if type(targetApp) == "boolean" then targetApp = urlevent.getDefaultHandler("http") end if not urlevent.openURLWithBundle(targetURL, targetApp) then hs.luaSkinLog.wf("%s.help - hs.urlevent.openURLWithBundle failed to launch for bundle ID %s", USERDATA_TAG, targetApp) os.execute("/usr/bin/open " .. targetURL) end end end --- hs.doc.hsdocs.browserFrame([frameTable]) -> currentValue --- Function --- Get or set the currently saved initial frame location for the documentation browser. --- --- Parameters: --- * frameTable - a frame table containing x, y, h, and w values specifying the browser's initial position when Hammerspoon starts. --- --- Returns: --- * the current, possibly new, value --- --- Notes: --- * If [hs.doc.hsdocs.trackBrowserFrame](#trackBrowserFrame) is false or nil (the default), then you can use this function to specify the initial position of the documentation browser. --- * If [hs.doc.hsdocs.trackBrowserFrame](#trackBrowserFrame) is true, then this any value set with this function will be overwritten whenever the browser window is moved or resized. --- --- * Changes made with this function are saved with `hs.settings` with the label "_documentationServer.browserFrame" and will persist through a reload or restart of Hammerspoon. module.browserFrame = function(...) local args = table.pack(...) local value = args[1] if args.n == 1 and (type(value) == "table" or type(value) == "nil") then if value and value.x and value.y and value.h and value.w then settings.set("_documentationServer.browserFrame", value) end end return settings.get("_documentationServer.browserFrame") end --- hs.doc.hsdocs.trackBrowserFrame([value]) -> currentValue --- Function --- Get or set whether or not changes in the documentation browsers location and size persist through launches of Hammerspoon. --- --- Parameters: --- * value - an optional boolean specifying whether or not the browsers location should be saved across launches of Hammerspoon. --- --- Returns: --- * the current, possibly new, value --- --- Notes: --- * Changes made with this function are saved with `hs.settings` with the label "_documentationServer.trackBrowserFrameChanges" and will persist through a reload or restart of Hammerspoon. module.trackBrowserFrame = function(...) local args = table.pack(...) if args.n == 1 and (type(args[1]) == "boolean" or type(args[1]) == "nil") then settings.set("_documentationServer.trackBrowserFrameChanges", args[1]) end return settings.get("_documentationServer.trackBrowserFrameChanges") end --- hs.doc.hsdocs.moduleEntitiesInSidebar([value]) -> currentValue --- Function --- Get or set whether or not a module's entity list is displayed as a column on the left of the rendered page. --- --- Parameters: --- * value - an optional boolean specifying whether or not a module's entity list is displayed inline in the documentation (false) or in a sidebar on the left (true). --- --- Returns: --- * the current, possibly new, value --- --- Notes: --- * This is experimental and is disabled by default. It was inspired by a Userscript written by krasnovpro. The original can be found at https://openuserjs.org/scripts/krasnovpro/hammerspoon.org_Documentation/source. --- --- * Changes made with this function are saved with `hs.settings` with the label "_documentationServer.entitiesInSidebar" and will persist through a reload or restart of Hammerspoon. module.moduleEntitiesInSidebar = function(...) local args = table.pack(...) if args.n == 1 and (type(args[1]) == "boolean" or type(args[1]) == "nil") then settings.set("_documentationServer.entitiesInSidebar", args[1]) end return settings.get("_documentationServer.entitiesInSidebar") end --- hs.doc.hsdocs.browserDarkMode([value]) -> currentValue --- Function --- Get or set whether or not the Hammerspoon browser renders output in Dark mode. --- --- Parameters: --- * value - an optional boolean, number, or nil specifying whether or not the documentation browser renders in Dark mode. --- * if value is `true`, then the HTML output will always be inverted --- * if value is `false`, then the HTML output will never be inverted --- * if value is `nil`, then the output will be inverted only when the OS X theme is set to Dark mode --- * if the value is a number between 0 and 100, the number specifies the inversion ratio, where 0 means no inversion, 100 means full inversion, and 50 is completely unreadable because the foreground and background are equally adjusted. --- --- Returns: --- * the current, possibly new, value --- --- Notes: --- * Inversion is applied through the use of CSS filtering, so while numeric values other than 0 (false) and 100 (true) are allowed, the result is generally not what is desired. --- --- * Changes made with this function are saved with `hs.settings` with the label "_documentationServer.invertDocs" and will persist through a reload or restart of Hammerspoon. module.browserDarkMode = function(...) local args = table.pack(...) local value = args[1] if args.n == 1 and ({ ["number"] = 1, ["boolean"] = 1, ["nil"] = 1 })[type(value)] then if type(value) == "number" then value = (value < 0 and 0) or (value > 100 and 100) or value end settings.set("_documentationServer.invertDocs", value) end return settings.get("_documentationServer.invertDocs") end --- hs.doc.hsdocs.forceExternalBrowser([value]) -> currentValue --- Function --- Get or set whether or not [hs.doc.hsdocs.help](#help) uses an external browser. --- --- Parameters: --- * value - an optional boolean or string, default false, specifying whether or not documentation requests will be displayed in an external browser or the internal one handled by `hs.webview`. --- --- Returns: --- * the current, possibly new, value --- --- Notes: --- * If this value is set to true, help requests invoked by [hs.doc.hsdocs.help](#help) will be invoked by your system's default handler for the `http` scheme. --- * If this value is set to a string, the string specifies the bundle ID of an application which will be used to handle the url request for the documentation. The string should match one of the items returned by `hs.urlevent.getAllHandlersForScheme("http")`. --- --- * This behavior is triggered automatically, regardless of this setting, if you are running with a version of OS X prior to 10.10, since `hs.webview` requires OS X 10.10 or later. --- --- * Changes made with this function are saved with `hs.settings` with the label "_documentationServer.forceExternalBrowser" and will persist through a reload or restart of Hammerspoon. module.forceExternalBrowser = function(...) local args = table.pack(...) local value = args[1] if args.n == 1 and (type(value) == "string" or type(value) == "boolean" or type(value) == "nil") then if type(value) == "string" then local validBundleIDs = require"hs.urlevent".getAllHandlersForScheme("http") local found = false for i, v in ipairs(validBundleIDs) do if v == value then found = true break end end if not found then error([[the string must match one of those returned by hs.urlevent.getAllHandlersForScheme("http")]]) end end settings.set("_documentationServer.forceExternalBrowser", args[1]) end return settings.get("_documentationServer.forceExternalBrowser") end -- Return Module Object -------------------------------------------------- return module
mit
thedraked/darkstar
scripts/zones/Western_Adoulin/npcs/Dangueubert.lua
14
1682
----------------------------------- -- Area: Western Adoulin -- NPC: Dangueubert -- Type: Standard NPC and Quest NPC -- Involved with Quest: 'A Certain Substitute Patrolman' -- @zone 256 -- @pos 5 0 -136 256 ----------------------------------- require("scripts/globals/missions"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local SOA_Mission = player:getCurrentMission(SOA); if (SOA_Mission >= LIFE_ON_THE_FRONTIER) then if ((ACSP == QUEST_ACCEPTED) and (player:getVar("ACSP_NPCs_Visited") == 6)) then -- Progresses Quest: 'A Certain Substitute Patrolman' player:startEvent(0x09FE); else -- Standard dialogue player:startEvent(0x0222, 0, 1); end else -- Dialogue prior to joining colonization effort player:startEvent(0x0222); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x09FE) then -- Progresses Quest: 'A Certain Substitute Patrolman' player:setVar("ACSP_NPCs_Visited", 7); elseif (csid == 0x0222) then if (option == 1) then -- Warps player to Mog Garden player:setPos(0, 0, 0, 0, 280); end end end;
gpl-3.0
mtroyka/Zero-K
units/factoryshield.lua
2
3425
unitDef = { unitname = [[factoryshield]], name = [[Shield Bot Factory]], description = [[Produces Tough Robots, Builds at 10 m/s]], acceleration = 0, brakeRate = 0, buildCostEnergy = 600, buildCostMetal = 600, builder = true, buildingGroundDecalDecaySpeed = 30, buildingGroundDecalSizeX = 7, buildingGroundDecalSizeY = 7, buildingGroundDecalType = [[factoryshield_aoplane.dds]], buildoptions = { [[cornecro]], [[corclog]], [[corak]], [[corstorm]], [[corthud]], [[cormak]], [[shieldfelon]], [[shieldarty]], [[corcrash]], [[corroach]], [[core_spectre]], }, buildPic = [[factoryshield.png]], buildTime = 600, canMove = true, canPatrol = true, canstop = [[1]], category = [[SINK UNARMED]], corpse = [[DEAD]], customParams = { description_fr = [[Produit des Robots d'Infanterie L. une vitesse de 10 m/s]], description_de = [[Produziert zähe Roboter, Baut mit 10 M/s]], helptext = [[The Shield Bot Factory is tough yet flexible. Its units are built to take the pain and dish it back out, without compromising mobility. Clever use of unit combos is well rewarded. Key units: Bandit, Thug, Outlaw, Rogue, Racketeer]], helptext_de = [[Die Shield Bot Factory ist robust aber flexibel. Diese Einheiten werden gebaut, um all die Schmerzen auf sich zu nehmen und wieder zu verteilen, aber ohne Kompromisse bei der Mobilität. Schlauer Einsatz von Einheitenkombos wird gut belohnt. Wichtigste Einheiten: Bandit, Thug, Outlaw, Roach, Dirtbag]], sortName = [[1]], }, energyMake = 0.3, energyUse = 0, explodeAs = [[LARGE_BUILDINGEX]], footprintX = 6, footprintZ = 6, iconType = [[facwalker]], idleAutoHeal = 5, idleTime = 1800, maxDamage = 4000, maxSlope = 15, maxVelocity = 0, maxWaterDepth = 0, metalMake = 0.3, minCloakDistance = 150, noAutoFire = false, objectName = [[factory.s3o]], script = "factoryshield.lua", seismicSignature = 4, selfDestructAs = [[LARGE_BUILDINGEX]], showNanoSpray = false, sightDistance = 273, turnRate = 0, useBuildingGroundDecal = true, workerTime = 10, yardMap = [[oooooo occcco occcco occcco occcco occcco]], featureDefs = { DEAD = { blocking = true, featureDead = [[HEAP]], footprintX = 5, footprintZ = 6, object = [[factory_dead.s3o]], }, HEAP = { blocking = false, footprintX = 5, footprintZ = 5, object = [[debris4x4a.s3o]], }, }, } return lowerkeys({ factoryshield = unitDef })
gpl-2.0