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
ASHRAF97/ASHRAFKASPER
libs/url.lua
567
9183
--[[ Copyright 2004-2007 Diego Nehab. 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. ]] ----------------------------------------------------------------------------- -- URI parsing, composition and relative URL resolution -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id: url.lua,v 1.38 2006/04/03 04:45:42 diego Exp $ ----------------------------------------------------------------------------- -- updated for a module()-free world of 5.3 by slact local string = require("string") local base = _G local table = require("table") local Url={} Url._VERSION = "URL 1.0.2" function Url.escape(s) return string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02x", string.byte(c)) end) end local function make_set(t) local s = {} for i,v in base.ipairs(t) do s[t[i]] = 1 end return s end local segment_set = make_set { "-", "_", ".", "!", "~", "*", "'", "(", ")", ":", "@", "&", "=", "+", "$", ",", } local function protect_segment(s) return string.gsub(s, "([^A-Za-z0-9_])", function (c) if segment_set[c] then return c else return string.format("%%%02x", string.byte(c)) end end) end function Url.unescape(s) return string.gsub(s, "%%(%x%x)", function(hex) return string.char(base.tonumber(hex, 16)) end) end local function absolute_path(base_path, relative_path) if string.sub(relative_path, 1, 1) == "/" then return relative_path end local path = string.gsub(base_path, "[^/]*$", "") path = path .. relative_path path = string.gsub(path, "([^/]*%./)", function (s) if s ~= "./" then return s else return "" end end) path = string.gsub(path, "/%.$", "/") local reduced while reduced ~= path do reduced = path path = string.gsub(reduced, "([^/]*/%.%./)", function (s) if s ~= "../../" then return "" else return s end end) end path = string.gsub(reduced, "([^/]*/%.%.)$", function (s) if s ~= "../.." then return "" else return s end end) return path end ----------------------------------------------------------------------------- -- Parses a url and returns a table with all its parts according to RFC 2396 -- The following grammar describes the names given to the URL parts -- <url> ::= <scheme>://<authority>/<path>;<params>?<query>#<fragment> -- <authority> ::= <userinfo>@<host>:<port> -- <userinfo> ::= <user>[:<password>] -- <path> :: = {<segment>/}<segment> -- Input -- url: uniform resource locator of request -- default: table with default values for each field -- Returns -- table with the following fields, where RFC naming conventions have -- been preserved: -- scheme, authority, userinfo, user, password, host, port, -- path, params, query, fragment -- Obs: -- the leading '/' in {/<path>} is considered part of <path> ----------------------------------------------------------------------------- function Url.parse(url, default) -- initialize default parameters local parsed = {} for i,v in base.pairs(default or parsed) do parsed[i] = v end -- empty url is parsed to nil if not url or url == "" then return nil, "invalid url" end -- remove whitespace -- url = string.gsub(url, "%s", "") -- get fragment url = string.gsub(url, "#(.*)$", function(f) parsed.fragment = f return "" end) -- get scheme url = string.gsub(url, "^([%w][%w%+%-%.]*)%:", function(s) parsed.scheme = s; return "" end) -- get authority url = string.gsub(url, "^//([^/]*)", function(n) parsed.authority = n return "" end) -- get query stringing url = string.gsub(url, "%?(.*)", function(q) parsed.query = q return "" end) -- get params url = string.gsub(url, "%;(.*)", function(p) parsed.params = p return "" end) -- path is whatever was left if url ~= "" then parsed.path = url end local authority = parsed.authority if not authority then return parsed end authority = string.gsub(authority,"^([^@]*)@", function(u) parsed.userinfo = u; return "" end) authority = string.gsub(authority, ":([^:]*)$", function(p) parsed.port = p; return "" end) if authority ~= "" then parsed.host = authority end local userinfo = parsed.userinfo if not userinfo then return parsed end userinfo = string.gsub(userinfo, ":([^:]*)$", function(p) parsed.password = p; return "" end) parsed.user = userinfo return parsed end ----------------------------------------------------------------------------- -- Rebuilds a parsed URL from its components. -- Components are protected if any reserved or unallowed characters are found -- Input -- parsed: parsed URL, as returned by parse -- Returns -- a stringing with the corresponding URL ----------------------------------------------------------------------------- function Url.build(parsed) local ppath = Url.parse_path(parsed.path or "") local url = Url.build_path(ppath) if parsed.params then url = url .. ";" .. parsed.params end if parsed.query then url = url .. "?" .. parsed.query end local authority = parsed.authority if parsed.host then authority = parsed.host if parsed.port then authority = authority .. ":" .. parsed.port end local userinfo = parsed.userinfo if parsed.user then userinfo = parsed.user if parsed.password then userinfo = userinfo .. ":" .. parsed.password end end if userinfo then authority = userinfo .. "@" .. authority end end if authority then url = "//" .. authority .. url end if parsed.scheme then url = parsed.scheme .. ":" .. url end if parsed.fragment then url = url .. "#" .. parsed.fragment end -- url = string.gsub(url, "%s", "") return url end -- Builds a absolute URL from a base and a relative URL according to RFC 2396 function Url.absolute(base_url, relative_url) if base.type(base_url) == "table" then base_parsed = base_url base_url = Url.build(base_parsed) else base_parsed = Url.parse(base_url) end local relative_parsed = Url.parse(relative_url) if not base_parsed then return relative_url elseif not relative_parsed then return base_url elseif relative_parsed.scheme then return relative_url else relative_parsed.scheme = base_parsed.scheme if not relative_parsed.authority then relative_parsed.authority = base_parsed.authority if not relative_parsed.path then relative_parsed.path = base_parsed.path if not relative_parsed.params then relative_parsed.params = base_parsed.params if not relative_parsed.query then relative_parsed.query = base_parsed.query end end else relative_parsed.path = absolute_path(base_parsed.path or "", relative_parsed.path) end end return Url.build(relative_parsed) end end -- Breaks a path into its segments, unescaping the segments function Url.parse_path(path) local parsed = {} path = path or "" --path = string.gsub(path, "%s", "") string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end) for i = 1, #parsed do parsed[i] = Url.unescape(parsed[i]) end if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end return parsed end -- Builds a path component from its segments, escaping protected characters. function Url.build_path(parsed, unsafe) local path = "" local n = #parsed if unsafe then for i = 1, n-1 do path = path .. parsed[i] path = path .. "/" end if n > 0 then path = path .. parsed[n] if parsed.is_directory then path = path .. "/" end end else for i = 1, n-1 do path = path .. protect_segment(parsed[i]) path = path .. "/" end if n > 0 then path = path .. protect_segment(parsed[n]) if parsed.is_directory then path = path .. "/" end end end if parsed.is_absolute then path = "/" .. path end return path end return Url
gpl-2.0
abosalah22/zak
libs/url.lua
567
9183
--[[ Copyright 2004-2007 Diego Nehab. 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. ]] ----------------------------------------------------------------------------- -- URI parsing, composition and relative URL resolution -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id: url.lua,v 1.38 2006/04/03 04:45:42 diego Exp $ ----------------------------------------------------------------------------- -- updated for a module()-free world of 5.3 by slact local string = require("string") local base = _G local table = require("table") local Url={} Url._VERSION = "URL 1.0.2" function Url.escape(s) return string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02x", string.byte(c)) end) end local function make_set(t) local s = {} for i,v in base.ipairs(t) do s[t[i]] = 1 end return s end local segment_set = make_set { "-", "_", ".", "!", "~", "*", "'", "(", ")", ":", "@", "&", "=", "+", "$", ",", } local function protect_segment(s) return string.gsub(s, "([^A-Za-z0-9_])", function (c) if segment_set[c] then return c else return string.format("%%%02x", string.byte(c)) end end) end function Url.unescape(s) return string.gsub(s, "%%(%x%x)", function(hex) return string.char(base.tonumber(hex, 16)) end) end local function absolute_path(base_path, relative_path) if string.sub(relative_path, 1, 1) == "/" then return relative_path end local path = string.gsub(base_path, "[^/]*$", "") path = path .. relative_path path = string.gsub(path, "([^/]*%./)", function (s) if s ~= "./" then return s else return "" end end) path = string.gsub(path, "/%.$", "/") local reduced while reduced ~= path do reduced = path path = string.gsub(reduced, "([^/]*/%.%./)", function (s) if s ~= "../../" then return "" else return s end end) end path = string.gsub(reduced, "([^/]*/%.%.)$", function (s) if s ~= "../.." then return "" else return s end end) return path end ----------------------------------------------------------------------------- -- Parses a url and returns a table with all its parts according to RFC 2396 -- The following grammar describes the names given to the URL parts -- <url> ::= <scheme>://<authority>/<path>;<params>?<query>#<fragment> -- <authority> ::= <userinfo>@<host>:<port> -- <userinfo> ::= <user>[:<password>] -- <path> :: = {<segment>/}<segment> -- Input -- url: uniform resource locator of request -- default: table with default values for each field -- Returns -- table with the following fields, where RFC naming conventions have -- been preserved: -- scheme, authority, userinfo, user, password, host, port, -- path, params, query, fragment -- Obs: -- the leading '/' in {/<path>} is considered part of <path> ----------------------------------------------------------------------------- function Url.parse(url, default) -- initialize default parameters local parsed = {} for i,v in base.pairs(default or parsed) do parsed[i] = v end -- empty url is parsed to nil if not url or url == "" then return nil, "invalid url" end -- remove whitespace -- url = string.gsub(url, "%s", "") -- get fragment url = string.gsub(url, "#(.*)$", function(f) parsed.fragment = f return "" end) -- get scheme url = string.gsub(url, "^([%w][%w%+%-%.]*)%:", function(s) parsed.scheme = s; return "" end) -- get authority url = string.gsub(url, "^//([^/]*)", function(n) parsed.authority = n return "" end) -- get query stringing url = string.gsub(url, "%?(.*)", function(q) parsed.query = q return "" end) -- get params url = string.gsub(url, "%;(.*)", function(p) parsed.params = p return "" end) -- path is whatever was left if url ~= "" then parsed.path = url end local authority = parsed.authority if not authority then return parsed end authority = string.gsub(authority,"^([^@]*)@", function(u) parsed.userinfo = u; return "" end) authority = string.gsub(authority, ":([^:]*)$", function(p) parsed.port = p; return "" end) if authority ~= "" then parsed.host = authority end local userinfo = parsed.userinfo if not userinfo then return parsed end userinfo = string.gsub(userinfo, ":([^:]*)$", function(p) parsed.password = p; return "" end) parsed.user = userinfo return parsed end ----------------------------------------------------------------------------- -- Rebuilds a parsed URL from its components. -- Components are protected if any reserved or unallowed characters are found -- Input -- parsed: parsed URL, as returned by parse -- Returns -- a stringing with the corresponding URL ----------------------------------------------------------------------------- function Url.build(parsed) local ppath = Url.parse_path(parsed.path or "") local url = Url.build_path(ppath) if parsed.params then url = url .. ";" .. parsed.params end if parsed.query then url = url .. "?" .. parsed.query end local authority = parsed.authority if parsed.host then authority = parsed.host if parsed.port then authority = authority .. ":" .. parsed.port end local userinfo = parsed.userinfo if parsed.user then userinfo = parsed.user if parsed.password then userinfo = userinfo .. ":" .. parsed.password end end if userinfo then authority = userinfo .. "@" .. authority end end if authority then url = "//" .. authority .. url end if parsed.scheme then url = parsed.scheme .. ":" .. url end if parsed.fragment then url = url .. "#" .. parsed.fragment end -- url = string.gsub(url, "%s", "") return url end -- Builds a absolute URL from a base and a relative URL according to RFC 2396 function Url.absolute(base_url, relative_url) if base.type(base_url) == "table" then base_parsed = base_url base_url = Url.build(base_parsed) else base_parsed = Url.parse(base_url) end local relative_parsed = Url.parse(relative_url) if not base_parsed then return relative_url elseif not relative_parsed then return base_url elseif relative_parsed.scheme then return relative_url else relative_parsed.scheme = base_parsed.scheme if not relative_parsed.authority then relative_parsed.authority = base_parsed.authority if not relative_parsed.path then relative_parsed.path = base_parsed.path if not relative_parsed.params then relative_parsed.params = base_parsed.params if not relative_parsed.query then relative_parsed.query = base_parsed.query end end else relative_parsed.path = absolute_path(base_parsed.path or "", relative_parsed.path) end end return Url.build(relative_parsed) end end -- Breaks a path into its segments, unescaping the segments function Url.parse_path(path) local parsed = {} path = path or "" --path = string.gsub(path, "%s", "") string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end) for i = 1, #parsed do parsed[i] = Url.unescape(parsed[i]) end if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end return parsed end -- Builds a path component from its segments, escaping protected characters. function Url.build_path(parsed, unsafe) local path = "" local n = #parsed if unsafe then for i = 1, n-1 do path = path .. parsed[i] path = path .. "/" end if n > 0 then path = path .. parsed[n] if parsed.is_directory then path = path .. "/" end end else for i = 1, n-1 do path = path .. protect_segment(parsed[i]) path = path .. "/" end if n > 0 then path = path .. protect_segment(parsed[n]) if parsed.is_directory then path = path .. "/" end end end if parsed.is_absolute then path = "/" .. path end return path end return Url
gpl-2.0
Inorizushi/DDR-SN1HD
BGAnimations/ScreenPlayerOptionsPopUp underlay/default.lua
1
1481
return Def.ActorFrame { Def.Quad{ InitCommand=cmd(FullScreen;diffuse,color("0,0,0,1")); OnCommand=cmd(diffusealpha,0;linear,0.5;diffusealpha,0.5); OffCommand=cmd(linear,0.5;diffusealpha,0); }; LoadActor( THEME:GetPathG("ScreenWithMenuElements","header/regular/top"))..{ InitCommand=cmd(x,SCREEN_LEFT;halign,0;y,SCREEN_TOP+38); OffCommand=cmd(diffusealpha,0) }; LoadActor( THEME:GetPathG("ScreenWithMenuElements","header/Options"))..{ InitCommand=cmd(x,SCREEN_LEFT+12;halign,0;valign,1;y,SCREEN_TOP+51); OffCommand=cmd(diffusealpha,0) }; --p1 LoadActor( "../ScreenPlayerOptions underlay/Back" )..{ InitCommand=cmd(Center;zoomto,SCREEN_WIDTH,480); OnCommand=cmd(addx,-SCREEN_WIDTH;sleep,0.5;accelerate,0.5;addx,SCREEN_WIDTH); OffCommand=cmd(sleep,0.2;accelerate,0.5;addx,SCREEN_WIDTH); }; LoadActor( "../ScreenPlayerOptions underlay/Explanation" )..{ InitCommand=cmd(visible,GAMESTATE:IsHumanPlayer(PLAYER_1);x,SCREEN_CENTER_X-300;y,SCREEN_CENTER_Y+150;halign,0); OnCommand=cmd(addx,-SCREEN_WIDTH;sleep,0.5;accelerate,0.5;addx,SCREEN_WIDTH); OffCommand=cmd(sleep,0.2;accelerate,0.5;addx,SCREEN_WIDTH); }; --p2 LoadActor( "../ScreenPlayerOptions underlay/Explanation" )..{ InitCommand=cmd(visible,GAMESTATE:IsHumanPlayer(PLAYER_2);x,SCREEN_CENTER_X+300;y,SCREEN_CENTER_Y+150;halign,0;zoomx,-1); OnCommand=cmd(addx,-SCREEN_WIDTH;sleep,0.5;accelerate,0.5;addx,SCREEN_WIDTH); OffCommand=cmd(sleep,0.2;accelerate,0.5;addx,SCREEN_WIDTH); }; }
gpl-3.0
scan-bot/scan-bot
plugins/weather.lua
351
1443
do local BASE_URL = "http://api.openweathermap.org/data/2.5/weather" local function get_weather(location) print("Finding weather in ", location) local url = BASE_URL url = url..'?q='..location url = url..'&units=metric' local b, c, h = http.request(url) if c ~= 200 then return nil end local weather = json:decode(b) local city = weather.name local country = weather.sys.country local temp = 'The temperature in '..city ..' (' ..country..')' ..' is '..weather.main.temp..'°C' local conditions = 'Current conditions are: ' .. weather.weather[1].description if weather.weather[1].main == 'Clear' then conditions = conditions .. ' ☀' elseif weather.weather[1].main == 'Clouds' then conditions = conditions .. ' ☁☁' elseif weather.weather[1].main == 'Rain' then conditions = conditions .. ' ☔' elseif weather.weather[1].main == 'Thunderstorm' then conditions = conditions .. ' ☔☔☔☔' end return temp .. '\n' .. conditions end local function run(msg, matches) local city = 'Yogyakarta' if matches[1] ~= '!weather' then city = matches[1] end local text = get_weather(city) if not text then text = 'Can\'t get weather from that city.' end return text end return { description = "weather in that city (Yogyakarta is default)", usage = "!weather (city)", patterns = { "^!weather$", "^!weather (.*)$" }, run = run } end
gpl-2.0
xboybigcampishere/Full
plugins/id.lua
31
6231
-------------------------------------------------- -- ____ ____ _____ -- -- | \| _ )_ _|___ ____ __ __ -- -- | |_ ) _ \ | |/ ·__| _ \_| \/ | -- -- |____/|____/ |_|\____/\_____|_/\/\_| -- -- -- -------------------------------------------------- -- -- -- Developers: @Josepdal & @MaSkAoS -- -- Support: @Skneos, @iicc1 & @serx666 -- -- -- -------------------------------------------------- local function usernameinfo (user) if user.username then return '@'..user.username end if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end local function whoisname(cb_extra, success, result) chat_type = cb_extra.chat_type chat_id = cb_extra.chat_id user_id = result.peer_id user_username = result.username if chat_type == 'chat' then send_msg('chat#id'..chat_id, '👤 '..lang_text(chat_id, 'user')..' @'..user_username..' ('..user_id..')', ok_cb, false) elseif chat_type == 'channel' then send_msg('channel#id'..chat_id, '👤 '..lang_text(chat_id, 'user')..' @'..user_username..' ('..user_id..')', ok_cb, false) end end local function whoisid(cb_extra, success, result) chat_id = cb_extra.chat_id user_id = cb_extra.user_id if cb_extra.chat_type == 'chat' then send_msg('chat#id'..chat_id, '👤 '..lang_text(chat_id, 'user')..' @'..result.username..' ('..user_id..')', ok_cb, false) elseif cb_extra.chat_type == 'channel' then send_msg('channel#id'..chat_id, '👤 '..lang_text(chat_id, 'user')..' @'..result.username..' ('..user_id..')', ok_cb, false) end end local function channelUserIDs (extra, success, result) local receiver = extra.receiver print('Result') vardump(result) local text = '' for k,user in ipairs(result) do local id = user.peer_id local username = usernameinfo (user) text = text..("%s - %s\n"):format(username, id) end send_large_msg(receiver, text) end local function get_id_who(extra, success, result) result = backward_msg_format(result) local msg = result local chat = msg.to.id local user = msg.from.id if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, '🆔 '..lang_text(chat, 'user')..' ID: '..msg.from.id, ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, '🆔 '..lang_text(chat, 'user')..' ID: '..msg.from.id, ok_cb, false) end end local function returnids (extra, success, result) local receiver = extra.receiver local chatname = result.print_name local id = result.peer_id local text = ('ID for chat %s (%s):\n'):format(chatname, id) for k,user in ipairs(result.members) do local username = usernameinfo(user) local id = user.peer_id local userinfo = ("%s - %s\n"):format(username, id) text = text .. userinfo end send_large_msg(receiver, text) end local function run(msg, matches) local receiver = get_receiver(msg) local chat = msg.to.id -- Id of the user and info about group / channel if matches[1] == "#id" then if permissions(msg.from.id, msg.to.id, "id") then if msg.to.type == 'channel' then send_msg(msg.to.peer_id, '🔠 '..lang_text(chat, 'supergroupName')..': '..msg.to.print_name:gsub("_", " ")..'\n👥 '..lang_text(chat, 'supergroup')..' ID: '..msg.to.id..'\n🆔 '..lang_text(chat, 'user')..' ID: '..msg.from.id, ok_cb, false) elseif msg.to.type == 'chat' then send_msg(msg.to.peer_id, '🔠 '..lang_text(chat, 'chatName')..': '..msg.to.print_name:gsub("_", " ")..'\n👥 '..lang_text(chat, 'chat')..' ID: '..msg.to.id..'\n🆔 '..lang_text(chat, 'user')..' ID: '..msg.from.id, ok_cb, false) end end elseif matches[1] == 'whois' then if permissions(msg.from.id, msg.to.id, "whois") then chat_type = msg.to.type chat_id = msg.to.id if msg.reply_id then get_message(msg.reply_id, get_id_who, {receiver=get_receiver(msg)}) return end if is_id(matches[2]) then print(1) user_info('user#id'..matches[2], whoisid, {chat_type=chat_type, chat_id=chat_id, user_id=matches[2]}) return else local member = string.gsub(matches[2], '@', '') resolve_username(member, whoisname, {chat_id=chat_id, member=member, chat_type=chat_type}) return end else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'chat' or matches[1] == 'channel' then if permissions(msg.from.id, msg.to.id, "whois") then local type = matches[1] local chanId = matches[2] -- !ids? (chat) (%d+) if chanId then local chan = ("%s#id%s"):format(type, chanId) if type == 'chat' then chat_info(chan, returnids, {receiver=receiver}) else channel_get_users(chan, channelUserIDs, {receiver=receiver}) end else -- !id chat/channel local chan = ("%s#id%s"):format(msg.to.type, msg.to.id) if msg.to.type == 'channel' then channel_get_users(chan, channelUserIDs, {receiver=receiver}) end if msg.to.type == 'chat' then chat_info(chan, returnids, {receiver=receiver}) end end else return '🚫 '..lang_text(msg.to.id, 'require_mod') end end end return { patterns = { "^#(whois)$", "^#id$", "^#ids? (chat)$", "^#ids? (channel)$", "^#(whois) (.*)$" }, run = run }
gpl-2.0
Ninjistix/darkstar
scripts/zones/Beaucedine_Glacier/npcs/Rattling_Rain_IM.lua
3
2986
----------------------------------- -- Area: Beaucedine Glacier -- NPC: Rattling Rain, I.M. -- Type: Border Conquest Guards -- !pos -227.956 -81.475 260.442 111 ----------------------------------- package.loaded["scripts/zones/Beaucedine_Glacier/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Beaucedine_Glacier/TextIDs"); local guardnation = NATION_BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = FAUREGANDI; local csid = 0x7ff8; function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; 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; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; 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
neofob/sile
lua-libraries/imagesize/format/swf.lua
9
1697
local MIME_TYPE = "application/x-shockwave-flash" local function _bytes_to_bits (s) local bits = "" for i = 1, s:len() do local c = s:byte(i) bits = bits .. (c >= 0x80 and "1" or "0") .. ((c % 0x80) >= 0x40 and "1" or "0") .. ((c % 0x40) >= 0x20 and "1" or "0") .. ((c % 0x20) >= 0x10 and "1" or "0") .. ((c % 0x10) >= 0x08 and "1" or "0") .. ((c % 0x08) >= 0x04 and "1" or "0") .. ((c % 0x04) >= 0x02 and "1" or "0") .. ((c % 0x02) >= 0x01 and "1" or "0") end return bits end local function _bin2int (s) local n = 0 for i = 1, s:len() do n = n * 2 if s:sub(i, i) == "1" then n = n + 1 end end return n end -- Determine size of ShockWave/Flash files. Adapted from code sent by -- Dmitry Dorofeev <dima@yasp.com> local function size (stream, options) local buf = stream:read(33) if not buf or buf:len() ~= 33 then return nil, nil, "SWF file header incomplete" end local bs if buf:sub(1, 1) == "C" then -- Decompress enough of the file to get the FrameSize RECT. -- TODO - decompress into bs, update docs about module required return nil, nil, "compressed SWF files are currently not supported" else bs = _bytes_to_bits(buf:sub(9, 25)) end local bits = _bin2int(bs:sub(1, 5)) local x = _bin2int(bs:sub(6 + bits, 5 + bits * 2)) local y = _bin2int(bs:sub(6 + bits * 3, 5 + bits * 4)) return math.floor((x + 19) / 20), math.floor((y + 19) / 20), MIME_TYPE end return size -- vi:ts=4 sw=4 expandtab
mit
rigeirani/sgyt
plugins/tweet.lua
634
7120
local OAuth = require "OAuth" local consumer_key = "" local consumer_secret = "" local access_token = "" local access_token_secret = "" local twitter_url = "https://api.twitter.com/1.1/statuses/user_timeline.json" local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token"}, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret}) local function send_generics_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path local f = cb_extra.func -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path, func = f } -- Send first and postpone the others as callback f(receiver, file_path, send_generics_from_url_callback, cb_extra) end local function send_generics_from_url(f, receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil, func = f } send_generics_from_url_callback(cb_extra) end local function send_gifs_from_url(receiver, urls) send_generics_from_url(send_document, receiver, urls) end local function send_videos_from_url(receiver, urls) send_generics_from_url(send_video, receiver, urls) end local function send_all_files(receiver, urls) local data = { images = { func = send_photos_from_url, urls = {} }, gifs = { func = send_gifs_from_url, urls = {} }, videos = { func = send_videos_from_url, urls = {} } } local table_to_insert = nil for i,url in pairs(urls) do local _, _, extension = string.match(url, "(https?)://([^\\]-([^\\%.]+))$") local mime_type = mimetype.get_content_type_no_sub(extension) if extension == 'gif' then table_to_insert = data.gifs.urls elseif mime_type == 'image' then table_to_insert = data.images.urls elseif mime_type == 'video' then table_to_insert = data.videos.urls else table_to_insert = nil end if table_to_insert then table.insert(table_to_insert, url) end end for k, v in pairs(data) do if #v.urls > 0 then end v.func(receiver, v.urls) end end local function check_keys() if consumer_key:isempty() then return "Twitter Consumer Key is empty, write it in plugins/tweet.lua" end if consumer_secret:isempty() then return "Twitter Consumer Secret is empty, write it in plugins/tweet.lua" end if access_token:isempty() then return "Twitter Access Token is empty, write it in plugins/tweet.lua" end if access_token_secret:isempty() then return "Twitter Access Token Secret is empty, write it in plugins/tweet.lua" end return "" end local function analyze_tweet(tweet) local header = "Tweet from " .. tweet.user.name .. " (@" .. tweet.user.screen_name .. ")\n" -- "Link: https://twitter.com/statuses/" .. tweet.id_str local text = tweet.text -- replace short URLs if tweet.entities.url then for k, v in pairs(tweet.entities.urls) do local short = v.url local long = v.expanded_url text = text:gsub(short, long) end end -- remove urls local urls = {} if tweet.extended_entities and tweet.extended_entities.media then for k, v in pairs(tweet.extended_entities.media) do if v.video_info and v.video_info.variants then -- If it's a video! table.insert(urls, v.video_info.variants[1].url) else -- If not, is an image table.insert(urls, v.media_url) end text = text:gsub(v.url, "") -- Replace the URL in text end end return header, text, urls end local function sendTweet(receiver, tweet) local header, text, urls = analyze_tweet(tweet) -- send the parts send_msg(receiver, header .. "\n" .. text, ok_cb, false) send_all_files(receiver, urls) return nil end local function getTweet(msg, base, all) local receiver = get_receiver(msg) local response_code, response_headers, response_status_line, response_body = client:PerformRequest("GET", twitter_url, base) if response_code ~= 200 then return "Can't connect, maybe the user doesn't exist." end local response = json:decode(response_body) if #response == 0 then return "Can't retrieve any tweets, sorry" end if all then for i,tweet in pairs(response) do sendTweet(receiver, tweet) end else local i = math.random(#response) local tweet = response[i] sendTweet(receiver, tweet) end return nil end function isint(n) return n==math.floor(n) end local function run(msg, matches) local checked = check_keys() if not checked:isempty() then return checked end local base = {include_rts = 1} if matches[1] == 'id' then local userid = tonumber(matches[2]) if userid == nil or not isint(userid) then return "The id of a user is a number, check this web: http://gettwitterid.com/" end base.user_id = userid elseif matches[1] == 'name' then base.screen_name = matches[2] else return "" end local count = 200 local all = false if #matches > 2 and matches[3] == 'last' then count = 1 if #matches == 4 then local n = tonumber(matches[4]) if n > 10 then return "You only can ask for 10 tweets at most" end count = matches[4] all = true end end base.count = count return getTweet(msg, base, all) end return { description = "Random tweet from user", usage = { "!tweet id [id]: Get a random tweet from the user with that ID", "!tweet id [id] last: Get a random tweet from the user with that ID", "!tweet name [name]: Get a random tweet from the user with that name", "!tweet name [name] last: Get a random tweet from the user with that name" }, patterns = { "^!tweet (id) ([%w_%.%-]+)$", "^!tweet (id) ([%w_%.%-]+) (last)$", "^!tweet (id) ([%w_%.%-]+) (last) ([%d]+)$", "^!tweet (name) ([%w_%.%-]+)$", "^!tweet (name) ([%w_%.%-]+) (last)$", "^!tweet (name) ([%w_%.%-]+) (last) ([%d]+)$" }, run = run }
gpl-2.0
BooM-amour/bomb
plugins/ingroup.lua
1
57462
do -- Check Member local function check_member_autorealm(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)] = { group_type = 'Realm', 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 realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Welcome to your new realm !') end end end local function check_member_realm_add(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)] = { group_type = 'Realm', 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 realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been added!') end end end function check_member_group(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)] = { group_type = 'Group', 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)] = { group_type = 'Group', 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_group,{receiver=receiver, data=data, msg = msg}) end end local function autorealmadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg}) end end local function check_member_realmrem(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 -- Realm configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = nil save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been removed!') end 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 --End Check Member 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 = 0 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 lock_link = "no" if data[tostring(msg.to.id)]['settings']['lock_link'] then lock_link = data[tostring(msg.to.id)]['settings']['lock_link'] end local lock_adds= "no" if data[tostring(msg.to.id)]['settings']['lock_adds'] then lock_adds = data[tostring(msg.to.id)]['settings']['lock_adds'] end local lock_eng = "no" if data[tostring(msg.to.id)]['settings']['lock_eng'] then lock_eng = data[tostring(msg.to.id)]['settings']['lock_eng'] end local lock_badw = "no" if data[tostring(msg.to.id)]['settings']['lock_badw'] then lock_badw = data[tostring(msg.to.id)]['settings']['lock_badw'] end local lock_tag = "no" if data[tostring(msg.to.id)]['settings']['lock_tag'] then lock_tag = data[tostring(msg.to.id)]['settings']['lock_tag'] end local lock_leave = "no" if data[tostring(msg.to.id)]['settings']['lock_leave'] then lock_leave = data[tostring(msg.to.id)]['settings']['lock_leave'] end local lock_sticker = "no" if data[tostring(msg.to.id)]['settings']['sticker'] then lock_tag = data[tostring(msg.to.id)]['settings']['sticker'] 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 tag : "..lock_tag.."\nLock group member : "..settings.lock_member.."\nLock group english 🗣 : "..lock_eng.."\n Lock group leave : "..lock_leave.."\nLock group bad words : "..lock_badw.."\nLock group links : "..lock_link.."\nLock group join : "..lock_adds.."\nLock group sticker : "..lock_sticker.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public 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_link(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'link is already locked!' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'link has been locked!' end end local function lock_group_sticker(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_sticker_lock = data[tostring(target)]['settings']['sticker'] if group_sticker_lock == 'kick' then return 'Sticker protection is already enabled!' else data[tostring(target)]['settings']['sticker'] = 'kick' save_data(_config.moderation.data, data) return 'Sticker protection has been enabled!' end end local function unlock_group_sticker(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_sticker_lock = data[tostring(target)]['settings']['sticker'] if group_sticker_lock == 'ok' then return 'Sticker protection is already disabled!' else data[tostring(target)]['settings']['sticker'] = 'ok' save_data(_config.moderation.data, data) return 'Sticker protection has been disabled!' end end local function unlock_group_link(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'link is already unlocked!' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'link has been unlocked!' end end local function lock_group_link(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'link is already locked!' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'link has been locked!' end end local function unlock_group_link(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'link is already unlocked!' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'link has been unlocked!' end end local function lock_group_eng(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_eng_lock = data[tostring(target)]['settings']['lock_eng'] if group_eng_lock == 'yes' then return 'english is already locked!' else data[tostring(target)]['settings']['lock_eng'] = 'yes' save_data(_config.moderation.data, data) return 'english has been locked!' end end local function unlock_group_eng(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_eng_lock = data[tostring(target)]['settings']['lock_eng'] if group_eng_lock == 'no' then return 'english is already unlocked!' else data[tostring(target)]['settings']['lock_eng'] = 'no' save_data(_config.moderation.data, data) return 'english has been unlocked!' end end local function lock_group_eng(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_eng_lock = data[tostring(target)]['settings']['lock_eng'] if group_eng_lock == 'yes' then return 'english is already locked!' else data[tostring(target)]['settings']['lock_eng'] = 'yes' save_data(_config.moderation.data, data) return 'english has been locked!' end end local function unlock_group_eng(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_eng_lock = data[tostring(target)]['settings']['lock_eng'] if group_eng_lock == 'no' then return 'english is already unlocked!' else data[tostring(target)]['settings']['lock_eng'] = 'no' save_data(_config.moderation.data, data) return 'english has been unlocked!' end end local function lock_group_tag(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_tag_lock = data[tostring(target)]['settings']['lock_tag'] if group_tag_lock == 'yes' then return '# is already locked!' else data[tostring(target)]['settings']['lock_tag'] = 'yes' save_data(_config.moderation.data, data) return '# has been locked!' end end local function unlock_group_tag(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_tag_lock = data[tostring(target)]['settings']['lock_tag'] if group_tag_lock == 'no' then return '# is already unlocked!' else data[tostring(target)]['settings']['lock_tag'] = 'no' save_data(_config.moderation.data, data) return '# has been unlocked!' end end local function lock_group_tag(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_tag_lock = data[tostring(target)]['settings']['lock_tag'] if group_tag_lock == 'yes' then return '# is already locked!' else data[tostring(target)]['settings']['lock_tag'] = 'yes' save_data(_config.moderation.data, data) return '# has been locked!' end end local function unlock_group_tag(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_tag_lock = data[tostring(target)]['settings']['lock_tag'] if group_tag_lock == 'no' then return '# is already unlocked!' else data[tostring(target)]['settings']['lock_tag'] = 'no' save_data(_config.moderation.data, data) return '# has been unlocked!' end end local function lock_group_badw(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_badw_lock = data[tostring(target)]['settings']['lock_badw'] if group_badw_lock == 'yes' then return 'bad words is already locked!' else data[tostring(target)]['settings']['lock_badw'] = 'yes' save_data(_config.moderation.data, data) return 'bad words has been locked!' end end local function unlock_group_badw(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_badw_lock = data[tostring(target)]['settings']['lock_badw'] if group_badw_lock == 'no' then return 'bad words is already unlocked!' else data[tostring(target)]['settings']['lock_badw'] = 'no' save_data(_config.moderation.data, data) return 'bad words has been unlocked!' end end local function lock_group_badw(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_badw_lock = data[tostring(target)]['settings']['lock_badw'] if group_badw_lock == 'yes' then return 'bad words is already locked!' else data[tostring(target)]['settings']['lock_badw'] = 'yes' save_data(_config.moderation.data, data) return 'bad words has been locked!' end end local function unlock_group_badw(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_badw_lock = data[tostring(target)]['settings']['lock_badw'] if group_badw_lock == 'no' then return 'bad words is already unlocked!' else data[tostring(target)]['settings']['lock_badw'] = 'no' save_data(_config.moderation.data, data) return 'bad words has been unlocked!' end end local function lock_group_adds(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local adds_ban = data[tostring(msg.to.id)]['settings']['adds_ban'] if adds_ban == 'yes' then return 'join by link has been locked!' else data[tostring(msg.to.id)]['settings']['adds_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'join by link is already locked!' end local function unlock_group_adds(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local adds_ban = data[tostring(msg.to.id)]['settings']['adds_ban'] if adds_ban == 'no' then return 'join by link hes been unlocked!' else data[tostring(msg.to.id)]['settings']['adds_ban'] = 'no' save_data(_config.moderation.data, data) return 'join by link is already unlocked!' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'yes' then return 'Leaving users will be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'Leaving users will be banned' end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'no' then return 'Leaving users will not be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no' save_data(_config.moderation.data, data) return 'Leaving users will not be banned' 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 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 is_group(msg) 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 realmadd(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 is_realm(msg) then return 'Realm is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg}) end -- Global functions 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 is_group(msg) then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end function realmrem(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 is_realm(msg) then return 'Realm is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realmrem,{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 promote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'.. msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return promote(get_receiver(msg), member_username, member_id) end 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 demote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return demote(get_receiver(msg), member_username, member_id) end end local function setowner_by_reply(extra, success, result) local msg = result local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) local name_log = msg.from.print_name:gsub("_", " ") data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner") local text = msg.from.print_name:gsub("_", " ").." is the owner now" return send_large_msg(receiver, text) end local function promote_demote_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local member_username = "@"..result.username local chat_id = extra.chat_id local mod_cmd = extra.mod_cmd local receiver = "chat#id"..chat_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 local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][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) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function 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 for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function user_msgs(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 = tonumber(redis:get(um_hash) or 0) return user_info end local function kick_zero(cb_extra, success, result) local chat_id = cb_extra.chat_id local chat = "chat#id"..chat_id local ci_user local re_user for k,v in pairs(result.members) do local si = false ci_user = v.id local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) for i = 1, #users do re_user = users[i] if tonumber(ci_user) == tonumber(re_user) then si = true end end if not si then if ci_user ~= our_id then if not is_momod2(ci_user, chat_id) then chat_del_user(chat, 'user#id'..ci_user, ok_cb, true) end end end end end local function kick_inactive(chat_id, num, receiver) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) -- Get user info for i = 1, #users do local user_id = users[i] local user_info = user_msgs(user_id, chat_id) local nmsg = user_info if tonumber(nmsg) < tonumber(num) then if not is_momod2(user_id, chat_id) then chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true) end end end return chat_info(receiver, kick_zero, {chat_id = chat_id}) 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' and not matches[2] then if is_realm(msg) then return 'Error: Already a realm.' end print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'add' and matches[2] == 'realm' then if is_group(msg) then return 'Error: Already a group.' end print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm") return realmadd(msg) end if matches[1] == 'rem' and not matches[2] then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'rem' and matches[2] == 'realm' then print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm") return realmrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then return autorealmadd(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_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 not matches[2] then if not is_owner(msg) then return "Only the owner can prmote new moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, promote_by_reply, false) end end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can promote" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'promote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'demote' and not matches[2] then if not is_owner(msg) then return "Only the owner can demote moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, demote_by_reply, false) end end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then return "You can't demote yourself" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'demote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) 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' or matches[1] == 'l' then local target = msg.to.id if matches[2] == 'sticker' or matches[2] == 's' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker ") return lock_group_sticker(msg, data, target) end if matches[2] == 'name' or matches[2] == 'n' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' or matches[2] == 'm' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' or matches[2] == 'f' 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] == 'adds' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link ") return lock_group_link(msg, data, target) end if matches[2] == 'eng' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked eng ") return lock_group_eng(msg, data, target) end if matches[2] == 'tag' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked tag ") return lock_group_tag(msg, data, target) end if matches[2] == 'badw' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked badw ") return lock_group_badw(msg, data, target) end if matches[2] == 'join' or matches[2] == 'j' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked adds ") return lock_group_adds(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ") return lock_group_leave(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' or matches[1] == 'u' then local target = msg.to.id if matches[2] == 'sticker' or matches[2] == 's' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker ") return unlock_group_sticker(msg, data, target) end if matches[2] == 'name' or matches[2] == 'n' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' or matches[2] == 'm' 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' or matches[2] == 'f' 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] == 'adds' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link ") return unlock_group_link(msg, data, target) end if matches[2] == 'eng' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked eng ") return unlock_group_eng(msg, data, target) end if matches[2] == 'tag' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tag ") return unlock_group_tag(msg, data, target) end if matches[2] == 'badw' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked badw ") return unlock_group_badw(msg, data, target) end if matches[2] == 'join' or matches[2] == 'j' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked adds ") return unlock_group_adds(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ") return unlock_group_leave(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] == 'public' then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public") return unset_public_membermod(msg, data, target) end end]] if matches[1] == 'newlink' and not is_realm(msg) 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 for ("..string.gsub(msg.to.print_name, "_", " ")..":\n"..group_link end if matches[1] == 'setowner' and matches[2] 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] == 'setowner' and not matches[2] then if not is_owner(msg) then return "only for the owner!" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, setowner_by_reply, false) end end if matches[1] == 'dead' and matches[2] == 'kings' then return"DEAD_KINGs \n Advanced Bot Base On Seed\n@danyyyx[DeVeLoPeR] \n\n@KinG0fDeaD \n#Open_Source\n\n[@DeaD_T34M](Https://telegra.me/DeaD_T34M)" end if matches[1] == 'deadkings' then return "DEAD_KINGs \n Advanced Bot Base On Seed\n@danyyyx[DeVeLoPeR] \n\n@KinG0fDeaD \n#Open_Source\n\n[@DeaD_T34M](Https://telegra.me/DeaD_T34M)" 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]) < 2 or tonumber(matches[2]) > 85 then return "Wrong number,range is [2-85]" 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] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if not is_realm(msg) then local receiver = get_receiver(msg) return modrem(msg), print("Closing Group..."), chat_info(receiver, killchat, {receiver=receiver}) else return 'This is a realm' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if not is_group(msg) then local receiver = get_receiver(msg) return realmrem(msg), print("Closing Realm..."), chat_info(receiver, killrealm, {receiver=receiver}) else return 'This is a group' end end if matches[1] == 'help' then if not is_momod(msg) or is_realm(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 if matches[1] == 'kickinactive' then --send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]') if not is_momod(msg) then return 'Only a moderator can kick inactive users' end local num = 1 if matches[2] then num = matches[2] end local chat_id = msg.to.id local receiver = get_receiver(msg) return kick_inactive(chat_id, num, receiver) end end end return { usage ={ "add: Add Group In Moderations.", "add realm: Add Group As Realm.", "rem: Remove Group Of Moderation.", "rem realm: Removed Realm.", "rules: Return Group Rules.", "setname: Change Group Name.", "about: Return Group About.", "setphoto: Set Group Photo And Lock It.", "promote , promote[Reply]: Promote User In Group.", "demote , demote[Reply]: Demote Iser In Group.", "clean member: Remove All Users In Group.", "clean modlist: Demote All Moderation.", "clean rules: Clear Rules.", "set rules: Set Group Rules.", "set about: Set Group About.", "lock member: Nobody Can't Add User In Group.", "lock name: Nobdy Can't Change Group Name.", "lock flood: Banned Spammer If Flood Is Locked.", "unlock member: Anyone Can Add User In Group.", "unlock name: Anyone Can Change Group Name.", "unlock flood: No Action Execute I Spamming.", "owner: Return Group Owner Id.", "setowner: Set Group Owner.", "kill [Chat], kill [Realm]: Removed Group.", "setflood: Set Flood Sensitivity.", "newlink: Create New Link.", "link: Return Active Link For Group.", "kickinactive: Kick Users [Last Seen A Long Time Ago] Of Group.", "settings: Return Group Settings.", }, patterns = { "^(add)$", "^(add) (realm)$", "^(rem)$", "^(rem) (realm)$", "^(rules)$", "^([Dd]ead) (kings)$", "^(about)$", "^(setname) (.*)$", "^(setphoto)$", "^(promote) (.*)$", "^(promote)", "^(help)$", "^([Dd]eadkings)$", "^(clean) (.*)$", "^(kill) (chat)$", "^(kill) (realm)$", "^(demote) (.*)$", "^(demote)", "^(set) ([^%s]+) (.*)$", "^(lock) (.*)$", "^(setowner) (%d+)$", "^(setowner)", "^(owner)$", "^(res) (.*)$", "^(setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^(unlock) (.*)$", "^(setflood) (%d+)$", "^(settings)$", -- "^[!/](public) (.*)$", "^(modlist)$", "^(newlink)$", "^(link)$", "^(kickinactive)$", "^(kickinactive) (%d+)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
Ninjistix/darkstar
scripts/zones/Windurst_Woods/npcs/Panoquieur_TK.lua
5
2532
----------------------------------- -- Area: Windurst Woods -- NPC: Panoquieur, T.K. -- !pos -60 0 -31 241 -- X Grant Signet -- X Recharge Emperor Band, Empress Band, or Chariot Band -- X Accepts traded Crystals to fill up the Rank bar to open new Missions. -- X Sells items in exchange for Conquest Points -- X Start Supply Run Missions and offers a list of already-delivered supplies. -- Start an Expeditionary Force by giving an E.F. region insignia to you. ------------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/globals/common"); require("scripts/zones/Windurst_Woods/TextIDs"); local guardnation = NATION_SANDORIA; -- SANDORIA, BASTOK, WINDURST, JEUNO local guardtype = 2; -- 1: city, 2: foreign, 3: outpost, 4: border local size = #SandInv; local inventory = SandInv; function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; function onTrigger(player,npc) if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies." local region = player:getVar("supplyQuest_region"); player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region)); player:setVar("supplyQuest_started",0); player:setVar("supplyQuest_region",0); player:setVar("supplyQuest_fresh",0); else local Menu1 = getArg1(guardnation,player); local Menu2 = getExForceAvailable(guardnation,player); local Menu3 = conquestRanking(); local Menu4 = getSupplyAvailable(guardnation,player); local Menu5 = player:getNationTeleport(guardnation); local Menu6 = getArg6(player); local Menu7 = player:getCP(); local Menu8 = getRewardExForce(guardnation,player); player:startEvent(32763,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8); end end; function onEventUpdate(player,csid,option) -- printf("onUpdateCSID: %u",csid); -- printf("onUpdateOPTION: %u",option); updateConquestGuard(player,csid,option,size,inventory); end; function onEventFinish(player,csid,option) -- printf("onFinishCSID: %u",csid); -- printf("onFinishOPTION: %u",option); finishConquestGuard(player,csid,option,size,inventory,guardnation); end
gpl-3.0
dragoonreas/Timeless-Answers
Locales/zhTW.lua
1
1470
--[[ Traditional Chinese localisation strings for Timeless Answers. Translation Credits: http://wow.curseforge.com/addons/timeless-answers/localization/translators/ Please update http://www.wowace.com/addons/timeless-answers/localization/zhTW/ for any translation additions or changes. Once reviewed, the translations will be automatically incorperated in the next build by the localization application. These translations are released under the Public Domain. ]]-- -- Get addon name local addon = ... -- Create the Traditional Chinese localisation table local L = LibStub("AceLocale-3.0"):NewLocale(addon, "zhTW", false) if not L then return; end -- Messages output to the user's chat frame --@localization(locale="zhTW", format="lua_additive_table", handle-unlocalized="english", same-key-is-true=true, namespace="Message2")@ -- Gossip from the NPC that's neither an answer nor a question --@localization(locale="zhTW", format="lua_additive_table", handle-unlocalized="english", same-key-is-true=true, namespace="Gossip")@ -- The complete gossip text from when the NPC asks the question --@localization(locale="zhTW", format="lua_additive_table", handle-unlocalized="english", same-key-is-true=true, namespace="Question2")@ -- The complete gossip option text of the correct answer from when the NPC asks the question --@localization(locale="zhTW", format="lua_additive_table", handle-unlocalized="english", same-key-is-true=true, namespace="Answer")@
gpl-3.0
Ninjistix/darkstar
scripts/globals/weaponskills/mandalic_stab.lua
5
1630
----------------------------------- -- Mandalic Stab -- Dagger weapon skill -- Skill Level: N/A -- Damage Varies with TP. Vajra: Aftermath effect varies with TP. -- Multiplies attack by 1.66 -- Available only after completing the Unlocking a Myth (Thief) quest. -- Will stack with Sneak Attack. -- Aligned with the Shadow Gorget, Flame Gorget & Light Gorget. -- Aligned with the Shadow Belt, Flame Belt & Light Belt. -- Element: None -- Modifiers: DEX:30% -- 100%TP 200%TP 300%TP -- 2.00 2.13 2.50 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 2; params.ftp200 = 2.13; params.ftp300 = 2.5; params.str_wsc = 0.0; params.dex_wsc = 0.3; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1.66; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 4; params.ftp200 = 6.09; params.ftp300 = 8.5; params.dex_wsc = 0.6; params.atkmulti = 1.75; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Ninjistix/darkstar
scripts/globals/spells/foe_lullaby.lua
5
1274
----------------------------------------- -- Spell: Foe Lullaby ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local duration = 30; local pCHR = caster:getStat(MOD_CHR); local mCHR = target:getStat(MOD_CHR); local dCHR = (pCHR - mCHR); local params = {}; params.diff = nil; params.attribute = MOD_CHR; params.skillType = SINGING_SKILL; params.bonus = 0; params.effect = EFFECT_LULLABY; resm = applyResistanceEffect(caster, target, spell, params); if (resm < 0.5) then spell:setMsg(msgBasic.MAGIC_RESIST); -- resist message else local iBoost = caster:getMod(MOD_LULLABY_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (target:addStatusEffect(EFFECT_LULLABY,1,0,duration)) then spell:setMsg(msgBasic.MAGIC_ENFEEB); else spell:setMsg(msgBasic.MAGIC_NO_EFFECT); end end return EFFECT_LULLABY; end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/abilities/desperate_flourish.lua
3
2943
----------------------------------- -- Ability: Desperate Flourish -- Weighs down a target with a low rate of success. Requires one Finishing Move. -- Obtained: Dancer Level 30 -- Finishing Moves Used: 1 -- Recast Time: 00:20 -- Duration: ?? ----------------------------------- require("scripts/globals/weaponskills"); require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------- function onAbilityCheck(player,target,ability) if (player:getAnimation() ~= 1) then return msgBasic.REQUIRES_COMBAT,0; else if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then player:delStatusEffect(EFFECT_FINISHING_MOVE_1); return 0,0; elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_2); player:addStatusEffect(EFFECT_FINISHING_MOVE_1,1,0,7200); return 0,0; elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_3); player:addStatusEffect(EFFECT_FINISHING_MOVE_2,1,0,7200); return 0,0; elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_4); player:addStatusEffect(EFFECT_FINISHING_MOVE_3,1,0,7200); return 0,0; elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_5); player:addStatusEffect(EFFECT_FINISHING_MOVE_4,1,0,7200); return 0,0; else return msgBasic.NO_FINISHINGMOVES,0; end end end; function onUseAbility(player,target,ability,action) local isSneakValid = player:hasStatusEffect(EFFECT_SNEAK_ATTACK); if (isSneakValid and not player:isBehind(target)) then isSneakValid = false; end local hitrate = getHitRate(player,target,true); if (math.random() <= hitrate or isSneakValid) then local spell = getSpell(216); local params = {}; params.diff = 0; params.skillType = player:getWeaponSkillType(SLOT_MAIN); params.bonus = 50 - target:getMod(MOD_STUNRES); local resist = applyResistance(player, target, spell, params) if resist > 0.25 then target:delStatusEffectSilent(EFFECT_WEIGHT); target:addStatusEffect(EFFECT_WEIGHT, 50, 0, 60 * resist); else ability:setMsg(msgBasic.JA_DAMAGE); end ability:setMsg(msgBasic.JA_ENFEEB_IS); action:animation(target:getID(), getFlourishAnimation(player:getWeaponSkillType(SLOT_MAIN))) action:speceffect(target:getID(), 2) return EFFECT_WEIGHT else ability:setMsg(msgBasic.JA_MISS); return 0; end end;
gpl-3.0
jamiepg1/MCServer
lib/tolua++/src/bin/lua/basic.lua
2
9073
-- tolua: basic utility functions -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 1998 -- Last update: Apr 2003 -- $Id: $ -- This code is free software; you can redistribute it and/or modify it. -- The software provided hereunder is on an "as is" basis, and -- the author has no obligation to provide maintenance, support, updates, -- enhancements, or modifications. -- Basic C types and their corresponding Lua types -- All occurrences of "char*" will be replaced by "_cstring", -- and all occurrences of "void*" will be replaced by "_userdata" _basic = { ['void'] = '', ['char'] = 'number', ['int'] = 'number', ['short'] = 'number', ['long'] = 'number', ['unsigned'] = 'number', ['float'] = 'number', ['double'] = 'number', ['size_t'] = 'number', ['_cstring'] = 'string', ['_userdata'] = 'userdata', ['char*'] = 'string', ['void*'] = 'userdata', ['bool'] = 'boolean', ['lua_Object'] = 'value', ['LUA_VALUE'] = 'value', -- for compatibility with tolua 4.0 ['lua_State*'] = 'state', ['_lstate'] = 'state', ['lua_Function'] = 'value', } _basic_ctype = { number = "lua_Number", string = "const char*", userdata = "void*", boolean = "bool", value = "int", state = "lua_State*", } -- functions the are used to do a 'raw push' of basic types _basic_raw_push = {} -- List of user defined types -- Each type corresponds to a variable name that stores its tag value. _usertype = {} -- List of types that have to be collected _collect = {} -- List of types _global_types = {n=0} _global_types_hash = {} -- list of classes _global_classes = {} -- List of enum constants _global_enums = {} -- List of auto renaming _renaming = {} _enums = {} function appendrenaming (s) local b,e,old,new = strfind(s,"%s*(.-)%s*@%s*(.-)%s*$") if not b then error("#Invalid renaming syntax; it should be of the form: pattern@pattern") end tinsert(_renaming,{old=old, new=new}) end function applyrenaming (s) for i=1,getn(_renaming) do local m,n = gsub(s,_renaming[i].old,_renaming[i].new) if n ~= 0 then return m end end return nil end -- Error handler function tolua_error (s,f) if _curr_code then print("***curr code for error is "..tostring(_curr_code)) print(debug.traceback()) end local out = _OUTPUT _OUTPUT = _STDERR if strsub(s,1,1) == '#' then write("\n** tolua: "..strsub(s,2)..".\n\n") if _curr_code then local _,_,s = strfind(_curr_code,"^%s*(.-\n)") -- extract first line if s==nil then s = _curr_code end s = gsub(s,"_userdata","void*") -- return with 'void*' s = gsub(s,"_cstring","char*") -- return with 'char*' s = gsub(s,"_lstate","lua_State*") -- return with 'lua_State*' write("Code being processed:\n"..s.."\n") end else if not f then f = "(f is nil)" end print("\n** tolua internal error: "..f..s..".\n\n") return end _OUTPUT = out end function warning (msg) if flags.q then return end local out = _OUTPUT _OUTPUT = _STDERR write("\n** tolua warning: "..msg..".\n\n") _OUTPUT = out end -- register an user defined type: returns full type function regtype (t) --if isbasic(t) then -- return t --end local ft = findtype(t) if not _usertype[ft] then return appendusertype(t) end return ft end -- return type name: returns full type function typevar(type) if type == '' or type == 'void' then return type else local ft = findtype(type) if ft then return ft end _usertype[type] = type return type end end -- is enum function isenumtype (type) return _enums[type] end -- check if basic type function isbasic (type) local t = gsub(type,'const ','') local m,t = applytypedef('', t) local b = _basic[t] if b then return b,_basic_ctype[b] end return nil end -- split string using a token function split (s,t) local l = {n=0} local f = function (s) l.n = l.n + 1 l[l.n] = s return "" end local p = "%s*(.-)%s*"..t.."%s*" s = gsub(s,"^%s+","") s = gsub(s,"%s+$","") s = gsub(s,p,f) l.n = l.n + 1 l[l.n] = gsub(s,"(%s%s*)$","") return l end -- splits a string using a pattern, considering the spacial cases of C code (templates, function parameters, etc) -- pattern can't contain the '^' (as used to identify the begining of the line) -- also strips whitespace function split_c_tokens(s, pat) s = string.gsub(s, "^%s*", "") s = string.gsub(s, "%s*$", "") local token_begin = 1 local token_end = 1 local ofs = 1 local ret = {n=0} function add_token(ofs) local t = string.sub(s, token_begin, ofs) t = string.gsub(t, "^%s*", "") t = string.gsub(t, "%s*$", "") ret.n = ret.n + 1 ret[ret.n] = t end while ofs <= string.len(s) do local sub = string.sub(s, ofs, -1) local b,e = string.find(sub, "^"..pat) if b then add_token(ofs-1) ofs = ofs+e token_begin = ofs else local char = string.sub(s, ofs, ofs) if char == "(" or char == "<" then local block if char == "(" then block = "^%b()" end if char == "<" then block = "^%b<>" end b,e = string.find(sub, block) if not b then -- unterminated block? ofs = ofs+1 else ofs = ofs + e end else ofs = ofs+1 end end end add_token(ofs) --if ret.n == 0 then -- ret.n=1 -- ret[1] = "" --end return ret end -- concatenate strings of a table function concat (t,f,l,jstr) jstr = jstr or " " local s = '' local i=f while i<=l do s = s..t[i] i = i+1 if i <= l then s = s..jstr end end return s end -- concatenate all parameters, following output rules function concatparam (line, ...) local i=1 while i<=arg.n do if _cont and not strfind(_cont,'[%(,"]') and strfind(arg[i],"^[%a_~]") then line = line .. ' ' end line = line .. arg[i] if arg[i] ~= '' then _cont = strsub(arg[i],-1,-1) end i = i+1 end if strfind(arg[arg.n],"[%/%)%;%{%}]$") then _cont=nil line = line .. '\n' end return line end -- output line function output (...) local i=1 while i<=arg.n do if _cont and not strfind(_cont,'[%(,"]') and strfind(arg[i],"^[%a_~]") then write(' ') end write(arg[i]) if arg[i] ~= '' then _cont = strsub(arg[i],-1,-1) end i = i+1 end if strfind(arg[arg.n],"[%/%)%;%{%}]$") then _cont=nil write('\n') end end function get_property_methods(ptype, name) if get_property_methods_hook and get_property_methods_hook(ptype,name) then return get_property_methods_hook(ptype, name) end if ptype == "default" then -- get_name, set_name return "get_"..name, "set_"..name end if ptype == "qt" then -- name, setName return name, "set"..string.upper(string.sub(name, 1, 1))..string.sub(name, 2, -1) end if ptype == "overload" then -- name, name return name,name end return nil end -------------- the hooks -- called right after processing the $[ichl]file directives, -- right before processing anything else -- takes the package object as the parameter function preprocess_hook(p) -- p.code has all the input code from the pkg end -- called for every $ifile directive -- takes a table with a string called 'code' inside, the filename, and any extra arguments -- passed to $ifile. no return value function include_file_hook(t, filename, ...) end -- called after processing anything that's not code (like '$renaming', comments, etc) -- and right before parsing the actual code. -- takes the Package object with all the code on the 'code' key. no return value function preparse_hook(package) end -- called before starting output function pre_output_hook(package) end -- called after writing all the output. -- takes the Package object function post_output_hook(package) end -- called from 'get_property_methods' to get the methods to retrieve a property -- according to its type function get_property_methods_hook(property_type, name) end -- called from ClassContainer:doparse with the string being parsed -- return nil, or a substring function parser_hook(s) return nil end -- called from classFunction:supcode, before the call to the function is output function pre_call_hook(f) end -- called from classFunction:supcode, after the call to the function is output function post_call_hook(f) end -- called before the register code is output function pre_register_hook(package) end -- called to output an error message function output_error_hook(...) return string.format(...) end -- custom pushers _push_functions = {} _is_functions = {} _enums = {} _to_functions = {} _base_push_functions = {} _base_is_functions = {} _base_to_functions = {} local function search_base(t, funcs) local class = _global_classes[t] while class do if funcs[class.type] then return funcs[class.type] end class = _global_classes[class.btype] end return nil end function get_push_function(t) return _push_functions[t] or search_base(t, _base_push_functions) or "tolua_pushusertype" end function get_to_function(t) return _to_functions[t] or search_base(t, _base_to_functions) or "tolua_tousertype" end function get_is_function(t) if _enums[t] then return "tolua_is" .. t end return _is_functions[t] or search_base(t, _base_is_functions) or "tolua_isusertype" end
apache-2.0
DarkRing/TeleDarkRing
plugins/gif.lua
1
1657
do local BASE_URL = 'http://api.giphy.com/v1' local API_KEY = 'dc6zaTOxFJmzC' -- public beta key local function get_image(response) local images = json:decode(response).data if #images == 0 then return nil end -- No images local i = math.random(#images) local image = images[i] -- A random one if image.images.downsized then return image.images.downsized.url end if image.images.original then return image.original.url end return nil end local function get_random_top() local url = BASE_URL.."/gifs/trending?api_key="..API_KEY local response, code = http.request(url) if code ~= 200 then return nil end return get_image(response) end local function search(text) text = URL.escape(text) local url = BASE_URL.."/gifs/search?q="..text.."&api_key="..API_KEY local response, code = http.request(url) if code ~= 200 then return nil end return get_image(response) end local function run(msg, matches) local gif_url = nil -- If no search data, a random trending GIF will be sent if matches[1] == "gif" or matches[1] == "giphy" then gif_url = get_random_top() else gif_url = search(matches[1]) end if not gif_url then return "Error! GIF Not Found." end local receiver = get_receiver(msg) print("GIF URL"..gif_url) send_document_from_url(receiver, gif_url) end return { description = "GIFs from telegram with Giphy API", usage = { "!gif (term): Search and sends GIF from Giphy. If no param, sends a trending GIF.", "!giphy (term): Search and sends GIF from Giphy. If no param, sends a trending GIF." }, patterns = { "^[!/#](gif)$", "^[!/#](gif) (.*)", "^[!/#](giphy) (.*)", "^[!/#](giphy)$" }, run = run } end
gpl-2.0
johnsoch/cuberite
Server/Plugins/APIDump/Hooks/OnPlayerJoined.lua
44
1244
return { HOOK_PLAYER_JOINED = { CalledWhen = "After Login and before Spawned, before being added to world. ", DefaultFnName = "OnPlayerJoined", -- also used as pagename Desc = [[ This hook is called whenever a {{cPlayer|player}} has completely logged in. If authentication is enabled, this function is called after their name has been authenticated. It is called after {{OnLogin|HOOK_LOGIN}} and before {{OnPlayerSpawned|HOOK_PLAYER_SPAWNED}}, right after the player's entity is created, but not added to the world yet. The player is not yet visible to other players. Returning true will block a join message from being broadcast, but otherwise, the player is still allowed to join. Plugins wishing to refuse player's entry should kick the player using the {{cPlayer}}:Kick() function. ]], Params = { { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has joined the game" }, }, Returns = [[ If the function returns false or no value, other plugins' callbacks are called and a join message is broadcast. If the function returns true, no other callbacks are called for this event and a join message is not sent. Either way the player is let in. ]], }, -- HOOK_PLAYER_JOINED }
apache-2.0
bluetomatoes/ExploreTimelines
Code/timelinechooser.lua
1
13705
display.setStatusBar( display.HiddenStatusBar ) local widget = require "widget" widget.setTheme( "theme_ios" ) local sbHeight = 0 local tbHeight = 44 local top = sbHeight + tbHeight local toolbarGradient = graphics.newGradient( {168, 181, 198, 255 }, {139, 157, 180, 255}, "down" ) local divider = display.newLine(320, 0, 320, 768) divider:setColor(0) divider.width = 0 local overlay = display.newImage("assets/popoveroverlay.png",0,0, 1024,768) overlay.alpha = 0 local left_middlebar = display.newImage("assets/tabbargrey.png") local left_leftbar = display.newImage("assets/tab_bar_left.png") local left_rightbar = display.newImage("assets/tab_bar_right.png") left_middlebar.width = 320 - left_leftbar.width - left_rightbar.width left_leftbar.x = left_middlebar.x - left_middlebar.width/2 - left_leftbar.width/2 left_rightbar.x = left_middlebar.x + left_middlebar.width/2 + left_rightbar.width/2 local leftTitleText = display.newEmbossedText( "Beginning Date", 0, 0, native.systemFontBold, 20 ) leftTitleText:setReferencePoint( display.CenterReferencePoint ) leftTitleText:setTextColor( 113, 120, 128, 255 ) leftTitleText.x = left_middlebar.x leftTitleText.y = left_middlebar.y local main_middlebar = display.newImage("assets/tabbargrey.png") local main_leftbar = display.newImage("assets/tab_bar_left.png") local main_rightbar = display.newImage("assets/tab_bar_right.png") main_middlebar.width = 704 - main_leftbar.width - main_rightbar.width main_leftbar.x = main_middlebar.x - main_middlebar.width/2 - main_leftbar.width/2 main_rightbar.x = main_middlebar.x + main_middlebar.width/2 + main_rightbar.width/2 -- create embossed text to go on toolbar local titleText = display.newEmbossedText( "Your Timeline Library", 0, 0, native.systemFontBold, 20 ) titleText:setReferencePoint( display.CenterReferencePoint ) titleText:setTextColor( 113, 120, 128, 255 ) titleText.x = main_middlebar.x titleText.y = main_middlebar.y -- create a shadow underneath the bar (for a nice touch) local shadow = display.newImage( "assets/shadow.png" ) shadow:setReferencePoint( display.TopLeftReferencePoint ) shadow.x, shadow.y = 0, top shadow.xScale = display.contentWidth / shadow.contentWidth shadow.alpha = 0.45 local beginDate, endDate local selectionViewGradient = graphics.newGradient ( { 1, 94, 230, 255}, { 5, 140, 245, 255}, "up") -------------------------------------------------------------------------- local storyboard = require( "storyboard" ) local scene = storyboard.newScene() -- Called when the scene's view does not exist: function scene:createScene( event ) local group = self.view local popoverGroup = display.newGroup() local left_barGroup = display.newGroup() left_barGroup:insert(left_rightbar) left_barGroup:insert(left_leftbar) left_barGroup:insert(left_middlebar) left_barGroup:insert(leftTitleText) left_barGroup:setReferencePoint(display.TopLeftReferencePoint) left_barGroup.x = 0 local main_barGroup = display.newGroup() main_barGroup:insert(main_rightbar) main_barGroup:insert(main_leftbar) main_barGroup:insert(main_middlebar) main_barGroup:insert(titleText) --Creates the actual widget that goes on the left side of the split view controller. local leftTableView = widget.newTableView { top = top, width = 320, height = 724, maskFile = "assets/mask-320x724.png" } --When the rows are rendered, sets the text for each row. local function onRowRenderLeft( event ) local row = event.row local rowGroup = event.view beginDate = 1500 + row.index * 100 endDate = beginDate + 99 row.textObj = display.newText( rowGroup, beginDate.."-"..endDate, 0, 0, native.systemFontBold, 24) row.textObj:setTextColor( 54 ) row.textObj:setReferencePoint( display.CenterLeftReferencePoint ) row.textObj.x, row.textObj.y = 20, rowGroup.contentHeight * 0.5 end --Listens for the rows to be created and then determines what happens when rows are pressed. local run_no = 0 local chosenRowColor local function rowListenerLeft( event ) local row = event.row local background = event.background local rowGroup = event.view if event.phase == "press" then if previousRow then previousBkg = (255) print("here") end print( "Pressed row: " .. row.index ) print( rowGroup.y) background:setFillColor(selectionViewGradient) row.textObj:toFront() elseif event.phase == "release" or event.phase == "tap" then background:setFillColor( selectionViewGradient ) row.reRender = false -- set chosen row index to this row's index chosenRowText = row.textObj.text print(chosenRowText) chosenRowColor = selectionViewGradient previousRow = event.row previousBkg = event.background -- go to row scene --storyboard.gotoScene( "1754USA", "slideLeft", 350 ) elseif event.phase == "swipeLeft" then print( "Swiped Left row: " .. row.index ) elseif event.phase == "swipeRight" then print( "Swiped Right row: " .. row.index ) end end --Creates the actual rows. In for i = 1, x do, x is the number of rows. for i = 1, 4 do local isCategory = false local rowColor = { 255, 255, 255, 255} local rowHeight = 60 local listener = rowListener local lineColor = { 212, 212, 212} --inserts the rows into the tableView. the table below --reflects variables used to create the tableView, --and how they equal the TableView's properties. leftTableView:insertRow { height = rowHeight, rowColor = rowColor, isCategory = isCategory, onRender = onRowRenderLeft, listener = rowListenerLeft, lineColor = lineColor } end local tableView = widget.newTableView { top = top, left = 321, width = 704, height = 724, maskFile = "assets/mask-704x724.png", listener = tableViewListener, } main_barGroup:setReferencePoint(display.TopLeftReferencePoint) main_barGroup.x = 321 local function onRowRender( event ) local row = event.row local rowGroup = event.view local var = tostring(row.index) local var_1 = var.."/name.txt" print(var_1) local path = system.pathForFile( var_1, system.ResourcesDirectory) local nameFile, reason = io.open(path, "r") local timelineName = nameFile:read("*a") local label = "(" local color = 0 if row.isCategory then label = "Category (" color = 255 end row.textObj = display.newRetinaText( rowGroup, label .. row.index .. ")"..timelineName, 0, 0, native.systemFont, 16 ) row.textObj:setTextColor( color ) row.textObj:setReferencePoint( display.CenterLeftReferencePoint ) row.textObj.x, row.textObj.y = 20, rowGroup.contentHeight * 0.5 end local function rowListener( event ) local row = event.row local background = event.background local rowGroup = event.view if event.phase == "press" then print( "Pressed row: " .. row.index ) print( rowGroup.y) local selectionViewGradient = graphics.newGradient ( { 1, 94, 230, 255}, { 5, 140, 245, 255}, "up") background:setFillColor(selectionViewGradient) row.textObj:toFront() if row.textObj then row.textObj:setText( "Row pressed..." ) row.textObj:setReferencePoint( display.TopLeftReferencePoint ) row.textObj.x = 20 row.textObj:toFront() end print("GOT THIS FAR") elseif event.phase == "release" or event.phase == "tap" then print( "Tapped and/or Released row: " .. row.index ) background:setFillColor( 0, 110, 233, 255 ) row.reRender = true -- set chosen row index to this row's index chosenRowIndex = row.index -- go to row scene storyboard.gotoScene( "1754USA", "slideLeft", 350 ) elseif event.phase == "swipeLeft" then print( "Swiped Left row: " .. row.index ) elseif event.phase == "swipeRight" then print( "Swiped Right row: " .. row.index ) end end for i = 1, 2 do local isCategory = false local rowColor = { 255, 255, 255, 255} local lineColor = { 212, 212, 212} local rowHeight = 30 local listener = rowListener if i == 25 or i == 50 or i == 75 then isCategory = true rowHeight = 24 rowColor = { 150, 160, 180, 200 } listener = nil end tableView:insertRow { height = rowHeight, rowColor = rowColor, isCategory = isCategory, onRender = onRowRender, listener = listener, lineColor = lineColor } end group:insert(tableView) local run_number = 0 local globeBtnSheetOptions = { width = 51, height = 50, numFrames = 2, sheetContentWidth = 102, sheetContentHeight = 50, } local globeBtnSheet = graphics.newImageSheet( "assets/globebtns.png", globeBtnSheetOptions) local function onButtonRelease ( event ) local globeBtn = event.target if run_number == 0 then local popovertop = display.newImage("assets/uipopovertop.png") popovertop.x, popovertop.y = 0, 0 popovertop.alpha = 0.97 local popoverbottom = display.newImage("assets/uipopoverbottom.png") popoverbottom:setReferencePoint(display.CenterReferencePoint) popoverbottom.x, popoverbottom.y = popovertop.x, popovertop.y local popoverText = display.newEmbossedText( "Popover", 0, 0, native.systemFontBold, 20) popoverText.x, popoverText.y = popoverbottom.x, popoverbottom.y popoverText:setTextColor(255) popoverbottom.height = popoverText.height/2 + 18 + 366 + 8 popoverbottom.y = popovertop.y + popoverbottom.height/2 + 3 popoverGroup:insert(popoverbottom) popoverGroup:insert(popovertop) popoverGroup:insert(popoverText) -- Create a tableView print(popovertop.y, popoverText.y) local popoverTable = widget.newTableView { top = popoverText.y + 22, width = 320, height = 366, maskFile = "assets/mask-320x366.png", listener = tableViewListener, onRowRender = onRowRender, onRowTouch = onRowTouch, } popoverTable:setReferencePoint(display.CenterReferencePoint) popoverTable.x = popoverbottom.x popoverGroup:insert( popoverTable ) group:insert(popoverGroup) popoverbottom.width = popoverTable.width + 14 popovertop.width = popoverbottom.width popoverbottom.height = 22 + popoverTable.height + 7 popoverbottom.y = popovertop.y + popoverbottom.height * 0.5 + 2 popoverGroup.x = globeBtn.x - popoverGroup.width * 0.5 + globeBtn.width * 0.5 + 2 popoverGroup.y = top + popovertop.height * 0.5 - 6 -- Create 100 rows for i = 1, 100 do local isCategory = false local rowHeight = 40 local rowColor = { default = { 255, 255, 255 }, } local lineColor = { 212, 212, 212 } -- Make some rows categories if i == 25 or i == 50 or i == 75 then isCategory = true rowHeight = 24 rowColor = { default = { 150, 160, 180, 200 }, } end -- Insert the row into the tableView popoverTable:insertRow { isCategory = isCategory, rowHeight = rowHeight, rowColor = rowColor, lineColor = lineColor, } end print(popoverGroup.contentBounds.yMax) elseif run_number > 0 then popoverGroup.alpha = 1 end run_number = run_number + 1 end local function removePopover(event) print("started") if event.phase == "ended" then display.remove(popoverGroup) popoverGroup = nil print("ended") end end --[[ local globeBtn = widget.newButton { left = 970, -- top = bar.y - bar.height * 0.5, sheet = globeBtnSheet, defaultIndex = 2, overIndex = 1, width = 38.25, height = 37.5, onRelease = onButtonRelease } ]] group:insert(left_barGroup) group:insert(main_barGroup) group:insert(divider) group:insert(shadow) leftTableView:toBack() overlay:toFront() overlay:addEventListener("touch", removePopover) end -- Called immediately after scene has moved onscreen: function scene:enterScene( event ) local group = self.view ----------------------------------------------------------------------------- -- INSERT code here (e.g. start timers, load audio, start listeners, etc.) ----------------------------------------------------------------------------- end -- Called when scene is about to move offscreen: function scene:exitScene( event ) local group = self.view display.remove(group) group = nil ----------------------------------------------------------------------------- -- INSERT code here (e.g. stop timers, remove listeners, unload sounds, etc.) ----------------------------------------------------------------------------- end -- Called prior to the removal of scene's "view" (display group) function scene:destroyScene( event ) local group = self.view ----------------------------------------------------------------------------- -- INSERT code here (e.g. remove listeners, widgets, save state, etc.) ----------------------------------------------------------------------------- end --------------------------------------------------------------------------------- -- END OF YOUR IMPLEMENTATION --------------------------------------------------------------------------------- -- "createScene" event is dispatched if scene's view does not exist scene:addEventListener( "createScene", scene ) -- "enterScene" event is dispatched whenever scene transition has finished scene:addEventListener( "enterScene", scene ) -- "exitScene" event is dispatched before next scene's transition begins scene:addEventListener( "exitScene", scene ) -- "destroyScene" event is dispatched before view is unloaded, which can be -- automatically unloaded in low memory situations, or explicitly via a call to -- storyboard.purgeScene() or storyboard.removeScene(). scene:addEventListener( "destroyScene", scene ) --------------------------------------------------------------------------------- return scene
mit
neofob/sile
languages/my.lua
3
3266
local function charclass(u) if (u >= 0x1000 and u <= 0x102A) or u == 0x104E or u == 0x25CC or u == 0x2d then return "CI" end if u == 0x1039 then return "VI" end if u >= 0x103B and u <= 0x103E then return "ME" end if u == 0x1031 then return "EV" end if u == 0x102F or u == 0x1030 then return "LV" end if u == 0x102D or u == 0x102E or u == 0x1032 then return "UV" end if u == 0x102C or u == 0x102B then -- 0x102b added by SC because it was splitting visargas return "AV" end if u == 0x1036 then return "AN" end if u == 0x103A then return "KI" end if u == 0x1037 then return "LD" end if u == 0x1038 then return "VG" end if u >= 0x1040 and u <= 0x1049 then return "MD" end if u == 0x104A or u == 0x104B or u == 0x2c or u == 0x2e or u == 0x3a or u == 0x3b then return "SE" end if u == 0x104C or u == 0x104D or u == 0x104F then return "VS" end if u >= 0x1050 and u <= 0x1055 then return "PL" end if u >= 0x1056 and u <= 0x1059 then return "PV" end if u == 0x20 or (u >= 0x2000 and u <= 0x200b) then return "SP" end if u == 0x28 or u == 0x5b or u == 0x7b or u == 0xab or u== 0x2018 or u == 0x201C or u == 0x2039 then return "LQ" end if u == 0x29 or u == 0x5d or u == 0x7d or u == 0xbb or u== 0x2019 or u == 0x201d or u == 0x203a then return "RQ" end if u == 0x200c then return "NJ" end if u == 0x2060 or u == 0x200d then return "WJ" end return "OT" end -- "Syllable Based Dual Weight Algorithm for Line Breaking in Myanmar Unicode" -- Keith Stribley, http://thanlwinsoft.github.io/www.thanlwinsoft.org/ThanLwinSoft/MyanmarUnicode/Parsing/my2weightLineBreakAlg1_1.pdf local p2 = SILE.nodefactory.newPenalty({ penalty = -25 }) local p1 = SILE.nodefactory.newPenalty({ penalty = -50 }) local penaltyFor = function (ca, cb) if ca == "WJ" or ca == "LQ" then return end if cb == "RQ" or cb == "WJ" then return end if ca == "OT" then return p1 end if ca == "RQ" then return p2 end if cb == "LQ" then return p2 end if cb == "CI" then if ca == "AN" or ca == "KI" or ca == "LD" or ca == "VG" or ca == "PL" or ca == "PV" or ca == "RQ" then return p2 end if ca == "MD" or ca == "SE" or ca == "VS" or ca == "SP" then return p1 end return end if ca == "MD" and not (cb == "VI" or cb == "MD") then return p1 end if cb == "PL" then if ca == "VI" then return end if ca == "SE" or ca == "VB" then return p1 end return p2 end end SILE.tokenizers.my = function(string) return coroutine.wrap(function() local db local lastcp = -1 local lastchar = "" local lastclass = "" local collection = "" for uchar in string.gmatch(string, "([%z\1-\127\194-\244][\128-\191]*)") do local thiscp = SU.codepoint(uchar) local thisclass = charclass(thiscp) if thisclass == "SP" then coroutine.yield({ separator = uchar }) else local pen = penaltyFor(lastclass, thisclass) if pen then coroutine.yield({ node = pen }) coroutine.yield({ string = collection}) collection = "" end collection = collection .. uchar end lastcp = thiscp lastchar = uchar lastclass = thisclass end coroutine.yield({ string = collection }) end) end
mit
imashkan/seedfire
plugins/plugins.lua
1
5936
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'> '..status..' '..v..'\n' end end local text = text..'\n______________________________\nNumber of all tools: '..nsum..'\nEnable tools= '..nact..' and Disables= '..nsum-nact return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..status..' '..v..'\n' end end local text = text..'\n___________________________\nAll tools= '..nsum..' ,Enable items= '..nact return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return plugin_name..' is enabled' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return plugin_name..' does not exists' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return name..' does not exists' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return name..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return plugin..' disabled in group' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return plugin..' enabled again' end local function run(msg, matches) -- Show the available plugins if matches[1] == 'plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == '+' and matches[3] == 'gp' then local receiver = get_receiver(msg) local plugin = matches[2] print(""..plugin..' enabled in group') return reenable_plugin_on_chat(receiver, plugin) end -- Enable a plugin if matches[1] == '+' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end -- Disable a plugin on a chat if matches[1] == '-' and matches[3] == 'gp' then local plugin = matches[2] local receiver = get_receiver(msg) print(""..plugin..' disabled in group') return disable_plugin_on_chat(receiver, plugin) end -- Disable a plugin if matches[1] == '-' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == '@' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin Manager", usage = { moderator = { "/plugins - (name) gp : disable item in group", "/plugins + (name) gp : enable item in group", }, sudo = { "/plugins : plugins list", "/plugins + (name) : enable bot item", "/plugins - (name) : disable bot item", "/plugins @ : reloads plugins" }, }, patterns = { "^plugins$", "^plugins? (+) ([%w_%.%-]+)$", "^plugins? (-) ([%w_%.%-]+)$", "^plugins? (+) ([%w_%.%-]+) (gp)", "^plugins? (-) ([%w_%.%-]+) (gp)", "^plugins? (@)$" }, run = run, moderated = true, -- set to moderator mode --privileged = true } end
gpl-2.0
Igalia/skia
tools/lua/scrape_dashing_full.lua
159
4610
local canvas -- holds the current canvas (from startcanvas()) --[[ startcanvas() is called at the start of each picture file, passing the canvas that we will be drawing into, and the name of the file. Following this call, there will be some number of calls to accumulate(t) where t is a table of parameters that were passed to that draw-op. t.verb is a string holding the name of the draw-op (e.g. "drawRect") when a given picture is done, we call endcanvas(canvas, fileName) ]] function sk_scrape_startcanvas(c, fileName) canvas = c end --[[ Called when the current canvas is done drawing. ]] function sk_scrape_endcanvas(c, fileName) canvas = nil end --[[ Use to initialize all keys passed in keyTable to zero in table. Useful so that keys that are never get incremented still output zero at end ]] function resetTableKeys(table, keyTable) for k, v in next, keyTable do table[v] = 0 end end function increment(table, key) table[key] = (table[key] or 0) + 1 end local dashCount = 0 local total_found = {} local drawPoints_count = {} local drawPoints_direction = {} resetTableKeys(drawPoints_direction, {"hori", "vert", "other"}) local dashInterval_count = {} local dashInterval_pattern = {} resetTableKeys(dashInterval_pattern, {"one_one", "zero_on", "other"}) local dash_phase = {} resetTableKeys(dash_phase, {"zero", "other"}) local dash_cap = {} resetTableKeys(dash_cap, {"butt", "round", "square"}) local dashTable = {} dashTable.total_found = total_found dashTable.drawPoints_count = drawPoints_count dashTable.drawPoints_direction = drawPoints_direction dashTable.dashInterval_count = dashInterval_count dashTable.dashInterval_pattern = dashInterval_pattern dashTable.dash_phase = dash_phase dashTable.dash_cap = dash_cap function sk_scrape_accumulate(t) local p = t.paint if p then local pe = p:getPathEffect() if pe then local de = pe:asADash() if de then dashCount = dashCount + 1 increment(total_found, t.verb); increment(dashInterval_count, #de.intervals) if 2 == #de.intervals then if 1 == de.intervals[1] and 1 == de.intervals[2] then increment(dashInterval_pattern, "one_one") elseif 0 == de.intervals[1] then increment(dashInterval_pattern, "zero_on") else increment(dashInterval_pattern, "other") end end if 0 == de.phase then increment(dash_phase, "zero") else increment(dash_phase, "other") end local cap = p:getStrokeCap() if 0 == cap then increment(dash_cap, "butt") elseif 1 == cap then increment(dash_cap, "round") else increment(dash_cap, "square") end if "drawPoints" == t.verb then local points = t.points increment(drawPoints_count, #points) if 2 == #points then if points[1].y == points[2].y then increment(drawPoints_direction, "hori") elseif points[1].x == points[2].x then increment(drawPoints_direction, "vert") else increment(drawPoints_direction, "other") end end end --[[ eventually would like to print out info on drawPath verbs with dashed effect ]] if "drawPath" == t.verb then end end end end end --[[ lua_pictures will call this function after all of the pictures have been "accumulated". ]] function sk_scrape_summarize() -- use for non telemetry --[[ io.write("Total dashed effects is: ", dashCount, "\n"); for k1, v1 in next, dashTable do io.write("\nTable: ", k1, "\n") for k, v in next, v1 do io.write("\"", k, "\": ", v, "\n") end end ]] -- use for telemetry io.write("\ndashCount = dashCount + ", tostring(dashCount), "\n") for k1, v1 in next, dashTable do for k, v in next, v1 do io.write("\nincrement(dashTable, \"", k1, "\", \"", k, "\", ", v, ")\n") end end end
bsd-3-clause
Ninjistix/darkstar
scripts/zones/Upper_Jeuno/npcs/Theraisie.lua
5
1601
----------------------------------- -- Area: Upper Jeuno -- NPC: Theraisie -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Upper_Jeuno/TextIDs"); require("scripts/globals/shop"); function onTrade(player,npc,trade) end; function onTrigger(player,npc) player:showText(npc, MP_SHOP_DIALOG); local stock = { 21444, 200, -- Livid Broth 21445, 344, -- Lyrical Broth 21446, 519, -- Airy Broth 21447,1016, -- Crumbly Soil 17922,1484, -- Blackwater Broth 21448,1747, -- Pale Sap 21498,1747, -- Crackling Broth 17920,2195, -- Meaty Broth 21497,2371, -- Rapid Broth 21499,2425, -- Creepy Broth 17921,2853, -- Muddy Broth 21449,3004, -- Dire Broth 17016, 100, -- Pet Food Alpha 17017, 200, -- Pet Food Beta 17018, 350, -- Pet Food Gamma 17019, 500, -- Pet Food Delta 17020, 750, -- Pet Food Epsilon 17021,1000, -- Pet Food Zeta 17022,1500, -- Pet Food Eta 17023,2000, -- Pet Food Theta 19251, 300, -- Pet Roborant 19252, 250 -- Pet Poultice } showShop(player, STATIC, stock); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Port_San_dOria/npcs/Parcarin.lua
5
1374
----------------------------------- -- Area: Port San d'Oria -- NPC: Parcarin -- Involved in Quest: Lure of the Wildcat (San d'Oria) -- !pos -9 -13 -151 232 ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer player:messageSpecial(FLYER_REFUSED); end end end; function onTrigger(player,npc) local WildcatSandy = player:getVar("WildcatSandy"); if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,13) == false) then player:startEvent(747); else player:startEvent(566); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 747) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",13,true); end end;
gpl-3.0
dmekersa/create2Dmobilegames
TextAdvanced/main.lua
1
1784
-- The options table will be used later to store text attributes local options -- Create a background rectangle for the title local titleBackground = display.newRect( display.contentCenterX, 50, display.actualContentWidth, 50 ) titleBackground:setFillColor( .2, .2, .4 ) -- Create the label for the title at the same position options = { text = "My nice title", x = display.contentCenterX, y = titleBackground.y, font = native.systemFont, fontSize = 25 } local mytitle = display.newText( options ) -- An underlined title options = { text = "My underlined title", x = display.contentCenterX, y = 150, font = native.systemFont, fontSize = 25 } local myTitle2 = display.newText( options ) -- Calculate the position and length of the underline local title2X1 = myTitle2.x - myTitle2.width/2 local title2X2 = myTitle2.x + myTitle2.width/2 local title2Y = myTitle2.y + myTitle2.height / 2 local title2Line = display.newLine( title2X1, title2Y, title2X2, title2Y ) title2Line:setStrokeColor( 1, .3, .3 ) -- A squared title options = { text = "I'm in a frame!", x = display.contentCenterX, y = 250, font = native.systemFont, fontSize = 25 } local myTitle3 = display.newText( options ) -- The square local padding = 5 local title3Square = display.newRect( myTitle3.x, myTitle3.y, myTitle3.width + padding, myTitle3.height + padding ) -- To be a square, the rect needs a stroke and a transparent fill title3Square.strokeWidth = 1 title3Square:setFillColor( 0, 0 ) title3Square:setStrokeColor( .6, .6, .8 ) local backButton = widget.newButton { left = 0, top = display.contentHeight-200, width = display.contentWidth, height = 200, label = "Back...", onEvent = handleButtonEvent }
unlicense
Ninjistix/darkstar
scripts/globals/mobskills/chains_of_rage.lua
5
1329
--------------------------------------------- -- Chains of Rage -- --------------------------------------------- package.loaded["scripts/zones/Empyreal_Paradox/TextIDs"] = nil; --------------------------------------------- require("scripts/zones/Empyreal_Paradox/TextIDs"); require("scripts/globals/monstertpmoves"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/msg"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) local targets = mob:getEnmityList(); for i,v in pairs(targets) do if (v.entity:isPC()) then local race = v.entity:getRace() if (race == 8) and not v.entity:hasKeyItem(LIGHT_OF_ALTAIEU) then mob:showText(mob, PROMATHIA_TEXT + 4); return 0; end end end return 1; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_TERROR; local power = 30; local duration = 30; if target:isPC() and ((target:getRace() == 8) and not target:hasKeyItem(LIGHT_OF_ALTAIEU)) then skill:setMsg(MobStatusEffectMove(mob, target, typeEffect, power, 0, duration)); else skill:setMsg(msgBasic.SKILL_NO_EFFECT); end return typeEffect; end;
gpl-3.0
hvbommel/domoticz
dzVents/runtime/device-adapters/evohome_device.lua
2
5055
local TimedCommand = require('TimedCommand') return { baseType = 'device', name = 'Evohome device adapter', matches = function (device, adapterManager) local res = ( device.hardwareTypeValue == 39 or device.hardwareTypeValue == 40 or device.hardwareTypeValue == 106 or device.hardwareTypeValue == 75 ) if (not res) then adapterManager.addDummyMethod(device, 'updateSetPoint') adapterManager.addDummyMethod(device, 'setHotWater') adapterManager.addDummyMethod(device, 'setMode') end return res end, process = function (device, data, domoticz, utils, adapterManager) if device.deviceSubType == "Hot Water" then if device.rawData[2] == "On" then device.state = "On" else device.state = "Off" end device.mode = tostring(device.rawData[3] or "n/a") device.untilDate = tostring(device.rawData[4] or "n/a") function device.setHotWater(state, mode, untilDate) if mode == 'TemporaryOverride' and untilDate then mode = mode .. "&until=" .. untilDate end local url = domoticz.settings['Domoticz url'] .. "/json.htm?type=setused&idx=" .. device.id .. "&setpoint=&state=" .. state .. "&mode=" .. mode .. "&used=true" return domoticz.openURL(url) end elseif device.deviceSubType == "Relay" then device.state = device._state == 'Off' and 'Off' or 'On' if device.state == 'Off' then device.level = 0 else device.level = device._state:match('%d+') or 100 end device.active = device.state ~= 'Off' else if device.hardwareTypeValue == 75 and device.deviceType == 'Heating' and device.deviceSubType == 'Evohome' then device.mode = device._state else device.state = device.rawData[2] device.mode = tostring(device.rawData[3]) end device.setPoint = tonumber(device.rawData[1] or 0) device.untilDate = tostring(device.rawData[4] or "n/a") function device.updateSetPoint(setPoint, mode, untilDate) if mode == domoticz.EVOHOME_MODE_TEMPORARY_OVERRIDE and not(untilDate) then return TimedCommand(domoticz, 'SetSetPoint:' .. tostring(device.id), tostring(setPoint) .. '#' .. mode, 'setpoint' ) else return TimedCommand(domoticz, 'SetSetPoint:' .. tostring(device.id), tostring(setPoint) .. '#' .. tostring(mode) .. '#' .. tostring(untilDate) , 'setpoint') end end function device.setMode(mode, dParm, action, ooc) local function checkTimeAndReturnISO(tm) local now = domoticz.time local iso8601Pattern = "(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+)Z" local iso8601Format = "%Y-%m-%dT%TZ" local function inFuture(tmISO) local function makeFutureISOTime(str, hours) local xyear, xmonth, xday, xhour, xminute, xseconds = str:match(iso8601Pattern) local seconds = os.time({year = xyear, month = xmonth, day = xday, hour = xhour, min = xminute, sec = xseconds}) local offset = (seconds + ( hours or 0 ) * 3600) return os.date(iso8601Format,offset), offset end local _, epoch = makeFutureISOTime(tmISO) return epoch >= now.dDate and tmISO end if type(tm) == 'string' and tm:find(iso8601Pattern) then return inFuture(tm) end -- Something like '2016-04-29T06:32:58Z' if type(tm) == 'table' and tm.getISO then return inFuture(tm.getISO()) end -- a dzVents time object if type(tm) == 'table' and tm.day then return inFuture(os.date(iso8601Format,os.time(tm))) end -- a standard time object if type(tm) == 'number' and tm > now.dDate then return inFuture(os.date(iso8601Format,tm)) end -- seconds since epoch if type(tm) == 'number' and tm > 0 and tm < ( 365 * 24 * 60 ) then return inFuture(os.date(iso8601Format,now.dDate + ( tm * 60 ))) end -- seconds since epoch + tm domoticz.log('dParm ' .. tostring(dParm) .. ' cannot be processed. (it will be ignored)',utils.LOG_ERROR) return false -- not a time as we know it end local function isValid(mode) for _, value in pairs(domoticz) do local res = type(value) == 'string' and value == mode if res then return res end end return mode == 'Busted' or false end local function binary(num, default) if num == 0 or num == 1 then return num else return default end end if isValid( tostring(mode) ) then -- is it in the list of valid modes ? local dParm = dParm and checkTimeAndReturnISO(dParm) -- if there is a dParm then check if valid and make a valid ISO date dParm = ( dParm and '&until=' .. dParm ) or '' local action = ( action and '&action=' .. binary(action, 1) ) or '&action=1' local ooc = ( ooc and '&ooc=' .. binary(ooc, 0) ) or '&ooc=0' local url = domoticz.settings['Domoticz url'] .. '/json.htm?type=command&param=switchmodal&idx=' .. device.id .. "&status=" .. mode .. dParm .. action .. ooc return domoticz.openURL(url) else utils.log('Unknown status for setMode requested: ' .. tostring(mode),utils.LOG_ERROR) end end end end }
gpl-3.0
EliasOenal/blobby
data/scripts/old/hyp09.lua
4
9122
g=0.28 pg=0.88 v0=14.5 v_p=4.5 pj=0.44 r1=31.5 p0=0 p1=0.5 p2=1 h=31.5+19+25 estt=0 nettime=0 touch=0 est=0 p=0.4 esto=10 function yb(y,vy,t) return y+(vy-g/10)*t-1/2*g*t^2 end function move(x) if (posx()<x) and (math.abs(posx()-x)>2.26) then right() elseif (posx()>x) and (math.abs(posx()-x)>2.26) then left() end end function tb(y,vy,height,typ) local sgn=0 if (typ==1) then sgn=-1 else sgn=1 end if vy^2/g^2-vy/(5*g)+1/100+2*(y-height)/g<0 then return -1 else return -1/10+vy/g+sgn*math.sqrt( vy^2/g^2-vy/(5*g)+1/100+2*(y-height)/g ) end end function time(t) return 1/5*math.ceil(5*t) end function pos(x) local x1,x2 x1=4.5*math.ceil((1/4.5)*x) x2=4.5*math.floor((1/4.5)*x) if (x1<0) or (x2<0) then return 0 else if (math.abs(x1-x)<math.abs(x2-x)) then return x1 else return x2 end end end function yp(t) -- Eingabe: Position und Geschwindigkeit des Players, Zeitpunkt an dem man die y-Koordinate des Players wissen möchte -- Ausgabe: Höhe des Players nach der Zeit t return 144.5+(14.5+pj/2+pg/10)*t-1/2*(pg-pj)*t^2 end function tp(y) return (14.5+pj/2+pg/10)/(pg-pj)-math.sqrt(((14.5+pj/2+pg/10)/(pg-pj))^2-(y-144.5)/(1/2*(pg-pj))) end function tp2(y1p,v1p) if (y1p>146) then return (v1p/0.88-1/2+math.sqrt((v1p/0.88-1/2)^2-(144.5-y1p)/0.44)) else return 0 end end function time(t) return 1/5*math.ceil(5*t) end -- </Abschnitt 2> function collide(x,y,vx,vy,objx,objy,r2) local t1=time(math.max(tb(y,vy,objy-(r1+r2),1)-0.2,0)) local t2=time(tb(y,vy,objy+(r1+r2),1)+0.2) local t3=time(math.max(tb(y,vy,objy+(r1+r2),2)-0.2,0)) local t4=time(tb(y,vy,objy-(r1+r2),2)+0.2) local t=-1 if (t1<t2) then for testimate=t1,t2,0.2 do if ( (yb(y,vy,testimate)-objy)^2+(x+vx*testimate-objx)^2 < (r1+r2)^2) then t=testimate break end end end if (t<=0) and (t3<t4) then for testimate=t3,t4,0.2 do if ( (yb(y,vy,testimate)-objy)^2+(x+vx*testimate-objx)^2 < (r1+r2)^2) then t=testimate break end end end if (t<=0) or (t>150) then t=-1 end return t end function estimate(x,y,vx,vy,height,typ) local collision=1 local tw,tn,ts=0,0,0 local tr,xr,yr,vxr,vyr,n=0,0,0,0,0,0 while(collision==1) do ts=collide(x,y,vx,vy,400,316,7) if (vx>0) then tw=time((768.5-x)/vx) tn=time((361.5-x)/vx) else tw=time((31.5-x)/vx) tn=time((438.5-x)/vx) end local th=time(tb(y,vy,height,typ)) local t=10000 if ((ts>0) and (ts<t)) then t=ts end if (((tn>0) and (tn<t)) and (yb(y,vy,tn)<316)) then t=tn end if ((tw>0) and (tw<t)) then t=tw end if (th>t) then if (t==ts) then tr=tr+t x=x+vx*t y=yb(y,vy,t) vy=vy-g*t xr=x yr=y vxr=0 vyr=0 n=1 collision=0 elseif ((t==tn) or (t==tw)) then tr=tr+t x=x+vx*t y=yb(y,vy,t) vx=-vx vy=vy-g*t collision=1 end else tr=tr+th vxr=vx vyr=vy-g*th xr=x+vx*th yr=yb(y,vy,th) collision=0 end end if (tr<0) then return -1,-1,-1,-1,-1,-1 else return xr,yr,vxr,vyr,tr,n end end function impact(x,y,vx,vy,xpos,ypos,targety,jump,move) local x1,y1,vx1,vy1=0,0,0,0 local x2,y2,vx2,vy2,t2,nn=0,0,0,0,0,0 local xpos1=xpos local ypos1=ypos for t=0,20,0.2 do if (jump==1) then ypos1=yp(tp(ypos)+t) end x1=x+vx*t if (x1<31.5) then x1=2*31.5-x1 end if (x1>368.5) then x1=2*368.5-x1 end y1=yb(y,vy,t) if ((xpos1-x1)^2+(ypos1+19-y1)^2<(31.5+25)^2) then local dx=x1-xpos1 local dy=y1-(ypos1+19) local l=math.sqrt(dx^2+dy^2) vx1=dx/l vy1=dy/l x1=x1+vx1*3 y1=y1+vy1*3 vy1=vy1*13.125 vx1=vx1*13.125 x2,y2,vx2,vy2,t2,nn=estimate(x1,y1,vx1,vy1,targety,2) break end end return x2,y2,x1,y1,vx1,vy1 end function lob() if (math.abs(est-esto)>0.2) then x1,y1,t1,x2,y2,t2,vx2,vy2,x1f,y1f,t1f,x2f,y2f,t2f,vx2f,vy2f,x1t,y1t,t1t,x2t,y2t,t2t,vx2t,vy2t=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 t2g=0 -- debug(-10) esto=est imp=0 x1=0 for t=33,0,-3 do if (t==0) then j=0 else j=1 end t1f=t y1f=yp(t1f) t2g=math.floor(tb(y,vy,y1f+h,2)) y2f=yb(y,vy,t2g) vy2f=vy-g*t2g x2f,y2f,vx2f,vy2f,t2f,_=estimate(x,y,vx,vy,y2f-vy2f/30,2) t1f=math.floor(tp(y2f-h)) y1f=yp(t1f) if (t1f+math.abs(tp2(posy(),vp))<t2f) and (t2g>1) and (t2f>1) and ((math.abs(posx()-(x2f+4.5))/4.5<t2f) or (math.abs(posx()-(x2f-15*4.5))/4.5<t2f)) then for x1f=pos(x2f)+4.5,pos(x2f)-15*4.5,-4.5 do impf,_,_,_,_,_=impact(x2f,y2f,vx2f,vy2f,x1f,y1f,220,j,0) if (impf>700) and (math.abs(posx()-x1f)/4.5<t2f) and (x1f<360) and (x1f>0) then impt=impf x1t=x1f y1t=y1f t1t=t1f x2t=x2f y2t=y2f t2t=t2f vx2t=vx2f vy2t=vy2f break end end if (impt>imp) then imp=impt x1=x1t y1=y1t t1=t1t x2=x2t y2=y2t t2=t2t vx2=vx2t vy2=vy2t end if (imp>740) then break end end end t2=t2+1 end t2=t2-1 if (x1>0) then move(x1) if (t2<=t1+0.1) and (y1>146) then jump() end else move(est) end end function attack() if (math.abs(est-esto)>0.2) then x1,y1,t1,x2,y2,t2,vx2,vy2,x1f,y1f,t1f,x2f,y2f,t2f,vx2f,vy2f,x1t,y1t,t1t,x2t,y2t,t2t,vx2t,vy2t=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 t2g=0 h2=900 -- debug(-10) esto=est imp=0 x1=0 for t=33,0,-3 do if (t==0) then j=0 else j=1 end t1f=t y1f=yp(t1f) t2g=math.floor(tb(y,vy,y1f+h,2)) y2f=yb(y,vy,t2g) vy2f=vy-g*t2g x2f,y2f,vx2f,vy2f,t2f,_=estimate(x,y,vx,vy,y2f-vy2f/30,2) t1f=math.floor(tp(y2f-h)) y1f=yp(t1f) if (t1f+math.abs(tp2(posy(),vp))<t2f) and (t2g>1) and (t2f>1) and ((math.abs(posx()-(x2f+4.5))/4.5<t2f) or (math.abs(posx()-(x2f-15*4.5))/4.5<t2f)) then for x1f=pos(x2f)-25*4.5,pos(x2f)+4.5,4.5 do impf,_,xaf,yaf,vxaf,vyaf=impact(x2f,y2f,vx2f,vy2f,x1f,y1f,220,j,0) if (impf>400) and (math.abs(posx()-x1f)/4.5+1<t2f) and (x1f>0) and (x1f<360) then impt=impf x1t=x1f y1t=y1f t1t=t1f x2t=x2f y2t=y2f t2t=t2f vx2t=vx2f vy2t=vy2f xat=xaf yat=yaf vxat=vxaf vyat=vyaf break end end h2t=yb(yat,vyat,(400-xat)/vxat) if (h2t<h2) and (h2t>316+31.5) then imp=impt x1=x1t y1=y1t t1=t1t x2=x2t y2=y2t t2=t2t vx2=vx2t vy2=vy2t xa=xat ya=yat vxa=vxat vya=vyat end h2=yb(ya,vya,(400-xa)/vxa) if (h2<316+31.5+10) and (h2>316+31.5) then break end end end t2=t2+1 end t2=t2-1 if (x1>0) then move(x1) if (t2<=t1+0.1) and (y1>146) then jump() end else move(est) end end function netp() if (math.abs(est-esto)>0.2) then x1,y1,t1,x2,y2,t2,vx2,vy2,x1f,y1f,t1f,x2f,y2f,t2f,vx2f,vy2f,x1t,y1t,t1t,x2t,y2t,t2t,vx2t,vy2t=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 t2g=0 -- debug(-10) esto=est imp=0 x1=0 for t=33,0,-3 do if (t==0) then j=0 else j=1 end t1f=t y1f=yp(t1f) t2g=math.floor(tb(y,vy,y1f+h,2)) y2f=yb(y,vy,t2g) vy2f=vy-g*t2g x2f,y2f,vx2f,vy2f,t2f,nn=estimate(x,y,vx,vy,y2f-vy2f/30,2) t1f=math.floor(tp(y2f-h)) y1f=yp(t1f) if (t1f+math.abs(tp2(posy(),vp))<t2f) and (t2g>1) and (t2f>1) and ((math.abs(posx()-(x2f+4.5))/4.5<t2f) or (math.abs(posx()-(x2f-15*4.5))/4.5<t2f)) and (nn==0) then for x1f=pos(x2f)+4.5,pos(x2f)-15*4.5,-4.5 do impf,_,_,_,_,_=impact(x2f,y2f,vx2f,vy2f,x1f,y1f,220,j,0) if (impf>400) and (math.abs(posx()-x1f)/4.5<t2f) and (x1f<360) and (x1f>0) then impt=impf x1t=x1f y1t=y1f t1t=t1f x2t=x2f y2t=y2f t2t=t2f vx2t=vx2f vy2t=vy2f break end end if (impt>imp) and (impt<431.5) then imp=impt x1=x1t y1=y1t t1=t1t x2=x2t y2=y2t t2=t2t vx2=vx2t vy2=vy2t end if (imp>428) then break end end end t2=t2+1 end t2=t2-1 if (x1>0) and (est<368.5) then move(x1) if (t2<=t1+0.1) and (y1>146) then jump() end else move(est) end end function OnOpponentServe() y1p=144.5 if (math.abs(pos(posx())-posx())>1) then move(400) else move(200) end valid=1 end function OnServe(ballready) y1p=144.5 est=700 if (math.abs(pos(posx())-posx())>1) then move(400) else if (math.abs(posx()-180)<2) then jump() else move(180) end end valid=1 end function OnGame() yp2=y1p y1p=oppy() vp=y1p-yp2 esttold=estt netold=net toucho=touch touch=touches() if (touch<toucho) then p=math.random() end x,y,vx,vy=ballx(),bally(),bspeedx(),bspeedy() estt,_,_,_,tnet,net=estimate(x,y,vx,vy,220) if (math.abs(esttold-estt)<0.1) then -- Schutz gegen Fehler bei der estimate-Funktion während Netz/Wandkollisionen est=estt end --1 Player --2 Ball -- debug(0) -- debug(est) -- debug(imp) -- debug(t2) if (est<(400-31.5)) then if (p<0.85) then attack() else lob() end elseif (est<400-22) and (est>400-31.5) then move (250) elseif (est<400-10) and (est>400-22) then move(200) elseif (est<400) and (est>400-10) then move(180) else move(230) end end
gpl-2.0
Ninjistix/darkstar
scripts/zones/La_Theine_Plateau/npcs/Coumaine.lua
3
1345
----------------------------------- -- Area: La Theine Plateau -- NPC: Coumaine -- Type: Chocobo Vendor ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/chocobo"); require("scripts/globals/status"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local level = player:getMainLvl(); local gil = player:getGil(); if (player:hasKeyItem(CHOCOBO_LICENSE) and level >= 20) then local price = getChocoboPrice(player); player:setLocalVar("chocoboPriceOffer",price); player:startEvent(120,price,gil); else player:startEvent(121); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local price = player:getLocalVar("chocoboPriceOffer"); if (csid == 120 and option == 0) then if (player:delGil(price)) then updateChocoboPrice(player, price); local duration = 1800 + (player:getMod(MOD_CHOCOBO_RIDING_TIME) * 60) player:addStatusEffectEx(EFFECT_MOUNTED,EFFECT_MOUNTED,0,0,duration,true); end end end;
gpl-3.0
dafei2015/hugular_cstolua
Client/Assets/uLua/Source/LuaJIT/src/jit/dis_mips.lua
88
13222
---------------------------------------------------------------------------- -- LuaJIT MIPS disassembler module. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT/X license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- It disassembles all standard MIPS32R1/R2 instructions. -- Default mode is big-endian, but see: dis_mipsel.lua ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local concat = table.concat local bit = require("bit") local band, bor, tohex = bit.band, bit.bor, bit.tohex local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift ------------------------------------------------------------------------------ -- Primary and extended opcode maps ------------------------------------------------------------------------------ local map_movci = { shift = 16, mask = 1, [0] = "movfDSC", "movtDSC", } local map_srl = { shift = 21, mask = 1, [0] = "srlDTA", "rotrDTA", } local map_srlv = { shift = 6, mask = 1, [0] = "srlvDTS", "rotrvDTS", } local map_special = { shift = 0, mask = 63, [0] = { shift = 0, mask = -1, [0] = "nop", _ = "sllDTA" }, map_movci, map_srl, "sraDTA", "sllvDTS", false, map_srlv, "sravDTS", "jrS", "jalrD1S", "movzDST", "movnDST", "syscallY", "breakY", false, "sync", "mfhiD", "mthiS", "mfloD", "mtloS", false, false, false, false, "multST", "multuST", "divST", "divuST", false, false, false, false, "addDST", "addu|moveDST0", "subDST", "subu|neguDS0T", "andDST", "orDST", "xorDST", "nor|notDST0", false, false, "sltDST", "sltuDST", false, false, false, false, "tgeSTZ", "tgeuSTZ", "tltSTZ", "tltuSTZ", "teqSTZ", false, "tneSTZ", } local map_special2 = { shift = 0, mask = 63, [0] = "maddST", "madduST", "mulDST", false, "msubST", "msubuST", [32] = "clzDS", [33] = "cloDS", [63] = "sdbbpY", } local map_bshfl = { shift = 6, mask = 31, [2] = "wsbhDT", [16] = "sebDT", [24] = "sehDT", } local map_special3 = { shift = 0, mask = 63, [0] = "extTSAK", [4] = "insTSAL", [32] = map_bshfl, [59] = "rdhwrTD", } local map_regimm = { shift = 16, mask = 31, [0] = "bltzSB", "bgezSB", "bltzlSB", "bgezlSB", false, false, false, false, "tgeiSI", "tgeiuSI", "tltiSI", "tltiuSI", "teqiSI", false, "tneiSI", false, "bltzalSB", "bgezalSB", "bltzallSB", "bgezallSB", false, false, false, false, false, false, false, false, false, false, false, "synciSO", } local map_cop0 = { shift = 25, mask = 1, [0] = { shift = 21, mask = 15, [0] = "mfc0TDW", [4] = "mtc0TDW", [10] = "rdpgprDT", [11] = { shift = 5, mask = 1, [0] = "diT0", "eiT0", }, [14] = "wrpgprDT", }, { shift = 0, mask = 63, [1] = "tlbr", [2] = "tlbwi", [6] = "tlbwr", [8] = "tlbp", [24] = "eret", [31] = "deret", [32] = "wait", }, } local map_cop1s = { shift = 0, mask = 63, [0] = "add.sFGH", "sub.sFGH", "mul.sFGH", "div.sFGH", "sqrt.sFG", "abs.sFG", "mov.sFG", "neg.sFG", "round.l.sFG", "trunc.l.sFG", "ceil.l.sFG", "floor.l.sFG", "round.w.sFG", "trunc.w.sFG", "ceil.w.sFG", "floor.w.sFG", false, { shift = 16, mask = 1, [0] = "movf.sFGC", "movt.sFGC" }, "movz.sFGT", "movn.sFGT", false, "recip.sFG", "rsqrt.sFG", false, false, false, false, false, false, false, false, false, false, "cvt.d.sFG", false, false, "cvt.w.sFG", "cvt.l.sFG", "cvt.ps.sFGH", false, false, false, false, false, false, false, false, false, "c.f.sVGH", "c.un.sVGH", "c.eq.sVGH", "c.ueq.sVGH", "c.olt.sVGH", "c.ult.sVGH", "c.ole.sVGH", "c.ule.sVGH", "c.sf.sVGH", "c.ngle.sVGH", "c.seq.sVGH", "c.ngl.sVGH", "c.lt.sVGH", "c.nge.sVGH", "c.le.sVGH", "c.ngt.sVGH", } local map_cop1d = { shift = 0, mask = 63, [0] = "add.dFGH", "sub.dFGH", "mul.dFGH", "div.dFGH", "sqrt.dFG", "abs.dFG", "mov.dFG", "neg.dFG", "round.l.dFG", "trunc.l.dFG", "ceil.l.dFG", "floor.l.dFG", "round.w.dFG", "trunc.w.dFG", "ceil.w.dFG", "floor.w.dFG", false, { shift = 16, mask = 1, [0] = "movf.dFGC", "movt.dFGC" }, "movz.dFGT", "movn.dFGT", false, "recip.dFG", "rsqrt.dFG", false, false, false, false, false, false, false, false, false, "cvt.s.dFG", false, false, false, "cvt.w.dFG", "cvt.l.dFG", false, false, false, false, false, false, false, false, false, false, "c.f.dVGH", "c.un.dVGH", "c.eq.dVGH", "c.ueq.dVGH", "c.olt.dVGH", "c.ult.dVGH", "c.ole.dVGH", "c.ule.dVGH", "c.df.dVGH", "c.ngle.dVGH", "c.deq.dVGH", "c.ngl.dVGH", "c.lt.dVGH", "c.nge.dVGH", "c.le.dVGH", "c.ngt.dVGH", } local map_cop1ps = { shift = 0, mask = 63, [0] = "add.psFGH", "sub.psFGH", "mul.psFGH", false, false, "abs.psFG", "mov.psFG", "neg.psFG", false, false, false, false, false, false, false, false, false, { shift = 16, mask = 1, [0] = "movf.psFGC", "movt.psFGC" }, "movz.psFGT", "movn.psFGT", false, false, false, false, false, false, false, false, false, false, false, false, "cvt.s.puFG", false, false, false, false, false, false, false, "cvt.s.plFG", false, false, false, "pll.psFGH", "plu.psFGH", "pul.psFGH", "puu.psFGH", "c.f.psVGH", "c.un.psVGH", "c.eq.psVGH", "c.ueq.psVGH", "c.olt.psVGH", "c.ult.psVGH", "c.ole.psVGH", "c.ule.psVGH", "c.psf.psVGH", "c.ngle.psVGH", "c.pseq.psVGH", "c.ngl.psVGH", "c.lt.psVGH", "c.nge.psVGH", "c.le.psVGH", "c.ngt.psVGH", } local map_cop1w = { shift = 0, mask = 63, [32] = "cvt.s.wFG", [33] = "cvt.d.wFG", } local map_cop1l = { shift = 0, mask = 63, [32] = "cvt.s.lFG", [33] = "cvt.d.lFG", } local map_cop1bc = { shift = 16, mask = 3, [0] = "bc1fCB", "bc1tCB", "bc1flCB", "bc1tlCB", } local map_cop1 = { shift = 21, mask = 31, [0] = "mfc1TG", false, "cfc1TG", "mfhc1TG", "mtc1TG", false, "ctc1TG", "mthc1TG", map_cop1bc, false, false, false, false, false, false, false, map_cop1s, map_cop1d, false, false, map_cop1w, map_cop1l, map_cop1ps, } local map_cop1x = { shift = 0, mask = 63, [0] = "lwxc1FSX", "ldxc1FSX", false, false, false, "luxc1FSX", false, false, "swxc1FSX", "sdxc1FSX", false, false, false, "suxc1FSX", false, "prefxMSX", false, false, false, false, false, false, false, false, false, false, false, false, false, false, "alnv.psFGHS", false, "madd.sFRGH", "madd.dFRGH", false, false, false, false, "madd.psFRGH", false, "msub.sFRGH", "msub.dFRGH", false, false, false, false, "msub.psFRGH", false, "nmadd.sFRGH", "nmadd.dFRGH", false, false, false, false, "nmadd.psFRGH", false, "nmsub.sFRGH", "nmsub.dFRGH", false, false, false, false, "nmsub.psFRGH", false, } local map_pri = { [0] = map_special, map_regimm, "jJ", "jalJ", "beq|beqz|bST00B", "bne|bnezST0B", "blezSB", "bgtzSB", "addiTSI", "addiu|liTS0I", "sltiTSI", "sltiuTSI", "andiTSU", "ori|liTS0U", "xoriTSU", "luiTU", map_cop0, map_cop1, false, map_cop1x, "beql|beqzlST0B", "bnel|bnezlST0B", "blezlSB", "bgtzlSB", false, false, false, false, map_special2, false, false, map_special3, "lbTSO", "lhTSO", "lwlTSO", "lwTSO", "lbuTSO", "lhuTSO", "lwrTSO", false, "sbTSO", "shTSO", "swlTSO", "swTSO", false, false, "swrTSO", "cacheNSO", "llTSO", "lwc1HSO", "lwc2TSO", "prefNSO", false, "ldc1HSO", "ldc2TSO", false, "scTSO", "swc1HSO", "swc2TSO", false, false, "sdc1HSO", "sdc2TSO", false, } ------------------------------------------------------------------------------ local map_gpr = { [0] = "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "sp", "r30", "ra", } ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local pos = ctx.pos local extra = "" if ctx.rel then local sym = ctx.symtab[ctx.rel] if sym then extra = "\t->"..sym end end if ctx.hexdump > 0 then ctx.out(format("%08x %s %-7s %s%s\n", ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra)) else ctx.out(format("%08x %-7s %s%s\n", ctx.addr+pos, text, concat(operands, ", "), extra)) end ctx.pos = pos + 4 end -- Fallback for unknown opcodes. local function unknown(ctx) return putop(ctx, ".long", { "0x"..tohex(ctx.op) }) end local function get_be(ctx) local pos = ctx.pos local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4) return bor(lshift(b0, 24), lshift(b1, 16), lshift(b2, 8), b3) end local function get_le(ctx) local pos = ctx.pos local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4) return bor(lshift(b3, 24), lshift(b2, 16), lshift(b1, 8), b0) end -- Disassemble a single instruction. local function disass_ins(ctx) local op = ctx:get() local operands = {} local last = nil ctx.op = op ctx.rel = nil local opat = map_pri[rshift(op, 26)] while type(opat) ~= "string" do if not opat then return unknown(ctx) end opat = opat[band(rshift(op, opat.shift), opat.mask)] or opat._ end local name, pat = match(opat, "^([a-z0-9_.]*)(.*)") local altname, pat2 = match(pat, "|([a-z0-9_.|]*)(.*)") if altname then pat = pat2 end for p in gmatch(pat, ".") do local x = nil if p == "S" then x = map_gpr[band(rshift(op, 21), 31)] elseif p == "T" then x = map_gpr[band(rshift(op, 16), 31)] elseif p == "D" then x = map_gpr[band(rshift(op, 11), 31)] elseif p == "F" then x = "f"..band(rshift(op, 6), 31) elseif p == "G" then x = "f"..band(rshift(op, 11), 31) elseif p == "H" then x = "f"..band(rshift(op, 16), 31) elseif p == "R" then x = "f"..band(rshift(op, 21), 31) elseif p == "A" then x = band(rshift(op, 6), 31) elseif p == "M" then x = band(rshift(op, 11), 31) elseif p == "N" then x = band(rshift(op, 16), 31) elseif p == "C" then x = band(rshift(op, 18), 7) if x == 0 then x = nil end elseif p == "K" then x = band(rshift(op, 11), 31) + 1 elseif p == "L" then x = band(rshift(op, 11), 31) - last + 1 elseif p == "I" then x = arshift(lshift(op, 16), 16) elseif p == "U" then x = band(op, 0xffff) elseif p == "O" then local disp = arshift(lshift(op, 16), 16) operands[#operands] = format("%d(%s)", disp, last) elseif p == "X" then local index = map_gpr[band(rshift(op, 16), 31)] operands[#operands] = format("%s(%s)", index, last) elseif p == "B" then x = ctx.addr + ctx.pos + arshift(lshift(op, 16), 16)*4 + 4 ctx.rel = x x = "0x"..tohex(x) elseif p == "J" then x = band(ctx.addr + ctx.pos, 0xf0000000) + band(op, 0x03ffffff)*4 ctx.rel = x x = "0x"..tohex(x) elseif p == "V" then x = band(rshift(op, 8), 7) if x == 0 then x = nil end elseif p == "W" then x = band(op, 7) if x == 0 then x = nil end elseif p == "Y" then x = band(rshift(op, 6), 0x000fffff) if x == 0 then x = nil end elseif p == "Z" then x = band(rshift(op, 6), 1023) if x == 0 then x = nil end elseif p == "0" then if last == "r0" or last == 0 then local n = #operands operands[n] = nil last = operands[n-1] if altname then local a1, a2 = match(altname, "([^|]*)|(.*)") if a1 then name, altname = a1, a2 else name = altname end end end elseif p == "1" then if last == "ra" then operands[#operands] = nil end else assert(false) end if x then operands[#operands+1] = x; last = x end end return putop(ctx, name, operands) end ------------------------------------------------------------------------------ -- Disassemble a block of code. local function disass_block(ctx, ofs, len) if not ofs then ofs = 0 end local stop = len and ofs+len or #ctx.code stop = stop - stop % 4 ctx.pos = ofs - ofs % 4 ctx.rel = nil while ctx.pos < stop do disass_ins(ctx) end end -- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). local function create_(code, addr, out) local ctx = {} ctx.code = code ctx.addr = addr or 0 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 8 ctx.get = get_be return ctx end local function create_el_(code, addr, out) local ctx = create_(code, addr, out) ctx.get = get_le return ctx end -- Simple API: disassemble code (a string) at address and output via out. local function disass_(code, addr, out) create_(code, addr, out):disass() end local function disass_el_(code, addr, out) create_el_(code, addr, out):disass() end -- Return register name for RID. local function regname_(r) if r < 32 then return map_gpr[r] end return "f"..(r-32) end -- Public module functions. module(...) create = create_ create_el = create_el_ disass = disass_ disass_el = disass_el_ regname = regname_
mit
Ninjistix/darkstar
scripts/zones/Port_San_dOria/npcs/Milva.lua
5
1641
----------------------------------- -- Area: Port San d'Oria -- NPC: Milva -- only sells when San d'Oria has control of Sarutabaruta ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/conquest"); require("scripts/globals/quests"); require("scripts/globals/shop"); ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; function onTrigger(player,npc) local RegionOwner = GetRegionOwner(SARUTABARUTA); if (RegionOwner ~= NATION_SANDORIA) then player:showText(npc,MILVA_CLOSED_DIALOG); else player:showText(npc,MILVA_OPEN_DIALOG); local stock = { 4444, 22, -- Rarab Tail 689, 33, -- Lauan Log 619, 43, -- Popoto 4392, 29, -- Saruta Orange 635, 18 -- Windurstian Tea Leaves } showShop(player,SANDORIA,stock); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
kazupon/kyototycoon
lab/docrefine.lua
11
1090
-- -- refine the documents -- INDEXFILE = "doc/luadoc/index.html" MODULEFILE = "doc/luadoc/modules/kyototycoon.html" CSSFILE = "doc/luadoc/luadoc.css" TMPFILE = INDEXFILE .. "~" OVERVIEWFILE = "luaoverview.html" ofd = io.open(TMPFILE, "wb") first = true for line in io.lines(INDEXFILE) do if first and string.match(line, "<h2> *Modules *</h2>") then for tline in io.lines(OVERVIEWFILE) do ofd:write(tline .. "\n") end first = false end ofd:write(line .. "\n") end ofd:close() os.remove(INDEXFILE) os.rename(TMPFILE, INDEXFILE) ofd = io.open(TMPFILE, "wb") first = true for line in io.lines(MODULEFILE) do if string.match(line, "<em>Fields</em>") then ofd:write("<br/>\n") end ofd:write(line .. "\n") end ofd:close() os.remove(MODULEFILE) os.rename(TMPFILE, MODULEFILE) ofd = io.open(TMPFILE, "wb") for line in io.lines(CSSFILE) do if not string.match(line, "#TODO:") then ofd:write(line .. "\n") end end ofd:write("table.function_list td.name { width: 20em; }\n") ofd:close() os.remove(CSSFILE) os.rename(TMPFILE, CSSFILE)
gpl-3.0
Ninjistix/darkstar
scripts/zones/Ship_bound_for_Mhaura/npcs/Chhaya.lua
5
1024
----------------------------------- -- Area: Ship Bound for Mhaura -- NPC: Chhaya -- Standard Merchant NPC -- !pos -1.139 -2.101 -9.000 221 ----------------------------------- package.loaded["scripts/zones/Ship_bound_for_Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Ship_bound_for_Mhaura/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) player:showText(npc,CHHAYA_SHOP_DIALOG); local stock = { 0x1010,910, --Potion 0x1020,4832, --Ether 0x1034,316, --Antidote 0x1036,2595, --Eye Drops 0x1037,800} --Echo Drops showShop(player, STATIC, stock); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/spells/foe_requiem_iv.lua
5
1802
----------------------------------------- -- Spell: Foe Requiem IV ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local effect = EFFECT_REQUIEM; local duration = 111; local power = 4; local pCHR = caster:getStat(MOD_CHR); local mCHR = target:getStat(MOD_CHR); local dCHR = (pCHR - mCHR); local params = {}; params.diff = nil; params.attribute = MOD_CHR; params.skillType = SINGING_SKILL; params.bonus = 0; params.effect = nil; resm = applyResistance(caster, target, spell, params); if (resm < 0.5) then spell:setMsg(msgBasic.MAGIC_RESIST); -- resist message return 1; end local iBoost = caster:getMod(MOD_REQUIEM_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; 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); duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end -- Try to overwrite weaker slow / haste if (canOverwrite(target, effect, power)) then -- overwrite them target:delStatusEffect(effect); target:addStatusEffect(effect,power,3,duration); spell:setMsg(msgBasic.MAGIC_ENFEEB); else spell:setMsg(msgBasic.MAGIC_NO_EFFECT); -- no effect end return effect; end;
gpl-3.0
premake/premake-4.x
tests/actions/vstudio/vc200x/debugdir.lua
57
2243
-- -- tests/actions/vstudio/vc200x/debugdir.lua -- Validate handling of the working directory for debugging. -- Copyright (c) 2011 Jason Perkins and the Premake project -- T.vstudio_vs200x_debugdir = { } local suite = T.vstudio_vs200x_debugdir local vc200x = premake.vstudio.vc200x -- -- Setup -- local sln, prj function suite.setup() sln = test.createsolution() end local function prepare() premake.bake.buildconfigs() prj = premake.solution.getproject(sln, 1) sln.vstudio_configs = premake.vstudio.buildconfigs(sln) vc200x.debugdir(prj) end -- -- Tests -- function suite.EmptyBlock_OnNoDebugSettings() prepare() test.capture [[ <DebugSettings /> ]] end function suite.WorkingDirectory_OnRelativePath() debugdir "bin/debug" prepare() test.capture [[ <DebugSettings WorkingDirectory="bin\debug" /> ]] end function suite.Arguments() debugargs { "arg1", "arg2" } prepare() test.capture [[ <DebugSettings CommandArguments="arg1 arg2" /> ]] end T.vc200x_env_args = { } local vs200x_env_args = T.vc200x_env_args function vs200x_env_args.environmentArgs_notSet_bufferDoesNotContainEnvironment() vc200x.environmentargs( {flags={}} ) test.string_does_not_contain(io.endcapture(),'Environment=') end function vs200x_env_args.environmentArgs_set_bufferContainsEnvironment() vc200x.environmentargs( {flags={},environmentargs={'key=value'}} ) test.string_contains(io.endcapture(),'Environment=') end function vs200x_env_args.environmentArgs_valueUsesQuotes_quotesMarksReplaced() vc200x.environmentargs( {flags={},environmentargs={'key="value"'}} ) test.string_contains(io.endcapture(),'Environment="key=&quot;value&quot;"') end function vs200x_env_args.environmentArgs_multipleArgs_seperatedUsingCorrectEscape() vc200x.environmentargs( {flags={},environmentargs={'key=value','foo=bar'}} ) test.string_contains(io.endcapture(),'Environment="key=value&#x0A;foo=bar"') end function vs200x_env_args.environmentArgs_withDontMergeFlag_EnvironmentArgsDontMergeEqualsFalse() vc200x.environmentargs( {flags={EnvironmentArgsDontMerge=1},environmentargs={'key=value'}} ) test.string_contains(io.endcapture(),'EnvironmentMerge="false"') end
bsd-3-clause
Ninjistix/darkstar
scripts/zones/Ifrits_Cauldron/npcs/qm2.lua
5
1141
----------------------------------- -- Area: Ifrit's Cauldron -- NPC: qm2 (???) -- Notes: Used to spawn Bomb Queen -- !pos 18 20 -104 205 ----------------------------------- package.loaded["scripts/zones/Ifrits_Cauldron/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Ifrits_Cauldron/TextIDs"); require("scripts/zones/Ifrits_Cauldron/MobIDs"); function onTrade(player,npc,trade) -- Trade 3 pinches of Bomb Queen Ash and a Bomb Queen Core and a verification if the nm is already spawned if (not GetMobByID(BOMB_QUEEN):isSpawned() and trade:hasItemQty(1187,3) and trade:hasItemQty(1186,1) and trade:getItemCount() == 4) then player:tradeComplete(); SpawnMob(BOMB_QUEEN):updateClaim(player); -- Spawn Bomb Queen npc:setStatus(STATUS_DISAPPEAR); end end; function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
ogahara/esp8266-devkit
Espressif/examples/nodemcu-firmware/lua_modules/mcp23008/mcp23008.lua
81
4973
--- -- @description Expands the ESP8266's GPIO to 8 more I/O pins via I2C with the MCP23008 I/O Expander -- MCP23008 Datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/21919e.pdf -- Tested on NodeMCU 0.9.5 build 20150213. -- @date March 02, 2015 -- @author Miguel -- GitHub: https://github.com/AllAboutEE -- YouTube: https://www.youtube.com/user/AllAboutEE -- Website: http://AllAboutEE.com -------------------------------------------------------------------------------- local moduleName = ... local M = {} _G[moduleName] = M -- Constant device address. local MCP23008_ADDRESS = 0x20 -- Registers' address as defined in the MCP23008's datashseet local MCP23008_IODIR = 0x00 local MCP23008_IPOL = 0x01 local MCP23008_GPINTEN = 0x02 local MCP23008_DEFVAL = 0x03 local MCP23008_INTCON = 0x04 local MCP23008_IOCON = 0x05 local MCP23008_GPPU = 0x06 local MCP23008_INTF = 0x07 local MCP23008_INTCAP = 0x08 local MCP23008_GPIO = 0x09 local MCP23008_OLAT = 0x0A -- Default value for i2c communication local id = 0 -- pin modes for I/O direction M.INPUT = 1 M.OUTPUT = 0 -- pin states for I/O i.e. on/off M.HIGH = 1 M.LOW = 0 -- Weak pull-up resistor state M.ENABLE = 1 M.DISABLE = 0 --- -- @name write -- @description Writes one byte to a register -- @param registerAddress The register where we'll write data -- @param data The data to write to the register -- @return void ---------------------------------------------------------- local function write(registerAddress, data) i2c.start(id) i2c.address(id,MCP23008_ADDRESS,i2c.TRANSMITTER) -- send MCP's address and write bit i2c.write(id,registerAddress) i2c.write(id,data) i2c.stop(id) end --- -- @name read -- @description Reads the value of a regsiter -- @param registerAddress The reigster address from which to read -- @return The byte stored in the register ---------------------------------------------------------- local function read(registerAddress) -- Tell the MCP which register you want to read from i2c.start(id) i2c.address(id,MCP23008_ADDRESS,i2c.TRANSMITTER) -- send MCP's address and write bit i2c.write(id,registerAddress) i2c.stop(id) i2c.start(id) -- Read the data form the register i2c.address(id,MCP23008_ADDRESS,i2c.RECEIVER) -- send the MCP's address and read bit local data = 0x00 data = i2c.read(id,1) -- we expect only one byte of data i2c.stop(id) return string.byte(data) -- i2c.read returns a string so we convert to it's int value end --- --! @name begin --! @description Sets the MCP23008 device address's last three bits. -- Note: The address is defined as binary 0100[A2][A1][A0] where -- A2, A1, and A0 are defined by the connection of the pins, -- e.g. if the pins are connected all to GND then the paramter address -- will need to be 0x0. -- @param address The 3 least significant bits (LSB) of the address -- @param pinSDA The pin to use for SDA -- @param pinSCL The pin to use for SCL -- @param speed The speed of the I2C signal -- @return void --------------------------------------------------------------------------- function M.begin(address,pinSDA,pinSCL,speed) MCP23008_ADDRESS = bit.bor(MCP23008_ADDRESS,address) i2c.setup(id,pinSDA,pinSCL,speed) end --- -- @name writeGPIO -- @description Writes a byte of data to the GPIO register -- @param dataByte The byte of data to write -- @return void ---------------------------------------------------------- function M.writeGPIO(dataByte) write(MCP23008_GPIO,dataByte) end --- -- @name readGPIO -- @description reads a byte of data from the GPIO register -- @return One byte of data ---------------------------------------------------------- function M.readGPIO() return read(MCP23008_GPIO) end --- -- @name writeIODIR -- @description Writes one byte of data to the IODIR register -- @param dataByte The byte of data to write -- @return void ---------------------------------------------------------- function M.writeIODIR(dataByte) write(MCP23008_IODIR,dataByte) end --- -- @name readIODIR -- @description Reads a byte from the IODIR register -- @return The byte of data in IODIR ---------------------------------------------------------- function M.readIODIR() return read(MCP23008_IODIR) end --- -- @name writeGPPU The byte to write to the GPPU -- @description Writes a byte of data to the -- PULL-UP RESISTOR CONFIGURATION (GPPU)REGISTER -- @param databyte the value to write to the GPPU register. -- each bit in this byte is assigned to an individual GPIO pin -- @return void ---------------------------------------------------------------- function M.writeGPPU(dataByte) write(MCP23008_GPPU,dataByte) end --- -- @name readGPPU -- @description Reads the GPPU (Pull-UP resistors register) byte -- @return The GPPU byte i.e. state of all internal pull-up resistors ------------------------------------------------------------------- function M.readGPPU() return read(MCP23008_GPPU) end return M
gpl-3.0
dan-cleinmark/nodemcu-firmware
lua_modules/mcp23008/mcp23008.lua
81
4973
--- -- @description Expands the ESP8266's GPIO to 8 more I/O pins via I2C with the MCP23008 I/O Expander -- MCP23008 Datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/21919e.pdf -- Tested on NodeMCU 0.9.5 build 20150213. -- @date March 02, 2015 -- @author Miguel -- GitHub: https://github.com/AllAboutEE -- YouTube: https://www.youtube.com/user/AllAboutEE -- Website: http://AllAboutEE.com -------------------------------------------------------------------------------- local moduleName = ... local M = {} _G[moduleName] = M -- Constant device address. local MCP23008_ADDRESS = 0x20 -- Registers' address as defined in the MCP23008's datashseet local MCP23008_IODIR = 0x00 local MCP23008_IPOL = 0x01 local MCP23008_GPINTEN = 0x02 local MCP23008_DEFVAL = 0x03 local MCP23008_INTCON = 0x04 local MCP23008_IOCON = 0x05 local MCP23008_GPPU = 0x06 local MCP23008_INTF = 0x07 local MCP23008_INTCAP = 0x08 local MCP23008_GPIO = 0x09 local MCP23008_OLAT = 0x0A -- Default value for i2c communication local id = 0 -- pin modes for I/O direction M.INPUT = 1 M.OUTPUT = 0 -- pin states for I/O i.e. on/off M.HIGH = 1 M.LOW = 0 -- Weak pull-up resistor state M.ENABLE = 1 M.DISABLE = 0 --- -- @name write -- @description Writes one byte to a register -- @param registerAddress The register where we'll write data -- @param data The data to write to the register -- @return void ---------------------------------------------------------- local function write(registerAddress, data) i2c.start(id) i2c.address(id,MCP23008_ADDRESS,i2c.TRANSMITTER) -- send MCP's address and write bit i2c.write(id,registerAddress) i2c.write(id,data) i2c.stop(id) end --- -- @name read -- @description Reads the value of a regsiter -- @param registerAddress The reigster address from which to read -- @return The byte stored in the register ---------------------------------------------------------- local function read(registerAddress) -- Tell the MCP which register you want to read from i2c.start(id) i2c.address(id,MCP23008_ADDRESS,i2c.TRANSMITTER) -- send MCP's address and write bit i2c.write(id,registerAddress) i2c.stop(id) i2c.start(id) -- Read the data form the register i2c.address(id,MCP23008_ADDRESS,i2c.RECEIVER) -- send the MCP's address and read bit local data = 0x00 data = i2c.read(id,1) -- we expect only one byte of data i2c.stop(id) return string.byte(data) -- i2c.read returns a string so we convert to it's int value end --- --! @name begin --! @description Sets the MCP23008 device address's last three bits. -- Note: The address is defined as binary 0100[A2][A1][A0] where -- A2, A1, and A0 are defined by the connection of the pins, -- e.g. if the pins are connected all to GND then the paramter address -- will need to be 0x0. -- @param address The 3 least significant bits (LSB) of the address -- @param pinSDA The pin to use for SDA -- @param pinSCL The pin to use for SCL -- @param speed The speed of the I2C signal -- @return void --------------------------------------------------------------------------- function M.begin(address,pinSDA,pinSCL,speed) MCP23008_ADDRESS = bit.bor(MCP23008_ADDRESS,address) i2c.setup(id,pinSDA,pinSCL,speed) end --- -- @name writeGPIO -- @description Writes a byte of data to the GPIO register -- @param dataByte The byte of data to write -- @return void ---------------------------------------------------------- function M.writeGPIO(dataByte) write(MCP23008_GPIO,dataByte) end --- -- @name readGPIO -- @description reads a byte of data from the GPIO register -- @return One byte of data ---------------------------------------------------------- function M.readGPIO() return read(MCP23008_GPIO) end --- -- @name writeIODIR -- @description Writes one byte of data to the IODIR register -- @param dataByte The byte of data to write -- @return void ---------------------------------------------------------- function M.writeIODIR(dataByte) write(MCP23008_IODIR,dataByte) end --- -- @name readIODIR -- @description Reads a byte from the IODIR register -- @return The byte of data in IODIR ---------------------------------------------------------- function M.readIODIR() return read(MCP23008_IODIR) end --- -- @name writeGPPU The byte to write to the GPPU -- @description Writes a byte of data to the -- PULL-UP RESISTOR CONFIGURATION (GPPU)REGISTER -- @param databyte the value to write to the GPPU register. -- each bit in this byte is assigned to an individual GPIO pin -- @return void ---------------------------------------------------------------- function M.writeGPPU(dataByte) write(MCP23008_GPPU,dataByte) end --- -- @name readGPPU -- @description Reads the GPPU (Pull-UP resistors register) byte -- @return The GPPU byte i.e. state of all internal pull-up resistors ------------------------------------------------------------------- function M.readGPPU() return read(MCP23008_GPPU) end return M
mit
chroteus/clay
class/upgrade.lua
1
2362
Upgrade = Button:subclass "Upgrade" function Upgrade:initialize(arg) self.name = tostring(arg.name) or "Undefined name" self.text = self.name -- text to be displayed on the button self.desc = tostring(arg.desc) or "Undefined desc" self.cost = tonumber(arg.cost) or error("No cost defined") self.upg_func = function(level, region) arg.func(level, region) end self.func = function() self:upgrade() end self.max_level = arg.max_level or 10 self.width = arg.width or 140 self.height = arg.height or 60 self.level = 0 Button.initialize(self, 0,0, self.width, self.height, self.text, self.func) end function Upgrade:upgrade() if self.level + 1 > self.max_level and not self.tricked then local show = false if not self.tricked then DialogBoxes:new("Maximum level reached!", {"Unacceptable!", function() DialogBoxes:new( "Well, for triple the price, ".. "we can upgrade disregarding".. " the level cap.\n *the merchant ".. "is rubbing his hands*", {"Cancel", dbox2}, {"Upgrade", function() self.tricked = true self.cost = self.cost*3 self:upgrade() end} ):show() end }, {"OK"} ):show() end else if Player.money - self.cost >= 0 then if disregard then self.max_level = self.max_level+1 end self.level = self.level + 1 self.upg_func(self, self.level) Player.money = Player.money - self.cost else DialogBoxes:new("Not enough money!", {"OK"}):show() end end end function Upgrade:draw() Button.draw(self) local PADDING = 5 local barH = 10 if not (self.level > self.max_level) then love.graphics.setColor(100,120,160, 100) love.graphics.rectangle("fill", self.x,self.y, ((self.width)/self.max_level)*self.level,self.height) else love.graphics.setColor(guiColors.fg) love.graphics.setFont(gameFont[12]) love.graphics.printf("Level: " .. self.level, self.x, self.y+self.height-PADDING*4, self.width-PADDING, "center") love.graphics.setFont(gameFont["default"]) end love.graphics.setColor(255,255,255) if checkCol(the.mouse, self) then guiInfoBox(the.mouse.x, the.mouse.y, self.text .. " ("..self.cost.."G)",self.desc) end end
gpl-2.0
Ninjistix/darkstar
scripts/zones/Metalworks/npcs/Ferghus.lua
5
1339
----------------------------------- -- Area: Metalworks -- NPC: Ferghus -- Starts Quest: Too Many Chefs (1,86) ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Metalworks/TextIDs"); require("scripts/globals/status"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local TooManyChefs = player:getQuestStatus(BASTOK,TOO_MANY_CHEFS); local pFame = player:getFameLevel(BASTOK); if (TooManyChefs == QUEST_AVAILABLE and pFame >= 5) then player:startEvent(946); -- Start Quest "Too Many Chefs" elseif (player:getVar("TOO_MANY_CHEFS") == 4) then -- after trade to Leonhardt player:startEvent(947); else player:startEvent(420); -- Standard end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 946 and option == 0) then player:addQuest(BASTOK,TOO_MANY_CHEFS); player:setVar("TOO_MANY_CHEFS",1); elseif (csid == 947) then player:setVar("TOO_MANY_CHEFS",5); end end;
gpl-3.0
draekko/keys
Build/VSCOKeys.lrplugin/halfway_server/socket/smtp.lua
142
7961
----------------------------------------------------------------------------- -- SMTP client support for the Lua language. -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id: smtp.lua,v 1.46 2007/03/12 04:08:40 diego Exp $ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ----------------------------------------------------------------------------- local base = _G local coroutine = require("coroutine") local string = require("string") local math = require("math") local os = require("os") local socket = require("socket") local tp = require("socket.tp") local ltn12 = require("ltn12") local mime = require("mime") module("socket.smtp") ----------------------------------------------------------------------------- -- Program constants ----------------------------------------------------------------------------- -- timeout for connection TIMEOUT = 60 -- default server used to send e-mails SERVER = "localhost" -- default port PORT = 25 -- domain used in HELO command and default sendmail -- If we are under a CGI, try to get from environment DOMAIN = os.getenv("SERVER_NAME") or "localhost" -- default time zone (means we don't know) ZONE = "-0000" --------------------------------------------------------------------------- -- Low level SMTP API ----------------------------------------------------------------------------- local metat = { __index = {} } function metat.__index:greet(domain) self.try(self.tp:check("2..")) self.try(self.tp:command("EHLO", domain or DOMAIN)) return socket.skip(1, self.try(self.tp:check("2.."))) end function metat.__index:mail(from) self.try(self.tp:command("MAIL", "FROM:" .. from)) return self.try(self.tp:check("2..")) end function metat.__index:rcpt(to) self.try(self.tp:command("RCPT", "TO:" .. to)) return self.try(self.tp:check("2..")) end function metat.__index:data(src, step) self.try(self.tp:command("DATA")) self.try(self.tp:check("3..")) self.try(self.tp:source(src, step)) self.try(self.tp:send("\r\n.\r\n")) return self.try(self.tp:check("2..")) end function metat.__index:quit() self.try(self.tp:command("QUIT")) return self.try(self.tp:check("2..")) end function metat.__index:close() return self.tp:close() end function metat.__index:login(user, password) self.try(self.tp:command("AUTH", "LOGIN")) self.try(self.tp:check("3..")) self.try(self.tp:command(mime.b64(user))) self.try(self.tp:check("3..")) self.try(self.tp:command(mime.b64(password))) return self.try(self.tp:check("2..")) end function metat.__index:plain(user, password) local auth = "PLAIN " .. mime.b64("\0" .. user .. "\0" .. password) self.try(self.tp:command("AUTH", auth)) return self.try(self.tp:check("2..")) end function metat.__index:auth(user, password, ext) if not user or not password then return 1 end if string.find(ext, "AUTH[^\n]+LOGIN") then return self:login(user, password) elseif string.find(ext, "AUTH[^\n]+PLAIN") then return self:plain(user, password) else self.try(nil, "authentication not supported") end end -- send message or throw an exception function metat.__index:send(mailt) self:mail(mailt.from) if base.type(mailt.rcpt) == "table" then for i,v in base.ipairs(mailt.rcpt) do self:rcpt(v) end else self:rcpt(mailt.rcpt) end self:data(ltn12.source.chain(mailt.source, mime.stuff()), mailt.step) end function open(server, port, create) local tp = socket.try(tp.connect(server or SERVER, port or PORT, TIMEOUT, create)) local s = base.setmetatable({tp = tp}, metat) -- make sure tp is closed if we get an exception s.try = socket.newtry(function() s:close() end) return s end -- convert headers to lowercase local function lower_headers(headers) local lower = {} for i,v in base.pairs(headers or lower) do lower[string.lower(i)] = v end return lower end --------------------------------------------------------------------------- -- Multipart message source ----------------------------------------------------------------------------- -- returns a hopefully unique mime boundary local seqno = 0 local function newboundary() seqno = seqno + 1 return string.format('%s%05d==%05u', os.date('%d%m%Y%H%M%S'), math.random(0, 99999), seqno) end -- send_message forward declaration local send_message -- yield the headers all at once, it's faster local function send_headers(headers) local h = "\r\n" for i,v in base.pairs(headers) do h = i .. ': ' .. v .. "\r\n" .. h end coroutine.yield(h) end -- yield multipart message body from a multipart message table local function send_multipart(mesgt) -- make sure we have our boundary and send headers local bd = newboundary() local headers = lower_headers(mesgt.headers or {}) headers['content-type'] = headers['content-type'] or 'multipart/mixed' headers['content-type'] = headers['content-type'] .. '; boundary="' .. bd .. '"' send_headers(headers) -- send preamble if mesgt.body.preamble then coroutine.yield(mesgt.body.preamble) coroutine.yield("\r\n") end -- send each part separated by a boundary for i, m in base.ipairs(mesgt.body) do coroutine.yield("\r\n--" .. bd .. "\r\n") send_message(m) end -- send last boundary coroutine.yield("\r\n--" .. bd .. "--\r\n\r\n") -- send epilogue if mesgt.body.epilogue then coroutine.yield(mesgt.body.epilogue) coroutine.yield("\r\n") end end -- yield message body from a source local function send_source(mesgt) -- make sure we have a content-type local headers = lower_headers(mesgt.headers or {}) headers['content-type'] = headers['content-type'] or 'text/plain; charset="iso-8859-1"' send_headers(headers) -- send body from source while true do local chunk, err = mesgt.body() if err then coroutine.yield(nil, err) elseif chunk then coroutine.yield(chunk) else break end end end -- yield message body from a string local function send_string(mesgt) -- make sure we have a content-type local headers = lower_headers(mesgt.headers or {}) headers['content-type'] = headers['content-type'] or 'text/plain; charset="iso-8859-1"' send_headers(headers) -- send body from string coroutine.yield(mesgt.body) end -- message source function send_message(mesgt) if base.type(mesgt.body) == "table" then send_multipart(mesgt) elseif base.type(mesgt.body) == "function" then send_source(mesgt) else send_string(mesgt) end end -- set defaul headers local function adjust_headers(mesgt) local lower = lower_headers(mesgt.headers) lower["date"] = lower["date"] or os.date("!%a, %d %b %Y %H:%M:%S ") .. (mesgt.zone or ZONE) lower["x-mailer"] = lower["x-mailer"] or socket._VERSION -- this can't be overriden lower["mime-version"] = "1.0" return lower end function message(mesgt) mesgt.headers = adjust_headers(mesgt) -- create and return message source local co = coroutine.create(function() send_message(mesgt) end) return function() local ret, a, b = coroutine.resume(co) if ret then return a, b else return nil, a end end end --------------------------------------------------------------------------- -- High level SMTP API ----------------------------------------------------------------------------- send = socket.protect(function(mailt) local s = open(mailt.server, mailt.port, mailt.create) local ext = s:greet(mailt.domain) s:auth(mailt.user, mailt.password, ext) s:send(mailt) s:quit() return s:close() end)
gpl-2.0
devnulllabs/xmpp.devnulllabs.io
modules/mod_carbons.lua
1
5146
-- XEP-0280: Message Carbons implementation for Prosody -- Copyright (C) 2011 Kim Alvefur -- -- This file is MIT/X11 licensed. local st = require "util.stanza"; local jid_bare = require "util.jid".bare; local xmlns_carbons = "urn:xmpp:carbons:2"; local xmlns_carbons_old = "urn:xmpp:carbons:1"; local xmlns_carbons_really_old = "urn:xmpp:carbons:0"; local xmlns_forward = "urn:xmpp:forward:0"; local full_sessions, bare_sessions = prosody.full_sessions, prosody.bare_sessions; local function toggle_carbons(event) local origin, stanza = event.origin, event.stanza; local state = stanza.tags[1].attr.mode or stanza.tags[1].name; module:log("debug", "%s %sd carbons", origin.full_jid, state); origin.want_carbons = state == "enable" and stanza.tags[1].attr.xmlns; return origin.send(st.reply(stanza)); end module:hook("iq-set/self/"..xmlns_carbons..":disable", toggle_carbons); module:hook("iq-set/self/"..xmlns_carbons..":enable", toggle_carbons); -- COMPAT module:hook("iq-set/self/"..xmlns_carbons_old..":disable", toggle_carbons); module:hook("iq-set/self/"..xmlns_carbons_old..":enable", toggle_carbons); module:hook("iq-set/self/"..xmlns_carbons_really_old..":carbons", toggle_carbons); local function message_handler(event, c2s) local origin, stanza = event.origin, event.stanza; local orig_type = stanza.attr.type or "normal"; local orig_from = stanza.attr.from; local orig_to = stanza.attr.to; if not(orig_type == "chat" or orig_type == "normal" and stanza:get_child("body")) then return -- Only chat type messages end -- Stanza sent by a local client local bare_jid = jid_bare(orig_from); local target_session = origin; local top_priority = false; local user_sessions = bare_sessions[bare_jid]; -- Stanza about to be delivered to a local client if not c2s then bare_jid = jid_bare(orig_to); target_session = full_sessions[orig_to]; user_sessions = bare_sessions[bare_jid]; if not target_session and user_sessions then -- The top resources will already receive this message per normal routing rules, -- so we are going to skip them in order to avoid sending duplicated messages. local top_resources = user_sessions.top_resources; top_priority = top_resources and top_resources[1].priority end end if not user_sessions then module:log("debug", "Skip carbons for offline user"); return -- No use in sending carbons to an offline user end if stanza:get_child("private", xmlns_carbons) then if not c2s then stanza:maptags(function(tag) if not ( tag.attr.xmlns == xmlns_carbons and tag.name == "private" ) then return tag; end end); end module:log("debug", "Message tagged private, ignoring"); return elseif stanza:get_child("no-copy", "urn:xmpp:hints") then module:log("debug", "Message has no-copy hint, ignoring"); return elseif stanza:get_child("x", "http://jabber.org/protocol/muc#user") then module:log("debug", "MUC PM, ignoring"); return end -- Create the carbon copy and wrap it as per the Stanza Forwarding XEP local copy = st.clone(stanza); copy.attr.xmlns = "jabber:client"; local carbon = st.message{ from = bare_jid, type = orig_type, } :tag(c2s and "sent" or "received", { xmlns = xmlns_carbons }) :tag("forwarded", { xmlns = xmlns_forward }) :add_child(copy):reset(); -- COMPAT local carbon_old = st.message{ from = bare_jid, type = orig_type, } :tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_old }):up() :tag("forwarded", { xmlns = xmlns_forward }) :add_child(copy):reset(); -- COMPAT local carbon_really_old = st.clone(stanza) :tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_really_old }):up() user_sessions = user_sessions and user_sessions.sessions; for _, session in pairs(user_sessions) do -- Carbons are sent to resources that have enabled it if session.want_carbons -- but not the resource that sent the message, or the one that it's directed to and session ~= target_session -- and isn't among the top resources that would receive the message per standard routing rules and (c2s or session.priority ~= top_priority) -- don't send v0 carbons (or copies) for c2s and (not c2s or session.want_carbons ~= xmlns_carbons_really_old) then carbon.attr.to = session.full_jid; module:log("debug", "Sending carbon to %s", session.full_jid); local carbon = session.want_carbons == xmlns_carbons_old and carbon_old -- COMPAT or session.want_carbons == xmlns_carbons_really_old and carbon_really_old -- COMPAT or carbon; session.send(carbon); end end end local function c2s_message_handler(event) return message_handler(event, true) end -- Stanzas sent by local clients module:hook("pre-message/host", c2s_message_handler, 1); module:hook("pre-message/bare", c2s_message_handler, 1); module:hook("pre-message/full", c2s_message_handler, 1); -- Stanzas to local clients module:hook("message/bare", message_handler, 1); module:hook("message/full", message_handler, 1); module:add_feature(xmlns_carbons); module:add_feature(xmlns_carbons_old); if module:get_option_boolean("carbons_v0") then module:add_feature(xmlns_carbons_really_old); end
gpl-3.0
Ninjistix/darkstar
scripts/globals/spells/bluemagic/bludgeon.lua
33
1690
----------------------------------------- -- Spell: Bludgeon -- Delivers a threefold attack. Accuracy varies with TP -- Spell cost: 16 MP -- Monster Type: Arcana -- Spell Type: Physical (Blunt) -- Blue Magic Points: 2 -- Stat Bonus: STR+1 -- Level: 18 -- Casting Time: 0.5 seconds -- Recast Time: 11.75 seconds -- Skillchain Element(s): Fire (can open Scission or Fusion; can close Liquefaction) -- Combos: Undead Killer ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_ACC; params.dmgtype = DMGTYPE_H2H; params.scattr = SC_IMPACTION; params.numhits = 3; params.multiplier = 1.0; params.tp150 = 1.05; params.tp300 = 1.1; params.azuretp = 1.2; params.duppercap = 21; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.3; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
amirb8/telepersian
plugins/owners.lua
194
23755
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 lock_group_arabic(msg, data, target) 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) local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic/Persian is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic/Persian has been unlocked' end end local function lock_group_links(msg, data, target) local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'Link posting is already locked' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'Link posting has been locked' end end local function unlock_group_links(msg, data, target) local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'Link posting is not locked' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'Link posting has been unlocked' end end local function lock_group_spam(msg, data, target) local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'yes' then return 'SuperGroup spam is already locked' else data[tostring(target)]['settings']['lock_spam'] = 'yes' save_data(_config.moderation.data, data) return 'SuperGroup spam has been locked' end end local function unlock_group_spam(msg, data, target) local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'no' then return 'SuperGroup spam is not locked' else data[tostring(target)]['settings']['lock_spam'] = 'no' save_data(_config.moderation.data, data) return 'SuperGroup spam has been unlocked' end end local function lock_group_sticker(msg, data, target) local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'yes' then return 'Sticker posting is already locked' else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return 'Sticker posting has been locked' end end local function unlock_group_sticker(msg, data, target) local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'no' then return 'Sticker posting is already unlocked' else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return 'Sticker posting has been unlocked' end end local function lock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'yes' then return 'Contact posting is already locked' else data[tostring(target)]['settings']['lock_contacts'] = 'yes' save_data(_config.moderation.data, data) return 'Contact posting has been locked' end end local function unlock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'no' then return 'Contact posting is already unlocked' else data[tostring(target)]['settings']['lock_contacts'] = 'no' save_data(_config.moderation.data, data) return 'Contact posting has been unlocked' end end local function enable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['strict'] if strict == 'yes' then return 'Settings are already strictly enforced' else data[tostring(target)]['settings']['strict'] = 'yes' save_data(_config.moderation.data, data) return 'Settings will be strictly enforced' end end local function disable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['strict'] if strict == 'no' then return 'Settings will not be strictly enforced' else data[tostring(target)]['settings']['strict'] = 'no' save_data(_config.moderation.data, data) return 'Settings are not strictly enforced' end end -- Show group settings local function show_group_settingsmod(msg, data, target) 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 bots_protection = "Yes" if data[tostring(target)]['settings']['lock_bots'] then bots_protection = data[tostring(target)]['settings']['lock_bots'] end local leave_ban = "no" if data[tostring(target)]['settings']['leave_ban'] then leave_ban = data[tostring(target)]['settings']['leave_ban'] end local public = "no" if data[tostring(target)]['settings'] then if data[tostring(target)]['settings']['public'] then public = data[tostring(target)]['settings']['public'] 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.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection.."\nPublic: "..public return text end -- Show SuperGroup settings local function show_super_group_settings(msg, data, target) 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 if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_member'] then data[tostring(target)]['settings']['lock_member'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "SuperGroup settings for "..target..":\nLock links : "..settings.lock_link.."\nLock flood: "..settings.flood.."\nLock spam: "..settings.lock_spam.."\nLock Arabic: "..settings.lock_arabic.."\nLock Member: "..settings.lock_member.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public.."\nStrict settings: "..settings.strict 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 == 'user' then local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", " ") 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) 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], chat_id) 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 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) 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) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") channel_set_about(receiver, about_text, ok_cb, false) return "About has been cleaned" end if matches[3] == 'mutelist' then chat_id = string.match(matches[1], '^%d+$') local hash = 'mute_user:'..chat_id redis:del(hash) return "Mutelist Cleaned" 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) 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] local group_type = data[tostring(matches[1])]['group_type'] if matches[3] == 'name' then savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[3] == 'arabic' then savelog(matches[1], name.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[3] == 'links' then savelog(matches[1], name.." ["..msg.from.id.."] locked links ") return lock_group_links(msg, data, target) end if matches[3] == 'spam' then savelog(matches[1], name.." ["..msg.from.id.."] locked spam ") return lock_group_spam(msg, data, target) end if matches[3] == 'rtl' then savelog(matches[1], name.." ["..msg.from.id.."] locked RTL chars. in names") return unlock_group_rtl(msg, data, target) end if matches[3] == 'sticker' then savelog(matches[1], name.." ["..msg.from.id.."] locked sticker") return lock_group_sticker(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] local group_type = data[tostring(matches[1])]['group_type'] if matches[3] == 'name' then savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[3] == 'arabic' then savelog(matches[1], name.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[3] == 'links' and group_type == "SuperGroup" then savelog(matches[1], name.." ["..msg.from.id.."] unlocked links ") return unlock_group_links(msg, data, target) end if matches[3] == 'spam' and group_type == "SuperGroup" then savelog(matches[1], name.." ["..msg.from.id.."] unlocked spam ") return unlock_group_spam(msg, data, target) end if matches[3] == 'rtl' then savelog(matches[1], name.." ["..msg.from.id.."] unlocked RTL chars. in names") return unlock_group_rtl(msg, data, target) end if matches[3] == 'sticker' and group_type == "SuperGroup" then savelog(matches[1], name.." ["..msg.from.id.."] unlocked sticker") return unlock_group_sticker(msg, data, target) end if matches[3] == 'contacts' and group_type == "SuperGroup" then savelog(matches[1], name_log.." ["..msg.from.id.."] locked contact posting") return lock_group_contacts(msg, data, target) end if matches[3] == 'strict' and group_type == "SuperGroup" then savelog(matches[1], name_log.." ["..msg.from.id.."] locked enabled strict settings") return enable_strict_rules(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then local group_type = data[tostring(matches[1])]['group_type'] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback_grouplink (extra , success, result) local receiver = 'chat#id'..matches[1] if success == 0 then send_large_msg(receiver, '*Error: Failed to retrieve link* \nReason: Not creator.') end data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local function callback_superlink (extra , success, result) vardump(result) local receiver = 'channel#id'..matches[1] local user = extra.user if success == 0 then data[tostring(matches[1])]['settings']['set_link'] = nil save_data(_config.moderation.data, data) return send_large_msg(user, '*Error: Failed to retrieve link* \nReason: Not creator.\n\nIf you have the link, please use /setlink to set it') else data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return send_large_msg(user, "Created a new link") end end if group_type == "Group" then local receiver = 'chat#id'..matches[1] savelog(matches[1], name.." ["..msg.from.id.."] created/revoked group link ") export_chat_link(receiver, callback_grouplink, false) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" elseif group_type == "SuperGroup" then local receiver = 'channel#id'..matches[1] local user = 'user#id'..msg.from.id savelog(matches[1], name.." ["..msg.from.id.."] attempted to create a new SuperGroup link") export_channel_link(receiver, callback_superlink, {user = user}) end 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 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] then if not is_owner2(msg.from.id, matches[2]) then return "You are not the owner of this group" end local group_type = data[tostring(matches[2])]['group_type'] if group_type == "Group" or group_type == "Realm" 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) elseif group_type == "SuperGroup" then local channel = 'channel#id'..matches[2] local about_text = matches[3] local data_cat = 'description' local target = matches[2] channel_set_about(channel, about_text, ok_cb, false) data[tostring(target)][data_cat] = about_text save_data(_config.moderation.data, data) savelog(matches[2], name.." ["..msg.from.id.."] has changed SuperGroup description to ["..matches[3].."]") return "Description has been set for ["..matches[2]..']' end end if matches[1] == 'viewsettings' and data[tostring(matches[2])]['settings'] then if not is_owner2(msg.from.id, matches[2]) then return "You are not the owner of this group" end local target = matches[2] local group_type = data[tostring(matches[2])]['group_type'] if group_type == "Group" or group_type == "Realm" then savelog(matches[2], name.." ["..msg.from.id.."] requested group settings ") return show_group_settings(msg, data, target) elseif group_type == "SuperGroup" then savelog(matches[2], name.." ["..msg.from.id.."] requested SuperGroup settings ") return show_super_group_settings(msg, data, target) end 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 local group_name_set = data[tostring(matches[2])]['settings']['set_name'] save_data(_config.moderation.data, data) local chat_to_rename = 'chat#id'..matches[2] local channel_to_rename = 'channel#id'..matches[2] savelog(matches[2], "Group name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(chat_to_rename, group_name_set, ok_cb, false) rename_channel(channel_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], "log file created by owner/support/admin") send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[#!/]owners (%d+) ([^%s]+) (.*)$", "^[#!/]owners (%d+) ([^%s]+)$", "^[#!/](changeabout) (%d+) (.*)$", "^[#!/](changerules) (%d+) (.*)$", "^[#!/](changename) (%d+) (.*)$", "^[#!/](viewsettings) (%d+)$", "^[#!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
scan-bot/scan-bot
plugins/trivia.lua
647
6784
do -- Trivia plugin developed by Guy Spronck -- Returns the chat hash for storing information local function get_hash(msg) local hash = nil if msg.to.type == 'chat' then hash = 'chat:'..msg.to.id..':trivia' end if msg.to.type == 'user' then hash = 'user:'..msg.from.id..':trivia' end return hash end -- Sets the question variables local function set_question(msg, question, answer) local hash =get_hash(msg) if hash then redis:hset(hash, "question", question) redis:hset(hash, "answer", answer) redis:hset(hash, "time", os.time()) end end -- Returns the current question local function get_question( msg ) local hash = get_hash(msg) if hash then local question = redis:hget(hash, 'question') if question ~= "NA" then return question end end return nil end -- Returns the answer of the last question local function get_answer(msg) local hash = get_hash(msg) if hash then return redis:hget(hash, 'answer') else return nil end end -- Returns the time of the last question local function get_time(msg) local hash = get_hash(msg) if hash then return redis:hget(hash, 'time') else return nil end end -- This function generates a new question if available local function get_newquestion(msg) local timediff = 601 if(get_time(msg)) then timediff = os.time() - get_time(msg) end if(timediff > 600 or get_question(msg) == nil)then -- Let's show the answer if no-body guessed it right. if(get_question(msg)) then send_large_msg(get_receiver(msg), "The question '" .. get_question(msg) .."' has not been answered. \nThe answer was '" .. get_answer(msg) .."'") end local url = "http://jservice.io/api/random/" local b,c = http.request(url) local query = json:decode(b) if query then local stringQuestion = "" if(query[1].category)then stringQuestion = "Category: " .. query[1].category.title .. "\n" end if query[1].question then stringQuestion = stringQuestion .. "Question: " .. query[1].question set_question(msg, query[1].question, query[1].answer:lower()) return stringQuestion end end return 'Something went wrong, please try again.' else return 'Please wait ' .. 600 - timediff .. ' seconds before requesting a new question. \nUse !triviaquestion to see the current question.' end end -- This function generates a new question when forced local function force_newquestion(msg) -- Let's show the answer if no-body guessed it right. if(get_question(msg)) then send_large_msg(get_receiver(msg), "The question '" .. get_question(msg) .."' has not been answered. \nThe answer was '" .. get_answer(msg) .."'") end local url = "http://jservice.io/api/random/" local b,c = http.request(url) local query = json:decode(b) if query then local stringQuestion = "" if(query[1].category)then stringQuestion = "Category: " .. query[1].category.title .. "\n" end if query[1].question then stringQuestion = stringQuestion .. "Question: " .. query[1].question set_question(msg, query[1].question, query[1].answer:lower()) return stringQuestion end end return 'Something went wrong, please try again.' end -- This function adds a point to the player local function give_point(msg) local hash = get_hash(msg) if hash then local score = tonumber(redis:hget(hash, msg.from.id) or 0) redis:hset(hash, msg.from.id, score+1) end end -- This function checks for a correct answer local function check_answer(msg, answer) if(get_answer(msg)) then -- Safety for first time use if(get_answer(msg) == "NA")then -- Question has not been set, give a new one --get_newquestion(msg) return "No question set, please use !trivia first." elseif (get_answer(msg) == answer:lower()) then -- Question is set, lets check the answer set_question(msg, "NA", "NA") -- Correct, clear the answer give_point(msg) -- gives out point to player for correct answer return msg.from.print_name .. " has answered correctly! \nUse !trivia to get a new question." else return "Sorry " .. msg.from.print_name .. ", but '" .. answer .. "' is not the correct answer!" end else return "No question set, please use !trivia first." end end local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end local function get_user_score(msg, user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local hash = 'chat:'..msg.to.id..':trivia' user_info.score = tonumber(redis:hget(hash, user_id) or 0) user_info.name = user_print_name(user)..' ('..user_id..')' return user_info end -- Function to print score local function trivia_scores(msg) if msg.to.type == 'chat' then -- Users on chat local hash = 'chat:'..msg.to.id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_user_score(msg, user_id, msg.to.id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.score and b.score then return a.score > b.score end end) local text = '' for k,user in pairs(users_info) do text = text..user.name..' => '..user.score..'\n' end return text else return "This function is only available in group chats." end end local function run(msg, matches) if(matches[1] == "!triviascore" or matches[1] == "!triviascores") then -- Output all scores return trivia_scores(msg) elseif(matches[1] == "!triviaquestion")then return "Question: " .. get_question(msg) elseif(matches[1] == "!triviaskip") then if is_sudo(msg) then return force_newquestion(msg) end elseif(matches[1] ~= "!trivia") then return check_answer(msg, matches[1]) end return get_newquestion(msg) end return { description = "Trivia plugin for Telegram", usage = { "!trivia to obtain a new question.", "!trivia [answer] to answer the question.", "!triviaquestion to show the current question.", "!triviascore to get a scoretable of all players.", "!triviaskip to skip a question (requires sudo)" }, patterns = {"^!trivia (.*)$", "^!trivia$", "^!triviaquestion$", "^!triviascore$", "^!triviascores$", "^!triviaskip$"}, run = run } end
gpl-2.0
neofob/sile
vendor/luafilesystem/tests/test.lua
2
6099
#!/usr/bin/env lua5.1 local tmp = "/tmp" local sep = string.match (package.config, "[^\n]+") local upper = ".." local lfs = require"lfs" print (lfs._VERSION) io.write(".") io.flush() function attrdir (path) for file in lfs.dir(path) do if file ~= "." and file ~= ".." then local f = path..sep..file print ("\t=> "..f.." <=") local attr = lfs.attributes (f) assert (type(attr) == "table") if attr.mode == "directory" then attrdir (f) else for name, value in pairs(attr) do print (name, value) end end end end end -- Checking changing directories local current = assert (lfs.currentdir()) local reldir = string.gsub (current, "^.*%"..sep.."([^"..sep.."])$", "%1") assert (lfs.chdir (upper), "could not change to upper directory") assert (lfs.chdir (reldir), "could not change back to current directory") assert (lfs.currentdir() == current, "error trying to change directories") assert (lfs.chdir ("this couldn't be an actual directory") == nil, "could change to a non-existent directory") io.write(".") io.flush() -- Changing creating and removing directories local tmpdir = current..sep.."lfs_tmp_dir" local tmpfile = tmpdir..sep.."tmp_file" -- Test for existence of a previous lfs_tmp_dir -- that may have resulted from an interrupted test execution and remove it if lfs.chdir (tmpdir) then assert (lfs.chdir (upper), "could not change to upper directory") assert (os.remove (tmpfile), "could not remove file from previous test") assert (lfs.rmdir (tmpdir), "could not remove directory from previous test") end io.write(".") io.flush() -- tries to create a directory assert (lfs.mkdir (tmpdir), "could not make a new directory") local attrib, errmsg = lfs.attributes (tmpdir) if not attrib then error ("could not get attributes of file `"..tmpdir.."':\n"..errmsg) end local f = io.open(tmpfile, "w") f:close() io.write(".") io.flush() -- Change access time local testdate = os.time({ year = 2007, day = 10, month = 2, hour=0}) assert (lfs.touch (tmpfile, testdate)) local new_att = assert (lfs.attributes (tmpfile)) assert (new_att.access == testdate, "could not set access time") assert (new_att.modification == testdate, "could not set modification time") io.write(".") io.flush() -- Change access and modification time local testdate1 = os.time({ year = 2007, day = 10, month = 2, hour=0}) local testdate2 = os.time({ year = 2007, day = 11, month = 2, hour=0}) assert (lfs.touch (tmpfile, testdate2, testdate1)) local new_att = assert (lfs.attributes (tmpfile)) assert (new_att.access == testdate2, "could not set access time") assert (new_att.modification == testdate1, "could not set modification time") io.write(".") io.flush() -- Checking link (does not work on Windows) if lfs.link (tmpfile, "_a_link_for_test_", true) then assert (lfs.attributes"_a_link_for_test_".mode == "file") assert (lfs.symlinkattributes"_a_link_for_test_".mode == "link") assert (lfs.symlinkattributes"_a_link_for_test_".target == tmpfile) assert (lfs.symlinkattributes("_a_link_for_test_", "target") == tmpfile) assert (lfs.link (tmpfile, "_a_hard_link_for_test_")) assert (lfs.attributes (tmpfile, "nlink") == 2) assert (os.remove"_a_link_for_test_") assert (os.remove"_a_hard_link_for_test_") end io.write(".") io.flush() -- Checking text/binary modes (only has an effect in Windows) local f = io.open(tmpfile, "w") local result, mode = lfs.setmode(f, "binary") assert(result) -- on non-Windows platforms, mode is always returned as "binary" result, mode = lfs.setmode(f, "text") assert(result and mode == "binary") f:close() local ok, err = pcall(lfs.setmode, f, "binary") assert(not ok, "could setmode on closed file") assert(err:find("closed file"), "bad error message for setmode on closed file") io.write(".") io.flush() -- Restore access time to current value assert (lfs.touch (tmpfile, attrib.access, attrib.modification)) new_att = assert (lfs.attributes (tmpfile)) assert (new_att.access == attrib.access) assert (new_att.modification == attrib.modification) io.write(".") io.flush() -- Check consistency of lfs.attributes values local attr = lfs.attributes (tmpfile) for key, value in pairs(attr) do assert (value == lfs.attributes (tmpfile, key), "lfs.attributes values not consistent") end -- Check that lfs.attributes accepts a table as second argument local attr2 = {} lfs.attributes(tmpfile, attr2) for key, value in pairs(attr2) do assert (value == lfs.attributes (tmpfile, key), "lfs.attributes values with table argument not consistent") end -- Check that extra arguments are ignored lfs.attributes(tmpfile, attr2, nil) -- Remove new file and directory assert (os.remove (tmpfile), "could not remove new file") assert (lfs.rmdir (tmpdir), "could not remove new directory") assert (lfs.mkdir (tmpdir..sep.."lfs_tmp_dir") == nil, "could create a directory inside a non-existent one") io.write(".") io.flush() -- Trying to get attributes of a non-existent file assert (lfs.attributes ("this couldn't be an actual file") == nil, "could get attributes of a non-existent file") assert (type(lfs.attributes (upper)) == "table", "couldn't get attributes of upper directory") io.write(".") io.flush() -- Stressing directory iterator count = 0 for i = 1, 4000 do for file in lfs.dir (tmp) do count = count + 1 end end io.write(".") io.flush() -- Stressing directory iterator, explicit version count = 0 for i = 1, 4000 do local iter, dir = lfs.dir(tmp) local file = dir:next() while file do count = count + 1 file = dir:next() end assert(not pcall(dir.next, dir)) end io.write(".") io.flush() -- directory explicit close local iter, dir = lfs.dir(tmp) dir:close() assert(not pcall(dir.next, dir)) print"Ok!"
mit
neofob/sile
packages/background.lua
2
1697
SILE.require("packages/color") local outputBackground = function(color) local page = SILE.getFrame("page") local backgroundColor = SILE.colorparser(color) SILE.outputter:pushColor(backgroundColor) SILE.outputter.rule(page:left(), page:top(), page:right(), page:bottom()) SILE.outputter:popColor() end SILE.registerCommand("background", function (options, content) options.color = options.color or "white" options.allpages = options.allpages or true outputBackground(options.color) if options.allpages and options.allpages ~= "false" then local oldNewPage = SILE.documentState.documentClass.newPage SILE.documentState.documentClass.newPage = function(self) local page = oldNewPage(self) outputBackground(options.color) return page end end end, "Draws a solid background color <color> on pages after initialization.") return { documentation = [[\begin{document} The \code{background} package allows you to set the color of the canvas background (by drawing a solid color block the full size of the page on page initialization). The package provides a \code{\\background} command which requires at least one parameter, \code{color=\em{<color \nobreak{}specification}}, and sets the backgound of the current and all following pages to that color. If setting only the current page background different from the default is desired, an extra parameter \code{allpages=false} can be passed. The color specification in the same as specified in the \code{color} package. \background[color=#e9d8ba,allpages=false] So, for example, \code{\\background[color=#e9d8ba,allpages=false]} will set a sepia tone background on the current page. \end{document}]] }
mit
kbullaughey/lstm-play
toys/toy/variable_width_2-4-direct.lua
1
2214
#!/usr/bin/env th -- This toy variant is designed to test MemoryChainDirect and so it is -- simulating a one-to-one sequence problem. tablex = require 'pl.tablex' nn = require 'nn' toy = require './toy' -- Allow for command-line control over the seed and number of examples. cmd = torch.CmdLine() cmd:text() cmd:text('Simulate from toy model, examples have length either 2, 3, or 4') cmd:text() cmd:text('Options') cmd:option('-seed',os.time(),'initial random seed (defaults to current time)') cmd:option('-n',1000,'number of examples to simulate') cmd:option('-sd',0.2,'noise standard deviation') cmd:option('-outfile','variable_width_2-4-direct.t7','output file name') cmd:text() -- parse input params params = cmd:parse(arg) -- Make it reproduceable --torch.manualSeed(params.seed) torch.manualSeed(0) -- Simulate n examples. Each example will have between 2 and 4 inputs, namely our function -- valuated at time lags of 0, 1, 2, up to 4. i.e.: -- -- f(target), f(target-1) -- or -- f(target), f(target-1), f(target-2) -- or -- f(target), f(target-1), f(target-2), f(target-3) -- n = math.floor(params.n/16)*16 target = torch.rand(n,1):mul(toy.max_target) inputs, targets = toy.direct_target_to_inputs(target, params.sd, 4) -- Sample the lengths 2, 3, 4 at prob 1/3 each. --lengths = torch.rand(n):mul(2):floor():add(3) lengths = {} chunk_size = 8 for i=1,n/chunk_size do if i % 2 == 0 then lengths[i] = torch.Tensor(chunk_size):fill(3) else lengths[i] = torch.Tensor(chunk_size):fill(4) end end lengths = nn.JoinTable(1):forward(lengths) -- This method returns a vector containing L ones with the rest zeros. local mapRow = function(L) v = torch.zeros(4) v:narrow(1,1,L):fill(1) return v:view(1,-1) end -- We use mapRow to make a mask matrix so we can zero out inputs that -- are not really part of each example. mask = nn.JoinTable(1):forward(tablex.map(mapRow, lengths:totable())) inputs:cmul(mask) targets:cmul(mask) -- Save the data as nine columns, four columns of inputs, four of targets -- and one column, last, for lengths. Save as t7 file. data = nn.JoinTable(2):forward({inputs,targets,lengths:view(-1,1)}) torch.save(params.outfile, data) -- END
mit
Ninjistix/darkstar
scripts/zones/Windurst_Woods/npcs/Roberta.lua
5
1933
----------------------------------- -- Area: Windurst Woods -- NPC: Roberta -- !pos 21 -4 -157 241 ----------------------------------- require("scripts/globals/settings"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local BlueRibbonBlues = player:getQuestStatus(WINDURST,BLUE_RIBBON_BLUES); if (BlueRibbonBlues == QUEST_ACCEPTED) then local blueRibbonProg = player:getVar("BlueRibbonBluesProg"); if (blueRibbonProg >= 2 and player:hasItem(13569)) then player:startEvent(380); elseif (player:hasItem(13569)) then player:startEvent(379); elseif (player:hasItem(13569) == false) then if (blueRibbonProg == 1 or blueRibbonProg == 3) then player:startEvent(377,0,13569); -- replaces ribbon if lost elseif (blueRibbonProg < 1) then player:startEvent(376,0,13569); --gives us ribbon end else player:startEvent(436); end else player:startEvent(436); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 376 and option == 1 or csid == 377 and option == 1) then if (player:getFreeSlotsCount() >= 1) then local blueRibbonProg = player:getVar("BlueRibbonBluesProg"); if (blueRibbonProg < 1) then player:setVar("BlueRibbonBluesProg",1); elseif (blueRibbonProg == 3) then player:setVar("BlueRibbonBluesProg",4); end player:addItem(13569); player:messageSpecial(ITEM_OBTAINED,13569); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13569); end end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Thierride.lua
5
2810
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Thierride -- @zone 80 -- !pos -124 -2 14 ----------------------------------- require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- Item 1019 = Lufet Salt -- Had to use setVar because you have to trade Salts one at a time according to the wiki. -- Lufet Salt can be obtained by killing Crabs in normal West Ronfaure. function onTrade(player,npc,trade) local lufetSalt = trade:hasItemQty(1019,1); local cnt = trade:getItemCount(); local beansAhoy = player:getQuestStatus(CRYSTAL_WAR,BEANS_AHOY); if (lufetSalt and cnt == 1 and beansAhoy == QUEST_ACCEPTED) then if (player:getVar("BeansAhoy") == 0 == true) then player:startEvent(337); -- Traded the Correct Item Dialogue (NOTE: You have to trade the Salts one at according to wiki) elseif (player:needsToZone() == false) then player:startEvent(340); -- Quest Complete Dialogue end else player:startEvent(339); -- Wrong Item Traded end end; function onTrigger(player,npc) local beansAhoy = player:getQuestStatus(CRYSTAL_WAR,BEANS_AHOY); if (beansAhoy == QUEST_AVAILABLE) then player:startEvent(334); -- Quest Start elseif (beansAhoy == QUEST_ACCEPTED) then player:startEvent(335); -- Quest Active, NPC Repeats what he says but as normal 'text' instead of cutscene. elseif (beansAhoy == QUEST_COMPLETED and getConquestTally() ~= player:getVar("BeansAhoy_ConquestWeek")) then player:startEvent(342); elseif (beansAhoy == QUEST_COMPLETED) then player:startEvent(341); else player:startEvent(333); -- Default Dialogue end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 334) then player:addQuest(CRYSTAL_WAR,BEANS_AHOY); elseif (csid == 337) then player:tradeComplete(); player:setVar("BeansAhoy",1); player:needsToZone(true); elseif (csid == 340 or csid == 342) then if (player:hasItem(5704,1) or player:getFreeSlotsCount() < 1) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,5704) else player:addItem(5704,1); player:messageSpecial(ITEM_OBTAINED,5704); player:setVar("BeansAhoy_ConquestWeek",getConquestTally()); if (csid == 340) then player:completeQuest(CRYSTAL_WAR,BEANS_AHOY); player:setVar("BeansAhoy",0); player:tradeComplete(); end end end end;
gpl-3.0
pombredanne/duktape
perf-testcases/test-string-compare.lua
19
1069
function test() local a, b, c, d, e, f, g local ign local function mk(n) local res = {} for i=1,n do table.insert(res, 'x') end res = table.concat(res) print(#res) return res end a = mk(0) b = mk(1) c = mk(16) d = mk(256) e = mk(4096) f = mk(65536) g = mk(1048576) for i=1,1e7 do ign = (a == a); ign = (a == b); ign = (a == c); ign = (a == d); ign = (a == e); ign = (a == f); ign = (a == g); ign = (b == b); ign = (b == c); ign = (b == d); ign = (b == e); ign = (b == f); ign = (b == g); ign = (c == c); ign = (c == d); ign = (c == e); ign = (c == f); ign = (c == g); ign = (d == d); ign = (d == e); ign = (d == f); ign = (d == g); ign = (e == e); ign = (e == f); ign = (e == g); ign = (f == f); ign = (f == g); ign = (g == g); end end test()
mit
mohammad25253/persianguard12
plugins/service_entergroup.lua
279
2147
local add_user_cfg = load_from_file('data/add_user_cfg.lua') local function template_add_user(base, to_username, from_username, chat_name, chat_id) base = base or '' to_username = '@' .. (to_username or '') from_username = '@' .. (from_username or '') chat_name = chat_name or '' chat_id = "chat#id" .. (chat_id or '') if to_username == "@" then to_username = '' end if from_username == "@" then from_username = '' end base = string.gsub(base, "{to_username}", to_username) base = string.gsub(base, "{from_username}", from_username) base = string.gsub(base, "{chat_name}", chat_name) base = string.gsub(base, "{chat_id}", chat_id) return base end function chat_new_user_link(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.from.username local from_username = '[link](@' .. (msg.action.link_issuer.username or '') .. ')' local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end function chat_new_user(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.action.user.username local from_username = msg.from.username local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end local function run(msg, matches) if not msg.service then return "Are you trying to troll me?" end if matches[1] == "chat_add_user" then chat_new_user(msg) elseif matches[1] == "chat_add_user_link" then chat_new_user_link(msg) end end return { description = "Service plugin that sends a custom message when an user enters a chat.", usage = "", patterns = { "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_add_user_link)$" }, run = run }
gpl-2.0
blackman1380/antispam
plugins/txtsticker.lua
8
1950
do local function run(msg, matches) --Created by @LionTeam local lionteam = URL.escape(matches[1]) local size = '150' if matches[2] == 'big' then size = '400' elseif matches[2] == 'normal' then size = '100' elseif matches[2] == '300' then size = '300' elseif matches[2] == '200' then size = '200' elseif matches[2] == '100' then size = '100' elseif matches[2] == 'small' then size = '50' elseif matches[2] then size = matches[2] end local f = 'ff2e4357' if matches[3] == 'red' then f = 'FF0000' elseif matches[3] == 'blue' then f = '002BFF' elseif matches[3] == 'yellow' then f = 'F7FF00' elseif matches[3] == 'black' then f = '000000' elseif matches[3] == 'orange' then f = 'FF8000' elseif matches[3] == 'lowblue' then f = '00FFFB' elseif matches[3] == 'purple' then f = 'CB00FD' elseif matches[3] == 'gray' then f = '929C9A' elseif matches[3] == 'green' then f = '2AFF00' elseif matches[3] == 'pink' then f = 'FF00E8' elseif matches[3] then f = matches[3] end local url = "http://assets.imgix.net/examples/redleaf.jpg?blur=120&w=700&h=400&fit=crop&txt="..lionteam.."&txtsize="..size.."&txtclr="..f.."&txtalign=middle,center&txtfont=Futura%20Condensed%20Medium&mono=ff6598cc=?markscale=60&markalign=center%2Cdown&mark64=aHR0cDovL2xpb250ZWFtLmlyL2ltZy9zcGVjdHJlbG9nby5wbmc" local ext = ".webp" local cb_extra = {file_path=file} --Created by LionTeam local receiver = get_receiver(msg) local file = download_to_file(url, ".webp") send_document(receiver, file, rmtmp_cb, cb_extra) end return { patterns = { "^[/#!]sticker (.+) (.+) (.+)$", "^[/#!]sticker (.+) (.+)$", "^[/#!]sticker (.+)$" }, run = run } end --Created by @LionTeam
gpl-2.0
ehrenbrav/FCEUX_Learning_Environment
output/luaScripts/SMB2U.lua
9
6222
-- Super Mario Bros. 2 USA - Grids & Contents (Unfinished) -- Super Mario Bros. 2 (U) (PRG0) [!].nes -- Written by QFox -- 31 July 2008 -- shows (proper!) grid and contents. disable grid by setting variable to false -- shows any non-air grid's tile-id -- Slow! Will be heavy on lighter systems local angrybirdo = false; -- makes birdo freak, but can skew other creatures with timing :) local drawgrid = true; -- draws a green grid local function box(x1,y1,x2,y2,color) -- gui.text(50,50,x1..","..y1.." "..x2..","..y2); if (x1 > 0 and x1 < 0xFF and x2 > 0 and x2 < 0xFF and y1 > 0 and y1 < 239 and y2 > 0 and y2 < 239) then gui.drawbox(x1,y1,x2,y2,color); end; end; local function text(x,y,str) if (x > 0 and x < 0xFF and y > 0 and y < 240) then gui.text(x,y,str); end; end; local function toHexStr(n) local meh = "%X"; return meh:format(n); end; while (true) do if (angrybirdo and memory.readbyte(0x0010) > 0x81) then memory.writebyte(0x0010, 0x6D); end; -- birdo fires eggs constantly :p -- px = horzizontal page of current level -- x = page x (relative to current page) -- rx = real x (relative to whole level) -- sx = screen x (relative to viewport) local playerpx = memory.readbyte(0x0014); local playerpy = memory.readbyte(0x001E); local playerx = memory.readbyte(0x0028); local playery = memory.readbyte(0x0032); local playerrx = (playerpx*0xFF)+playerx; local playerry = (playerpy*0xFF)+playery; local playerstate = memory.readbyte(0x0050); local screenoffsetx = memory.readbyte(0x04C0); local screenoffsety = memory.readbyte(0x00CB); local playersx = (playerx - screenoffsetx); if (playersx < 0) then playersx = playersx + 0xFF; end; local playersy = (playery - screenoffsety); if (playersy < 0) then playersy = playersy + 0xFF; end; if (playerstate ~= 0x07) then box(playersx, playersy, playersx+16, playersy+16, "green"); end; if (memory.readbyte(0x00D8) == 0) then -- not scrolling vertically -- show environment -- i have playerrx, which is my real position in this level -- i have the level, which is located at 0x6000 (the SRAM) -- each tile (denoted by one byte) is 16x16 pixels -- each screen is 15 tiles high and about 16 tiles wide -- to get the right column, we add our playerrx/16 to 0x6000 -- to be exact: -- 0x6000 + (math.floor(playerrx/16) * 0xF0) + math.mod(playerx,0x0F) local levelstart = 0x6000; -- start of level layout in RAM -- ok, here we have two choices. either this is a horizontal level or -- it is a vertical level. We have no real way of checking this, but -- luckily levels are either horizontal or vertical :) -- so there are three possibilities -- 1: you're in 0:0, no worries -- 2: you're in x:0, you're in a horizontal level -- 3: you're in 0:y, you're in a vertical level local addleftcrap = math.mod(screenoffsetx,16)*-1; -- works as padding to keep the grid aligned local leftsplitrx = (memory.readbyte(0x04BE)*0x100) + (screenoffsetx + addleftcrap); -- column start left. add addleftcrap to iterative stuff to build up local addtopcrap = math.mod(screenoffsety,15); -- works as padding to keep the grid aligned local columns = math.floor(leftsplitrx/16); -- column x of the level is on the left side of the screen if (drawgrid) then -- print grid? for i=0,15 do -- text(addleftcrap+(i*16)-1, 37, toHexStr(columns+i)); -- print colnumber in each column for j=0,17 do box(addleftcrap+(i*16), addtopcrap+(j*16), addleftcrap+(i*16)+16, addtopcrap+(j*16)+16, "green"); -- draw green box for each cell end; end; end; -- 42=mushroom if you go sub -- 45=small -- 44=big -- 49=subspace -- 6c=pow -- 4e=cherry local topsplitry = (screenoffsety); -- starting page (might flow into next page). if the number of columns -- is > 16, its a horizontal level, else its a vertical level. in either -- case, the other will not up this value. local levelpage = levelstart + ((math.floor(columns/16))*0xF0) + (memory.readbyte(0x00CA)*0x100) + topsplitry; local levelcol = math.mod(columns,16); -- this is our starting column --text(10,150,toHexStr(topsplitry).." "..toHexStr(levelcol).." "..toHexStr(levelpage+levelcol).." "..toHexStr(leftsplitrx)); for j=0,15 do -- 16 columns if (levelcol + j > 15) then -- go to next page levelpage = levelpage + 0xF0; levelcol = -j; end; for i=0,14 do -- 15 rows local tile = memory.readbyte(levelpage+(levelcol+j)+(i*0x10)); if (tile ~= 0x40) then text(-2+addleftcrap+(j*16),5+(i*16),toHexStr(tile)); end; end; end; end; -- not scrolling if -- print some generic stats text(2,10,"x:"..toHexStr(screenoffsetx)); text(2,25,"y: "..toHexStr(screenoffsety)); text(230,10,memory.readbyte(0x04C1)); text(100,10,"Page: "..playerpx..","..playerpy); text(playersx,playersy,playerrx.."\n"..playery); -- draw enemy info local startpx = 0x0015; local startpy = 0x001F; local startx = 0x0029; local starty = 0x0033; local drawn = 0x0051; local type = 0x0090; for i=0,9 do local estate = memory.readbyte(drawn+i); if (estate ~= 0) then local ex = memory.readbyte(startx+i); local epx = memory.readbyte(startpx+i); local ey = memory.readbyte(starty+i); local epy = memory.readbyte(startpy+i); local erx = (epx*0xFF)+ex; local ery = (epy*0xFF)+ey; local esx = (ex - screenoffsetx); if (esx < 0) then esx = esx + 0xFF; end; local esy = (ey - screenoffsety); if (esy < 0) then esy = esy + 0xFF; end; --text(10, 20+(16*i), i..": "..esx.." "..erx); -- show enemy position list -- show enemy information if ((erx > playerrx-127) and erx < (playerrx+120)) then --text(esx,esy,erx); -- show level x pos above enemy local wtf = "%X"; text(esx,esy,wtf:format(memory.readbyte(type+i))); -- show enemy code if (estate == 1 and i < 5) then box(esx, esy, esx+16, esy+16, "red"); else box(esx, esy, esx+16, esy+16, "blue"); end; end; end; end; -- enemy info FCEU.frameadvance(); end;
gpl-2.0
abosalah22/zak
DevProx/DevProx.lua
2
8671
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./DevProx/utils") local f = assert(io.popen('/usr/bin/git describe --tags', 'r')) VERSION = assert(f:read('*a')) f:close() -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end msg = backward_msg_format(msg) local receiver = get_receiver(msg) print(receiver) --vardump(msg) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) -- See plugins/isup.lua as an example for cron _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < os.time() - 5 then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then --send_large_msg(*group id*, msg.text) *login code will be sent to GroupID* return false end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Sudo user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "admin", "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "invite", "all", "leave_ban", "supergroup", "whitelist", "msg_checks", "plugins", "send", "lk_fwd", "lk_media", "welcome", "help", "lk_tag", "lk_username", "lk_join", "lk_english", "lk_emoji", "he1", "he2", "he3", "he4", "hedev", "time", "tagall", "textphoto", "sticker23", "rebot", "leave", "block", "dev", "voice", "weather", "translate", "writer", "deltmsg", "me", "info", "azan", "run", "info", "iq_abs", "remsg", "run1", "redis", "aboshosho", "aboshosho1", "aboshosho2", "aboshosho3", "aboshosho4", "aboshoshoo1", "ar-badword", "ar-banhammer", "ar-beoadcast", "ar-english", "ar-fwd", "ar-getfile", "ar-help", "ar-lock-bot", "ar-me", "ar-media", "ar-msg-checks", "ar-onservice", "ar-owners", "ar-plugins", "ar-redis", "ar-run1", "ar-supergroup", "ar-tag", "ar-username", "ch", "dd", }, sudo_users = { 188248946,0,tonumber(our_id)},--Sudo users moderation = {data = 'data/moderation.json'}, about_text = [[🚏- اهلا بك عزيزي WeLcOmE سورس ديف بروكس ( DevProx ) 〰 ➗ 〰 ✖️ 〰 ➕ 〰 Developer ⛳️🏒 : 🔸 - @IQ_ABS Channel sors 🏈 : 🔹 - @DEV_PROX 〰 ➗ 〰 ✖️ 〰 ➕ 〰 🛰 - رابط السورس : https://github.com/iqabs/DevProx.git : link in githup]], help_text = [[ْDEV @IQ_ABS]], help_text_super =[[ْDEV @IQ_ABS]], help_text_realm = [[ْDEV @IQ_ABS]], } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) --vardump (chat) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
aqasaeed/hesambot
plugins/anti_spam.lua
923
3750
--An empty table for solving multiple kicking problem(thanks to @topkecleon ) kicktable = {} do local TIME_CHECK = 2 -- seconds local data = load_data(_config.moderation.data) -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then return msg end if msg.from.id == our_id then return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) --Load moderation data local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then --Check if flood is one or off if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then return msg end end -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) local data = load_data(_config.moderation.data) local NUM_MSG_MAX = 5 if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])--Obtain group flood sensitivity end end local max_msg = NUM_MSG_MAX * 1 if msgs > max_msg then local user = msg.from.id -- Ignore mods,owner and admins if is_momod(msg) then return msg end local chat = msg.to.id local user = msg.from.id -- Return end if user was kicked before if kicktable[user] == true then return end kick_user(user, chat) local name = user_print_name(msg.from) --save it to log file savelog(msg.to.id, name.." ["..msg.from.id.."] spammed and kicked ! ") -- incr it on redis local gbanspam = 'gban:spam'..msg.from.id redis:incr(gbanspam) local gbanspam = 'gban:spam'..msg.from.id local gbanspamonredis = redis:get(gbanspam) --Check if user has spammed is group more than 4 times if gbanspamonredis then if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then --Global ban that user banall_user(msg.from.id) local gbanspam = 'gban:spam'..msg.from.id --reset the counter redis:set(gbanspam, 0) local username = " " if msg.from.username ~= nil then username = msg.from.username end local name = user_print_name(msg.from) --Send this to that chat send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." Globally banned (spamming)") local log_group = 1 --set log group caht id --send it to log group send_large_msg("chat#id"..log_group, "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)") end end kicktable[user] = true msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function cron() --clear that table on the top of the plugins kicktable = {} end return { patterns = {}, cron = cron, pre_process = pre_process } end
gpl-2.0
davidbuzz/ardupilot
libraries/AP_Scripting/examples/terrain_warning.lua
22
1780
-- height above terrain warning script -- min altitude above terrain, script will warn if lower than this local terrain_min_alt = 20 -- warning is only enabled further than this distance from home local home_dist_enable = 25 -- must have climbed at least this distance above terrain since arming to enable warning local height_enable = 10 -- warning repeat time in ms local warn_ms = 10000 local height_threshold_passed = false local last_warn = 0 function update() if not arming:is_armed() then -- not armed, nothing to do, reset height threshold height_threshold_passed = false return update, 1000 end -- get the height above terrain, allowing extrapolation -- this used the terrain database only, not considering rangefinders local terrain_height = terrain:height_above_terrain(true) if not terrain_height then -- could not get a valid terrain alt return update, 1000 end if (not height_threshold_passed) and (terrain_height < height_enable) then -- not climbed far enough to enable, nothing to do return update, 1000 end height_threshold_passed = true local home_dist = ahrs:get_relative_position_NED_home() if home_dist then -- only check home dist if we have a valid home -- do not consider altitude above home in radius calc home_dist:z(0) if home_dist:length() < home_dist_enable then -- to close to home return update, 1000 end end if terrain_height < terrain_min_alt then -- send message at severity level 2 (MAV_SEVERITY_CRITICAL), this will appear on the MP HUD and be read out if speech is enabled gcs:send_text(2, string.format("Terrain Warning: %0.1f meters",terrain_height)) return update, warn_ms end return update, 1000 end return update, 10000
gpl-3.0
Ninjistix/darkstar
scripts/zones/Western_Adoulin/npcs/Dangueubert.lua
7
1338
----------------------------------- -- 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"); ----------------------------------- function onTrade(player,npc,trade) end; 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(2558); else -- Standard dialogue player:startEvent(546, 0, 1); end else -- Dialogue prior to joining colonization effort player:startEvent(546); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 2558) then -- Progresses Quest: 'A Certain Substitute Patrolman' player:setVar("ACSP_NPCs_Visited", 7); elseif (csid == 546) then if (option == 1) then -- Warps player to Mog Garden player:setPos(0, 0, 0, 0, 280); end end end;
gpl-3.0
vovochka404/eiskaltdcpp
data/luascripts/adccommands.lua
7
1061
--// adccommands.lua: rev005/20080510 --// adccommands.lua: Let you change your nick on ADC hubs local adccommands = {} function adccommands.tokenize(text) local ret = {} string.gsub(text, "([^ ]+)", function(s) table.insert(ret, s) end ) return ret end function adccommands.changeNick(hub, newnick) local sid = hub:getOwnSid() newnick = dcu:AdcEscape(newnick) DC():SendHubMessage( hub:getId(), "BINF " .. sid .. " NI" .. newnick .. "\n" ) end dcpp:setListener( "ownChatOut", "adccommands", function( hub, text ) if (hub:getProtocol() == "adc" and string.sub(text, 1, 1) == "/") then local params = adccommands.tokenize(text) if params[1] == "/help" then hub:addLine( "(adccommands.lua) /nick <nick>", true ) return nil elseif params[1] == "/nick" then if params[2] then adccommands.changeNick(hub, string.sub(text, 7)) return true else hub:addLine("Usage: /nick <nick>") return true end end end end ) DC():PrintDebug( " ** Loaded adccommands.lua **" )
gpl-3.0
Ninjistix/darkstar
scripts/globals/items/bowl_of_humpty_soup.lua
3
1034
----------------------------------------- -- ID: 4521 -- Item: Bowl of Humpty Soup -- Food Effect: 240Min, All Races ----------------------------------------- -- Health % 6 -- Health Cap 35 -- Magic 5 -- Health Regen While Healing 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4521); end; function onEffectGain(target, effect) target:addMod(MOD_FOOD_HPP, 6); target:addMod(MOD_FOOD_HP_CAP, 35); target:addMod(MOD_MP, 5); target:addMod(MOD_HPHEAL, 5); end; function onEffectLose(target, effect) target:delMod(MOD_FOOD_HPP, 6); target:delMod(MOD_FOOD_HP_CAP, 35); target:delMod(MOD_MP, 5); target:delMod(MOD_HPHEAL, 5); end;
gpl-3.0
Ninjistix/darkstar
scripts/commands/setweather.lua
8
1872
--------------------------------------------------------------------------------------------------- -- func: setweather -- desc: Sets the current weather for the current zone. --------------------------------------------------------------------------------------------------- require("scripts/globals/weather"); cmdprops = { permission = 1, parameters = "s" }; function error(player, msg) player:PrintToPlayer(msg); player:PrintToPlayer("!setweather <weather ID>"); end; function onTrigger(player, weather) local weatherList = { ["none"] = 0, ["sunshine"] = 1, ["clouds"] = 2, ["fog"] = 3, ["hot spell"] = 4, ["heat wave"] = 5, ["rain"] = 6, ["squall"] = 7, ["dust storm"] = 8, ["sand storm"] = 9, ["wind"] = 10, ["gales"] = 11, ["snow"] = 12, ["blizzards"] = 13, ["thunder"] = 14, ["thunderstorms"] = 15, ["auroras"] = 16, ["stellar glare"] = 17, ["gloom"] = 18, ["darkness"] = 19 }; -- validate weather if (weather == nil) then error(player, "You must supply a weather ID."); return; end weather = tonumber(weather) or _G[string.upper(weather)] or weatherList[string.lower(weather)]; if (weather == nil or weather < 0 or weather > 19) then error(player, "Invalid weather ID."); return; end -- invert weather table local weatherByNum={}; for k,v in pairs(weatherList) do weatherByNum[v]=k; end -- set weather player:setWeather( weather ); player:PrintToPlayer( string.format("Set weather to %s.", weatherByNum[weather]) ); end
gpl-3.0
Ninjistix/darkstar
scripts/zones/The_Boyahda_Tree/npcs/Mandragora_Warden.lua
5
1727
----------------------------------- -- Area: The Boyahda Tree -- NPC: Mandragora Warden -- Type: Mission NPC -- !pos 81.981 7.593 139.556 153 ----------------------------------- package.loaded["scripts/zones/The_Boyahda_Tree/TextIDs"] = nil; ----------------------------------- function onTrade(player,npc,trade) local MissionStatus = player:getVar("MissionStatus"); if (player:getCurrentMission(WINDURST) == DOLL_OF_THE_DEAD and (MissionStatus == 4 or MissionStatus == 5)) then if (trade:hasItemQty(1181,1) == true) and (trade:getItemCount() == 1) then player:startEvent(13); end end end; function onTrigger(player,npc) local MissionStatus = player:getVar ("MissionStatus"); local dialog = player:getVar ("mandialog"); if (MissionStatus == 4) then if (dialog == 0) then player:startEvent(10); player:setVar("mandialog",1); player:PrintToPlayer("Seems like he wants something"); elseif (dialog == 1) then player:startEvent(11); player:setVar("mandialog",2); elseif (dialog == 2) then player:startEvent(12); player:setVar("mandialog",3); player:PrintToPlayer("Seems like he wants some Gobbu Hummus"); end end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 13) then player:setVar("MissionStatus",6); player:messageSpecial(KEYITEM_OBTAINED,LETTER_FROM_ZONPAZIPPA); player:addKeyItem(LETTER_FROM_ZONPAZIPPA); end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Bastok_Mines/npcs/Titus.lua
3
1395
----------------------------------- -- Area: Bastok Mines -- NPC: Titus -- Alchemy Synthesis Image Support ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local guildMember = isGuildMember(player,1); local SkillCap = getCraftSkillCap(player,SKILL_ALCHEMY); local SkillLevel = player:getSkillLevel(SKILL_ALCHEMY); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_ALCHEMY_IMAGERY) == false) then player:startEvent(123,SkillCap,SkillLevel,1,137,player:getGil(),0,0,0); else player:startEvent(123,SkillCap,SkillLevel,1,137,player:getGil(),6758,0,0); end else player:startEvent(123); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 123 and option == 1) then player:messageSpecial(ALCHEMY_SUPPORT,0,7,1); player:addStatusEffect(EFFECT_ALCHEMY_IMAGERY,1,0,120); end end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/items/porcupine_pie.lua
3
1702
----------------------------------------- -- ID: 5156 -- Item: porcupine_pie -- Food Effect: 30Min, All Races ----------------------------------------- -- HP 55 -- Strength 6 -- Vitality 2 -- Intelligence -3 -- Mind 3 -- HP recovered while healing 2 -- MP recovered while healing 2 -- Accuracy 5 -- Attack % 18 (cap 95) -- Ranged Attack % 18 (cap 95) ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5156); end; function onEffectGain(target, effect) target:addMod(MOD_HP, 55); target:addMod(MOD_STR, 6); target:addMod(MOD_VIT, 2); target:addMod(MOD_INT, -3); target:addMod(MOD_MND, 3); target:addMod(MOD_HPHEAL, 2); target:addMod(MOD_MPHEAL, 2); target:addMod(MOD_ACC, 5); target:addMod(MOD_FOOD_ATTP, 18); target:addMod(MOD_FOOD_ATT_CAP, 95); target:addMod(MOD_FOOD_RATTP, 18); target:addMod(MOD_FOOD_RATT_CAP, 95); end; function onEffectLose(target, effect) target:delMod(MOD_HP, 55); target:delMod(MOD_STR, 6); target:delMod(MOD_VIT, 2); target:delMod(MOD_INT, -3); target:delMod(MOD_MND, 3); target:delMod(MOD_HPHEAL, 2); target:delMod(MOD_MPHEAL, 2); target:delMod(MOD_ACC, 5); target:delMod(MOD_FOOD_ATTP, 18); target:delMod(MOD_FOOD_ATT_CAP, 95); target:delMod(MOD_FOOD_RATTP, 18); target:delMod(MOD_FOOD_RATT_CAP, 95); end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/spells/regen_ii.lua
5
1480
----------------------------------------- -- Spell: Regen II -- Gradually restores target's HP. ----------------------------------------- -- Scale down duration based on level -- Composure increases duration 3x ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local hp = math.ceil(12 * (1 + 0.01 * caster:getMod(MOD_REGEN_MULTIPLIER))); -- spell base times gear multipliers hp = hp + caster:getMerit(MERIT_REGEN_EFFECT); -- bonus hp from merits hp = hp + caster:getMod(MOD_LIGHT_ARTS_REGEN); -- bonus hp from light arts local duration = 60; duration = duration + caster:getMod(MOD_REGEN_DURATION); if (caster:hasStatusEffect(EFFECT_COMPOSURE) == true and caster:getID() == target:getID()) then duration = duration * 3; end duration = calculateDurationForLvl(duration, 44, target:getMainLvl()); if (target:hasStatusEffect(EFFECT_REGEN) and target:getStatusEffect(EFFECT_REGEN):getTier() == 1) then target:delStatusEffect(EFFECT_REGEN); end if (target:addStatusEffect(EFFECT_REGEN,hp,3,duration,0,0,0)) then spell:setMsg(msgBasic.MAGIC_GAIN_EFFECT); else spell:setMsg(msgBasic.MAGIC_NO_EFFECT); -- no effect end return EFFECT_REGEN; end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/spells/bluemagic/magic_fruit.lua
7
1612
----------------------------------------- -- Spell: Magic Fruit -- Restores HP for the target party member -- Spell cost: 72 MP -- Monster Type: Beasts -- Spell Type: Magical (Light) -- Blue Magic Points: 3 -- Stat Bonus: CHR+1 HP+5 -- Level: 58 -- Casting Time: 3.5 seconds -- Recast Time: 6 seconds -- -- Combos: Resist Sleep ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local minCure = 250; local divisor = 0.6666; local constant = 130; local power = getCurePowerOld(caster); local final = getCureFinal(caster,spell,getBaseCureOld(power,divisor,constant),minCure,true); local diff = (target:getMaxHP() - target:getHP()); if (power > 559) then divisor = 2.8333; constant = 391.2 elseif (power > 319) then divisor = 1; constant = 210; end final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then --Applying server mods.... final = final * CURE_POWER; end if (final > diff) then final = diff; end target:addHP(final); target:wakeUp(); caster:updateEnmityFromCure(target,final); spell:setMsg(msgBasic.MAGIC_RECOVERS_HP); return final; end;
gpl-3.0
codedash64/Urho3D
bin/Data/LuaScripts/15_Navigation.lua
8
22136
-- Navigation example. -- This sample demonstrates: -- - Generating a navigation mesh into the scene -- - Performing path queries to the navigation mesh -- - Rebuilding the navigation mesh partially when adding or removing objects -- - Visualizing custom debug geometry -- - Raycasting drawable components -- - Making a node follow the Detour path require "LuaScripts/Utilities/Sample" local endPos = nil local currentPath = {} local useStreaming = false local streamingDistance = 2 local navigationTiles = {} local addedTiles = {} function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateUI() -- Setup the viewport for displaying the scene SetupViewport() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_RELATIVE) -- Hook up to the frame update and render post-update events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000) -- Also create a DebugRenderer component so that we can draw debug geometry scene_:CreateComponent("Octree") scene_:CreateComponent("DebugRenderer") -- Create scene node & StaticModel component for showing a static plane local planeNode = scene_:CreateChild("Plane") planeNode.scale = Vector3(100.0, 1.0, 100.0) local planeObject = planeNode:CreateComponent("StaticModel") planeObject.model = cache:GetResource("Model", "Models/Plane.mdl") planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml") -- Create a Zone component for ambient lighting & fog control local zoneNode = scene_:CreateChild("Zone") local zone = zoneNode:CreateComponent("Zone") zone.boundingBox = BoundingBox(-1000.0, 1000.0) zone.ambientColor = Color(0.15, 0.15, 0.15) zone.fogColor = Color(0.5, 0.5, 0.7) zone.fogStart = 100.0 zone.fogEnd = 300.0 -- Create a directional light to the world. Enable cascaded shadows on it local lightNode = scene_:CreateChild("DirectionalLight") lightNode.direction = Vector3(0.6, -1.0, 0.8) local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL light.castShadows = true light.shadowBias = BiasParameters(0.00025, 0.5) -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8) -- Create some mushrooms local NUM_MUSHROOMS = 100 for i = 1, NUM_MUSHROOMS do CreateMushroom(Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0)) end -- Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before -- rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility local NUM_BOXES = 20 for i = 1, NUM_BOXES do local boxNode = scene_:CreateChild("Box") local size = 1.0 + Random(10.0) boxNode.position = Vector3(Random(80.0) - 40.0, size * 0.5, Random(80.0) - 40.0) boxNode:SetScale(size) local boxObject = boxNode:CreateComponent("StaticModel") boxObject.model = cache:GetResource("Model", "Models/Box.mdl") boxObject.material = cache:GetResource("Material", "Materials/Stone.xml") boxObject.castShadows = true if size >= 3.0 then boxObject.occluder = true end end -- Create Jack node that will follow the path jackNode = scene_:CreateChild("Jack") jackNode.position = Vector3(-5, 0, 20) local modelObject = jackNode:CreateComponent("AnimatedModel") modelObject.model = cache:GetResource("Model", "Models/Jack.mdl") modelObject.material = cache:GetResource("Material", "Materials/Jack.xml") modelObject.castShadows = true -- Create a NavigationMesh component to the scene root local navMesh = scene_:CreateComponent("NavigationMesh") -- Set small tiles to show navigation mesh streaming navMesh.tileSize = 32 -- Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the -- navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable scene_:CreateComponent("Navigable") -- Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes -- in the scene and still update the mesh correctly navMesh.padding = Vector3(0.0, 10.0, 0.0) -- Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use -- physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example) -- it will use renderable geometry instead navMesh:Build() -- Create the camera. Limit far clip distance to match the fog cameraNode = scene_:CreateChild("Camera") local camera = cameraNode:CreateComponent("Camera") camera.farClip = 300.0 -- Set an initial position for the camera scene node above the plane and looking down cameraNode.position = Vector3(0.0, 50.0, 0.0) pitch = 80.0 cameraNode.rotation = Quaternion(pitch, yaw, 0.0) end function CreateUI() -- Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will -- control the camera, and when visible, it will point the raycast target local style = cache:GetResource("XMLFile", "UI/DefaultStyle.xml") local cursor = Cursor:new() cursor:SetStyleAuto(style) ui.cursor = cursor -- Set starting position of the cursor at the rendering window center cursor:SetPosition(graphics.width / 2, graphics.height / 2) -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText.text = "Use WASD keys to move, RMB to rotate view\n".. "LMB to set destination, SHIFT+LMB to teleport\n".. "MMB or O key to add or remove obstacles\n".. "Tab to toggle navigation mesh streaming\n".. "Space to toggle debug geometry" instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- The text has multiple rows. Center them in relation to each other instructionText.textAlignment = HA_CENTER -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request -- debug geometry SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate") end function MoveCamera(timeStep) input.mouseVisible = input.mouseMode ~= MM_RELATIVE mouseDown = input:GetMouseButtonDown(MOUSEB_RIGHT) -- Override the MM_RELATIVE mouse grabbed settings, to allow interaction with UI input.mouseGrabbed = mouseDown -- Right mouse button controls mouse cursor visibility: hide when pressed ui.cursor.visible = not mouseDown -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 20.0 -- Mouse sensitivity as degrees per pixel local MOUSE_SENSITIVITY = 0.1 -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees -- Only move the camera when the cursor is hidden if not ui.cursor.visible then local mouseMove = input.mouseMove yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, -90.0, 90.0) -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) end -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end -- Set destination or teleport with left mouse button if input:GetMouseButtonPress(MOUSEB_LEFT) then SetPathPoint() end -- Add or remove objects with middle mouse button, then rebuild navigation mesh partially if input:GetMouseButtonPress(MOUSEB_MIDDLE) or input:GetKeyPress(KEY_O) then AddOrRemoveObject() end -- Toggle debug geometry with space if input:GetKeyPress(KEY_SPACE) then drawDebug = not drawDebug end end function SetPathPoint() local hitPos, hitDrawable = Raycast(250.0) local navMesh = scene_:GetComponent("NavigationMesh") if hitPos then local pathPos = navMesh:FindNearestPoint(hitPos, Vector3.ONE) if input:GetQualifierDown(QUAL_SHIFT) then -- Teleport currentPath = {} jackNode:LookAt(Vector3(pathPos.x, jackNode.position.y, pathPos.z), Vector3(0.0, 1.0, 0.0)) jackNode.position = pathPos else -- Calculate path from Jack's current position to the end point endPos = pathPos currentPath = navMesh:FindPath(jackNode.position, endPos) end end end function AddOrRemoveObject() -- Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one local hitPos, hitDrawable = Raycast(250.0) if not useStreaming and hitDrawable then -- The part of the navigation mesh we must update, which is the world bounding box of the associated -- drawable component local updateBox = nil local hitNode = hitDrawable.node if hitNode.name == "Mushroom" then updateBox = hitDrawable.worldBoundingBox hitNode:Remove() else local newNode = CreateMushroom(hitPos) local newObject = newNode:GetComponent("StaticModel") updateBox = newObject.worldBoundingBox end -- Rebuild part of the navigation mesh, then recalculate path if applicable local navMesh = scene_:GetComponent("NavigationMesh") navMesh:Build(updateBox) if table.maxn(currentPath) > 0 then currentPath = navMesh:FindPath(jackNode.position, endPos) end end end function CreateMushroom(pos) local mushroomNode = scene_:CreateChild("Mushroom") mushroomNode.position = pos mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0) mushroomNode:SetScale(2.0 + Random(0.5)) local mushroomObject = mushroomNode:CreateComponent("StaticModel") mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl") mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml") mushroomObject.castShadows = true return mushroomNode end function Raycast(maxDistance) local pos = ui.cursorPosition -- Check the cursor is visible and there is no UI element in front of the cursor if (not ui.cursor.visible) or (ui:GetElementAt(pos, true) ~= nil) then return nil, nil end local camera = cameraNode:GetComponent("Camera") local cameraRay = camera:GetScreenRay(pos.x / graphics.width, pos.y / graphics.height) -- Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit local octree = scene_:GetComponent("Octree") local result = octree:RaycastSingle(cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY) if result.drawable ~= nil then return result.position, result.drawable end return nil, nil end function ToggleStreaming(enabled) local navMesh = scene_:GetComponent("NavigationMesh") if enabled then local maxTiles = (2 * streamingDistance + 1) * (2 * streamingDistance + 1) local boundingBox = BoundingBox(navMesh.boundingBox) SaveNavigationData() navMesh:Allocate(boundingBox, maxTiles); else navMesh:Build(); end end function UpdateStreaming() local navMesh = scene_:GetComponent("NavigationMesh") -- Center the navigation mesh at the jack local jackTile = navMesh:GetTileIndex(jackNode.worldPosition) local beginTile = VectorMax(IntVector2(0, 0), jackTile - IntVector2(1, 1) * streamingDistance) local endTile = VectorMin(jackTile + IntVector2(1, 1) * streamingDistance, navMesh.numTiles - IntVector2(1, 1)) -- Remove tiles local numTiles = navMesh.numTiles for i,tileIdx in pairs(addedTiles) do if not (beginTile.x <= tileIdx.x and tileIdx.x <= endTile.x and beginTile.y <= tileIdx.y and tileIdx.y <= endTile.y) then addedTiles[i] = nil navMesh:RemoveTile(tileIdx) end end -- Add tiles for z = beginTile.y, endTile.y do for x = beginTile.x, endTile.x do local i = z * numTiles.x + x if not navMesh:HasTile(IntVector2(x, z)) and navigationTiles[i] then addedTiles[i] = IntVector2(x, z) navMesh:AddTile(navigationTiles[i]) end end end end function SaveNavigationData() local navMesh = scene_:GetComponent("NavigationMesh") navigationTiles = {} addedTiles = {} local numTiles = navMesh.numTiles for z = 0, numTiles.y - 1 do for x = 0, numTiles.x - 1 do local i = z * numTiles.x + x navigationTiles[i] = navMesh:GetTileData(IntVector2(x, z)) end end end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) -- Make Jack follow the Detour path FollowPath(timeStep) -- Update streaming if input:GetKeyPress(KEY_TAB) then useStreaming = not useStreaming ToggleStreaming(useStreaming) end if useStreaming then UpdateStreaming() end end function FollowPath(timeStep) if table.maxn(currentPath) > 0 then local nextWaypoint = currentPath[1] -- NB: currentPath[1] is the next waypoint in order -- Rotate Jack toward next waypoint to reach and move. Check for not overshooting the target local move = 5 * timeStep local distance = (jackNode.position - nextWaypoint):Length() if move > distance then move = distance end jackNode:LookAt(nextWaypoint, Vector3(0.0, 1.0, 0.0)) jackNode:Translate(Vector3(0.0, 0.0, 1.0) * move) -- Remove waypoint if reached it if distance < 0.1 then table.remove(currentPath, 1) end end end function HandlePostRenderUpdate(eventType, eventData) -- If draw debug mode is enabled, draw navigation mesh debug geometry if drawDebug then local navMesh = scene_:GetComponent("NavigationMesh") navMesh:DrawDebugGeometry(true) end -- Visualize the start and end points and the last calculated path local size = table.maxn(currentPath) if size > 0 then local debug = scene_:GetComponent("DebugRenderer") debug:AddBoundingBox(BoundingBox(endPos - Vector3(0.1, 0.1, 0.1), endPos + Vector3(0.1, 0.1, 0.1)), Color(1.0, 1.0, 1.0)) -- Draw the path with a small upward bias so that it does not clip into the surfaces local bias = Vector3(0.0, 0.05, 0.0) debug:AddLine(jackNode.position + bias, currentPath[1] + bias, Color(1.0, 1.0, 1.0)) if size > 1 then for i = 1, size - 1 do debug:AddLine(currentPath[i] + bias, currentPath[i + 1] + bias, Color(1.0, 1.0, 1.0)) end end end end -- Create XML patch instructions for screen joystick layout specific to this sample app function GetScreenJoystickPatchString() return "<patch>" .. " <add sel=\"/element\">" .. " <element type=\"Button\">" .. " <attribute name=\"Name\" value=\"Button3\" />" .. " <attribute name=\"Position\" value=\"-120 -120\" />" .. " <attribute name=\"Size\" value=\"96 96\" />" .. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" .. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" .. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" .. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" .. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" .. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"Label\" />" .. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" .. " <attribute name=\"Vert Alignment\" value=\"Center\" />" .. " <attribute name=\"Color\" value=\"0 0 0 1\" />" .. " <attribute name=\"Text\" value=\"Teleport\" />" .. " </element>" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"LSHIFT\" />" .. " </element>" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" .. " <attribute name=\"Text\" value=\"LEFT\" />" .. " </element>" .. " </element>" .. " <element type=\"Button\">" .. " <attribute name=\"Name\" value=\"Button4\" />" .. " <attribute name=\"Position\" value=\"-120 -12\" />" .. " <attribute name=\"Size\" value=\"96 96\" />" .. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" .. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" .. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" .. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" .. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" .. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"Label\" />" .. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" .. " <attribute name=\"Vert Alignment\" value=\"Center\" />" .. " <attribute name=\"Color\" value=\"0 0 0 1\" />" .. " <attribute name=\"Text\" value=\"Obstacles\" />" .. " </element>" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" .. " <attribute name=\"Text\" value=\"MIDDLE\" />" .. " </element>" .. " </element>" .. " </add>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Set</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" .. " <attribute name=\"Text\" value=\"LEFT\" />" .. " </element>" .. " </add>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"SPACE\" />" .. " </element>" .. " </add>" .. "</patch>" end
mit
Ninjistix/darkstar
scripts/globals/items/bowl_of_miso_ramen+1.lua
3
1571
----------------------------------------- -- ID: 6461 -- Item: bowl_of_miso_ramen_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- HP +105 -- STR +6 -- VIT +6 -- DEF +11% (cap 175) -- Magic Evasion +11% (cap 55) -- Magic Def. Bonus +6 -- Resist Slow +15 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,6461); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 105); target:addMod(MOD_STR, 6); target:addMod(MOD_VIT, 6); target:addMod(MOD_FOOD_DEFP, 11); target:addMod(MOD_FOOD_DEF_CAP, 175); -- target:addMod(MOD_FOOD_MEVAP, 11); -- target:addMod(MOD_FOOD_MEVA_CAP, 55); target:addMod(MOD_MDEF, 6); target:addMod(MOD_SLOWRES, 15); end; function onEffectLose(target, effect) target:delMod(MOD_HP, 105); target:delMod(MOD_STR, 6); target:delMod(MOD_VIT, 6); target:delMod(MOD_FOOD_DEFP, 11); target:delMod(MOD_FOOD_DEF_CAP, 175); -- target:delMod(MOD_FOOD_MEVAP, 11); -- target:delMod(MOD_FOOD_MEVA_CAP, 55); target:delMod(MOD_MDEF, 6); target:delMod(MOD_SLOWRES, 15); end;
gpl-3.0
Xagul/forgottenserver
data/migrations/13.lua
58
2963
function onUpdateDatabase() print("> Updating database to version 14 (account_bans, ip_bans and player_bans)") db.query("CREATE TABLE IF NOT EXISTS `account_bans` (`account_id` int(11) NOT NULL, `reason` varchar(255) NOT NULL, `banned_at` bigint(20) NOT NULL, `expires_at` bigint(20) NOT NULL, `banned_by` int(11) NOT NULL, PRIMARY KEY (`account_id`), KEY `banned_by` (`banned_by`), FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (`banned_by`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB") db.query("CREATE TABLE IF NOT EXISTS `account_ban_history` (`account_id` int(11) NOT NULL, `reason` varchar(255) NOT NULL, `banned_at` bigint(20) NOT NULL, `expired_at` bigint(20) NOT NULL, `banned_by` int(11) NOT NULL, PRIMARY KEY (`account_id`), KEY `banned_by` (`banned_by`), FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (`banned_by`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB") db.query("CREATE TABLE IF NOT EXISTS `ip_bans` (`ip` int(10) unsigned NOT NULL, `reason` varchar(255) NOT NULL, `banned_at` bigint(20) NOT NULL, `expires_at` bigint(20) NOT NULL, `banned_by` int(11) NOT NULL, PRIMARY KEY (`ip`), KEY `banned_by` (`banned_by`), FOREIGN KEY (`banned_by`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB") db.query("CREATE TABLE IF NOT EXISTS `player_namelocks` (`player_id` int(11) NOT NULL, `reason` varchar(255) NOT NULL, `namelocked_at` bigint(20) NOT NULL, `namelocked_by` int(11) NOT NULL, PRIMARY KEY (`player_id`), KEY `namelocked_by` (`namelocked_by`), FOREIGN KEY (`player_id`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (`namelocked_by`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB") local resultId = db.storeQuery("SELECT `player`, `time` FROM `bans` WHERE `type` = 2") if resultId ~= false then local stmt = "INSERT INTO `player_namelocks` (`player_id`, `namelocked_at`, `namelocked_by`) VALUES " repeat stmt = stmt .. "(" .. result.getDataInt(resultId, "player") .. "," .. result.getDataInt(resultId, "time") .. "," .. result.getDataInt(resultId, "player") .. ")," until not result.next(resultId) result.free(resultId) local stmtLen = string.len(stmt) if stmtLen > 86 then stmt = string.sub(stmt, 1, stmtLen - 1) db.query(stmt) end end db.query("DROP TRIGGER `ondelete_accounts`") db.query("DROP TRIGGER `ondelete_players`") db.query("ALTER TABLE `accounts` DROP `warnings`") db.query("DROP TABLE `bans`") print("Run this query in your database to create the ondelete_players trigger:") print("DELIMITER //") print("CREATE TRIGGER `ondelete_players` BEFORE DELETE ON `players`") print(" FOR EACH ROW BEGIN") print(" UPDATE `houses` SET `owner` = 0 WHERE `owner` = OLD.`id`;") print("END //") return true end
gpl-2.0
Ninjistix/darkstar
scripts/globals/items/slice_of_diatryma_meat.lua
3
1199
----------------------------------------- -- ID: 5290 -- Item: Slice of Diatryma Meat -- Effect: 5 Minutes, food effect, Galka Only ----------------------------------------- -- Strength +3 -- Intelligence -5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 8) then result = 247; end if (target:getMod(MOD_EAT_RAW_MEAT) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5290); end; ----------------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 3); target:addMod(MOD_INT, -5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 3); target:delMod(MOD_INT, -5); end;
gpl-3.0
dragoonreas/Timeless-Answers
Locales/zhCN.lua
1
1468
--[[ Simplified Chinese localisation strings for Timeless Answers. Translation Credits: http://wow.curseforge.com/addons/timeless-answers/localization/translators/ Please update http://www.wowace.com/addons/timeless-answers/localization/zhCN/ for any translation additions or changes. Once reviewed, the translations will be automatically incorperated in the next build by the localization application. These translations are released under the Public Domain. ]]-- -- Get addon name local addon = ... -- Create the Simplified Chinese localisation table local L = LibStub("AceLocale-3.0"):NewLocale(addon, "zhCN", false) if not L then return; end -- Messages output to the user's chat frame --@localization(locale="zhCN", format="lua_additive_table", handle-unlocalized="english", same-key-is-true=true, namespace="Message2")@ -- Gossip from the NPC that's neither an answer nor a question --@localization(locale="zhCN", format="lua_additive_table", handle-unlocalized="english", same-key-is-true=true, namespace="Gossip")@ -- The complete gossip text from when the NPC asks the question --@localization(locale="zhCN", format="lua_additive_table", handle-unlocalized="english", same-key-is-true=true, namespace="Question2")@ -- The complete gossip option text of the correct answer from when the NPC asks the question --@localization(locale="zhCN", format="lua_additive_table", handle-unlocalized="english", same-key-is-true=true, namespace="Answer")@
gpl-3.0
Ninjistix/darkstar
scripts/globals/spells/bluemagic/exuviation.lua
7
1674
----------------------------------------- -- Spell: Exuviation -- Restores HP and removes one detrimental magic effect -- Spell cost: 40 MP -- Monster Type: Vermin -- Spell Type: Magical (Fire) -- Blue Magic Points: 4 -- Stat Bonus: HP+5 MP+5 CHR+1 -- Level: 75 -- Casting Time: 3 seconds -- Recast Time: 60 seconds -- -- Combos: Resist Sleep ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local minCure = 60; local effect = target:eraseStatusEffect(); local divisor = 0.6666; local constant = -45; local power = getCurePowerOld(caster); if (power > 459) then divisor = 1.5; constant = 144.6666; elseif (power > 219) then divisor = 2; constant = 65; end local final = getCureFinal(caster,spell,getBaseCureOld(power,divisor,constant),minCure,true); final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then --Applying server mods.... final = final * CURE_POWER; end local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:addHP(final); target:wakeUp(); caster:updateEnmityFromCure(target,final); spell:setMsg(msgBasic.MAGIC_RECOVERS_HP); return final; end;
gpl-3.0
dafei2015/hugular_cstolua
Client/Assets/uLua/Source/LuaJIT/dynasm/dasm_arm.lua
120
34598
------------------------------------------------------------------------------ -- DynASM ARM module. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ -- Module information: local _info = { arch = "arm", description = "DynASM ARM module", version = "1.3.0", vernum = 10300, release = "2011-05-05", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, setmetatable, rawget = assert, setmetatable, rawget local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local match, gmatch, gsub = _s.match, _s.gmatch, _s.gsub local concat, sort, insert = table.concat, table.sort, table.insert local bit = bit or require("bit") local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift local ror, tohex = bit.ror, bit.tohex -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { "STOP", "SECTION", "ESC", "REL_EXT", "ALIGN", "REL_LG", "LABEL_LG", "REL_PC", "LABEL_PC", "IMM", "IMM12", "IMM16", "IMML8", "IMML12", "IMMV8", } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number. local map_action = {} for n,name in ipairs(action_names) do map_action[name] = n-1 end -- Action list buffer. local actlist = {} -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 ------------------------------------------------------------------------------ -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist if nn == 0 then nn = 1; actlist[0] = map_action.STOP end out:write("static const unsigned int ", name, "[", nn, "] = {\n") for i = 1,nn-1 do assert(out:write("0x", tohex(actlist[i]), ",\n")) end assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n")) end ------------------------------------------------------------------------------ -- Add word to action list. local function wputxw(n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, val, a, num) local w = assert(map_action[action], "bad action name `"..action.."'") wputxw(w * 0x10000 + (val or 0)) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) if #actlist == actargs[1] then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true) actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped word. local function wputw(n) if n <= 0x000fffff then waction("ESC") end wputxw(n) end -- Reserve position for word. local function wpos() local pos = #actlist+1 actlist[pos] = "" return pos end -- Store word to reserved position. local function wputpos(pos, n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") if n <= 0x000fffff then insert(actlist, pos+1, n) n = map_action.ESC * 0x10000 end actlist[pos] = n end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 20 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end local n = next_global if n > 2047 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=20,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=20,next_global-1 do out:write(" ", prefix, t[i], ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=20,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = 0 local map_extern_ = {} local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n > 2047 then werror("too many extern labels") end next_extern = n + 1 t[name] = n map_extern_[n] = name return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) out:write("Extern labels:\n") for i=0,next_extern-1 do out:write(format(" %s\n", map_extern_[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) out:write("static const char *const ", name, "[] = {\n") for i=0,next_extern-1 do out:write(" \"", map_extern_[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. -- Ext. register name -> int. name. local map_archdef = { sp = "r13", lr = "r14", pc = "r15", } -- Int. register name -> ext. name. local map_reg_rev = { r13 = "sp", r14 = "lr", r15 = "pc", } local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for Dt... macros). -- Reverse defines for registers. function _M.revdef(s) return map_reg_rev[s] or s end local map_shift = { lsl = 0, lsr = 1, asr = 2, ror = 3, } local map_cond = { eq = 0, ne = 1, cs = 2, cc = 3, mi = 4, pl = 5, vs = 6, vc = 7, hi = 8, ls = 9, ge = 10, lt = 11, gt = 12, le = 13, al = 14, hs = 2, lo = 3, } ------------------------------------------------------------------------------ -- Template strings for ARM instructions. local map_op = { -- Basic data processing instructions. and_3 = "e0000000DNPs", eor_3 = "e0200000DNPs", sub_3 = "e0400000DNPs", rsb_3 = "e0600000DNPs", add_3 = "e0800000DNPs", adc_3 = "e0a00000DNPs", sbc_3 = "e0c00000DNPs", rsc_3 = "e0e00000DNPs", tst_2 = "e1100000NP", teq_2 = "e1300000NP", cmp_2 = "e1500000NP", cmn_2 = "e1700000NP", orr_3 = "e1800000DNPs", mov_2 = "e1a00000DPs", bic_3 = "e1c00000DNPs", mvn_2 = "e1e00000DPs", and_4 = "e0000000DNMps", eor_4 = "e0200000DNMps", sub_4 = "e0400000DNMps", rsb_4 = "e0600000DNMps", add_4 = "e0800000DNMps", adc_4 = "e0a00000DNMps", sbc_4 = "e0c00000DNMps", rsc_4 = "e0e00000DNMps", tst_3 = "e1100000NMp", teq_3 = "e1300000NMp", cmp_3 = "e1500000NMp", cmn_3 = "e1700000NMp", orr_4 = "e1800000DNMps", mov_3 = "e1a00000DMps", bic_4 = "e1c00000DNMps", mvn_3 = "e1e00000DMps", lsl_3 = "e1a00000DMws", lsr_3 = "e1a00020DMws", asr_3 = "e1a00040DMws", ror_3 = "e1a00060DMws", rrx_2 = "e1a00060DMs", -- Multiply and multiply-accumulate. mul_3 = "e0000090NMSs", mla_4 = "e0200090NMSDs", umaal_4 = "e0400090DNMSs", -- v6 mls_4 = "e0600090DNMSs", -- v6T2 umull_4 = "e0800090DNMSs", umlal_4 = "e0a00090DNMSs", smull_4 = "e0c00090DNMSs", smlal_4 = "e0e00090DNMSs", -- Halfword multiply and multiply-accumulate. smlabb_4 = "e1000080NMSD", -- v5TE smlatb_4 = "e10000a0NMSD", -- v5TE smlabt_4 = "e10000c0NMSD", -- v5TE smlatt_4 = "e10000e0NMSD", -- v5TE smlawb_4 = "e1200080NMSD", -- v5TE smulwb_3 = "e12000a0NMS", -- v5TE smlawt_4 = "e12000c0NMSD", -- v5TE smulwt_3 = "e12000e0NMS", -- v5TE smlalbb_4 = "e1400080NMSD", -- v5TE smlaltb_4 = "e14000a0NMSD", -- v5TE smlalbt_4 = "e14000c0NMSD", -- v5TE smlaltt_4 = "e14000e0NMSD", -- v5TE smulbb_3 = "e1600080NMS", -- v5TE smultb_3 = "e16000a0NMS", -- v5TE smulbt_3 = "e16000c0NMS", -- v5TE smultt_3 = "e16000e0NMS", -- v5TE -- Miscellaneous data processing instructions. clz_2 = "e16f0f10DM", -- v5T rev_2 = "e6bf0f30DM", -- v6 rev16_2 = "e6bf0fb0DM", -- v6 revsh_2 = "e6ff0fb0DM", -- v6 sel_3 = "e6800fb0DNM", -- v6 usad8_3 = "e780f010NMS", -- v6 usada8_4 = "e7800010NMSD", -- v6 rbit_2 = "e6ff0f30DM", -- v6T2 movw_2 = "e3000000DW", -- v6T2 movt_2 = "e3400000DW", -- v6T2 -- Note: the X encodes width-1, not width. sbfx_4 = "e7a00050DMvX", -- v6T2 ubfx_4 = "e7e00050DMvX", -- v6T2 -- Note: the X encodes the msb field, not the width. bfc_3 = "e7c0001fDvX", -- v6T2 bfi_4 = "e7c00010DMvX", -- v6T2 -- Packing and unpacking instructions. pkhbt_3 = "e6800010DNM", pkhbt_4 = "e6800010DNMv", -- v6 pkhtb_3 = "e6800050DNM", pkhtb_4 = "e6800050DNMv", -- v6 sxtab_3 = "e6a00070DNM", sxtab_4 = "e6a00070DNMv", -- v6 sxtab16_3 = "e6800070DNM", sxtab16_4 = "e6800070DNMv", -- v6 sxtah_3 = "e6b00070DNM", sxtah_4 = "e6b00070DNMv", -- v6 sxtb_2 = "e6af0070DM", sxtb_3 = "e6af0070DMv", -- v6 sxtb16_2 = "e68f0070DM", sxtb16_3 = "e68f0070DMv", -- v6 sxth_2 = "e6bf0070DM", sxth_3 = "e6bf0070DMv", -- v6 uxtab_3 = "e6e00070DNM", uxtab_4 = "e6e00070DNMv", -- v6 uxtab16_3 = "e6c00070DNM", uxtab16_4 = "e6c00070DNMv", -- v6 uxtah_3 = "e6f00070DNM", uxtah_4 = "e6f00070DNMv", -- v6 uxtb_2 = "e6ef0070DM", uxtb_3 = "e6ef0070DMv", -- v6 uxtb16_2 = "e6cf0070DM", uxtb16_3 = "e6cf0070DMv", -- v6 uxth_2 = "e6ff0070DM", uxth_3 = "e6ff0070DMv", -- v6 -- Saturating instructions. qadd_3 = "e1000050DMN", -- v5TE qsub_3 = "e1200050DMN", -- v5TE qdadd_3 = "e1400050DMN", -- v5TE qdsub_3 = "e1600050DMN", -- v5TE -- Note: the X for ssat* encodes sat_imm-1, not sat_imm. ssat_3 = "e6a00010DXM", ssat_4 = "e6a00010DXMp", -- v6 usat_3 = "e6e00010DXM", usat_4 = "e6e00010DXMp", -- v6 ssat16_3 = "e6a00f30DXM", -- v6 usat16_3 = "e6e00f30DXM", -- v6 -- Parallel addition and subtraction. sadd16_3 = "e6100f10DNM", -- v6 sasx_3 = "e6100f30DNM", -- v6 ssax_3 = "e6100f50DNM", -- v6 ssub16_3 = "e6100f70DNM", -- v6 sadd8_3 = "e6100f90DNM", -- v6 ssub8_3 = "e6100ff0DNM", -- v6 qadd16_3 = "e6200f10DNM", -- v6 qasx_3 = "e6200f30DNM", -- v6 qsax_3 = "e6200f50DNM", -- v6 qsub16_3 = "e6200f70DNM", -- v6 qadd8_3 = "e6200f90DNM", -- v6 qsub8_3 = "e6200ff0DNM", -- v6 shadd16_3 = "e6300f10DNM", -- v6 shasx_3 = "e6300f30DNM", -- v6 shsax_3 = "e6300f50DNM", -- v6 shsub16_3 = "e6300f70DNM", -- v6 shadd8_3 = "e6300f90DNM", -- v6 shsub8_3 = "e6300ff0DNM", -- v6 uadd16_3 = "e6500f10DNM", -- v6 uasx_3 = "e6500f30DNM", -- v6 usax_3 = "e6500f50DNM", -- v6 usub16_3 = "e6500f70DNM", -- v6 uadd8_3 = "e6500f90DNM", -- v6 usub8_3 = "e6500ff0DNM", -- v6 uqadd16_3 = "e6600f10DNM", -- v6 uqasx_3 = "e6600f30DNM", -- v6 uqsax_3 = "e6600f50DNM", -- v6 uqsub16_3 = "e6600f70DNM", -- v6 uqadd8_3 = "e6600f90DNM", -- v6 uqsub8_3 = "e6600ff0DNM", -- v6 uhadd16_3 = "e6700f10DNM", -- v6 uhasx_3 = "e6700f30DNM", -- v6 uhsax_3 = "e6700f50DNM", -- v6 uhsub16_3 = "e6700f70DNM", -- v6 uhadd8_3 = "e6700f90DNM", -- v6 uhsub8_3 = "e6700ff0DNM", -- v6 -- Load/store instructions. str_2 = "e4000000DL", str_3 = "e4000000DL", str_4 = "e4000000DL", strb_2 = "e4400000DL", strb_3 = "e4400000DL", strb_4 = "e4400000DL", ldr_2 = "e4100000DL", ldr_3 = "e4100000DL", ldr_4 = "e4100000DL", ldrb_2 = "e4500000DL", ldrb_3 = "e4500000DL", ldrb_4 = "e4500000DL", strh_2 = "e00000b0DL", strh_3 = "e00000b0DL", ldrh_2 = "e01000b0DL", ldrh_3 = "e01000b0DL", ldrd_2 = "e00000d0DL", ldrd_3 = "e00000d0DL", -- v5TE ldrsb_2 = "e01000d0DL", ldrsb_3 = "e01000d0DL", strd_2 = "e00000f0DL", strd_3 = "e00000f0DL", -- v5TE ldrsh_2 = "e01000f0DL", ldrsh_3 = "e01000f0DL", ldm_2 = "e8900000oR", ldmia_2 = "e8900000oR", ldmfd_2 = "e8900000oR", ldmda_2 = "e8100000oR", ldmfa_2 = "e8100000oR", ldmdb_2 = "e9100000oR", ldmea_2 = "e9100000oR", ldmib_2 = "e9900000oR", ldmed_2 = "e9900000oR", stm_2 = "e8800000oR", stmia_2 = "e8800000oR", stmfd_2 = "e8800000oR", stmda_2 = "e8000000oR", stmfa_2 = "e8000000oR", stmdb_2 = "e9000000oR", stmea_2 = "e9000000oR", stmib_2 = "e9800000oR", stmed_2 = "e9800000oR", pop_1 = "e8bd0000R", push_1 = "e92d0000R", -- Branch instructions. b_1 = "ea000000B", bl_1 = "eb000000B", blx_1 = "e12fff30C", bx_1 = "e12fff10M", -- Miscellaneous instructions. nop_0 = "e1a00000", mrs_1 = "e10f0000D", bkpt_1 = "e1200070K", -- v5T svc_1 = "ef000000T", swi_1 = "ef000000T", ud_0 = "e7f001f0", -- VFP instructions. ["vadd.f32_3"] = "ee300a00dnm", ["vadd.f64_3"] = "ee300b00Gdnm", ["vsub.f32_3"] = "ee300a40dnm", ["vsub.f64_3"] = "ee300b40Gdnm", ["vmul.f32_3"] = "ee200a00dnm", ["vmul.f64_3"] = "ee200b00Gdnm", ["vnmul.f32_3"] = "ee200a40dnm", ["vnmul.f64_3"] = "ee200b40Gdnm", ["vmla.f32_3"] = "ee000a00dnm", ["vmla.f64_3"] = "ee000b00Gdnm", ["vmls.f32_3"] = "ee000a40dnm", ["vmls.f64_3"] = "ee000b40Gdnm", ["vnmla.f32_3"] = "ee100a40dnm", ["vnmla.f64_3"] = "ee100b40Gdnm", ["vnmls.f32_3"] = "ee100a00dnm", ["vnmls.f64_3"] = "ee100b00Gdnm", ["vdiv.f32_3"] = "ee800a00dnm", ["vdiv.f64_3"] = "ee800b00Gdnm", ["vabs.f32_2"] = "eeb00ac0dm", ["vabs.f64_2"] = "eeb00bc0Gdm", ["vneg.f32_2"] = "eeb10a40dm", ["vneg.f64_2"] = "eeb10b40Gdm", ["vsqrt.f32_2"] = "eeb10ac0dm", ["vsqrt.f64_2"] = "eeb10bc0Gdm", ["vcmp.f32_2"] = "eeb40a40dm", ["vcmp.f64_2"] = "eeb40b40Gdm", ["vcmpe.f32_2"] = "eeb40ac0dm", ["vcmpe.f64_2"] = "eeb40bc0Gdm", ["vcmpz.f32_1"] = "eeb50a40d", ["vcmpz.f64_1"] = "eeb50b40Gd", ["vcmpze.f32_1"] = "eeb50ac0d", ["vcmpze.f64_1"] = "eeb50bc0Gd", vldr_2 = "ed100a00dl|ed100b00Gdl", vstr_2 = "ed000a00dl|ed000b00Gdl", vldm_2 = "ec900a00or", vldmia_2 = "ec900a00or", vldmdb_2 = "ed100a00or", vpop_1 = "ecbd0a00r", vstm_2 = "ec800a00or", vstmia_2 = "ec800a00or", vstmdb_2 = "ed000a00or", vpush_1 = "ed2d0a00r", ["vmov.f32_2"] = "eeb00a40dm|eeb00a00dY", -- #imm is VFPv3 only ["vmov.f64_2"] = "eeb00b40Gdm|eeb00b00GdY", -- #imm is VFPv3 only vmov_2 = "ee100a10Dn|ee000a10nD", vmov_3 = "ec500a10DNm|ec400a10mDN|ec500b10GDNm|ec400b10GmDN", vmrs_0 = "eef1fa10", vmrs_1 = "eef10a10D", vmsr_1 = "eee10a10D", ["vcvt.s32.f32_2"] = "eebd0ac0dm", ["vcvt.s32.f64_2"] = "eebd0bc0dGm", ["vcvt.u32.f32_2"] = "eebc0ac0dm", ["vcvt.u32.f64_2"] = "eebc0bc0dGm", ["vcvtr.s32.f32_2"] = "eebd0a40dm", ["vcvtr.s32.f64_2"] = "eebd0b40dGm", ["vcvtr.u32.f32_2"] = "eebc0a40dm", ["vcvtr.u32.f64_2"] = "eebc0b40dGm", ["vcvt.f32.s32_2"] = "eeb80ac0dm", ["vcvt.f64.s32_2"] = "eeb80bc0GdFm", ["vcvt.f32.u32_2"] = "eeb80a40dm", ["vcvt.f64.u32_2"] = "eeb80b40GdFm", ["vcvt.f32.f64_2"] = "eeb70bc0dGm", ["vcvt.f64.f32_2"] = "eeb70ac0GdFm", -- VFPv4 only: ["vfma.f32_3"] = "eea00a00dnm", ["vfma.f64_3"] = "eea00b00Gdnm", ["vfms.f32_3"] = "eea00a40dnm", ["vfms.f64_3"] = "eea00b40Gdnm", ["vfnma.f32_3"] = "ee900a40dnm", ["vfnma.f64_3"] = "ee900b40Gdnm", ["vfnms.f32_3"] = "ee900a00dnm", ["vfnms.f64_3"] = "ee900b00Gdnm", -- NYI: Advanced SIMD instructions. -- NYI: I have no need for these instructions right now: -- swp, swpb, strex, ldrex, strexd, ldrexd, strexb, ldrexb, strexh, ldrexh -- msr, nopv6, yield, wfe, wfi, sev, dbg, bxj, smc, srs, rfe -- cps, setend, pli, pld, pldw, clrex, dsb, dmb, isb -- stc, ldc, mcr, mcr2, mrc, mrc2, mcrr, mcrr2, mrrc, mrrc2, cdp, cdp2 } -- Add mnemonics for "s" variants. do local t = {} for k,v in pairs(map_op) do if sub(v, -1) == "s" then local v2 = sub(v, 1, 2)..char(byte(v, 3)+1)..sub(v, 4, -2) t[sub(k, 1, -3).."s"..sub(k, -2)] = v2 end end for k,v in pairs(t) do map_op[k] = v end end ------------------------------------------------------------------------------ local function parse_gpr(expr) local tname, ovreg = match(expr, "^([%w_]+):(r1?[0-9])$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg if not reg then werror("type `"..(tname or expr).."' needs a register override") end expr = reg end local r = match(expr, "^r(1?[0-9])$") if r then r = tonumber(r) if r <= 15 then return r, tp end end werror("bad register name `"..expr.."'") end local function parse_gpr_pm(expr) local pm, expr2 = match(expr, "^([+-]?)(.*)$") return parse_gpr(expr2), (pm == "-") end local function parse_vr(expr, tp) local t, r = match(expr, "^([sd])([0-9]+)$") if t == tp then r = tonumber(r) if r <= 31 then if t == "s" then return shr(r, 1), band(r, 1) end return band(r, 15), shr(r, 4) end end werror("bad register name `"..expr.."'") end local function parse_reglist(reglist) reglist = match(reglist, "^{%s*([^}]*)}$") if not reglist then werror("register list expected") end local rr = 0 for p in gmatch(reglist..",", "%s*([^,]*),") do local rbit = shl(1, parse_gpr(gsub(p, "%s+$", ""))) if band(rr, rbit) ~= 0 then werror("duplicate register `"..p.."'") end rr = rr + rbit end return rr end local function parse_vrlist(reglist) local ta, ra, tb, rb = match(reglist, "^{%s*([sd])([0-9]+)%s*%-%s*([sd])([0-9]+)%s*}$") ra, rb = tonumber(ra), tonumber(rb) if ta and ta == tb and ra and rb and ra <= 31 and rb <= 31 and ra <= rb then local nr = rb+1 - ra if ta == "s" then return shl(shr(ra,1),12)+shl(band(ra,1),22) + nr else return shl(band(ra,15),12)+shl(shr(ra,4),22) + nr*2 + 0x100 end end werror("register list expected") end local function parse_imm(imm, bits, shift, scale, signed) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = tonumber(imm) if n then local m = sar(n, scale) if shl(m, scale) == n then if signed then local s = sar(m, bits-1) if s == 0 then return shl(m, shift) elseif s == -1 then return shl(m + shl(1, bits), shift) end else if sar(m, bits) == 0 then return shl(m, shift) end end end werror("out of range immediate `"..imm.."'") else waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm) return 0 end end local function parse_imm12(imm) local n = tonumber(imm) if n then local m = band(n) for i=0,-15,-1 do if shr(m, 8) == 0 then return m + shl(band(i, 15), 8) end m = ror(m, 2) end werror("out of range immediate `"..imm.."'") else waction("IMM12", 0, imm) return 0 end end local function parse_imm16(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = tonumber(imm) if n then if shr(n, 16) == 0 then return band(n, 0x0fff) + shl(band(n, 0xf000), 4) end werror("out of range immediate `"..imm.."'") else waction("IMM16", 32*16, imm) return 0 end end local function parse_imm_load(imm, ext) local n = tonumber(imm) if n then if ext then if n >= -255 and n <= 255 then local up = 0x00800000 if n < 0 then n = -n; up = 0 end return shl(band(n, 0xf0), 4) + band(n, 0x0f) + up end else if n >= -4095 and n <= 4095 then if n >= 0 then return n+0x00800000 end return -n end end werror("out of range immediate `"..imm.."'") else waction(ext and "IMML8" or "IMML12", 32768 + shl(ext and 8 or 12, 5), imm) return 0 end end local function parse_shift(shift, gprok) if shift == "rrx" then return 3 * 32 else local s, s2 = match(shift, "^(%S+)%s*(.*)$") s = map_shift[s] if not s then werror("expected shift operand") end if sub(s2, 1, 1) == "#" then return parse_imm(s2, 5, 7, 0, false) + shl(s, 5) else if not gprok then werror("expected immediate shift operand") end return shl(parse_gpr(s2), 8) + shl(s, 5) + 16 end end end local function parse_label(label, def) local prefix = sub(label, 1, 2) -- =>label (pc label reference) if prefix == "=>" then return "PC", 0, sub(label, 3) end -- ->name (global label reference) if prefix == "->" then return "LG", map_global[sub(label, 3)] end if def then -- [1-9] (local label definition) if match(label, "^[1-9]$") then return "LG", 10+tonumber(label) end else -- [<>][1-9] (local label reference) local dir, lnum = match(label, "^([<>])([1-9])$") if dir then -- Fwd: 1-9, Bkwd: 11-19. return "LG", lnum + (dir == ">" and 0 or 10) end -- extern label (extern label reference) local extname = match(label, "^extern%s+(%S+)$") if extname then return "EXT", map_extern[extname] end end werror("bad label `"..label.."'") end local function parse_load(params, nparams, n, op) local oplo = band(op, 255) local ext, ldrd = (oplo ~= 0), (oplo == 208) local d if (ldrd or oplo == 240) then d = band(shr(op, 12), 15) if band(d, 1) ~= 0 then werror("odd destination register") end end local pn = params[n] local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$") local p2 = params[n+1] if not p1 then if not p2 then if match(pn, "^[<>=%-]") or match(pn, "^extern%s+") then local mode, n, s = parse_label(pn, false) waction("REL_"..mode, n + (ext and 0x1800 or 0x0800), s, 1) return op + 15 * 65536 + 0x01000000 + (ext and 0x00400000 or 0) end local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local d, tp = parse_gpr(reg) if tp then waction(ext and "IMML8" or "IMML12", 32768 + 32*(ext and 8 or 12), format(tp.ctypefmt, tailr)) return op + shl(d, 16) + 0x01000000 + (ext and 0x00400000 or 0) end end end werror("expected address operand") end if wb == "!" then op = op + 0x00200000 end if p2 then if wb == "!" then werror("bad use of '!'") end local p3 = params[n+2] op = op + shl(parse_gpr(p1), 16) local imm = match(p2, "^#(.*)$") if imm then local m = parse_imm_load(imm, ext) if p3 then werror("too many parameters") end op = op + m + (ext and 0x00400000 or 0) else local m, neg = parse_gpr_pm(p2) if ldrd and (m == d or m-1 == d) then werror("register conflict") end op = op + m + (neg and 0 or 0x00800000) + (ext and 0 or 0x02000000) if p3 then op = op + parse_shift(p3) end end else local p1a, p2 = match(p1, "^([^,%s]*)%s*(.*)$") op = op + shl(parse_gpr(p1a), 16) + 0x01000000 if p2 ~= "" then local imm = match(p2, "^,%s*#(.*)$") if imm then local m = parse_imm_load(imm, ext) op = op + m + (ext and 0x00400000 or 0) else local p2a, p3 = match(p2, "^,%s*([^,%s]*)%s*,?%s*(.*)$") local m, neg = parse_gpr_pm(p2a) if ldrd and (m == d or m-1 == d) then werror("register conflict") end op = op + m + (neg and 0 or 0x00800000) + (ext and 0 or 0x02000000) if p3 ~= "" then if ext then werror("too many parameters") end op = op + parse_shift(p3) end end else if wb == "!" then werror("bad use of '!'") end op = op + (ext and 0x00c00000 or 0x00800000) end end return op end local function parse_vload(q) local reg, imm = match(q, "^%[%s*([^,%s]*)%s*(.*)%]$") if reg then local d = shl(parse_gpr(reg), 16) if imm == "" then return d end imm = match(imm, "^,%s*#(.*)$") if imm then local n = tonumber(imm) if n then if n >= -1020 and n <= 1020 and n%4 == 0 then return d + (n >= 0 and n/4+0x00800000 or -n/4) end werror("out of range immediate `"..imm.."'") else waction("IMMV8", 32768 + 32*8, imm) return d end end else if match(q, "^[<>=%-]") or match(q, "^extern%s+") then local mode, n, s = parse_label(q, false) waction("REL_"..mode, n + 0x2800, s, 1) return 15 * 65536 end local reg, tailr = match(q, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local d, tp = parse_gpr(reg) if tp then waction("IMMV8", 32768 + 32*8, format(tp.ctypefmt, tailr)) return shl(d, 16) end end end werror("expected address operand") end ------------------------------------------------------------------------------ -- Handle opcodes defined with template strings. local function parse_template(params, template, nparams, pos) local op = tonumber(sub(template, 1, 8), 16) local n = 1 local vr = "s" -- Process each character. for p in gmatch(sub(template, 9), ".") do local q = params[n] if p == "D" then op = op + shl(parse_gpr(q), 12); n = n + 1 elseif p == "N" then op = op + shl(parse_gpr(q), 16); n = n + 1 elseif p == "S" then op = op + shl(parse_gpr(q), 8); n = n + 1 elseif p == "M" then op = op + parse_gpr(q); n = n + 1 elseif p == "d" then local r,h = parse_vr(q, vr); op = op+shl(r,12)+shl(h,22); n = n + 1 elseif p == "n" then local r,h = parse_vr(q, vr); op = op+shl(r,16)+shl(h,7); n = n + 1 elseif p == "m" then local r,h = parse_vr(q, vr); op = op+r+shl(h,5); n = n + 1 elseif p == "P" then local imm = match(q, "^#(.*)$") if imm then op = op + parse_imm12(imm) + 0x02000000 else op = op + parse_gpr(q) end n = n + 1 elseif p == "p" then op = op + parse_shift(q, true); n = n + 1 elseif p == "L" then op = parse_load(params, nparams, n, op) elseif p == "l" then op = op + parse_vload(q) elseif p == "B" then local mode, n, s = parse_label(q, false) waction("REL_"..mode, n, s, 1) elseif p == "C" then -- blx gpr vs. blx label. if match(q, "^([%w_]+):(r1?[0-9])$") or match(q, "^r(1?[0-9])$") then op = op + parse_gpr(q) else if op < 0xe0000000 then werror("unconditional instruction") end local mode, n, s = parse_label(q, false) waction("REL_"..mode, n, s, 1) op = 0xfa000000 end elseif p == "F" then vr = "s" elseif p == "G" then vr = "d" elseif p == "o" then local r, wb = match(q, "^([^!]*)(!?)$") op = op + shl(parse_gpr(r), 16) + (wb == "!" and 0x00200000 or 0) n = n + 1 elseif p == "R" then op = op + parse_reglist(q); n = n + 1 elseif p == "r" then op = op + parse_vrlist(q); n = n + 1 elseif p == "W" then op = op + parse_imm16(q); n = n + 1 elseif p == "v" then op = op + parse_imm(q, 5, 7, 0, false); n = n + 1 elseif p == "w" then local imm = match(q, "^#(.*)$") if imm then op = op + parse_imm(q, 5, 7, 0, false); n = n + 1 else op = op + shl(parse_gpr(q), 8) + 16 end elseif p == "X" then op = op + parse_imm(q, 5, 16, 0, false); n = n + 1 elseif p == "Y" then local imm = tonumber(match(q, "^#(.*)$")); n = n + 1 if not imm or shr(imm, 8) ~= 0 then werror("bad immediate operand") end op = op + shl(band(imm, 0xf0), 12) + band(imm, 0x0f) elseif p == "K" then local imm = tonumber(match(q, "^#(.*)$")); n = n + 1 if not imm or shr(imm, 16) ~= 0 then werror("bad immediate operand") end op = op + shl(band(imm, 0xfff0), 4) + band(imm, 0x000f) elseif p == "T" then op = op + parse_imm(q, 24, 0, 0, false); n = n + 1 elseif p == "s" then -- Ignored. else assert(false) end end wputpos(pos, op) end map_op[".template__"] = function(params, template, nparams) if not params then return template:gsub("%x%x%x%x%x%x%x%x", "") end -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 3 positions. if secpos+3 > maxsecpos then wflush() end local pos = wpos() local lpos, apos, spos = #actlist, #actargs, secpos local ok, err for t in gmatch(template, "[^|]+") do ok, err = pcall(parse_template, params, t, nparams, pos) if ok then return end secpos = spos actlist[lpos+1] = nil actlist[lpos+2] = nil actlist[lpos+3] = nil actargs[apos+1] = nil actargs[apos+2] = nil actargs[apos+3] = nil end error(err, 0) end ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_1"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr" end if secpos+1 > maxsecpos then wflush() end local mode, n, s = parse_label(params[1], true) if mode == "EXT" then werror("bad label definition") end waction("LABEL_"..mode, n, s, 1) end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. map_op[".long_*"] = function(params) if not params then return "imm..." end for _,p in ipairs(params) do local n = tonumber(p) if not n then werror("bad immediate `"..p.."'") end if n < 0 then n = n + 2^32 end wputw(n) if secpos+2 > maxsecpos then wflush() end end end -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION", num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = function(t, k) local v = map_coreop[k] if v then return v end local k1, cc, k2 = match(k, "^(.-)(..)([._].*)$") local cv = map_cond[cc] if cv then local v = rawget(t, k1..k2) if type(v) == "string" then local scv = format("%x", cv) return gsub(scv..sub(v, 2), "|e", "|"..scv) end end end }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
mit
Ninjistix/darkstar
scripts/globals/mobskills/sable_breath.lua
35
1160
--------------------------------------------- -- Sable Breath -- -- Description: Deals darkness damage to enemies within a fan-shaped area. -- Type: Breath -- Utsusemi/Blink absorb: Ignores shadows -- Range: Unknown cone -- Notes: Used only by Vrtra and Azdaja --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/utils"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (target:isBehind(mob, 48) == true) then return 1; elseif (mob:AnimationSub() ~= 0) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local dmgmod = MobBreathMove(mob, target, 0.2, 1.25, ELE_DARK, 1400); local angle = mob:getAngle(target); angle = mob:getRotPos() - angle; dmgmod = dmgmod * ((128-math.abs(angle))/128); dmgmod = utils.clamp(dmgmod, 50, 1600); local dmg = MobFinalAdjustments(dmgmod,mob,skill,target,MOBSKILL_BREATH,MOBPARAM_DARK,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
chroteus/clay
states/fighterScr.lua
1
1482
-- not to be confused with "fightersScr", which is plural "fighters" fighterScr = {} function fighterScr.set(fighter) fighterScr.fighter = fighter end function fighterScr:enter() if fighterScr.fighter == nil then error("Set fighter to display with fighterScr.set") end end function fighterScr:update(dt) local fighter = fighterScr.fighter fighter.anim[fighter.anim_state]:update(dt) screenBtn:update(dt) end function fighterScr:draw() screenBtn:draw() love.graphics.setColor(20,20,20,128) love.graphics.rectangle("fill", 0,0,the.screen.width,the.screen.height) love.graphics.setColor(255,255,255) local fighter = fighterScr.fighter fighter:draw() love.graphics.setFont(gameFont[20]) love.graphics.printf("ATT: " .. fighter.attack_stat, fighter.x-5, fighter.y +fighter.height + 15, fighter.width, "center") love.graphics.printf("DEF: " .. fighter.defense, fighter.x-5, fighter.y + fighter.height + 35, fighter.width, "center") love.graphics.setFont(gameFont["default"]) end function fighterScr:mousereleased(x,y,btn) if btn == "l" and y < screenBtn.list[1].y then Gamestate.switch(fightersScr, "none") end screenBtn:mousereleased(x,y,btn) end function fighterScr:keyreleased(key) if key == "tab" or key == "escape" then Gamestate.switch(fightersScr, "none") end end
gpl-2.0
Ninjistix/darkstar
scripts/zones/Port_San_dOria/npcs/Albinie.lua
5
1113
----------------------------------- -- Area: Port San d'Oria -- NPC: Albinie -- Standard Merchant NPC -- Working 100% ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) player:showText(npc,ALBINIE_SHOP_DIALOG); stock = { 0x02bb,5688,1, --Oak Log 0x0284,1800,1, --Mythril Ore 0x0343,225,1, --Flax Flower 0x02b6,2543,2, --Chestnut Log 0x0280,10,2, --Copper Ore 0x0283,810,2, --Iron Ore 0x0341,18,2, --Moko Grass 0x11da,50,2, --Bird Egg 0x02ba,86,3, --Ash Log 0x0001,1800,3 --Chocobo Bedding } showNationShop(player, NATION_SANDORIA, stock); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/weaponskills/mistral_axe.lua
25
1597
----------------------------------- -- Mistral Axe -- Axe weapon skill -- Skill level: 225 (Beastmasters and Warriors only.) -- Delivers a single-hit ranged attack at a maximum distance of 15.7'. Damage varies with TP. -- Despite being able to be used from a distance it is considered a melee attack and can be stacked with Sneak Attack and/or Trick Attack -- Aligned with the Flame Gorget & Light Gorget. -- Aligned with the Flame Belt & Light Belt. -- Element: None -- Modifiers: STR:50% -- 100%TP 200%TP 300%TP -- 2.50 3.00 3.50 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 2.5; params.ftp200 = 3; params.ftp300 = 3.5; params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 4; params.ftp200 = 10.5; params.ftp300 = 13.625; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
DEVll190ll/DEV_HR
libs/dkjson.lua
3282
26558
-- Module options: local always_try_using_lpeg = true local register_global_module_table = false local global_module_name = 'json' --[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.4* In the default configuration this module writes no global values, not even the module table. Import it using json = require ("dkjson") In environments where `require` or a similiar function are not available and you cannot receive the return value of the module, you can set the option `register_global_module_table` to `true`. The module table will then be saved in the global variable with the name given by the option `global_module_name`. Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) To prevent the assigning of metatables pass `nil`: json.decode (string, position, null, nil) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This value is only checked for empty tables. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.4"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the `decode` function. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable the option `always_try_using_lpeg` in the options section at the top of the module. In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. --------------------------------------------------------------------- Contact ------- You can contact the author by sending an e-mail to 'david' at the domain 'dkolf.de'. --------------------------------------------------------------------- *Copyright (C) 2010-2013 David Heiko Kolf* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall, select = error, require, pcall, select local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local strmatch = string.match local concat = table.concat local json = { version = "dkjson 2.4" } if register_global_module_table then _G[global_module_name] = json end local _ENV = nil -- blocking globals in Lua 5.2 pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176-\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function replace(str, o, n) local i, j = strfind (str, o, 1, true) if i then return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1) else return str end end -- locale independent num2str and str2num functions local decpoint, numfilter local function updatedecpoint () decpoint = strmatch(tostring(0.5), "([^05+])") -- build a filter that can be used to remove group separators numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+" end updatedecpoint() local function num2str (num) return replace(fsub(tostring(num), numfilter, ""), decpoint, ".") end local function str2num (str) local num = tonumber(replace(str, ".", decpoint)) if not num then updatedecpoint() num = tonumber(replace(str, ".", decpoint)) end return num end local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = num2str (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local isa, n = isarray (value) if n == 0 and valmeta and valmeta.__jsontype == 'object' then isa = false end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} updatedecpoint() local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 0 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = str2num (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end local function optionalmetatables(...) if select("#", ...) > 0 then return ... else return {__jsontype = 'object'}, {__jsontype = 'array'} end end function json.decode (str, pos, nullval, ...) local objectmeta, arraymeta = optionalmetatables(...) return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") if g.version() == "0.11" then error "due to a bug in LPeg 0.11, it cannot be used for JSON matching" end local pegmatch = g.match local P, S, R = g.P, g.S, g.R local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, ...) local state = {} state.objectmeta, state.arraymeta = optionalmetatables(...) local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
gpl-2.0
ASHRAF97/ASHRAFKASPER
plugins/banhammer.lua
8
14076
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY MOHAMMED HISHAM ▀▄ ▄▀ ▀▄ ▄▀ BY MOHAMMEDHISHAM (@TH3BOSS) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY MOHAMMED HISHA ▀▄ ▄▀ ▀▄ ▄▀ ban hammer : الطرد والحظر ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] local function pre_process(msg) local data = load_data(_config.moderation.data) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned and not is_momod2(msg.from.id, msg.to.id) or is_gbanned(user_id) and not is_admin2(msg.from.id) then -- Check it with redis print('User is banned!') local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) >= 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) >= 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' or msg.to.type == 'channel' then local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) local chat_id = extra.chat_id local chat_type = extra.chat_type if chat_type == "chat" then receiver = 'chat#id'..chat_id else receiver = 'channel#id'..chat_id end if success == 0 then return send_large_msg(receiver, "Cannot find user by that username!") end local member_id = result.peer_id local user_id = member_id local member = result.username local from_id = extra.from_id local get_cmd = extra.get_cmd if get_cmd == "دي" then if member_id == from_id then send_large_msg(receiver, "لا تستطيع طرد نفسك ❌") return end if is_momod2(member_id, chat_id) and not is_admin2(sender) then send_large_msg(receiver, "لا تستطيع طرد او طرد الادمنيه او المدراء ❌ ") return end kick_user(member_id, chat_id) elseif get_cmd == 'حظر' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then send_large_msg(receiver, "لا تسطيع حضر الادمنية او المدراء ❌") return end send_large_msg(receiver, 'العضو @'..member..' ['..member_id..'] ☑️ تم حضره') ban_user(member_id, chat_id) elseif get_cmd == 'الغاء الحظر' then send_large_msg(receiver, 'العضو @'..member..' ['..member_id..'] ☑️ راح الحضر منة') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'العضو '..user_id..' ☑️ راح الحضر منة' elseif get_cmd == 'حظر عام' then send_large_msg(receiver, 'العضو @'..member..' ['..member_id..'] ☑️ تم حضره عام ') banall_user(member_id) elseif get_cmd == 'الغاء العام' then send_large_msg(receiver, 'العضو @'..member..' ['..member_id..'] ☑️ راح العام منة') unbanall_user(member_id) end end local function run(msg, matches) local support_id = msg.from.id if matches[1]:lower() == 'ايدي' and msg.to.type == "chat" or msg.to.type == "user" then if msg.to.type == "user" then return " 🆔 ايدي البوت▫️: "..msg.to.id.. "\n\n 🆔 ايدي حسابك▫️: "..msg.from.id.. "\n مـطـور الـسـورس\n الــــزعـــيـــــم > @TH3BOSS " end if type(msg.reply_id) ~= "nil" then local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'ايدي' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "ايدي المجموعه" ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'مغادره' and msg.to.type == "chat" then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "قائمه المحظورين" then --🚩قـائـمـه الـمـحـظـوريـن🚩 local chat_id = msg.to.id if matches[2] and is_admin1(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'حظر' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin1(msg) then msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id elseif string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then return "❌ لا تستطيع حظر الادمنية او المدراء" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "❌ لا تستطيع حظر نفسك" end local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") local receiver = get_receiver(msg) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(matches[2], msg.to.id) send_large_msg(receiver, 'العضو ['..matches[2]..'] ☑️ تم حضره') else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'حظر', from_id = msg.from.id, chat_type = msg.to.type } local username = string.gsub(matches[2], '@', '') resolve_username(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'الغاء الحظر' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'العضو '..user_id..' ☑️ راح الحضر منه' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'الغاء الحظر', from_id = msg.from.id, chat_type = msg.to.type } local username = string.gsub(matches[2], '@', '') resolve_username(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'دي' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin1(msg) then msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end elseif string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then return "❌ لا تستطيع طرد الادمنية او المدراء" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "❌ لا تستطيع طرد نفسك" end local user_id = matches[2] local chat_id = msg.to.id print("sexy") local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'دي', from_id = msg.from.id, chat_type = msg.to.type } local username = string.gsub(matches[2], '@', '') resolve_username(username, kick_ban_res, cbres_extra) end end if not is_admin1(msg) and not is_support(support_id) then return end if matches[1]:lower() == 'حظر عام' and is_admin1(msg) then -- Global ban if type(msg.reply_id) ~="nil" and is_admin1(msg) then banall = get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'العضو ['..user_id..' ] ☑️ تم حضره عام' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'حظر عام', from_id = msg.from.id, chat_type = msg.to.type } local username = string.gsub(matches[2], '@', '') resolve_username(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'الغاء العام' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'العضو ['..user_id..' ] ☑️ راح العام منه' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'الغاء العام', from_id = msg.from.id, chat_type = msg.to.type } local username = string.gsub(matches[2], '@', '') resolve_username(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "قائمه العام" then --🚩قـائـمـه الـمـحـظـوريـن ـعـام🚩 return banall_list() end end return { patterns = { "^(حظر عام) (.*)$", "^(حظر عام)$", "^(قائمه المحظورين) (.*)$", "^(قائمه المحظورين)$", "^(قائمه العام)$", "^(مغادره)", "^(دي)$", "^(حظر)$", "^(حظر) (.*)$", "^(الغاء الحظر) (.*)$", "^(الغاء العام) (.*)$", "^(الغاء العام)$", "^(دي) (.*)$", "^(الغاء الحظر)$", "^(ايدي)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
anonbyte/pvpgn
lua/handle_command.lua
1
1976
--[[ Copyright (C) 2014 HarpyWar (harpywar@gmail.com) This file is a part of the PvPGN Project http://pvpgn.pro Licensed under the same terms as Lua itself. ]]-- -- List of available lua commands -- (To create a new command - create a new file in directory "commands") local lua_command_table = { [1] = { ["/w3motd"] = command_w3motd, -- Quiz ["/quiz"] = command_quiz, }, [8] = { ["/redirect"] = command_redirect, }, } -- Global function to handle commands -- ("return 1" from a command will break next C++ code execution) function handle_command(account, text) -- find command in table for cg,cmdlist in pairs(lua_command_table) do for cmd,func in pairs(cmdlist) do if string.starts(text, cmd) then -- check if command group is in account.commandgroups if not math_and(account.commandgroups, cg) then api.message_send_text(account.name, message_type_error, account.name, "This command is reserved for admins.") return 1 end -- FIXME: we can use _G[func] if func is a text but not a function, -- like ["/dotastats"] = "command_dotastats" -- and function command_dotastats can be defined below, not only before return func(account, text) end end end return 0 end -- Split command to arguments, -- index 0 is always a command name without a slash -- return table with arguments function split_command(text, args_count) local count = args_count local result = {} local tmp = "" -- remove slash from the command if not string:empty(text) then text = string.sub(text, 2) end i = 0 -- split by space for token in string.split(text) do if not string:empty(token) then if (i < count) then result[i] = token i = i + 1 else if not string:empty(tmp) then tmp = tmp .. " " end tmp = tmp .. token end end end -- push remaining text at the end if not string:empty(tmp) then result[count] = tmp end return result end
gpl-2.0
Ninjistix/darkstar
scripts/zones/Windurst_Waters/Zone.lua
5
2806
----------------------------------- -- -- Zone: Windurst_Waters (238) -- ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Waters/TextIDs"); require("scripts/globals/events/harvest_festivals"); require("scripts/globals/missions"); require("scripts/globals/settings"); require("scripts/globals/zone"); ----------------------------------- function onInitialize(zone) -- Check if we are on Windurst Mission 1-3 zone:registerRegion(1, 23,-12,-208, 31,-8,-197); applyHalloweenNpcCostumes(zone:getID()) end; function onZoneIn(player,prevZone) local cs = -1; -- FIRST LOGIN (START CS) if (player:getPlaytime(false) == 0) then if (OPENING_CUTSCENE_ENABLE == 1) then cs = 531; end player:setPos(-40,-5,80,64); player:setHomePoint(); end -- MOG HOUSE EXIT if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then position = math.random(1,5) + 157; player:setPos(position,-5,-62,192); if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then cs = 30004; end player:setVar("PlayerMainJob",0); end if (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("MEMORIES_OF_A_MAIDEN_Status") == 1) then -- COP MEMORIES_OF_A_MAIDEN--3-3B: Windurst Route player:setVar("MEMORIES_OF_A_MAIDEN_Status",2); cs = 871; end return cs; end; function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; function onRegionEnter(player,region) switch (region:GetRegionID()): caseof { [1] = function (x) -- Windurst Mission 1-3, final cutscene with Leepe-Hoppe -- If we're on Windurst Mission 1-3 if (player:getCurrentMission(WINDURST) == THE_PRICE_OF_PEACE and player:getVar("MissionStatus") == 2) then player:startEvent(146); end end, } end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 531) then player:messageSpecial(ITEM_OBTAINED, 536); elseif (csid == 30004 and option == 0) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); elseif (csid == 146) then -- Returned from Giddeus, Windurst 1-3 player:setVar("MissionStatus", 3); player:setVar("ghoo_talk", 0); player:setVar("laa_talk", 0); end end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/items/slice_of_karakul_meat.lua
3
1198
----------------------------------------- -- ID: 5571 -- Item: Slice of Karakul Meat -- Effect: 5 Minutes, food effect, Galka Only ----------------------------------------- -- Strength +2 -- Intelligence -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 8) then result = 247; end if (target:getMod(MOD_EAT_RAW_MEAT) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5571); end; ----------------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 2); target:addMod(MOD_INT, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 2); target:delMod(MOD_INT, -4); end;
gpl-3.0
wounds1/zaza2
libs/dkjson.lua
3282
26558
-- Module options: local always_try_using_lpeg = true local register_global_module_table = false local global_module_name = 'json' --[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.4* In the default configuration this module writes no global values, not even the module table. Import it using json = require ("dkjson") In environments where `require` or a similiar function are not available and you cannot receive the return value of the module, you can set the option `register_global_module_table` to `true`. The module table will then be saved in the global variable with the name given by the option `global_module_name`. Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) To prevent the assigning of metatables pass `nil`: json.decode (string, position, null, nil) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This value is only checked for empty tables. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.4"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the `decode` function. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable the option `always_try_using_lpeg` in the options section at the top of the module. In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. --------------------------------------------------------------------- Contact ------- You can contact the author by sending an e-mail to 'david' at the domain 'dkolf.de'. --------------------------------------------------------------------- *Copyright (C) 2010-2013 David Heiko Kolf* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall, select = error, require, pcall, select local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local strmatch = string.match local concat = table.concat local json = { version = "dkjson 2.4" } if register_global_module_table then _G[global_module_name] = json end local _ENV = nil -- blocking globals in Lua 5.2 pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176-\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function replace(str, o, n) local i, j = strfind (str, o, 1, true) if i then return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1) else return str end end -- locale independent num2str and str2num functions local decpoint, numfilter local function updatedecpoint () decpoint = strmatch(tostring(0.5), "([^05+])") -- build a filter that can be used to remove group separators numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+" end updatedecpoint() local function num2str (num) return replace(fsub(tostring(num), numfilter, ""), decpoint, ".") end local function str2num (str) local num = tonumber(replace(str, ".", decpoint)) if not num then updatedecpoint() num = tonumber(replace(str, ".", decpoint)) end return num end local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = num2str (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local isa, n = isarray (value) if n == 0 and valmeta and valmeta.__jsontype == 'object' then isa = false end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} updatedecpoint() local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 0 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = str2num (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end local function optionalmetatables(...) if select("#", ...) > 0 then return ... else return {__jsontype = 'object'}, {__jsontype = 'array'} end end function json.decode (str, pos, nullval, ...) local objectmeta, arraymeta = optionalmetatables(...) return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") if g.version() == "0.11" then error "due to a bug in LPeg 0.11, it cannot be used for JSON matching" end local pegmatch = g.match local P, S, R = g.P, g.S, g.R local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, ...) local state = {} state.objectmeta, state.arraymeta = optionalmetatables(...) local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
gpl-2.0
Ninjistix/darkstar
scripts/globals/items/bowl_of_zoni_broth.lua
3
1828
----------------------------------------- -- ID: 5618 -- Item: bowl_of_zoni_broth -- Food Effect: 3Hrs, All Races ----------------------------------------- -- HP 10 -- MP 10 -- Strength 1 -- Dexterity 1 -- Vitality 1 -- Agility 1 -- Accuracy +1 -- Ranged Accuracy +1 -- Attack +1 -- Ranged Attack +1 -- Evasion +1 -- HP Recovered While Healing 1 -- MP Recovered While Healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5618); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_MP, 10); target:addMod(MOD_STR, 1); target:addMod(MOD_DEX, 1); target:addMod(MOD_VIT, 1); target:addMod(MOD_AGI, 1); target:addMod(MOD_ACC, 1); target:addMod(MOD_RACC, 1); target:addMod(MOD_ATT, 1); target:addMod(MOD_RATT, 1); target:addMod(MOD_EVA, 1); target:addMod(MOD_HPHEAL, 1); target:addMod(MOD_MPHEAL, 1); end; function onEffectLose(target, effect) target:delMod(MOD_HP, 10); target:delMod(MOD_MP, 10); target:delMod(MOD_STR, 1); target:delMod(MOD_DEX, 1); target:delMod(MOD_VIT, 1); target:delMod(MOD_AGI, 1); target:delMod(MOD_ACC, 1); target:delMod(MOD_RACC, 1); target:delMod(MOD_ATT, 1); target:delMod(MOD_RATT, 1); target:delMod(MOD_EVA, 1); target:delMod(MOD_HPHEAL, 1); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Sacrarium/npcs/Treasure_Chest.lua
5
2566
----------------------------------- -- Area: Sacrarium -- NPC: Treasure Chest -- @zone 28 ----------------------------------- package.loaded["scripts/zones/Sacrarium/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/treasure"); require("scripts/zones/Sacrarium/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 53; local TreasureMinLvL = 43; function onTrade(player,npc,trade) -- trade:hasItemQty(1061,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1061,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end UpdateTreasureSpawnPoint(npc:getID()); end end end end; function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1061); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Western_Adoulin/TextIDs.lua
3
3039
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6380; -- You cannot obtain the <item>. Come back after sorting your inventory. ITEM_CANNOT_BE_OBTAINED_2 = 6380; -- You cannot obtain the #. Come back after sorting your inventory. ITEM_CANNOT_BE_OBTAINED_3 = 6380; -- You cannot obtain the %. Come back after sorting your inventory. ITEM_OBTAINED = 6386; -- Obtained: <item> GIL_OBTAINED = 6387; -- Obtained <number> gil KEYITEM_OBTAINED = 6389; -- Obtained key item: <keyitem> KEYITEM_LOST = 6390; -- Lost key item: <keyitem> NOT_HAVE_ENOUGH_GIL = 6393; -- You do not have enough gil. BAYLD_OBTAINED = 7004; -- You have obtainedbayld! RETRIEVE_DIALOG_ID = 7740; -- You retrieve$ from the porter moogle's care. MOG_LOCKER_OFFSET = 7567; -- Your Mog Locker lease is valid until <timestamp>, kupo. HOMEPOINT_SET = 8299; -- Home point set! -- Shop Texts HUJETTE_SHOP_TEXT = 9788; -- How about indulging in some regional delicacies while taking a load off those tired feet of yours? PRETERIG_SHOP_TEXT = 9789; -- Want a way to beat the heat? Try some of the tasty beverages we have on hand. LEDERICUS_SHOP_TEXT = 9823; -- We've got a doozy of a magic scroll selection, tailored especially to your pioneering needs! ISHVAD_SHOP_TEXT = 9824; -- ...A pioneer, are ya? If that's the case, maybe we've finally found a client for our geomantic plates. EUKALLINE_SHOP_TEXT = 9825; -- Why, hello there! If you're looking for geomantic plates, look no further! I don't like to brag, but I'd say our selection is a bit more...sophisticated than what they offer next door. FLAPANO_SHOP_TEXT = 9826; -- Welcome, welcome! Going out into the eye of the jungle's storm? Then the last thing you want is your stomach rumbling during an important battle! THEOPHYLACTE_SHOP_TEXT = 9831; -- Would you care for some of my wares? If you do not, I cannot fault you, but please keep in mind that my revolutionary research into a new Ulbukan toxin antidote will have to be put on hold unless I can accrue the necessary funds. KANIL_SHOP_TEXT = 9832; -- Good day, Multiple Choice (Player Gender)[good sir/fair maiden]! You're certainly not in the Middle Lands anymore, but would you care for some products from your homeland in addition to some more traditional fare DEFLIAA_SHOP_TEXT = 9850; -- Hi there, pioneer! We wouldn't want you going out to the scary jungle on an empty stomach. Stock up on some of our delicious bread for the journey! ANSEGUSELE_SHOP_TEXT = 9851; -- Would you care for some fresh vegetables direct from the Rala Waterways? They're some of our most popular items! TEVIGOGO_SHOP_TEXT = 9852; -- Hidey ho! Make sure not to forgetaru anything before heading out into the great unknown! -- NPC Dialog MINNIFI_DIALOGUE = 10235; -- Come, ladies and gentlemen, and enjoy our delightful array of frrresh vegetables!
gpl-3.0
THEGENRRAL/GENERAL
plugins/wlc.lua
2
3047
--[[ كتابه المطور :- -- تم التعديل و التعريب بواسطه @KNSLTHM --[[ Dev @KNSLTHM Dev @NAHAR2_BOT CH > @NENO_CH --]] do local function run(msg, matches, callback, extra) local data = load_data(_config.moderation.data) local rules = data[tostring(msg.to.id)]['rules'] local about = data[tostring(msg.to.id)]['description'] local hash = 'group:'..msg.to.id local group_welcome = redis:hget(hash,'welcome') if matches[1] == 'حذف الترحيب' and not matches[2] and is_momod(msg) then redis:hdel(hash,'welcome') return 'تم حذف الترحيب بنجاح✅' end local url , res = http.request('http://api.gpmod.ir/time/') if res ~= 200 then return "No connection" end local jdat = json:decode(url) if is_momod(msg) and matches[1] == 'ضع ترحيب' then redis:hset(hash,'welcome',matches[2]) return 'تم حفظ الترحيب💡' end if matches[1] == 'chat_add_user' and msg.service then group_welcome = string.gsub(group_welcome, '$userlink', "telegram.me/"..(msg.action.user.username or '').."") group_welcome = string.gsub(group_welcome, '$gpname', msg.to.title) group_welcome = string.gsub(group_welcome, '$name', ""..(msg.action.user.print_name or '').."") group_welcome = string.gsub(group_welcome, '$username', "@"..(msg.action.user.username or '').."") group_welcome = string.gsub(group_welcome, '$entime', ""..(jdat.ENtime).."") group_welcome = string.gsub(group_welcome, '$endate', ""..(jdat.ENdate).."") group_welcome = string.gsub(group_welcome, '$rules', ""..(rules or '').."") group_welcome = string.gsub(group_welcome, '$about', ""..(about or '').."") elseif matches[1] == 'chat_add_user_link' and msg.service then group_welcome = string.gsub(group_welcome, '$userlink', "telegram.me/"..(msg.from.username or '').."") group_welcome = string.gsub(group_welcome, '$gpname', msg.to.title) group_welcome = string.gsub(group_welcome, '$name', ""..(msg.from.print_name or '').."") group_welcome = string.gsub(group_welcome, '$username', "@"..(msg.from.username or '').."") group_welcome = string.gsub(group_welcome, '$entime', ""..(jdat.ENtime).."") group_welcome = string.gsub(group_welcome, '$endate', ""..(jdat.ENdate).."") group_welcome = string.gsub(group_welcome, '$rules', ""..(rules or '').."") group_welcome = string.gsub(group_welcome, '$about', ""..(about or '').."") end return group_welcome end return { patterns = { "^[!/#](ضع ترحيب) +(.*)$", "^[!/#](حذف الترحيب)$", "^(ضع ترحيب) +(.*)$", "^(حذف الترحيب)$", "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_add_user_link)$", }, run = run } end --[[ كتابه المطور :-- تم التعديل و التعريب بواسطه @KNSLTHM --[[ Dev @KNSLTHM Dev @NAHAR2_BOT CH > @NENO_CH --]]
gpl-3.0
amir1213/tamir
libs/dkjson.lua
3282
26558
-- Module options: local always_try_using_lpeg = true local register_global_module_table = false local global_module_name = 'json' --[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.4* In the default configuration this module writes no global values, not even the module table. Import it using json = require ("dkjson") In environments where `require` or a similiar function are not available and you cannot receive the return value of the module, you can set the option `register_global_module_table` to `true`. The module table will then be saved in the global variable with the name given by the option `global_module_name`. Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) To prevent the assigning of metatables pass `nil`: json.decode (string, position, null, nil) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This value is only checked for empty tables. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.4"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the `decode` function. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable the option `always_try_using_lpeg` in the options section at the top of the module. In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. --------------------------------------------------------------------- Contact ------- You can contact the author by sending an e-mail to 'david' at the domain 'dkolf.de'. --------------------------------------------------------------------- *Copyright (C) 2010-2013 David Heiko Kolf* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall, select = error, require, pcall, select local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local strmatch = string.match local concat = table.concat local json = { version = "dkjson 2.4" } if register_global_module_table then _G[global_module_name] = json end local _ENV = nil -- blocking globals in Lua 5.2 pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176-\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function replace(str, o, n) local i, j = strfind (str, o, 1, true) if i then return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1) else return str end end -- locale independent num2str and str2num functions local decpoint, numfilter local function updatedecpoint () decpoint = strmatch(tostring(0.5), "([^05+])") -- build a filter that can be used to remove group separators numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+" end updatedecpoint() local function num2str (num) return replace(fsub(tostring(num), numfilter, ""), decpoint, ".") end local function str2num (str) local num = tonumber(replace(str, ".", decpoint)) if not num then updatedecpoint() num = tonumber(replace(str, ".", decpoint)) end return num end local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = num2str (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local isa, n = isarray (value) if n == 0 and valmeta and valmeta.__jsontype == 'object' then isa = false end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} updatedecpoint() local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 0 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = str2num (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end local function optionalmetatables(...) if select("#", ...) > 0 then return ... else return {__jsontype = 'object'}, {__jsontype = 'array'} end end function json.decode (str, pos, nullval, ...) local objectmeta, arraymeta = optionalmetatables(...) return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") if g.version() == "0.11" then error "due to a bug in LPeg 0.11, it cannot be used for JSON matching" end local pegmatch = g.match local P, S, R = g.P, g.S, g.R local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, ...) local state = {} state.objectmeta, state.arraymeta = optionalmetatables(...) local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
gpl-2.0
garlick/flux-sched
rdl/RDL/uuid.lua
5
7861
--------------------------------------------------------------------------------------- -- Copyright 2012 Rackspace (original), 2013 Thijs Schreijer (modifications) -- -- 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. -- -- see http://www.ietf.org/rfc/rfc4122.txt -- -- Note that this is not a true version 4 (random) UUID. Since `os.time()` precision is only 1 second, it would be hard -- to guarantee spacial uniqueness when two hosts generate a uuid after being seeded during the same second. This -- is solved by using the node field from a version 1 UUID. It represents the mac address. -- -- 28-apr-2013 modified by Thijs Schreijer from the original [Rackspace code](https://github.com/kans/zirgo/blob/807250b1af6725bad4776c931c89a784c1e34db2/util/uuid.lua) as a generic Lua module. -- Regarding the above mention on `os.time()`; the modifications use the `socket.gettime()` function from LuaSocket -- if available and hence reduce that problem (provided LuaSocket has been loaded before uuid). local M = {} local math = require('math') local os = require('os') local string = require('string') local bitsize = 32 -- bitsize assumed for Lua VM. See randomseed function below. local lua_version = tonumber(_VERSION:match("%d%.*%d*")) -- grab Lua version used local MATRIX_AND = {{0,0},{0,1} } local MATRIX_OR = {{0,1},{1,1}} local HEXES = '0123456789abcdef' -- performs the bitwise operation specified by truth matrix on two numbers. local function BITWISE(x, y, matrix) local z = 0 local pow = 1 while x > 0 or y > 0 do z = z + (matrix[x%2+1][y%2+1] * pow) pow = pow * 2 x = math.floor(x/2) y = math.floor(y/2) end return z end local function INT2HEX(x) local s,base = '',16 local d while x > 0 do d = x % base + 1 x = math.floor(x/base) s = string.sub(HEXES, d, d)..s end while #s < 2 do s = "0" .. s end return s end ---------------------------------------------------------------------------- -- Creates a new uuid. Either provide a unique hex string, or make sure the -- random seed is properly set. The module table itself is a shortcut to this -- function, so `my_uuid = uuid.new()` equals `my_uuid = uuid()`. -- -- For proper use there are 3 options; -- -- 1. first require `luasocket`, then call `uuid.seed()`, and request a uuid using no -- parameter, eg. `my_uuid = uuid()` -- 2. use `uuid` without `luasocket`, set a random seed using `uuid.randomseed(some_good_seed)`, -- and request a uuid using no parameter, eg. `my_uuid = uuid()` -- 3. use `uuid` without `luasocket`, and request a uuid using an unique hex string, -- eg. `my_uuid = uuid(my_networkcard_macaddress)` -- -- @return a properly formatted uuid string -- @param hwaddr (optional) string containing a unique hex value (e.g.: `00:0c:29:69:41:c6`), to be used to compensate for the lesser `math.random()` function. Use a mac address for solid results. If omitted, a fully randomized uuid will be generated, but then you must ensure that the random seed is set properly! -- @usage -- local uuid = require("uuid") -- print("here's a new uuid: ",uuid()) function M.new(hwaddr) -- bytes are treated as 8bit unsigned bytes. local bytes = { math.random(0, 255), math.random(0, 255), math.random(0, 255), math.random(0, 255), math.random(0, 255), math.random(0, 255), math.random(0, 255), math.random(0, 255), math.random(0, 255), math.random(0, 255), math.random(0, 255), math.random(0, 255), math.random(0, 255), math.random(0, 255), math.random(0, 255), math.random(0, 255), } if hwaddr then assert(type(hwaddr)=="string", "Expected hex string, got "..type(hwaddr)) -- Cleanup provided string, assume mac address, so start from back and cleanup until we've got 12 characters local i,str, hwaddr = #hwaddr, hwaddr, "" while i>0 and #hwaddr<12 do local c = str:sub(i,i):lower() if HEXES:find(c, 1, true) then -- valid HEX character, so append it hwaddr = c..hwaddr end i = i - 1 end assert(#hwaddr == 12, "Provided string did not contain at least 12 hex characters, retrieved '"..hwaddr.."' from '"..str.."'") -- no split() in lua. :( bytes[11] = tonumber(hwaddr:sub(1, 2), 16) bytes[12] = tonumber(hwaddr:sub(3, 4), 16) bytes[13] = tonumber(hwaddr:sub(5, 6), 16) bytes[14] = tonumber(hwaddr:sub(7, 8), 16) bytes[15] = tonumber(hwaddr:sub(9, 10), 16) bytes[16] = tonumber(hwaddr:sub(11, 12), 16) end -- set the version bytes[7] = BITWISE(bytes[7], 0x0f, MATRIX_AND) bytes[7] = BITWISE(bytes[7], 0x40, MATRIX_OR) -- set the variant bytes[9] = BITWISE(bytes[7], 0x3f, MATRIX_AND) bytes[9] = BITWISE(bytes[7], 0x80, MATRIX_OR) return INT2HEX(bytes[1])..INT2HEX(bytes[2])..INT2HEX(bytes[3])..INT2HEX(bytes[4]).."-".. INT2HEX(bytes[5])..INT2HEX(bytes[6]).."-".. INT2HEX(bytes[7])..INT2HEX(bytes[8]).."-".. INT2HEX(bytes[9])..INT2HEX(bytes[10]).."-".. INT2HEX(bytes[11])..INT2HEX(bytes[12])..INT2HEX(bytes[13])..INT2HEX(bytes[14])..INT2HEX(bytes[15])..INT2HEX(bytes[16]) end ---------------------------------------------------------------------------- -- Improved randomseed function. -- Lua 5.1 and 5.2 both truncate the seed given if it exceeds the integer -- range. If this happens, the seed will be 0 or 1 and all randomness will -- be gone (each application run will generate the same sequence of random -- numbers in that case). This improved version drops the most significant -- bits in those cases to get the seed within the proper range again. -- @param seed the random seed to set (integer from 0 - 2^32, negative values will be made positive) -- @return the (potentially modified) seed used -- @usage -- local socket = require("socket") -- gettime() has higher precision than os.time() -- local uuid = require("uuid") -- -- see also example at uuid.seed() -- uuid.randomseed(socket.gettime()*10000) -- print("here's a new uuid: ",uuid()) function M.randomseed(seed) seed = math.floor(math.abs(seed)) if seed >= (2^bitsize) then -- integer overflow, so reduce to prevent a bad seed seed = seed - math.floor(seed / 2^bitsize) * (2^bitsize) end if lua_version < 5.2 then -- 5.1 uses (incorrect) signed int math.randomseed(seed - 2^(bitsize-1)) else -- 5.2 uses (correct) unsigned int math.randomseed(seed) end return seed end ---------------------------------------------------------------------------- -- Seeds the random generator. -- It does so in 2 possible ways; -- -- 1. use `os.time()`: this only offers resolution to one second (used when -- LuaSocket hasn't been loaded yet -- 2. use luasocket `gettime()` function, but it only does so when LuaSocket -- has been required already. -- @usage -- local socket = require("socket") -- gettime() has higher precision than os.time() -- -- LuaSocket loaded, so below line does the same as the example from randomseed() -- uuid.seed() -- print("here's a new uuid: ",uuid()) function M.seed() if package.loaded["socket"] and package.loaded["socket"].gettime then return M.randomseed(package.loaded["socket"].gettime()*10000) else return M.randomseed(os.time()) end end return setmetatable( M, { __call = function(self, hwaddr) return self.new(hwaddr) end} )
gpl-2.0
Ninjistix/darkstar
scripts/zones/Western_Altepa_Desert/npcs/relic.lua
5
1567
----------------------------------- -- 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"); ----------------------------------- 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; function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; 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
jamiepg1/MCServer
MCServer/Plugins/APIDump/Hooks/OnChunkGenerated.lua
8
2855
return { HOOK_CHUNK_GENERATED = { CalledWhen = "After a chunk was generated. Notification only.", DefaultFnName = "OnChunkGenerated", -- also used as pagename Desc = [[ This hook is called when world generator finished its work on a chunk. The chunk data has already been generated and is about to be stored in the {{cWorld|world}}. A plugin may provide some last-minute finishing touches to the generated data. Note that the chunk is not yet stored in the world, so regular {{cWorld}} block API will not work! Instead, use the {{cChunkDesc}} object received as the parameter.</p> <p> See also the {{OnChunkGenerating|HOOK_CHUNK_GENERATING}} hook. ]], Params = { { Name = "World", Type = "{{cWorld}}", Notes = "The world to which the chunk will be added" }, { Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" }, { Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" }, { Name = "ChunkDesc", Type = "{{cChunkDesc}}", Notes = "Generated chunk data. Plugins may still modify the chunk data contained." }, }, Returns = [[ If the plugin returns false or no value, MCServer will call other plugins' callbacks for this event. If a plugin returns true, no other callback is called for this event.</p> <p> In either case, MCServer will then store the data from ChunkDesc as the chunk's contents in the world. ]], CodeExamples = { { Title = "Generate emerald ore", Desc = "This example callback function generates one block of emerald ore in each chunk, under the condition that the randomly chosen location is in an ExtremeHills biome.", Code = [[ function OnChunkGenerated(a_World, a_ChunkX, a_ChunkZ, a_ChunkDesc) -- Generate a psaudorandom value that is always the same for the same X/Z pair, but is otherwise random enough: -- This is actually similar to how MCServer does its noise functions local PseudoRandom = (a_ChunkX * 57 + a_ChunkZ) * 57 + 19785486 PseudoRandom = PseudoRandom * 8192 + PseudoRandom; PseudoRandom = ((PseudoRandom * (PseudoRandom * PseudoRandom * 15731 + 789221) + 1376312589) % 0x7fffffff; PseudoRandom = PseudoRandom / 7; -- Based on the PseudoRandom value, choose a location for the ore: local OreX = PseudoRandom % 16; local OreY = 2 + ((PseudoRandom / 16) % 20); local OreZ = (PseudoRandom / 320) % 16; -- Check if the location is in ExtremeHills: if (a_ChunkDesc:GetBiome(OreX, OreZ) ~= biExtremeHills) then return false; end -- Only replace allowed blocks with the ore: local CurrBlock = a_ChunDesc:GetBlockType(OreX, OreY, OreZ); if ( (CurrBlock == E_BLOCK_STONE) or (CurrBlock == E_BLOCK_DIRT) or (CurrBlock == E_BLOCK_GRAVEL) ) then a_ChunkDesc:SetBlockTypeMeta(OreX, OreY, OreZ, E_BLOCK_EMERALD_ORE, 0); end end; ]], }, } , -- CodeExamples }, -- HOOK_CHUNK_GENERATED }
apache-2.0
dragoonreas/Timeless-Answers
Locales/ruRU.lua
1
1446
--[[ Russian localisation strings for Timeless Answers. Translation Credits: http://wow.curseforge.com/addons/timeless-answers/localization/translators/ Please update http://www.wowace.com/addons/timeless-answers/localization/ruRU/ for any translation additions or changes. Once reviewed, the translations will be automatically incorperated in the next build by the localization application. These translations are released under the Public Domain. ]]-- -- Get addon name local addon = ... -- Create the Russian localisation table local L = LibStub("AceLocale-3.0"):NewLocale(addon, "ruRU", false) if not L then return; end -- Messages output to the user's chat frame --@localization(locale="ruRU", format="lua_additive_table", handle-unlocalized="english", same-key-is-true=true, namespace="Message2")@ -- Gossip from the NPC that's neither an answer nor a question --@localization(locale="ruRU", format="lua_additive_table", handle-unlocalized="english", same-key-is-true=true, namespace="Gossip")@ -- The complete gossip text from when the NPC asks the question --@localization(locale="ruRU", format="lua_additive_table", handle-unlocalized="english", same-key-is-true=true, namespace="Question2")@ -- The complete gossip option text of the correct answer from when the NPC asks the question --@localization(locale="ruRU", format="lua_additive_table", handle-unlocalized="english", same-key-is-true=true, namespace="Answer")@
gpl-3.0
carnalis/Urho3D
bin/Data/LuaScripts/10_RenderToTexture.lua
24
10107
-- Render to texture example -- This sample demonstrates: -- - Creating two 3D scenes and rendering the other into a texture -- - Creating rendertarget textures and materials programmatically require "LuaScripts/Utilities/Sample" local rttScene_ = nil local rttCameraNode = nil function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateInstructions() -- Setup the viewport for displaying the scene SetupViewport() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_RELATIVE) -- Hook up to the frame update events SubscribeToEvents() end function CreateScene() -- Create the scene which will be rendered to a texture rttScene_ = Scene() -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000) rttScene_:CreateComponent("Octree") -- Create a Zone for ambient light & fog control local zoneNode = rttScene_:CreateChild("Zone") local zone = zoneNode:CreateComponent("Zone") -- Set same volume as the Octree, set a close bluish fog and some ambient light zone.boundingBox = BoundingBox(-1000.0, 1000.0) zone.ambientColor = Color(0.05, 0.1, 0.15) zone.fogColor = Color(0.1, 0.2, 0.3) zone.fogStart = 10.0 zone.fogEnd = 100.0 -- Create randomly positioned and oriented box StaticModels in the scene local NUM_OBJECTS = 2000 for i = 1, NUM_OBJECTS do local boxNode = rttScene_:CreateChild("Box") boxNode.position = Vector3(Random(200.0) - 100.0, Random(200.0) - 100.0, Random(200.0) - 100.0) -- Orient using random pitch, yaw and roll Euler angles boxNode.rotation = Quaternion(Random(360.0), Random(360.0), Random(360.0)) local boxObject = boxNode:CreateComponent("StaticModel") boxObject.model = cache:GetResource("Model", "Models/Box.mdl") boxObject.material = cache:GetResource("Material", "Materials/Stone.xml") -- Add our custom Rotator component which will rotate the scene node each frame, when the scene sends its update event. -- Simply set same rotation speed for all objects local rotator = boxNode:CreateScriptObject("Rotator") rotator.rotationSpeed = { 10.0, 20.0, 30.0 } end -- Create a camera for the render-to-texture scene. Simply leave it at the world origin and let it observe the scene rttCameraNode = rttScene_:CreateChild("Camera") local camera = rttCameraNode:CreateComponent("Camera") camera.farClip = 100.0 -- Create a point light to the camera scene node local light = rttCameraNode:CreateComponent("Light") light.lightType = LIGHT_POINT light.range = 30.0 -- Create the scene in which we move around scene_ = Scene() -- Create octree, use also default volume (-1000, -1000, -1000) to (1000, 1000, 1000) scene_:CreateComponent("Octree") -- Create a Zone component for ambient lighting & fog control local zoneNode = scene_:CreateChild("Zone") local zone = zoneNode:CreateComponent("Zone") zone.boundingBox = BoundingBox(-1000.0, 1000.0) zone.ambientColor = Color(0.1, 0.1, 0.1) zone.fogStart = 100.0 zone.fogEnd = 300.0 -- Create a directional light without shadows local lightNode = scene_:CreateChild("DirectionalLight") lightNode.direction = Vector3(0.5, -1.0, 0.5) local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL light.color = Color(0.2, 0.2, 0.2) light.specularIntensity = 1.0 -- Create a "floor" consisting of several tiles for y = -5, 5 do for x = -5, 5 do local floorNode = scene_:CreateChild("FloorTile") floorNode.position = Vector3(x * 20.5, -0.5, y * 20.5) floorNode.scale = Vector3(20.0, 1.0, 20.) local floorObject = floorNode:CreateComponent("StaticModel") floorObject.model = cache:GetResource("Model", "Models/Box.mdl") floorObject.material = cache:GetResource("Material", "Materials/Stone.xml") end end -- Create a "screen" like object for viewing the second scene. Construct it from two StaticModels, a box for the frame -- and a plane for the actual view local boxNode = scene_:CreateChild("ScreenBox") boxNode.position = Vector3(0.0, 10.0, 0.0) boxNode.scale = Vector3(21.0, 16.0, 0.5) local boxObject = boxNode:CreateComponent("StaticModel") boxObject.model = cache:GetResource("Model", "Models/Box.mdl") boxObject.material = cache:GetResource("Material", "Materials/Stone.xml") local screenNode = scene_:CreateChild("Screen") screenNode.position = Vector3(0.0, 10.0, -0.27) screenNode.rotation = Quaternion(-90.0, 0.0, 0.0) screenNode.scale = Vector3(20.0, 0.0, 15.0) local screenObject = screenNode:CreateComponent("StaticModel") screenObject.model = cache:GetResource("Model", "Models/Plane.mdl") -- Create a renderable texture (1024x768, RGB format), enable bilinear filtering on it local renderTexture = Texture2D:new() renderTexture:SetSize(1024, 768, Graphics:GetRGBFormat(), TEXTURE_RENDERTARGET) renderTexture.filterMode = FILTER_BILINEAR -- Create a new material from scratch, use the diffuse unlit technique, assign the render texture -- as its diffuse texture, then assign the material to the screen plane object local renderMaterial = Material:new() renderMaterial:SetTechnique(0, cache:GetResource("Technique", "Techniques/DiffUnlit.xml")) renderMaterial:SetTexture(TU_DIFFUSE, renderTexture) -- Since the screen material is on top of the box model and may Z-fight, use negative depth bias -- to push it forward (particularly necessary on mobiles with possibly less Z resolution) renderMaterial.depthBias = BiasParameters(-0.001, 0.0) screenObject.material = renderMaterial -- Get the texture's RenderSurface object (exists when the texture has been created in rendertarget mode) -- and define the viewport for rendering the second scene, similarly as how backbuffer viewports are defined -- to the Renderer subsystem. By default the texture viewport will be updated when the texture is visible -- in the main view local surface = renderTexture.renderSurface local rttViewport = Viewport:new(rttScene_, rttCameraNode:GetComponent("Camera")) surface:SetViewport(0, rttViewport) -- Create the camera which we will move around. Limit far clip distance to match the fog cameraNode = scene_:CreateChild("Camera") local camera = cameraNode:CreateComponent("Camera") camera.farClip = 300.0 -- Set an initial position for the camera scene node above the plane cameraNode.position = Vector3(0.0, 7.0, -30.0) end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText.text = "Use WASD keys and mouse to move" instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function MoveCamera(timeStep) -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 20.0 -- Mouse sensitivity as degrees per pixel local MOUSE_SENSITIVITY = 0.1 -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees local mouseMove = input.mouseMove yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, -90.0, 90.0) -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed local delta = MOVE_SPEED * timeStep if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) end -- Rotator script object class. Script objects to be added to a scene node must implement the empty ScriptObject interface Rotator = ScriptObject() function Rotator:Start() self.rotationSpeed = {0.0, 0.0, 0.0} end -- Update is called during the variable timestep scene update function Rotator:Update(timeStep) local x = self.rotationSpeed[1] * timeStep local y = self.rotationSpeed[2] * timeStep local z = self.rotationSpeed[3] * timeStep self.node:Rotate(Quaternion(x, y, z)) end
mit
Ninjistix/darkstar
scripts/globals/spells/phalanx.lua
5
1169
----------------------------------------- -- Spell: PHALANX ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local enhskill = caster:getSkillLevel(ENHANCING_MAGIC_SKILL); local final = 0; local duration = 180; if (caster:hasStatusEffect(EFFECT_COMPOSURE) == true and caster:getID() == target:getID()) then duration = duration * 3; end if (enhskill<=300) then final = (enhskill/10) -2; if (final<0) then final = 0; end elseif (enhskill>300) then final = ((enhskill-300)/29) + 28; else print("Warning: Unknown enhancing magic skill for phalanx."); end if (final>35) then final = 35; end if (target:addStatusEffect(EFFECT_PHALANX,final,0,duration)) then spell:setMsg(msgBasic.MAGIC_GAIN_EFFECT); else spell:setMsg(msgBasic.MAGIC_NO_EFFECT); end return EFFECT_PHALANX; end;
gpl-3.0
garlick/flux-sched
rdl/RDL.lua
2
6082
--/***************************************************************************\ -- Copyright (c) 2014 Lawrence Livermore National Security, LLC. Produced at -- the Lawrence Livermore National Laboratory (cf, AUTHORS, DISCLAIMER.LLNS). -- LLNL-CODE-658032 All rights reserved. -- -- This file is part of the Flux resource manager framework. -- For details, see https://github.com/flux-framework. -- -- This program is free software; you can redistribute it and/or modify it -- under the terms of the GNU General Public License as published by the Free -- Software Foundation; either version 2 of the license, or (at your option) -- any later version. -- -- Flux 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 terms and conditions of the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License along -- with this program; if not, write to the Free Software Foundation, Inc., -- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. -- See also: http://www.gnu.org/licenses/ --\***************************************************************************/ -- --- RDL.lua : RDL parser driver file. -- -- First, load some useful modules: -- local hostlist = require 'flux.hostlist' local HAVE_LUA52_LOAD = pcall (load, '') -- -- Get the base path for this module to use in searching for -- types in the types db -- (XXX: This is really a hack temporarily used for this prototype, -- in the future types will be loaded from system defined path) local basepath = debug.getinfo(1,"S").source:match[[^@?(.*[\/])[^\/]-$]] local function loadfile_env (filename, env) if HAVE_LUA52_LOAD then return loadfile (filename, "t", env) else local f, err = loadfile (filename) if f then setfenv (f, env) end return f, err end end local function loadstring_env (s, env) if HAVE_LUA52_LOAD then return load (s, nil, "t", env) else local f, err = loadstring (s) if f then setfenv (f, env) end return f, err end end -- Return an table suitable for use as RDL parse environment local function rdl_parse_environment () -- -- Restrict access to functions for RDL, which might be user -- supplied: -- local env = { print = print, pairs = pairs, tonumber = tonumber, assert = assert, unpack = unpack, table = table, hostlist = hostlist } local rdl = require 'RDL.memstore'.new() if not rdl then return nil, "failed to load rdl memory store" end --- -- the "uses" function is like 'require' but loads a resource definition -- file from the current resource types path -- function env.uses (t, dir) local dir = dir or basepath .. "RDL/types" local filename = dir .. "/" .. t .. ".lua" if env[t] then return end local uses_env = setmetatable ({}, { __index = function (t,k) return env[k] or _G[k] end } ) local f = assert (loadfile_env (filename, uses_env)) local rc, r = pcall (f) if not rc then return nil, r end env [t] = r return r end --- -- Hierarchy() definition function inserts a new hierarchy into -- the current RDL db. -- function env.Hierarchy (name) return function (resource) if not resource.type then resource = resource[1] end assert (resource, "Resource argument required to Hierarchy keyword") rdl:hierarchy_put (name, resource) end end --- -- Load 'Resource' base class by default (i.e. use "Resource") --- env.uses ('Resource', basepath .. "RDL") --- -- Load extra functions defined in RDL/lib/?.lua --- local glob = require 'flux.posix'.glob for _,path in pairs (glob (basepath .. "RDL/lib/*.lua")) do local f = assert (loadfile (path)) local name = path:match("([^/]+)%.lua") local rc, r = pcall (f) if not rc then error ("Failed to load "..path..": "..r) end env[name] = r end env.rdl = rdl return env end -- -- Evaluate RDL in compiled lua function [f] and return RDL representation -- -- If RDL is in 'config language' format, then the function -- environment will contain an 'rdl' memstore db object ready -- to return. -- -- If RDL is serialized, then running the serialized code will -- *return* a table in RDL db format, which then must be -- "blessed" into a memstore object. -- local function rdl_eval (f) local rc, ret = pcall (f) if not rc then return nil, "Error! " .. ret end if type (ret) == 'table' then local memstore = require 'RDL.memstore' return memstore.bless (ret) end end -- -- Evaluate rdl in string `s' -- local function rdl_evals (s) if type (s) ~= "string" then return nil, "refusing to evaluate non-string argument" end if string.byte (s, 1) == 27 then return nil, "binary code prohibited" end local env = rdl_parse_environment () local f, err = loadstring_env (s, env) if not f then return nil, err end rdl_eval (f) return env.rdl end -- -- Load RDL from filename `f' -- local function rdl_evalf (filename) if filename then local f, err = io.open (filename, "r") if not f then return nil, err end local line = f:read() f:close() if (line:byte (1) == 27) then return nil, "binary code prohibited" end end local env = rdl_parse_environment () local fn, err = loadfile_env (filename, env) if not fn then return nil, "RDL eval failed: "..err end rdl_eval (fn) return env.rdl end return { eval = rdl_evals, evalf = rdl_evalf } -- vi: ts=4 sw=4 expandtab
gpl-2.0
carnalis/Urho3D
bin/Data/LuaScripts/23_Water.lua
11
9914
-- Water example. -- This sample demonstrates: -- - Creating a large plane to represent a water body for rendering -- - Setting up a second camera to render reflections on the water surface require "LuaScripts/Utilities/Sample" local reflectionCameraNode = nil local waterNode = nil local waterPlane = Plane() local waterClipPlane = Plane() function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateInstructions() -- Setup the viewport for displaying the scene SetupViewport() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_RELATIVE) -- Hook up to the frame update event SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000) scene_:CreateComponent("Octree") -- Create a Zone component for ambient lighting & fog control local zoneNode = scene_:CreateChild("Zone") local zone = zoneNode:CreateComponent("Zone") zone.boundingBox = BoundingBox(-1000.0, 1000.0) zone.ambientColor = Color(0.15, 0.15, 0.15) zone.fogColor = Color(1.0, 1.0, 1.0) zone.fogStart = 500.0 zone.fogEnd = 750.0 -- Create a directional light to the world. Enable cascaded shadows on it local lightNode = scene_:CreateChild("DirectionalLight") lightNode.direction = Vector3(0.6, -1.0, 0.8) local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL light.castShadows = true light.shadowBias = BiasParameters(0.00025, 0.5) light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8) light.specularIntensity = 0.5 -- Apply slightly overbright lighting to match the skybox light.color = Color(1.2, 1.2, 1.2) -- Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the -- illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will -- generate the necessary 3D texture coordinates for cube mapping local skyNode = scene_:CreateChild("Sky") skyNode:SetScale(500.0) -- The scale actually does not matter local skybox = skyNode:CreateComponent("Skybox") skybox.model = cache:GetResource("Model", "Models/Box.mdl") skybox.material = cache:GetResource("Material", "Materials/Skybox.xml") -- Create heightmap terrain local terrainNode = scene_:CreateChild("Terrain") terrainNode.position = Vector3(0.0, 0.0, 0.0) local terrain = terrainNode:CreateComponent("Terrain") terrain.patchSize = 64 terrain.spacing = Vector3(2.0, 0.5, 2.0) -- Spacing between vertices and vertical resolution of the height map terrain.smoothing = true terrain.heightMap = cache:GetResource("Image", "Textures/HeightMap.png") terrain.material = cache:GetResource("Material", "Materials/Terrain.xml") -- The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all -- terrain patches and other objects behind it terrain.occluder = true -- Create 1000 boxes in the terrain. Always face outward along the terrain normal local NUM_OBJECTS = 1000 for i = 1, NUM_OBJECTS do local objectNode = scene_:CreateChild("Box") local position = Vector3(Random(2000.0) - 1000.0, 0.0, Random(2000.0) - 1000.0) position.y = terrain:GetHeight(position) + 2.25 objectNode.position = position -- Create a rotation quaternion from up vector to terrain normal objectNode.rotation = Quaternion(Vector3(0.0, 1.0, 0.0), terrain:GetNormal(position)) objectNode:SetScale(5.0) local object = objectNode:CreateComponent("StaticModel") object.model = cache:GetResource("Model", "Models/Box.mdl") object.material = cache:GetResource("Material", "Materials/Stone.xml") object.castShadows = true end -- Create a water plane object that is as large as the terrain waterNode = scene_:CreateChild("Water") waterNode.scale = Vector3(2048.0, 1.0, 2048.0) waterNode.position = Vector3(0.0, 5.0, 0.0) local water = waterNode:CreateComponent("StaticModel") water.model = cache:GetResource("Model", "Models/Plane.mdl") water.material = cache:GetResource("Material", "Materials/Water.xml") -- Set a different viewmask on the water plane to be able to hide it from the reflection camera water.viewMask = 0x80000000 -- Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside -- the scene, because we want it to be unaffected by scene load / save cameraNode = Node() local camera = cameraNode:CreateComponent("Camera") camera.farClip = 750.0 -- Set an initial position for the camera scene node above the floor cameraNode.position = Vector3(0.0, 7.0, -20.0) end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText:SetText("Use WASD keys and mouse to move") instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) instructionText.textAlignment = HA_CENTER -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) -- Create a mathematical plane to represent the water in calculations waterPlane = Plane(waterNode.worldRotation * Vector3(0.0, 1.0, 0.0), waterNode.worldPosition) -- Create a downward biased plane for reflection view clipping. Biasing is necessary to avoid too aggressive clipping waterClipPlane = Plane(waterNode.worldRotation * Vector3(0.0, 1.0, 0.0), waterNode.worldPosition - Vector3(0.0, 0.1, 0.0)) -- Create camera for water reflection -- It will have the same farclip and position as the main viewport camera, but uses a reflection plane to modify -- its position when rendering reflectionCameraNode = cameraNode:CreateChild() local reflectionCamera = reflectionCameraNode:CreateComponent("Camera") reflectionCamera.farClip = 750.0 reflectionCamera.viewMask = 0x7fffffff -- Hide objects with only bit 31 in the viewmask (the water plane) reflectionCamera.autoAspectRatio = false reflectionCamera.useReflection = true reflectionCamera.reflectionPlane = waterPlane reflectionCamera.useClipping = true -- Enable clipping of geometry behind water plane reflectionCamera.clipPlane = waterClipPlane -- The water reflection texture is rectangular. Set reflection camera aspect ratio to match reflectionCamera.aspectRatio = graphics.width / graphics.height -- View override flags could be used to optimize reflection rendering. For example disable shadows --reflectionCamera.viewOverrideFlags = VO_DISABLE_SHADOWS -- Create a texture and setup viewport for water reflection. Assign the reflection texture to the diffuse -- texture unit of the water material local texSize = 1024 local renderTexture = Texture2D:new() renderTexture:SetSize(texSize, texSize, Graphics:GetRGBFormat(), TEXTURE_RENDERTARGET) renderTexture.filterMode = FILTER_BILINEAR local surface = renderTexture.renderSurface local rttViewport = Viewport:new(scene_, reflectionCamera) surface:SetViewport(0, rttViewport) local waterMat = cache:GetResource("Material", "Materials/Water.xml") waterMat:SetTexture(TU_DIFFUSE, renderTexture) end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") end function MoveCamera(timeStep) -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 20.0 -- Mouse sensitivity as degrees per pixel local MOUSE_SENSITIVITY = 0.1 -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees local mouseMove = input.mouseMove yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, -90.0, 90.0) -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end -- In case resolution has changed, adjust the reflection camera aspect ratio local reflectionCamera = reflectionCameraNode:GetComponent("Camera") reflectionCamera.aspectRatio = graphics.width / graphics.height end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) end
mit
Igalia/skia
tools/lua/dump_clipstack_at_restore.lua
147
1096
function sk_scrape_startcanvas(c, fileName) canvas = c clipstack = {} restoreCount = 0 end function sk_scrape_endcanvas(c, fileName) canvas = nil end function sk_scrape_accumulate(t) if (t.verb == "restore") then restoreCount = restoreCount + 1; -- io.write("Clip Stack at restore #", restoreCount, ":\n") io.write("Reduced Clip Stack at restore #", restoreCount, ":\n") for i = 1, #clipstack do local element = clipstack[i]; io.write("\t", element["op"], ", ", element["type"], ", aa:", tostring(element["aa"])) if (element["type"] == "path") then io.write(", fill: ", element["path"]:getFillType()) io.write(", segments: \"", element["path"]:getSegmentTypes(), "\"") io.write(", convex:", tostring(element["path"]:isConvex())) end io.write("\n") end io.write("\n") else -- clipstack = canvas:getClipStack() clipstack = canvas:getReducedClipStack() end end function sk_scrape_summarize() end
bsd-3-clause
Ninjistix/darkstar
scripts/commands/npchere.lua
8
1607
--------------------------------------------------------------------------------------------------- -- func: npchere <npcId> -- desc: Spawns an NPC and then moves it to the current position, if in same zone. -- Errors will despawn the NPC unless "noDepop" was specified (any value works). --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "is" }; function error(player, msg) player:PrintToPlayer(msg); player:PrintToPlayer("!npchere {npcID} {noDepop}"); end; function onTrigger(player, npcId, noDepop) require("scripts/globals/status"); -- validate npc local targ; if (npcId == nil) then targ = player:getCursorTarget(); if (targ == nil or not targ:isNPC()) then error(player, "You must either provide an npcID or target an NPC."); return; end else targ = GetNPCByID(npcId); if (targ == nil) then error(player, "Invalid npcID."); return; end end if (player:getZoneID() == targ:getZoneID()) then targ:setPos( player:getXPos(), player:getYPos(), player:getZPos(), player:getRotPos(), player:getZoneID() ); targ:setStatus(STATUS_NORMAL); else if (noDepop == nil or noDepop == 0) then targ:setStatus(STATUS_DISAPPEAR); player:PrintToPlayer("Despawned the NPC because of an error."); end player:PrintToPlayer("NPC could not be moved to current pos - you are probably in the wrong zone."); end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Lower_Jeuno/npcs/Mataligeat.lua
7
1466
----------------------------------- -- Area: Lower Jeuno -- NPC: Mataligeat -- Standard Info NPC -- !pos -24 0 -60 245 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local painfulMemory = player:getQuestStatus(JEUNO,PAINFUL_MEMORY); local theRequiem = player:getQuestStatus(JEUNO,THE_REQUIEM); local pathOfTheBard = player:getQuestStatus(JEUNO,PATH_OF_THE_BARD); -- THE OLD MONUMENT if (player:getVar("TheOldMonument_Event") == 1) then player:startEvent(141); -- looks like his girlfriend dumped him -- PAINFUL MEMORY elseif (painfulMemory == QUEST_ACCEPTED) then player:startEvent(140); -- he's forgotten why he took up the lute in the first place -- THE REQUIEM elseif (theRequiem == QUEST_ACCEPTED and player:getVar("TheRequiemCS") == 3) then player:startEvent(142); -- huh? the bard interred inside eldieme? -- PATH OF THE BARD elseif (pathOfTheBard == QUEST_COMPLETED) then player:startEvent(143); -- so now you're one of us, huh? -- DEFAULT RESPONSE else player:startEvent(144); -- have you heard of lewenhart? end; end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/weaponskills/tachi_goten.lua
25
1476
-- --------------------------------- -- Tachi Goten -- Great Katana weapon skill -- Skill Level: 70 -- Deals lightning elemental damage to enemy. Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Light Gorget / Thunder Gorget. -- Aligned with the Light Belt / Thunder Belt. -- Element: Thunder -- Modifiers: STR:60% -- 100%TP 200%TP 300%TP -- .5 .75 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 1.0; params.ftp200 = 1.0; params.ftp300 = 1.0; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = .5; params.ftp200 = .75; params.ftp300 = 1; params.str_wsc = 0.6; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Ninjistix/darkstar
scripts/globals/items/coffeecake_muffin_+1.lua
3
1108
----------------------------------------- -- ID: 5656 -- Item: coffeecake_muffin_+1 -- Food Effect: 1Hr, All Races ----------------------------------------- -- Mind 2 -- Strength -1 -- MP % 10 (cap 90) ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5656); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MND, 2); target:addMod(MOD_STR, -1); target:addMod(MOD_FOOD_MPP, 10); target:addMod(MOD_FOOD_MP_CAP, 90); end; function onEffectLose(target, effect) target:delMod(MOD_MND, 2); target:delMod(MOD_STR, -1); target:delMod(MOD_FOOD_MPP, 10); target:delMod(MOD_FOOD_MP_CAP, 90); end;
gpl-3.0