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 |
|---|---|---|---|---|---|
aqasaeed/creed | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
Whit3Tig3R/dragonbot | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
alisalartymory/telehack-bot | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
adminmagma/test | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
sose12/AOS_SHARO56 | plugins/ar-boomzain.lua | 1 | 1590 | -- only enable one of them
local Kick = true;
local Warn = false;
do
local function Memo(msg, matches)
if ( kick == true ) then
Warn = false;
elseif ( Warn == true ) then
Kick = false;
end
-- check if the user is owner
if ( is_realm(msg) and is_admin(msg)or is_sudo(msg) or is_momod(msg) ) then
-- if he is a owner then exit out of the code
return
end
-- load the data
local data = load_data(_config.moderation.data)
-- get the receiver and set the variable chat to it
local chat = get_receiver(msg)
-- get the sender id and set the variable user to it
local user = "user#id"..msg.from.id
-- check if the data 'LockFuck' from the table 'settings' is "yes"
if ( data[tostring(msg.to.id)]['settings']['LockFuck'] == "yes" ) then
-- send a message
send_large_msg(chat, "ู
ู
ููุน ุงูุชููู
ุนู ุงูุฌููุด ููุงโน๏ธ๐๐ป")
-- kick the user who sent the message
if ( Kick == true ) then
chat_del_user(chat, user, ok_cb, true)
elseif ( Warn == true ) then
send_large_msg( get_receiver(msg), "ู
ู
ููุน โ ุงูุชููู
ุนู ุงูุฌููุด ููุง ๐ช๐๐ป @" .. msg.from.username )
end
end
end
return {
patterns = {
"AHK",
"TNT",
"TIQ",
"tut",
"vip",
"ุฌูุด",
"ุงูููุงู",
"ุชู ุงู ููู",
"ุชูุณุงุณ",
"ูู ุงู ุจู",
"ุชู ุงู ุชู",
"ุงููุด",
"ุชูููุด",
"ุงูุฑุฆุงุณู",
},
run = Memo
}
end
| gpl-2.0 |
Sewerbird/Helios2400 | lib/statemachine.lua | 1 | 4922 | --[[
source: https://github.com/kyleconroy/lua-state-machine
Copyright (c) 2012 Kyle Conroy
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.
]]--
local machine = {}
machine.__index = machine
local NONE = "none"
local ASYNC = "async"
local function call_handler(handler, params)
if handler then
return handler(unpack(params))
end
end
local function create_transition(name)
local can, to, from, params
local function transition(self, ...)
if self.asyncState == NONE then
can, to = self:can(name)
from = self.current
params = { self, name, from, to, ...}
if not can then return false end
self.currentTransitioningEvent = name
local beforeReturn = call_handler(self["onbefore" .. name], params)
local leaveReturn = call_handler(self["onleave" .. from], params)
if beforeReturn == false or leaveReturn == false then
return false
end
self.asyncState = name .. "WaitingOnLeave"
if leaveReturn ~= ASYNC then
transition(self, ...)
end
return true
elseif self.asyncState == name .. "WaitingOnLeave" then
self.current = to
local enterReturn = call_handler(self["onenter" .. to] or self["on" .. to], params)
self.asyncState = name .. "WaitingOnEnter"
if enterReturn ~= ASYNC then
transition(self, ...)
end
return true
elseif self.asyncState == name .. "WaitingOnEnter" then
call_handler(self["onafter" .. name] or self["on" .. name], params)
call_handler(self["onstatechange"], params)
self.asyncState = NONE
self.currentTransitioningEvent = nil
return true
else
if string.find(self.asyncState, "WaitingOnLeave") or string.find(self.asyncState, "WaitingOnEnter") then
self.asyncState = NONE
transition(self, ...)
return true
end
end
self.currentTransitioningEvent = nil
return false
end
return transition
end
local function add_to_map(map, event)
if type(event.from) == 'string' then
map[event.from] = event.to
else
for _, from in ipairs(event.from) do
map[from] = event.to
end
end
end
function machine.create(options)
assert(options.events)
local fsm = {}
setmetatable(fsm, machine)
fsm.options = options
fsm.current = options.initial or 'none'
fsm.asyncState = NONE
fsm.events = {}
for _, event in ipairs(options.events or {}) do
local name = event.name
fsm[name] = fsm[name] or create_transition(name)
fsm.events[name] = fsm.events[name] or { map = {} }
add_to_map(fsm.events[name].map, event)
end
for name, callback in pairs(options.callbacks or {}) do
fsm[name] = callback
end
return fsm
end
function machine:is(state)
return self.current == state
end
function machine:can(e)
local event = self.events[e]
local to = event and event.map[self.current] or event.map['*']
return to ~= nil, to
end
function machine:cannot(e)
return not self:can(e)
end
function machine:todot(filename)
local dotfile = io.open(filename,'w')
dotfile:write('digraph {\n')
local transition = function(event,from,to)
dotfile:write(string.format('%s -> %s [label=%s];\n',from,to,event))
end
for _, event in pairs(self.options.events) do
if type(event.from) == 'table' then
for _, from in ipairs(event.from) do
transition(event.name,from,event.to)
end
else
transition(event.name,event.from,event.to)
end
end
dotfile:write('}\n')
dotfile:close()
end
function machine:transition(event)
if self.currentTransitioningEvent == event then
return self[self.currentTransitioningEvent](self)
end
end
function machine:cancelTransition(event)
if self.currentTransitioningEvent == event then
self.asyncState = NONE
self.currentTransitioningEvent = nil
end
end
machine.NONE = NONE
machine.ASYNC = ASYNC
return machine
| mit |
ximus/RIOT | dist/tools/wireshark_dissector/riot.lua | 21 | 2130 | -- RIOT native support for Wireshark
-- A Lua implementation for dissection of RIOT native packets in wireshark
-- @Version: 0.0.1
-- @Author: Martine Lenders
-- @E-Mail: mlenders@inf.fu-berlin.de
do
--Protocol name "RIOT"
local p_riot = Proto("RIOT", "RIOT native packet")
--Protocol Fields
local f_length = ProtoField.uint16("RIOT.length", "Length", base.DEC, nil)
local f_dst = ProtoField.uint16("RIOT.dst", "Destination", base.DEC, nil)
local f_src = ProtoField.uint16("RIOT.src", "Source", base.DEC, nil)
local f_pad = ProtoField.bytes("RIOT.pad", "Padding")
p_riot.fields = { f_length, f_dst, f_src }
local data_dis = Dissector.get("data")
-- local next_dis = Dissector.get("6lowpan") -- for 6LoWPAN
local next_dis = Dissector.get("wpan") -- for IEEE 802.15.4
function riot_dissector(buf, pkt, root)
local buf_len = buf:len()
local riot_tree = root:add(p_riot, buf)
if buf_len < 6 then return false end
local packet_len = buf(0,2):uint()
local dst = buf(2,2):uint()
local src = buf(4,2):uint()
if packet_len >= 46 and buf_len - 6 ~= packet_len then return false end
riot_tree:append_text(", Dst: ")
riot_tree:append_text(dst)
riot_tree:append_text(", Src: ")
riot_tree:append_text(src)
riot_tree:append_text(", Length: ")
riot_tree:append_text(packet_len)
riot_tree:add(f_length, buf(0, 2))
riot_tree:add(f_dst, buf(2, 2))
riot_tree:add(f_src, buf(4, 2))
-- to show the padding for small packets uncomment the
-- following line and append "f_pad" to p_riot.fields above.
-- riot_tree:add(f_pad, buf(packet_len + 6))
next_dis:call(buf(6, packet_len):tvb(), pkt, root)
return true
end
function p_riot.dissector(buf, pkt, root)
if not riot_dissector(buf, pkt, root) then
data_dis:call(buf, pkt, root)
end
end
local eth_encap_table = DissectorTable.get("ethertype")
--handle ethernet type 0x1234
eth_encap_table:add(0x1234, p_riot)
end
| lgpl-2.1 |
rpetit3/darkstar | scripts/globals/mobskills/Rime_Spray.lua | 33 | 1448 | ---------------------------------------------
-- Rime Spray
--
-- Description: Deals Ice damage to enemies within a fan-shaped area, inflicting them with Frost and All statuses down.
-- Type: Breath
-- Utsusemi/Blink absorb: Ignores shadows
-- Range: Unknown cone
-- Notes:
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_FROST;
MobStatusEffectMove(mob, target, EFFECT_FROST, 15, 3, 120);
MobStatusEffectMove(mob, target, EFFECT_STR_DOWN, 20, 3, 60);
MobStatusEffectMove(mob, target, EFFECT_VIT_DOWN, 20, 3, 60);
MobStatusEffectMove(mob, target, EFFECT_DEX_DOWN, 20, 3, 60);
MobStatusEffectMove(mob, target, EFFECT_AGI_DOWN, 20, 3, 60);
MobStatusEffectMove(mob, target, EFFECT_MND_DOWN, 20, 3, 60);
MobStatusEffectMove(mob, target, EFFECT_INT_DOWN, 20, 3, 60);
MobStatusEffectMove(mob, target, EFFECT_CHR_DOWN, 20, 3, 60);
local dmgmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_ICE,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_ICE,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
tommo/gii | template/game/lib/mock/effect/EffectSimpleParticleSystem.lua | 2 | 12170 | module 'mock'
--------------------------------------------------------------------
local function varianceRange( v, variance, minValue, maxValue )
local min, max = v-variance, v+variance
if minValue and min < minValue then min = minValue end
if maxValue and max > maxValue then max = maxValue end
return { min, max }
end
--------------------------------------------------------------------
local templateInitScript = [[
--init script
local function variance(a,b)
return b==0 and a or rand(a-b,a+b)
end
local function variance1(a,b)
return b==0 and a or rand(a-b<0 and 0 or a-b, a+b>1 and 1 or a+b)
end
angle=variance($angle,$angleVariance)
s0=variance($startParticleSize,$startParticleSizeVariance)
s1=variance($finishParticleSize,$finishParticleSizeVariance)
rot0=variance($rot0,$rot0Variance)
rot1=variance($rot1,$rot1Variance)
if '$emitterType'=='gravity' then
-- speed=variance($speed,$speedVariance)
-- vx=cos(angle)*speed
-- vy=sin(angle)*speed
vx = 0
vy = 0
if $hasRadAcc then radAcc=variance($radAcc,$radAccVariance) end
if $hasTanAcc then tanAcc=variance($tanAcc,$tanAccVariance) end
if $hasTanAcc or $hasRadAcc then
dx=variance($srcX,$srcXVariance)
dy=variance($srcY,$srcYVariance)
p.x=p.x+dx
p.y=p.y+dy
else
p.x=p.x+variance($srcX,$srcXVariance)
p.y=p.y+variance($srcY,$srcYVariance)
end
else --radial
x0=p.x
y0=p.y
rps=variance($rps, $rpsVariance)
minRadius=$minRadius
maxRadius=variance($maxRadius, $maxRadiusVariance)
end
r0,g0,b0,a0 = variance1($r0,$r0v),variance1($g0,$g0v),variance1($b0,$b0v),variance1($a0,$a0v)
r1,g1,b1,a1 = variance1($r1,$r1v),variance1($g1,$g1v),variance1($b1,$b1v),variance1($a1,$a1v)
]]
local templateRenderScript = [[
--render script
if '$emitterType'=='gravity' then
if $gravityX~=0 then vx=vx+$gravityX end
if $gravityY~=0 then vy=vy+$gravityY end
if $hasRadAcc or $hasTanAcc then
a=vecAngle(dy,dx) * (3.14159265355/180)
ca=cos(a)
sa=sin(a)
if $hasRadAcc then
vx=vx+ca*radAcc
vy=vy+sa*radAcc
end
if $hasTanAcc then
vx=vx-sa*tanAcc
vy=vy+ca*tanAcc
end
-- dx=dx+vx
-- dy=dy+vy
dx = dx + p.dx
dy = dy + p.dy
end
p.x=p.x+vx
p.y=p.y+vy
else --radial
radius=ease(maxRadius,minRadius)
p.x=x0+cos(angle)*radius
p.y=y0+sin(angle)*radius
angle=angle+rps
end
sprite()
local easeType=EaseType.LINEAR
if $easeR then sp.r = ease( r0, r1,easeType) else sp.r=$r0 end
if $easeG then sp.g = ease( g0, g1,easeType) else sp.g=$g0 end
if $easeB then sp.b = ease( b0, b1,easeType) else sp.b=$b0 end
if $easeA then sp.opacity = ease( a0, a1,easeType) else sp.opacity=$a0 end
size = ease(s0,s1)
sp.sx = size
sp.sy = size
sp.rot=ease(rot0,rot1)
]]
--------------------------------------------------------------------
---- PEX MODEL
--------------------------------------------------------------------
CLASS: EffectNodeSimpleParticleSystem ( EffectNodeParticleSystem )
:MODEL{
'----';
Field 'life' :number() :range( 0, 10 ) :widget('slider');
Field 'lifeVar' :number() :range( 0, 10 ) :widget('slider') :label( 'life.v' );
Field 'emission' :int() :range( 0, 100 ) :widget('slider');
Field 'frequency' :number() :range( 0.1, 100 ) :widget('slider');
Field 'emitSize' :type('vec2') :range( 0 ) :getset('EmitSize');
'----';
Field 'speed' :number() :range( 0, 2000 ) :widget('slider');
Field 'speedVar' :number() :range( 0, 2000 ) :widget('slider') :label('speed.v');
Field 'angle' :number() :range( 0, 360 ) :widget('slider');
Field 'angleVar' :number() :range( 0, 180 ) :widget('slider') :label('angle.v');
'----';
Field 'size' :number() :range( 0, 10 ) :widget('slider');
Field 'size1' :number() :range( 0, 10 ) :widget('slider');
Field 'sizeVar' :number() :range( 0, 10 ) :widget('slider') :label('size.v');
Field 'rot0' :number() :range( 0, 3600 ) :widget('slider');
Field 'rot0Var' :number() :range( 0, 3600 ) :widget('slider') :label('rot0.v');
Field 'rot1' :number() :range( 0, 3600 ) :widget('slider');
Field 'rot1Var' :number() :range( 0, 3600 ) :widget('slider') :label('rot1.v');
'----';
Field 'gravity' :type('vec2') :range( -5000, 5000 ) :getset('Gravity');
Field 'accRadial' :number() :range( -1000, 1000 ) :widget('slider');
Field 'accRadialVar' :number() :range( 0, 1000 ) :widget('slider') :label('accRadial.v');
Field 'accTan' :number() :range( -1000, 1000 ) :widget('slider');
Field 'accTanVar' :number() :range( 0, 1000 ) :widget('slider') :label('accTan.v');
'----';
Field 'color0' :type('color') :getset('Color0') ;
Field 'color1' :type('color') :getset('Color1') ;
Field 'colorVarR' :number() :range( 0, 1 ) :widget('slider') :label('red.v');
Field 'colorVarG' :number() :range( 0, 1 ) :widget('slider') :label('green.v');
Field 'colorVarB' :number() :range( 0, 1 ) :widget('slider') :label('blue.v');
Field 'colorVarA' :number() :range( 0, 1 ) :widget('slider') :label('alpha.v');
}
--------------------------------------------------------------------
function EffectNodeSimpleParticleSystem:__init()
self.childrenNodesAdded = false
self._stateNode = false
self._emitterNode = false
self.particles = 200
self.deck = false
self.blend = 'add'
self.life = 1
self.lifeVar = 0
self.emission = 1
self.frequency = 10
self.emitSize = {0,0}
self.size = 1
self.size1 = 1
self.sizeVar = 0
self.speed = 100
self.speedVar = 0
self.angle = 0
self.angleVar = 0
self.rot0 = 0
self.rot0Var = 0
self.rot1 = 0
self.rot1Var = 0
self.accRadial = 0
self.accRadialVar = 0
self.accTan = 0
self.accTanVar = 0
self.gravity = { 0, -10 }
self.color0 = {1,1,1,1}
self.color1 = {1,1,1,0}
self.colorVarR = 0
self.colorVarG = 0
self.colorVarB = 0
self.colorVarA = 0
end
function EffectNodeSimpleParticleSystem:getDefaultName()
return 'particle_simple'
end
function EffectNodeSimpleParticleSystem:getTypeName()
return 'system_simple'
end
--------------------------------------------------------------------
--CONFIG
--------------------------------------------------------------------
function EffectNodeSimpleParticleSystem:getColor0()
return unpack( self.color0 )
end
function EffectNodeSimpleParticleSystem:setColor0( r,g,b,a )
self.color0 = {r,g,b,a}
end
--------------------------------------------------------------------
function EffectNodeSimpleParticleSystem:getColor1()
return unpack( self.color1 )
end
function EffectNodeSimpleParticleSystem:setColor1( r,g,b,a )
self.color1 = {r,g,b,a}
end
--------------------------------------------------------------------
function EffectNodeSimpleParticleSystem:getEmitSize()
return unpack( self.emitSize )
end
function EffectNodeSimpleParticleSystem:setEmitSize( w, h )
self.emitSize = {w,h}
end
--------------------------------------------------------------------
function EffectNodeSimpleParticleSystem:getGravity()
return unpack( self.gravity )
end
function EffectNodeSimpleParticleSystem:setGravity( x, y )
self.gravity = { x, y }
end
--------------------------------------------------------------------
function EffectNodeSimpleParticleSystem:buildStateScript()
local fps = 60
local timeScale = 1/fps
local accScale = timeScale * timeScale
local initScript
local renderScript
local t = self
local emitterType = 'gravity'
local c0 = t.color0
local c1 = t.color1
local c0v = { t.colorVarR, t.colorVarG, t.colorVarB, t.colorVarA }
local c1v = { 0, 0, 0, 0 }
local hasRadAcc = t.accRadial~=0 or t.accRadialVar~=0
local hasTanAcc = t.accTan~=0 or t.accTanVar~=0
local dataInit = {
emitterType = emitterType,
speed = t.speed * timeScale,
speedVariance = t.speedVar * timeScale,
angle = t.angle / 180 * math.pi,
angleVariance = t.angleVar / 180 * math.pi,
r0 = c0[1], r0v = c0v[1],
g0 = c0[2], g0v = c0v[2],
b0 = c0[3], b0v = c0v[3],
a0 = c0[4], a0v = c0v[4],
r1 = c1[1], r1v = c1v[1],
g1 = c1[2], g1v = c1v[2],
b1 = c1[3], b1v = c1v[3],
a1 = c1[4], a1v = c1v[4],
startParticleSize = t.size,
startParticleSizeVariance = t.sizeVar,
finishParticleSize = t.size1,
finishParticleSizeVariance = 0, --TODO:?
rot0 = t.rot0,
rot0Variance = t.rot0Var,
rot1 = t.rot1,
rot1Variance = t.rot1Var,
radAcc = t.accRadial * accScale,
radAccVariance = t.accRadialVar * accScale,
tanAcc = t.accTan * accScale,
tanAccVariance = t.accTanVar * accScale,
hasRadAcc = tostring(hasRadAcc),
hasTanAcc = tostring(hasTanAcc),
srcX = 0,--t.sourcePosition.x,
srcXVariance = t.emitSize[1],
srcY = 0,--t.sourcePosition.y,
srcYVariance = t.emitSize[2],
--RADIAL EMITTER
--TODO
rps = 0 * math.pi/180 * timeScale, --TODO
rpsVariance = 0 * math.pi/180 * timeScale, --TODO
minRadius = 0,
maxRadius = 0,
maxRadiusVariance = 0,
}
-- if t.blendFuncSource == 1 then dataInit.a1 = 1 dataInit.a0 = 1 end
local init = string.gsub(
templateInitScript,
"%$(%w+)",
dataInit
)
local function checkColorEase( data, field )
local r0 = data[ field..'0' ]
local r0v = data[ field..'0v' ]
local r1 = data[ field..'1' ]
local r1v = data[ field..'1v' ]
return tostring( not( r0==r1 and r0v==0 and r1v==0 ) )
end
local gx,gy = self:getGravity()
local dataRender={
emitterType = emitterType,
gravityX = gx * accScale, --TODO
gravityY = gy * accScale, --TODO
hasRadAcc = tostring( hasRadAcc ),
hasTanAcc = tostring( hasTanAcc ),
easeR = checkColorEase( dataInit, 'r' ),
easeG = checkColorEase( dataInit, 'g' ),
easeB = checkColorEase( dataInit, 'b' ),
easeA = checkColorEase( dataInit, 'a' ),
r0 = c0[1],
g0 = c0[2],
b0 = c0[3],
a0 = c0[4],
}
local render = string.gsub(
templateRenderScript,
"%$(%w+)",
dataRender
)
-- print( init )
-- print( render )
return init, render
end
--------------------------------------------------------------------
function EffectNodeSimpleParticleSystem:buildSystemConfig()
end
--------------------------------------------------------------------
function EffectNodeSimpleParticleSystem:getSystemConfig()
if self.systemConfig then return self.systemConfig end
return self:buildSystemConfig()
end
--------------------------------------------------------------------
function EffectNodeSimpleParticleSystem:onBuild()
if not self.childrenNodesAdded then
--find previous created
for i, child in ipairs( self.children ) do
local cname = child:getClassName()
if cname == "EffectNodeParticleTimedEmitter" then
self._emitterNode = child
elseif cname == "EffectNodeParticleState" then
self._stateNode = child
end
end
if not self._stateNode then
self._stateNode = self:addChild( EffectNodeParticleState() )
end
if not self._emitterNode then
self._emitterNode = self:addChild( EffectNodeParticleTimedEmitter() )
end
self._stateNode._hidden = true
self._emitterNode._hidden = true
self.childrenNodesAdded = true
end
--state
local init, render = self:buildStateScript()
local script =
"function init()\n".. init .."\nend\n"
..
"function render()\n".. render .."\nend\n"
self._stateNode.script = script
self._stateNode:setLife( self.life - self.lifeVar, self.life + self.lifeVar )
--emitter
local w, h = self:getEmitSize()
self._emitterNode:setEmission( self.emission, self.emission )
self._emitterNode:setMagnitude( self.speed - self.speedVar, self.speed + self.speedVar )
self._emitterNode:setAngle( self.angle - self.angleVar, self.angle + self.angleVar )
self._emitterNode:setRect( w, h )
self._emitterNode:setFrequency( self.frequency, self.frequency )
end
registerTopEffectNodeType(
'simple-particle-system',
EffectNodeSimpleParticleSystem
)
| mit |
rpetit3/darkstar | scripts/globals/items/heat_rod.lua | 41 | 1097 | -----------------------------------------
-- ID: 17071
-- Item: Heat Rod
-- Additional Effect: Lightning Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(5,20);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_LIGHTNING, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHTNING,0);
dmg = adjustForTarget(target,dmg,ELE_LIGHTNING);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHTNING,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_LIGHTNING_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
rpetit3/darkstar | scripts/zones/Cape_Teriggan/npcs/Dultwa_IM.lua | 13 | 3303 | -----------------------------------
-- Area: Cape Teriggan
-- NPC: Dulwa, I.M.
-- Type: Border Conquest Guards
-- @pos 119 0 282 113
-----------------------------------
package.loaded["scripts/zones/Cape_Teriggan/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Cape_Teriggan/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = VOLLBOW;
local csid = 0x7ff8;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
sys4-fr/server-minetestforfun | mods/throwing/fire_arrow.lua | 6 | 4283 | minetest.register_craftitem("throwing:arrow_fire", {
description = "Fire Arrow",
inventory_image = "throwing_arrow_fire.png",
})
minetest.register_node("throwing:arrow_fire_box", {
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
-- Shaft
{-6.5/17, -1.5/17, -1.5/17, 6.5/17, 1.5/17, 1.5/17},
--Spitze
{-4.5/17, 2.5/17, 2.5/17, -3.5/17, -2.5/17, -2.5/17},
{-8.5/17, 0.5/17, 0.5/17, -6.5/17, -0.5/17, -0.5/17},
--Federn
{6.5/17, 1.5/17, 1.5/17, 7.5/17, 2.5/17, 2.5/17},
{7.5/17, -2.5/17, 2.5/17, 6.5/17, -1.5/17, 1.5/17},
{7.5/17, 2.5/17, -2.5/17, 6.5/17, 1.5/17, -1.5/17},
{6.5/17, -1.5/17, -1.5/17, 7.5/17, -2.5/17, -2.5/17},
{7.5/17, 2.5/17, 2.5/17, 8.5/17, 3.5/17, 3.5/17},
{8.5/17, -3.5/17, 3.5/17, 7.5/17, -2.5/17, 2.5/17},
{8.5/17, 3.5/17, -3.5/17, 7.5/17, 2.5/17, -2.5/17},
{7.5/17, -2.5/17, -2.5/17, 8.5/17, -3.5/17, -3.5/17},
}
},
tiles = {"throwing_arrow_fire.png", "throwing_arrow_fire.png", "throwing_arrow_fire_back.png", "throwing_arrow_fire_front.png", "throwing_arrow_fire_2.png", "throwing_arrow_fire.png"},
groups = {not_in_creative_inventory=1},
})
local THROWING_ARROW_ENTITY={
physical = false,
visual = "wielditem",
visual_size = {x=0.1, y=0.1},
textures = {"throwing:arrow_fire_box"},
lastpos={},
collisionbox = {0,0,0,0,0,0},
player = "",
bow_damage = 0,
}
THROWING_ARROW_ENTITY.on_step = function(self, dtime)
local newpos = self.object:getpos()
if self.lastpos.x ~= nil then
for _, pos in pairs(throwing_get_trajectoire(self, newpos)) do
local node = minetest.get_node(pos)
local objs = minetest.get_objects_inside_radius({x=pos.x,y=pos.y,z=pos.z}, 2)
for k, obj in pairs(objs) do
local objpos = obj:getpos()
if throwing_is_player(self.player, obj) or throwing_is_entity(obj) then
if throwing_touch(pos, objpos) then
local puncher = self.object
if self.player and minetest.get_player_by_name(self.player) then
puncher = minetest.get_player_by_name(self.player)
end
local damage = 4
if self.bow_damage and self.bow_damage > 0 then
damage = damage + (self.bow_damage/12)
end
obj:punch(puncher, 1.0, {
full_punch_interval=1.0,
damage_groups={fleshy=damage},
}, nil)
if math.random(0,100) % 2 == 0 then -- 50% of chance to drop //MFF (Mg|07/27/15)
minetest.add_item(pos, 'default:stick')
end
self.object:remove()
return
end
end
end
if node.name ~= "air"
and node.name ~= "throwing:light"
and node.name ~= "fire:basic_flame"
and not (string.find(node.name, 'grass') and not string.find(node.name, 'dirt'))
and not (string.find(node.name, 'farming:') and not string.find(node.name, 'soil'))
and not string.find(node.name, 'flowers:')
and not string.find(node.name, 'fire:') then
if node.name ~= "ignore" then
minetest.set_node(self.lastpos, {name="fire:basic_flame"})
end
self.object:remove()
return
end
if minetest.get_node(pos).name == "air" then
minetest.set_node(pos, {name="throwing:light"})
end
if minetest.get_node(self.lastpos).name == "throwing:light" then
minetest.remove_node(self.lastpos)
end
self.lastpos={x=pos.x, y=pos.y, z=pos.z}
end
end
self.lastpos={x=newpos.x, y=newpos.y, z=newpos.z}
end
minetest.register_entity("throwing:arrow_fire_entity", THROWING_ARROW_ENTITY)
minetest.register_node("throwing:light", {
drawtype = "airlike",
paramtype = "light",
sunlight_propagates = true,
tiles = {"throwing_empty.png"},
light_source = default.LIGHT_MAX-4,
selection_box = {
type = "fixed",
fixed = {
{0,0,0,0,0,0}
}
},
groups = {not_in_creative_inventory=1}
})
minetest.register_abm({
nodenames = {"throwing:light"},
interval = 10,
chance = 1,
action = function(pos, node)
minetest.remove_node(pos)
end
})
minetest.register_craft({
output = 'throwing:arrow_fire 4',
recipe = {
{'default:stick', 'default:stick', 'bucket:bucket_lava'},
},
replacements = {
{"bucket:bucket_lava", "bucket:bucket_empty"}
}
})
minetest.register_craft({
output = 'throwing:arrow_fire 4',
recipe = {
{'bucket:bucket_lava', 'default:stick', 'default:stick'},
},
replacements = {
{"bucket:bucket_lava", "bucket:bucket_empty"}
}
})
| unlicense |
nokizorque/ucd | UCDdamage/crimes.lua | 1 | 1439 | local spam = {}
local police = Team.getFromName("Law")
local admins = Team.getFromName("Admins")
function crime(attacker, killer, _, loss)
local criminal
if (not exports.UCDmafiaWars:isElementInLV(source)) then
if (isElement(attacker)) then
if (attacker.type == "player") then
if (attacker.team ~= police and source.team == police) then
criminal = attacker
end
elseif (attacker.type == "vehicle") then
if (attacker.occupant and attacker.occupant.team ~= police and source.team == police) then
criminal = attacker.occupant
end
end
elseif (isElement(killer)) then
if (killer.type == "player") then
if killer.team ~= police and source.team == police then
criminal = killer
end
elseif (killer.type == "vehicle") then
if (killer.occupant and killer.occupant.team ~= police and source.team == police) then
criminal = killer.occupant
end
end
end
if (criminal and criminal.team ~= admins) then
if (eventName == "onPlayerWasted") then
exports.UCDwanted:addWantedPoints(criminal, 30)
else
if (not spam[criminal] or spam[criminal] and getTickCount() - spam[criminal] > 5000) then
loss = (loss < 5 and 5) or math.ceil(loss / 3)
exports.UCDwanted:addWantedPoints(criminal, loss)
spam[criminal] = getTickCount()
end
end
end
end
end
addEventHandler("onPlayerDamage", root, crime)
addEventHandler("onPlayerWasted", root, crime)
| mit |
Easimer/ld33 | background.lua | 1 | 1094 | require "assets"
background = {}
background._image = nil
background.__mdraw = true --manual draw
background._nophysics = true --no collision
background.parallax = {
left = false,
right = false,
up = false,
down = false
}
function background.load(self)
self._image = assets.load_image("data/background.png")
end
function background.draw(self)
local drawx, drawy
drawx = -768 + game.player.vel.x
drawy = -576 + game.player.vel.y
love.graphics.draw(self._image, drawx, drawy)
end
function background.update(self, dt)
end
function background.keypressed(self, key)
if key == "w" then
self.parallax.down = true
end
if key == "s" then
self.parallax.up = true
end
if key == "a" then
self.parallax.right = true
end
if key == "d" then
self.parallax.left = true
end
end
function background.keyreleased(self, key)
if key == "w" then
self.parallax.down = false
end
if key == "s" then
self.parallax.up = false
end
if key == "a" then
self.parallax.right = false
end
if key == "d" then
self.parallax.left = false
end
end
| mit |
rpetit3/darkstar | scripts/zones/Leujaoam_Sanctum/instances/leujaoam_cleansing.lua | 28 | 2422 | -----------------------------------
--
-- Assault: Leujaoam Cleansing
--
-----------------------------------
require("scripts/globals/instance")
local Leujaoam = require("scripts/zones/Leujaoam_Sanctum/IDs");
-----------------------------------
-- afterInstanceRegister
-----------------------------------
function afterInstanceRegister(player)
local instance = player:getInstance();
player:messageSpecial(Leujaoam.text.ASSAULT_01_START, 1);
player:messageSpecial(Leujaoam.text.TIME_TO_COMPLETE, instance:getTimeLimit());
end;
-----------------------------------
-- onInstanceCreated
-----------------------------------
function onInstanceCreated(instance)
for i,v in pairs(Leujaoam.mobs[1]) do
SpawnMob(v, instance);
end
local rune = instance:getEntity(bit.band(Leujaoam.npcs.RUNE_OF_RELEASE, 0xFFF), TYPE_NPC);
local box = instance:getEntity(bit.band(Leujaoam.npcs.ANCIENT_LOCKBOX, 0xFFF), TYPE_NPC);
rune:setPos(476,8.479,39,49);
box:setPos(476,8.479,40,49);
instance:getEntity(bit.band(Leujaoam.npcs._1XN, 0xFFF), TYPE_NPC):setAnimation(8);
end;
-----------------------------------
-- onInstanceTimeUpdate
-----------------------------------
function onInstanceTimeUpdate(instance, elapsed)
updateInstanceTime(instance, elapsed, Leujaoam.text)
end;
-----------------------------------
-- onInstanceFailure
-----------------------------------
function onInstanceFailure(instance)
local chars = instance:getChars();
for i,v in pairs(chars) do
v:messageSpecial(Leujaoam.text.MISSION_FAILED,10,10);
v:startEvent(0x66);
end
end;
-----------------------------------
-- onInstanceProgressUpdate
-----------------------------------
function onInstanceProgressUpdate(instance, progress)
if (progress >= 15) then
instance:complete();
end
end;
-----------------------------------
-- onInstanceComplete
-----------------------------------
function onInstanceComplete(instance)
local chars = instance:getChars();
for i,v in pairs(chars) do
v:messageSpecial(Leujaoam.text.RUNE_UNLOCKED_POS, 8, 8);
end
local rune = instance:getEntity(bit.band(Leujaoam.npcs.RUNE_OF_RELEASE, 0xFFF), TYPE_NPC);
local box = instance:getEntity(bit.band(Leujaoam.npcs.ANCIENT_LOCKBOX, 0xFFF), TYPE_NPC);
rune:setStatus(STATUS_NORMAL);
box:setStatus(STATUS_NORMAL);
end;
| gpl-3.0 |
sys4-fr/server-minetestforfun | mods/snow/src/mapgen_v7.lua | 12 | 3183 | minetest.register_biome({
name = "snow_biome_default",
node_top = "default:dirt_with_snow",
depth_top = 1,
node_filler = "default:dirt",
depth_filler = 2,
height_min = snow.min_height,
height_max = snow.min_height+60,
heat_point = 10.0,
humidity_point = 40.0,
})
minetest.register_biome({
name = "snow_biome_forest",
node_top = "default:dirt_with_snow",
depth_top = 1,
node_filler = "default:dirt",
depth_filler = 2,
height_min = snow.min_height,
height_max = snow.min_height+60,
heat_point = 10.0,
humidity_point = 55.0,
})
minetest.register_biome({
name = "snow_biome_lush",
node_top = "default:dirt_with_snow",
depth_top = 1,
node_filler = "default:dirt",
depth_filler = 2,
height_min = snow.min_height,
height_max = snow.min_height+60,
heat_point = 10.0,
humidity_point = 70.0,
})
minetest.register_biome({
name = "snow_biome_alpine",
node_top = "default:stone",
depth_top = 1,
node_filler = "default:stone",
height_min = snow.min_height+60,
height_max = 31000,
heat_point = 10.0,
humidity_point = 40.0,
})
minetest.register_biome({
name = "snow_biome_sand",
node_top = "default:sand",
depth_top = 3,
node_filler = "default:stone",
depth_filler = 0,
height_min = -31000,
height_max = 2,
heat_point = 10.0,
humidity_point = 40.0,
})
--Pine tree.
minetest.register_decoration({
deco_type = "schematic",
place_on = "default:dirt_with_snow",
sidelen = 16,
fill_ratio = 0.005,
biomes = {"snow_biome_default"},
schematic = minetest.get_modpath("snow").."/schematics/pine.mts",
flags = "place_center_x, place_center_z",
})
minetest.register_decoration({
deco_type = "schematic",
place_on = "default:dirt_with_snow",
sidelen = 16,
fill_ratio = 0.05,
biomes = {"snow_biome_forest"},
schematic = minetest.get_modpath("snow").."/schematics/pine.mts",
flags = "place_center_x, place_center_z",
})
minetest.register_decoration({
deco_type = "schematic",
place_on = "default:dirt_with_snow",
sidelen = 16,
fill_ratio = 0.1,
biomes = {"snow_biome_lush"},
schematic = minetest.get_modpath("snow").."/schematics/pine.mts",
flags = "place_center_x, place_center_z",
})
--Dry shrubs.
minetest.register_decoration({
deco_type = "simple",
place_on = "default:dirt_with_snow",
sidelen = 16,
fill_ratio = 0.005,
biomes = {"snow_biome_default"},
decoration = "default:dry_shrub",
})
minetest.register_decoration({
deco_type = "simple",
place_on = "default:dirt_with_snow",
sidelen = 16,
fill_ratio = 0.05,
biomes = {"snow_biome_forest", "snow_biome_lush"},
decoration = "default:dry_shrub",
})
--Snow.
minetest.register_decoration({
deco_type = "simple",
place_on = "default:dirt_with_snow",
sidelen = 16,
fill_ratio = 10,
biomes = {"snow_biome_default", "snow_biome_forest", "snow_biome_lush"},
decoration = "default:snow",
})
minetest.register_decoration({
deco_type = "simple",
place_on = "default:stone",
sidelen = 16,
fill_ratio = 10,
biomes = {"snow_biome_alpine"},
decoration = "default:snow",
})
| unlicense |
Marnador/OpenRA-Marn-TS-Edition | mods/cnc/maps/nod06b/nod06b.lua | 25 | 7008 | NodUnitsVehicle1 = { 'bggy', 'bggy', 'bike', 'bike', 'bike' }
NodUnitsVehicle2 = { 'ltnk', 'ltnk', 'ltnk' }
NodUnitsGunner = { 'e1', 'e1', 'e1', 'e1', 'e1', 'e1' }
NodUnitsRocket = { 'e3', 'e3', 'e3', 'e3', 'e3', 'e3' }
Gdi1Units = { 'e1', 'e1', 'e2', 'e2', 'e2' }
HuntCellTriggerActivator = { CPos.New(61,34), CPos.New(60,34), CPos.New(59,34), CPos.New(58,34), CPos.New(57,34), CPos.New(56,34), CPos.New(55,34), CPos.New(61,33), CPos.New(60,33), CPos.New(59,33), CPos.New(58,33), CPos.New(57,33), CPos.New(56,33) }
DzneCellTriggerActivator = { CPos.New(50,30), CPos.New(49,30), CPos.New(48,30), CPos.New(47,30), CPos.New(46,30), CPos.New(45,30), CPos.New(50,29), CPos.New(49,29), CPos.New(48,29), CPos.New(47,29), CPos.New(46,29), CPos.New(45,29), CPos.New(50,28), CPos.New(49,28), CPos.New(48,28), CPos.New(47,28), CPos.New(46,28), CPos.New(45,28), CPos.New(50,27), CPos.New(49,27), CPos.New(46,27), CPos.New(45,27), CPos.New(50,26), CPos.New(49,26), CPos.New(48,26), CPos.New(47,26), CPos.New(46,26), CPos.New(45,26), CPos.New(50,25), CPos.New(49,25), CPos.New(48,25), CPos.New(47,25), CPos.New(46,25), CPos.New(45,25) }
Win1CellTriggerActivator = { CPos.New(47,27) }
Win2CellTriggerActivator = { CPos.New(57,57), CPos.New(56,57), CPos.New(55,57), CPos.New(57,56), CPos.New(56,56), CPos.New(55,56), CPos.New(57,55), CPos.New(56,55), CPos.New(55,55), CPos.New(57,54), CPos.New(56,54), CPos.New(55,54), CPos.New(57,53), CPos.New(56,53), CPos.New(55,53), CPos.New(57,52), CPos.New(56,52), CPos.New(55,52) }
ChnCellTriggerActivator = { CPos.New(61,52), CPos.New(60,52), CPos.New(59,52), CPos.New(58,52), CPos.New(61,51), CPos.New(60,51), CPos.New(59,51), CPos.New(58,51), CPos.New(61,50), CPos.New(60,50), CPos.New(59,50), CPos.New(58,50) }
Chn1ActorTriggerActivator = { Chn1Actor1, Chn1Actor2 }
Chn2ActorTriggerActivator = { Chn2Actor1 }
Atk1ActorTriggerActivator = { Atk1Actor1, Atk1Actor2 }
Atk2ActorTriggerActivator = { Atk2Actor1, Atk2Actor2 }
Chn1Waypoints = { ChnEntry.Location, waypoint0.Location }
Chn2Waypoints = { ChnEntry.Location, waypoint0.Location }
Gdi5Waypoint = { waypoint1, waypoint2, waypoint3, waypoint4, waypoint5, waypoint6, waypoint7 }
HuntTriggerFunction = function()
local list = enemy.GetGroundAttackers()
Utils.Do(list, function(unit)
IdleHunt(unit)
end)
end
Win1TriggerFunction = function()
NodObjective2 = player.AddPrimaryObjective("Move to the evacuation point.")
player.MarkCompletedObjective(NodObjective1)
end
Chn1TriggerFunction = function()
if not Chn1Switch then
local cargo = Reinforcements.ReinforceWithTransport(enemy, 'tran', Gdi1Units, Chn1Waypoints, { ChnEntry.Location })[2]
Utils.Do(cargo, function(actor)
IdleHunt(actor)
end)
Chn1Switch = true
end
end
Atk1TriggerFunction = function()
if not Atk1Switch then
for type, count in pairs({ ['e2'] = 2, ['jeep'] = 1, ['e1'] = 2}) do
MyActors = Utils.Take(count, enemy.GetActorsByType(type))
Utils.Do(MyActors, function(actor)
IdleHunt(actor)
end)
end
Atk1Switch = true
end
end
Atk2TriggerFunction = function()
if not Atk2Switch then
for type, count in pairs({ ['e2'] = 2, ['e1'] = 2}) do
MyActors = Utils.Take(count, enemy.GetActorsByType(type))
Utils.Do(MyActors, function(actor)
MoveAndHunt(actor, Gdi5Waypoint)
end)
end
Atk2Switch = true
end
end
Chn2TriggerFunction = function()
if not Chn2Switch then
local cargo = Reinforcements.ReinforceWithTransport(enemy, 'tran', Gdi1Units, Chn2Waypoints, { ChnEntry.Location })[2]
Utils.Do(cargo, function(actor)
IdleHunt(actor)
end)
Chn2Switch = true
end
end
MoveAndHunt = function(unit, waypoints)
if unit ~= nil then
Utils.Do(waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
IdleHunt(unit)
end
end
InsertNodUnits = function()
Media.PlaySpeechNotification(player, "Reinforce")
Camera.Position = UnitsRallyVehicle2.CenterPosition
Reinforcements.Reinforce(player, NodUnitsVehicle1, { UnitsEntryVehicle.Location, UnitsRallyVehicle1.Location }, 10)
Reinforcements.Reinforce(player, NodUnitsVehicle2, { UnitsEntryVehicle.Location, UnitsRallyVehicle2.Location }, 15)
Reinforcements.Reinforce(player, NodUnitsGunner, { UnitsEntryGunner.Location, UnitsRallyGunner.Location }, 15)
Reinforcements.Reinforce(player, NodUnitsRocket, { UnitsEntryRocket.Location, UnitsRallyRocket.Location }, 25)
end
WorldLoaded = function()
player = Player.GetPlayer("Nod")
enemy = Player.GetPlayer("GDI")
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "Win")
end)
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "Lose")
end)
NodObjective1 = player.AddPrimaryObjective("Steal the GDI nuclear detonator.")
GDIObjective = enemy.AddPrimaryObjective("Stop the Nod taskforce from escaping with the detonator.")
InsertNodUnits()
Trigger.OnEnteredFootprint(HuntCellTriggerActivator, function(a, id)
if a.Owner == player then
HuntTriggerFunction()
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnEnteredFootprint(DzneCellTriggerActivator, function(a, id)
if a.Owner == player then
Actor.Create('flare', true, { Owner = player, Location = waypoint17.Location })
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnEnteredFootprint(Win1CellTriggerActivator, function(a, id)
if a.Owner == player then
Win1TriggerFunction()
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnEnteredFootprint(Win2CellTriggerActivator, function(a, id)
if a.Owner == player and NodObjective2 then
player.MarkCompletedObjective(NodObjective2)
Trigger.RemoveFootprintTrigger(id)
end
end)
OnAnyDamaged(Chn1ActorTriggerActivator, Chn1TriggerFunction)
OnAnyDamaged(Atk1ActorTriggerActivator, Atk1TriggerFunction)
OnAnyDamaged(Atk2ActorTriggerActivator, Atk2TriggerFunction)
OnAnyDamaged(Chn2ActorTriggerActivator, Chn2TriggerFunction)
Trigger.OnEnteredFootprint(ChnCellTriggerActivator, function(a, id)
if a.Owner == player then
Media.PlaySpeechNotification(player, "Reinforce")
Reinforcements.ReinforceWithTransport(player, 'tran', nil, { ChnEntry.Location, waypoint17.Location }, nil, nil, nil)
Trigger.RemoveFootprintTrigger(id)
end
end)
end
Tick = function()
if player.HasNoRequiredUnits() then
if DateTime.GameTime > 2 then
enemy.MarkCompletedObjective(GDIObjective)
end
end
end
IdleHunt = function(unit)
if not unit.IsDead then
Trigger.OnIdle(unit, unit.Hunt)
end
end
OnAnyDamaged = function(actors, func)
Utils.Do(actors, function(actor)
Trigger.OnDamaged(actor, func)
end)
end
| gpl-3.0 |
tenvick/hugula | Client/tools/luaTools/jit21/jit/dis_x86.lua | 61 | 29376 | ----------------------------------------------------------------------------
-- LuaJIT x86/x64 disassembler module.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
-- This is a helper module used by the LuaJIT machine code dumper module.
--
-- Sending small code snippets to an external disassembler and mixing the
-- output with our own stuff was too fragile. So I had to bite the bullet
-- and write yet another x86 disassembler. Oh well ...
--
-- The output format is very similar to what ndisasm generates. But it has
-- been developed independently by looking at the opcode tables from the
-- Intel and AMD manuals. The supported instruction set is quite extensive
-- and reflects what a current generation Intel or AMD CPU implements in
-- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3,
-- SSE4.1, SSE4.2, SSE4a and even privileged and hypervisor (VMX/SVM)
-- instructions.
--
-- Notes:
-- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported.
-- * No attempt at optimization has been made -- it's fast enough for my needs.
-- * The public API may change when more architectures are added.
------------------------------------------------------------------------------
local type = type
local sub, byte, format = string.sub, string.byte, string.format
local match, gmatch, gsub = string.match, string.gmatch, string.gsub
local lower, rep = string.lower, string.rep
local bit = require("bit")
local tohex = bit.tohex
-- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on.
local map_opc1_32 = {
--0x
[0]="addBmr","addVmr","addBrm","addVrm","addBai","addVai","push es","pop es",
"orBmr","orVmr","orBrm","orVrm","orBai","orVai","push cs","opc2*",
--1x
"adcBmr","adcVmr","adcBrm","adcVrm","adcBai","adcVai","push ss","pop ss",
"sbbBmr","sbbVmr","sbbBrm","sbbVrm","sbbBai","sbbVai","push ds","pop ds",
--2x
"andBmr","andVmr","andBrm","andVrm","andBai","andVai","es:seg","daa",
"subBmr","subVmr","subBrm","subVrm","subBai","subVai","cs:seg","das",
--3x
"xorBmr","xorVmr","xorBrm","xorVrm","xorBai","xorVai","ss:seg","aaa",
"cmpBmr","cmpVmr","cmpBrm","cmpVrm","cmpBai","cmpVai","ds:seg","aas",
--4x
"incVR","incVR","incVR","incVR","incVR","incVR","incVR","incVR",
"decVR","decVR","decVR","decVR","decVR","decVR","decVR","decVR",
--5x
"pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR",
"popUR","popUR","popUR","popUR","popUR","popUR","popUR","popUR",
--6x
"sz*pushaw,pusha","sz*popaw,popa","boundVrm","arplWmr",
"fs:seg","gs:seg","o16:","a16",
"pushUi","imulVrmi","pushBs","imulVrms",
"insb","insVS","outsb","outsVS",
--7x
"joBj","jnoBj","jbBj","jnbBj","jzBj","jnzBj","jbeBj","jaBj",
"jsBj","jnsBj","jpeBj","jpoBj","jlBj","jgeBj","jleBj","jgBj",
--8x
"arith!Bmi","arith!Vmi","arith!Bmi","arith!Vms",
"testBmr","testVmr","xchgBrm","xchgVrm",
"movBmr","movVmr","movBrm","movVrm",
"movVmg","leaVrm","movWgm","popUm",
--9x
"nop*xchgVaR|pause|xchgWaR|repne nop","xchgVaR","xchgVaR","xchgVaR",
"xchgVaR","xchgVaR","xchgVaR","xchgVaR",
"sz*cbw,cwde,cdqe","sz*cwd,cdq,cqo","call farViw","wait",
"sz*pushfw,pushf","sz*popfw,popf","sahf","lahf",
--Ax
"movBao","movVao","movBoa","movVoa",
"movsb","movsVS","cmpsb","cmpsVS",
"testBai","testVai","stosb","stosVS",
"lodsb","lodsVS","scasb","scasVS",
--Bx
"movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi",
"movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI",
--Cx
"shift!Bmu","shift!Vmu","retBw","ret","$lesVrm","$ldsVrm","movBmi","movVmi",
"enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS",
--Dx
"shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb",
"fp*0","fp*1","fp*2","fp*3","fp*4","fp*5","fp*6","fp*7",
--Ex
"loopneBj","loopeBj","loopBj","sz*jcxzBj,jecxzBj,jrcxzBj",
"inBau","inVau","outBua","outVua",
"callVj","jmpVj","jmp farViw","jmpBj","inBad","inVad","outBda","outVda",
--Fx
"lock:","int1","repne:rep","rep:","hlt","cmc","testb!Bm","testv!Vm",
"clc","stc","cli","sti","cld","std","incb!Bm","incd!Vm",
}
assert(#map_opc1_32 == 255)
-- Map for 1st opcode byte in 64 bit mode (overrides only).
local map_opc1_64 = setmetatable({
[0x06]=false, [0x07]=false, [0x0e]=false,
[0x16]=false, [0x17]=false, [0x1e]=false, [0x1f]=false,
[0x27]=false, [0x2f]=false, [0x37]=false, [0x3f]=false,
[0x60]=false, [0x61]=false, [0x62]=false, [0x63]="movsxdVrDmt", [0x67]="a32:",
[0x40]="rex*", [0x41]="rex*b", [0x42]="rex*x", [0x43]="rex*xb",
[0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb",
[0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb",
[0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb",
[0x82]=false, [0x9a]=false, [0xc4]=false, [0xc5]=false, [0xce]=false,
[0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false,
}, { __index = map_opc1_32 })
-- Map for 2nd opcode byte (0F xx). True CISC hell. Hey, I told you.
-- Prefix dependent MMX/SSE opcodes: (none)|rep|o16|repne, -|F3|66|F2
local map_opc2 = {
--0x
[0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret",
"invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu",
--1x
"movupsXrm|movssXrm|movupdXrm|movsdXrm",
"movupsXmr|movssXmr|movupdXmr|movsdXmr",
"movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm",
"movlpsXmr||movlpdXmr",
"unpcklpsXrm||unpcklpdXrm",
"unpckhpsXrm||unpckhpdXrm",
"movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm",
"movhpsXmr||movhpdXmr",
"$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm",
"hintnopVm","hintnopVm","hintnopVm","hintnopVm",
--2x
"movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil,
"movapsXrm||movapdXrm",
"movapsXmr||movapdXmr",
"cvtpi2psXrMm|cvtsi2ssXrVmt|cvtpi2pdXrMm|cvtsi2sdXrVmt",
"movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr",
"cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm",
"cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm",
"ucomissXrm||ucomisdXrm",
"comissXrm||comisdXrm",
--3x
"wrmsr","rdtsc","rdmsr","rdpmc","sysenter","sysexit",nil,"getsec",
"opc3*38",nil,"opc3*3a",nil,nil,nil,nil,nil,
--4x
"cmovoVrm","cmovnoVrm","cmovbVrm","cmovnbVrm",
"cmovzVrm","cmovnzVrm","cmovbeVrm","cmovaVrm",
"cmovsVrm","cmovnsVrm","cmovpeVrm","cmovpoVrm",
"cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm",
--5x
"movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm",
"rsqrtpsXrm|rsqrtssXrm","rcppsXrm|rcpssXrm",
"andpsXrm||andpdXrm","andnpsXrm||andnpdXrm",
"orpsXrm||orpdXrm","xorpsXrm||xorpdXrm",
"addpsXrm|addssXrm|addpdXrm|addsdXrm","mulpsXrm|mulssXrm|mulpdXrm|mulsdXrm",
"cvtps2pdXrm|cvtss2sdXrm|cvtpd2psXrm|cvtsd2ssXrm",
"cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm",
"subpsXrm|subssXrm|subpdXrm|subsdXrm","minpsXrm|minssXrm|minpdXrm|minsdXrm",
"divpsXrm|divssXrm|divpdXrm|divsdXrm","maxpsXrm|maxssXrm|maxpdXrm|maxsdXrm",
--6x
"punpcklbwPrm","punpcklwdPrm","punpckldqPrm","packsswbPrm",
"pcmpgtbPrm","pcmpgtwPrm","pcmpgtdPrm","packuswbPrm",
"punpckhbwPrm","punpckhwdPrm","punpckhdqPrm","packssdwPrm",
"||punpcklqdqXrm","||punpckhqdqXrm",
"movPrVSm","movqMrm|movdquXrm|movdqaXrm",
--7x
"pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pmu",
"pshiftd!Pmu","pshiftq!Mmu||pshiftdq!Xmu",
"pcmpeqbPrm","pcmpeqwPrm","pcmpeqdPrm","emms|",
"vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$",
nil,nil,
"||haddpdXrm|haddpsXrm","||hsubpdXrm|hsubpsXrm",
"movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr",
--8x
"joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj",
"jsVj","jnsVj","jpeVj","jpoVj","jlVj","jgeVj","jleVj","jgVj",
--9x
"setoBm","setnoBm","setbBm","setnbBm","setzBm","setnzBm","setbeBm","setaBm",
"setsBm","setnsBm","setpeBm","setpoBm","setlBm","setgeBm","setleBm","setgBm",
--Ax
"push fs","pop fs","cpuid","btVmr","shldVmru","shldVmrc",nil,nil,
"push gs","pop gs","rsm","btsVmr","shrdVmru","shrdVmrc","fxsave!Dmp","imulVrm",
--Bx
"cmpxchgBmr","cmpxchgVmr","$lssVrm","btrVmr",
"$lfsVrm","$lgsVrm","movzxVrBmt","movzxVrWmt",
"|popcntVrm","ud2Dp","bt!Vmu","btcVmr",
"bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt",
--Cx
"xaddBmr","xaddVmr",
"cmppsXrmu|cmpssXrmu|cmppdXrmu|cmpsdXrmu","$movntiVmr|",
"pinsrwPrWmu","pextrwDrPmu",
"shufpsXrmu||shufpdXrmu","$cmpxchg!Qmp",
"bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR",
--Dx
"||addsubpdXrm|addsubpsXrm","psrlwPrm","psrldPrm","psrlqPrm",
"paddqPrm","pmullwPrm",
"|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm",
"psubusbPrm","psubuswPrm","pminubPrm","pandPrm",
"paddusbPrm","padduswPrm","pmaxubPrm","pandnPrm",
--Ex
"pavgbPrm","psrawPrm","psradPrm","pavgwPrm",
"pmulhuwPrm","pmulhwPrm",
"|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr",
"psubsbPrm","psubswPrm","pminswPrm","porPrm",
"paddsbPrm","paddswPrm","pmaxswPrm","pxorPrm",
--Fx
"|||lddquXrm","psllwPrm","pslldPrm","psllqPrm",
"pmuludqPrm","pmaddwdPrm","psadbwPrm","maskmovqMrm||maskmovdquXrm$",
"psubbPrm","psubwPrm","psubdPrm","psubqPrm",
"paddbPrm","paddwPrm","padddPrm","ud",
}
assert(map_opc2[255] == "ud")
-- Map for three-byte opcodes. Can't wait for their next invention.
local map_opc3 = {
["38"] = { -- [66] 0f 38 xx
--0x
[0]="pshufbPrm","phaddwPrm","phadddPrm","phaddswPrm",
"pmaddubswPrm","phsubwPrm","phsubdPrm","phsubswPrm",
"psignbPrm","psignwPrm","psigndPrm","pmulhrswPrm",
nil,nil,nil,nil,
--1x
"||pblendvbXrma",nil,nil,nil,
"||blendvpsXrma","||blendvpdXrma",nil,"||ptestXrm",
nil,nil,nil,nil,
"pabsbPrm","pabswPrm","pabsdPrm",nil,
--2x
"||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm",
"||pmovsxwqXrm","||pmovsxdqXrm",nil,nil,
"||pmuldqXrm","||pcmpeqqXrm","||$movntdqaXrm","||packusdwXrm",
nil,nil,nil,nil,
--3x
"||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm",
"||pmovzxwqXrm","||pmovzxdqXrm",nil,"||pcmpgtqXrm",
"||pminsbXrm","||pminsdXrm","||pminuwXrm","||pminudXrm",
"||pmaxsbXrm","||pmaxsdXrm","||pmaxuwXrm","||pmaxudXrm",
--4x
"||pmulddXrm","||phminposuwXrm",
--Fx
[0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt",
},
["3a"] = { -- [66] 0f 3a xx
--0x
[0x00]=nil,nil,nil,nil,nil,nil,nil,nil,
"||roundpsXrmu","||roundpdXrmu","||roundssXrmu","||roundsdXrmu",
"||blendpsXrmu","||blendpdXrmu","||pblendwXrmu","palignrPrmu",
--1x
nil,nil,nil,nil,
"||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru",
nil,nil,nil,nil,nil,nil,nil,nil,
--2x
"||pinsrbXrVmu","||insertpsXrmu","||pinsrXrVmuS",nil,
--4x
[0x40] = "||dppsXrmu",
[0x41] = "||dppdXrmu",
[0x42] = "||mpsadbwXrmu",
--6x
[0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu",
[0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu",
},
}
-- Map for VMX/SVM opcodes 0F 01 C0-FF (sgdt group with register operands).
local map_opcvm = {
[0xc1]="vmcall",[0xc2]="vmlaunch",[0xc3]="vmresume",[0xc4]="vmxoff",
[0xc8]="monitor",[0xc9]="mwait",
[0xd8]="vmrun",[0xd9]="vmmcall",[0xda]="vmload",[0xdb]="vmsave",
[0xdc]="stgi",[0xdd]="clgi",[0xde]="skinit",[0xdf]="invlpga",
[0xf8]="swapgs",[0xf9]="rdtscp",
}
-- Map for FP opcodes. And you thought stack machines are simple?
local map_opcfp = {
-- D8-DF 00-BF: opcodes with a memory operand.
-- D8
[0]="faddFm","fmulFm","fcomFm","fcompFm","fsubFm","fsubrFm","fdivFm","fdivrFm",
"fldFm",nil,"fstFm","fstpFm","fldenvVm","fldcwWm","fnstenvVm","fnstcwWm",
-- DA
"fiaddDm","fimulDm","ficomDm","ficompDm",
"fisubDm","fisubrDm","fidivDm","fidivrDm",
-- DB
"fildDm","fisttpDm","fistDm","fistpDm",nil,"fld twordFmp",nil,"fstp twordFmp",
-- DC
"faddGm","fmulGm","fcomGm","fcompGm","fsubGm","fsubrGm","fdivGm","fdivrGm",
-- DD
"fldGm","fisttpQm","fstGm","fstpGm","frstorDmp",nil,"fnsaveDmp","fnstswWm",
-- DE
"fiaddWm","fimulWm","ficomWm","ficompWm",
"fisubWm","fisubrWm","fidivWm","fidivrWm",
-- DF
"fildWm","fisttpWm","fistWm","fistpWm",
"fbld twordFmp","fildQm","fbstp twordFmp","fistpQm",
-- xx C0-FF: opcodes with a pseudo-register operand.
-- D8
"faddFf","fmulFf","fcomFf","fcompFf","fsubFf","fsubrFf","fdivFf","fdivrFf",
-- D9
"fldFf","fxchFf",{"fnop"},nil,
{"fchs","fabs",nil,nil,"ftst","fxam"},
{"fld1","fldl2t","fldl2e","fldpi","fldlg2","fldln2","fldz"},
{"f2xm1","fyl2x","fptan","fpatan","fxtract","fprem1","fdecstp","fincstp"},
{"fprem","fyl2xp1","fsqrt","fsincos","frndint","fscale","fsin","fcos"},
-- DA
"fcmovbFf","fcmoveFf","fcmovbeFf","fcmovuFf",nil,{nil,"fucompp"},nil,nil,
-- DB
"fcmovnbFf","fcmovneFf","fcmovnbeFf","fcmovnuFf",
{nil,nil,"fnclex","fninit"},"fucomiFf","fcomiFf",nil,
-- DC
"fadd toFf","fmul toFf",nil,nil,
"fsub toFf","fsubr toFf","fdivr toFf","fdiv toFf",
-- DD
"ffreeFf",nil,"fstFf","fstpFf","fucomFf","fucompFf",nil,nil,
-- DE
"faddpFf","fmulpFf",nil,{nil,"fcompp"},
"fsubrpFf","fsubpFf","fdivrpFf","fdivpFf",
-- DF
nil,nil,nil,nil,{"fnstsw ax"},"fucomipFf","fcomipFf",nil,
}
assert(map_opcfp[126] == "fcomipFf")
-- Map for opcode groups. The subkey is sp from the ModRM byte.
local map_opcgroup = {
arith = { "add", "or", "adc", "sbb", "and", "sub", "xor", "cmp" },
shift = { "rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar" },
testb = { "testBmi", "testBmi", "not", "neg", "mul", "imul", "div", "idiv" },
testv = { "testVmi", "testVmi", "not", "neg", "mul", "imul", "div", "idiv" },
incb = { "inc", "dec" },
incd = { "inc", "dec", "callUmp", "$call farDmp",
"jmpUmp", "$jmp farDmp", "pushUm" },
sldt = { "sldt", "str", "lldt", "ltr", "verr", "verw" },
sgdt = { "vm*$sgdt", "vm*$sidt", "$lgdt", "vm*$lidt",
"smsw", nil, "lmsw", "vm*$invlpg" },
bt = { nil, nil, nil, nil, "bt", "bts", "btr", "btc" },
cmpxchg = { nil, "sz*,cmpxchg8bQmp,cmpxchg16bXmp", nil, nil,
nil, nil, "vmptrld|vmxon|vmclear", "vmptrst" },
pshiftw = { nil, nil, "psrlw", nil, "psraw", nil, "psllw" },
pshiftd = { nil, nil, "psrld", nil, "psrad", nil, "pslld" },
pshiftq = { nil, nil, "psrlq", nil, nil, nil, "psllq" },
pshiftdq = { nil, nil, "psrlq", "psrldq", nil, nil, "psllq", "pslldq" },
fxsave = { "$fxsave", "$fxrstor", "$ldmxcsr", "$stmxcsr",
nil, "lfenceDp$", "mfenceDp$", "sfenceDp$clflush" },
prefetch = { "prefetch", "prefetchw" },
prefetcht = { "prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2" },
}
------------------------------------------------------------------------------
-- Maps for register names.
local map_regs = {
B = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh",
"r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" },
B64 = { "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil",
"r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" },
W = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di",
"r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w" },
D = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi",
"r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d" },
Q = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" },
M = { "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7",
"mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext!
X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
"xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" },
}
local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" }
-- Maps for size names.
local map_sz2n = {
B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16,
}
local map_sz2prefix = {
B = "byte", W = "word", D = "dword",
Q = "qword",
M = "qword", X = "xword",
F = "dword", G = "qword", -- No need for sizes/register names for these two.
}
------------------------------------------------------------------------------
-- Output a nicely formatted line with an opcode and operands.
local function putop(ctx, text, operands)
local code, pos, hex = ctx.code, ctx.pos, ""
local hmax = ctx.hexdump
if hmax > 0 then
for i=ctx.start,pos-1 do
hex = hex..format("%02X", byte(code, i, i))
end
if #hex > hmax then hex = sub(hex, 1, hmax)..". "
else hex = hex..rep(" ", hmax-#hex+2) end
end
if operands then text = text.." "..operands end
if ctx.o16 then text = "o16 "..text; ctx.o16 = false end
if ctx.a32 then text = "a32 "..text; ctx.a32 = false end
if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end
if ctx.rex then
local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "")..
(ctx.rexx and "x" or "")..(ctx.rexb and "b" or "")
if t ~= "" then text = "rex."..t.." "..text end
ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false
ctx.rex = false
end
if ctx.seg then
local text2, n = gsub(text, "%[", "["..ctx.seg..":")
if n == 0 then text = ctx.seg.." "..text else text = text2 end
ctx.seg = false
end
if ctx.lock then text = "lock "..text; ctx.lock = false end
local imm = ctx.imm
if imm then
local sym = ctx.symtab[imm]
if sym then text = text.."\t->"..sym end
end
ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text))
ctx.mrm = false
ctx.start = pos
ctx.imm = nil
end
-- Clear all prefix flags.
local function clearprefixes(ctx)
ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false
ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false
ctx.rex = false; ctx.a32 = false
end
-- Fallback for incomplete opcodes at the end.
local function incomplete(ctx)
ctx.pos = ctx.stop+1
clearprefixes(ctx)
return putop(ctx, "(incomplete)")
end
-- Fallback for unknown opcodes.
local function unknown(ctx)
clearprefixes(ctx)
return putop(ctx, "(unknown)")
end
-- Return an immediate of the specified size.
local function getimm(ctx, pos, n)
if pos+n-1 > ctx.stop then return incomplete(ctx) end
local code = ctx.code
if n == 1 then
local b1 = byte(code, pos, pos)
return b1
elseif n == 2 then
local b1, b2 = byte(code, pos, pos+1)
return b1+b2*256
else
local b1, b2, b3, b4 = byte(code, pos, pos+3)
local imm = b1+b2*256+b3*65536+b4*16777216
ctx.imm = imm
return imm
end
end
-- Process pattern string and generate the operands.
local function putpat(ctx, name, pat)
local operands, regs, sz, mode, sp, rm, sc, rx, sdisp
local code, pos, stop = ctx.code, ctx.pos, ctx.stop
-- Chars used: 1DFGIMPQRSTUVWXacdfgijmoprstuwxyz
for p in gmatch(pat, ".") do
local x = nil
if p == "V" or p == "U" then
if ctx.rexw then sz = "Q"; ctx.rexw = false
elseif ctx.o16 then sz = "W"; ctx.o16 = false
elseif p == "U" and ctx.x64 then sz = "Q"
else sz = "D" end
regs = map_regs[sz]
elseif p == "T" then
if ctx.rexw then sz = "Q"; ctx.rexw = false else sz = "D" end
regs = map_regs[sz]
elseif p == "B" then
sz = "B"
regs = ctx.rex and map_regs.B64 or map_regs.B
elseif match(p, "[WDQMXFG]") then
sz = p
regs = map_regs[sz]
elseif p == "P" then
sz = ctx.o16 and "X" or "M"; ctx.o16 = false
regs = map_regs[sz]
elseif p == "S" then
name = name..lower(sz)
elseif p == "s" then
local imm = getimm(ctx, pos, 1); if not imm then return end
x = imm <= 127 and format("+0x%02x", imm)
or format("-0x%02x", 256-imm)
pos = pos+1
elseif p == "u" then
local imm = getimm(ctx, pos, 1); if not imm then return end
x = format("0x%02x", imm)
pos = pos+1
elseif p == "w" then
local imm = getimm(ctx, pos, 2); if not imm then return end
x = format("0x%x", imm)
pos = pos+2
elseif p == "o" then -- [offset]
if ctx.x64 then
local imm1 = getimm(ctx, pos, 4); if not imm1 then return end
local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end
x = format("[0x%08x%08x]", imm2, imm1)
pos = pos+8
else
local imm = getimm(ctx, pos, 4); if not imm then return end
x = format("[0x%08x]", imm)
pos = pos+4
end
elseif p == "i" or p == "I" then
local n = map_sz2n[sz]
if n == 8 and ctx.x64 and p == "I" then
local imm1 = getimm(ctx, pos, 4); if not imm1 then return end
local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end
x = format("0x%08x%08x", imm2, imm1)
else
if n == 8 then n = 4 end
local imm = getimm(ctx, pos, n); if not imm then return end
if sz == "Q" and (imm < 0 or imm > 0x7fffffff) then
imm = (0xffffffff+1)-imm
x = format(imm > 65535 and "-0x%08x" or "-0x%x", imm)
else
x = format(imm > 65535 and "0x%08x" or "0x%x", imm)
end
end
pos = pos+n
elseif p == "j" then
local n = map_sz2n[sz]
if n == 8 then n = 4 end
local imm = getimm(ctx, pos, n); if not imm then return end
if sz == "B" and imm > 127 then imm = imm-256
elseif imm > 2147483647 then imm = imm-4294967296 end
pos = pos+n
imm = imm + pos + ctx.addr
if imm > 4294967295 and not ctx.x64 then imm = imm-4294967296 end
ctx.imm = imm
if sz == "W" then
x = format("word 0x%04x", imm%65536)
elseif ctx.x64 then
local lo = imm % 0x1000000
x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo)
else
x = "0x"..tohex(imm)
end
elseif p == "R" then
local r = byte(code, pos-1, pos-1)%8
if ctx.rexb then r = r + 8; ctx.rexb = false end
x = regs[r+1]
elseif p == "a" then x = regs[1]
elseif p == "c" then x = "cl"
elseif p == "d" then x = "dx"
elseif p == "1" then x = "1"
else
if not mode then
mode = ctx.mrm
if not mode then
if pos > stop then return incomplete(ctx) end
mode = byte(code, pos, pos)
pos = pos+1
end
rm = mode%8; mode = (mode-rm)/8
sp = mode%8; mode = (mode-sp)/8
sdisp = ""
if mode < 3 then
if rm == 4 then
if pos > stop then return incomplete(ctx) end
sc = byte(code, pos, pos)
pos = pos+1
rm = sc%8; sc = (sc-rm)/8
rx = sc%8; sc = (sc-rx)/8
if ctx.rexx then rx = rx + 8; ctx.rexx = false end
if rx == 4 then rx = nil end
end
if mode > 0 or rm == 5 then
local dsz = mode
if dsz ~= 1 then dsz = 4 end
local disp = getimm(ctx, pos, dsz); if not disp then return end
if mode == 0 then rm = nil end
if rm or rx or (not sc and ctx.x64 and not ctx.a32) then
if dsz == 1 and disp > 127 then
sdisp = format("-0x%x", 256-disp)
elseif disp >= 0 and disp <= 0x7fffffff then
sdisp = format("+0x%x", disp)
else
sdisp = format("-0x%x", (0xffffffff+1)-disp)
end
else
sdisp = format(ctx.x64 and not ctx.a32 and
not (disp >= 0 and disp <= 0x7fffffff)
and "0xffffffff%08x" or "0x%08x", disp)
end
pos = pos+dsz
end
end
if rm and ctx.rexb then rm = rm + 8; ctx.rexb = false end
if ctx.rexr then sp = sp + 8; ctx.rexr = false end
end
if p == "m" then
if mode == 3 then x = regs[rm+1]
else
local aregs = ctx.a32 and map_regs.D or ctx.aregs
local srm, srx = "", ""
if rm then srm = aregs[rm+1]
elseif not sc and ctx.x64 and not ctx.a32 then srm = "rip" end
ctx.a32 = false
if rx then
if rm then srm = srm.."+" end
srx = aregs[rx+1]
if sc > 0 then srx = srx.."*"..(2^sc) end
end
x = format("[%s%s%s]", srm, srx, sdisp)
end
if mode < 3 and
(not match(pat, "[aRrgp]") or match(pat, "t")) then -- Yuck.
x = map_sz2prefix[sz].." "..x
end
elseif p == "r" then x = regs[sp+1]
elseif p == "g" then x = map_segregs[sp+1]
elseif p == "p" then -- Suppress prefix.
elseif p == "f" then x = "st"..rm
elseif p == "x" then
if sp == 0 and ctx.lock and not ctx.x64 then
x = "CR8"; ctx.lock = false
else
x = "CR"..sp
end
elseif p == "y" then x = "DR"..sp
elseif p == "z" then x = "TR"..sp
elseif p == "t" then
else
error("bad pattern `"..pat.."'")
end
end
if x then operands = operands and operands..", "..x or x end
end
ctx.pos = pos
return putop(ctx, name, operands)
end
-- Forward declaration.
local map_act
-- Fetch and cache MRM byte.
local function getmrm(ctx)
local mrm = ctx.mrm
if not mrm then
local pos = ctx.pos
if pos > ctx.stop then return nil end
mrm = byte(ctx.code, pos, pos)
ctx.pos = pos+1
ctx.mrm = mrm
end
return mrm
end
-- Dispatch to handler depending on pattern.
local function dispatch(ctx, opat, patgrp)
if not opat then return unknown(ctx) end
if match(opat, "%|") then -- MMX/SSE variants depending on prefix.
local p
if ctx.rep then
p = ctx.rep=="rep" and "%|([^%|]*)" or "%|[^%|]*%|[^%|]*%|([^%|]*)"
ctx.rep = false
elseif ctx.o16 then p = "%|[^%|]*%|([^%|]*)"; ctx.o16 = false
else p = "^[^%|]*" end
opat = match(opat, p)
if not opat then return unknown(ctx) end
-- ctx.rep = false; ctx.o16 = false
--XXX fails for 66 f2 0f 38 f1 06 crc32 eax,WORD PTR [esi]
--XXX remove in branches?
end
if match(opat, "%$") then -- reg$mem variants.
local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end
opat = match(opat, mrm >= 192 and "^[^%$]*" or "%$(.*)")
if opat == "" then return unknown(ctx) end
end
if opat == "" then return unknown(ctx) end
local name, pat = match(opat, "^([a-z0-9 ]*)(.*)")
if pat == "" and patgrp then pat = patgrp end
return map_act[sub(pat, 1, 1)](ctx, name, pat)
end
-- Get a pattern from an opcode map and dispatch to handler.
local function dispatchmap(ctx, opcmap)
local pos = ctx.pos
local opat = opcmap[byte(ctx.code, pos, pos)]
pos = pos + 1
ctx.pos = pos
return dispatch(ctx, opat)
end
-- Map for action codes. The key is the first char after the name.
map_act = {
-- Simple opcodes without operands.
[""] = function(ctx, name, pat)
return putop(ctx, name)
end,
-- Operand size chars fall right through.
B = putpat, W = putpat, D = putpat, Q = putpat,
V = putpat, U = putpat, T = putpat,
M = putpat, X = putpat, P = putpat,
F = putpat, G = putpat,
-- Collect prefixes.
[":"] = function(ctx, name, pat)
ctx[pat == ":" and name or sub(pat, 2)] = name
if ctx.pos - ctx.start > 5 then return unknown(ctx) end -- Limit #prefixes.
end,
-- Chain to special handler specified by name.
["*"] = function(ctx, name, pat)
return map_act[name](ctx, name, sub(pat, 2))
end,
-- Use named subtable for opcode group.
["!"] = function(ctx, name, pat)
local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end
return dispatch(ctx, map_opcgroup[name][((mrm-(mrm%8))/8)%8+1], sub(pat, 2))
end,
-- o16,o32[,o64] variants.
sz = function(ctx, name, pat)
if ctx.o16 then ctx.o16 = false
else
pat = match(pat, ",(.*)")
if ctx.rexw then
local p = match(pat, ",(.*)")
if p then pat = p; ctx.rexw = false end
end
end
pat = match(pat, "^[^,]*")
return dispatch(ctx, pat)
end,
-- Two-byte opcode dispatch.
opc2 = function(ctx, name, pat)
return dispatchmap(ctx, map_opc2)
end,
-- Three-byte opcode dispatch.
opc3 = function(ctx, name, pat)
return dispatchmap(ctx, map_opc3[pat])
end,
-- VMX/SVM dispatch.
vm = function(ctx, name, pat)
return dispatch(ctx, map_opcvm[ctx.mrm])
end,
-- Floating point opcode dispatch.
fp = function(ctx, name, pat)
local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end
local rm = mrm%8
local idx = pat*8 + ((mrm-rm)/8)%8
if mrm >= 192 then idx = idx + 64 end
local opat = map_opcfp[idx]
if type(opat) == "table" then opat = opat[rm+1] end
return dispatch(ctx, opat)
end,
-- REX prefix.
rex = function(ctx, name, pat)
if ctx.rex then return unknown(ctx) end -- Only 1 REX prefix allowed.
for p in gmatch(pat, ".") do ctx["rex"..p] = true end
ctx.rex = true
end,
-- Special case for nop with REX prefix.
nop = function(ctx, name, pat)
return dispatch(ctx, ctx.rex and pat or "nop")
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
ofs = ofs + 1
ctx.start = ofs
ctx.pos = ofs
ctx.stop = stop
ctx.imm = nil
ctx.mrm = false
clearprefixes(ctx)
while ctx.pos <= stop do dispatchmap(ctx, ctx.map1) end
if ctx.pos ~= ctx.start then incomplete(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) - 1
ctx.out = out or io.write
ctx.symtab = {}
ctx.disass = disass_block
ctx.hexdump = 16
ctx.x64 = false
ctx.map1 = map_opc1_32
ctx.aregs = map_regs.D
return ctx
end
local function create64(code, addr, out)
local ctx = create(code, addr, out)
ctx.x64 = true
ctx.map1 = map_opc1_64
ctx.aregs = map_regs.Q
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 disass64(code, addr, out)
create64(code, addr, out):disass()
end
-- Return register name for RID.
local function regname(r)
if r < 8 then return map_regs.D[r+1] end
return map_regs.X[r-7]
end
local function regname64(r)
if r < 16 then return map_regs.Q[r+1] end
return map_regs.X[r-15]
end
-- Public module functions.
return {
create = create,
create64 = create64,
disass = disass,
disass64 = disass64,
regname = regname,
regname64 = regname64
}
| mit |
rpetit3/darkstar | scripts/zones/LaLoff_Amphitheater/npcs/qm1_5.lua | 13 | 2440 | -----------------------------------
-- Area: LaLoff_Amphitheater
-- NPC: Shimmering Circle (BCNM Entrances)
-------------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
package.loaded["scripts/globals/bcnm"] = nil;
-------------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
-- Death cutscenes:
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,0,0); -- hume
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,1,0); -- taru
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,2,0); -- mithra
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,3,0); -- elvaan
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,4,0); -- galka
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,5,0); -- divine might
-- param 1: entrance #
-- param 2: fastest time
-- param 3: unknown
-- param 4: clear time
-- param 5: zoneid
-- param 6: exit cs (0-4 AA, 5 DM, 6-10 neo AA, 11 neo DM)
-- param 7: skip (0 - no skip, 1 - prompt, 2 - force)
-- param 8: 0
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (TradeBCNM(player,player:getZoneID(),trade,npc)) then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (EventTriggerBCNM(player,npc)) then
return;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
if (EventUpdateBCNM(player,csid,option,5)) then
return;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if (EventFinishBCNM(player,csid,option)) then
return;
end
end; | gpl-3.0 |
vseledkin/april-ann | packages/basics/util/test/test.lua | 3 | 1980 | local check = utest.check
local T = utest.test
T("GenericOptionsTest", function()
check(function() return util.options.test() end)
local tbl,str2 = util.options.test()
check.TRUE(tbl.clock1)
check.TRUE(tbl.clock2)
check.TRUE(class.is_a(tbl.clock1, util.stopwatch))
check.TRUE(class.is_a(tbl.clock2, util.stopwatch))
check.eq(tbl.str, "Hello world!")
check.eq(str2, util.to_lua_string(tbl))
end)
T("BindFunctionTest", function()
-- bind function
local f = bind(math.add, 5)
local g = bind(math.div, nil, 3)
check.eq( f(3), 8 )
check.eq( g(6), 2 )
end)
T("MultipleUnpackTest", function()
local t = table.pack( multiple_unpack({1,2,3},{4,5},{6,7,8}) )
for i=1,#t do check.eq(t[i], i) end
local t = table.pack( multiple_unpack{1,2,3,4,5,6,7,8,9} )
for i=1,#t do check.eq(t[i], i) end
local t = table.pack( multiple_unpack(table.pack(1, nil, 3, nil),
table.pack(5, nil, nil, 8)) )
check.eq(t.n, 8)
for i=1,t.n do
check.TRUE(t[i] == i or t[i] == nil)
end
end)
T("SerializationTest", function()
local t = {1,2,3,a={2,3},c=util.stopwatch()}
local t2 = util.deserialize(util.serialize(t))
check.eq(t2[1],1)
check.eq(t2[2],2)
check.eq(t2[3],3)
check.eq(t2.a[1],2)
check.eq(t2.a[2],3)
check.eq(type(t2.c), "util.stopwatch")
end)
T("LambdaTest", function()
local f = lambda'|x|3*x'
local g = bind(lambda'|f,x|f(x)^2', f)
check.eq(f(4),12)
check.eq(g(4),144)
end)
T("CastTest", function()
local tmp = os.tmpname()
local f = aprilio.stream.file(tmp, "w")
local f1 = cast.to(f, aprilio.stream)
check.TRUE( class.is_a(f1, aprilio.stream) )
local f2 = cast.to(f, aprilio.stream.file)
check.TRUE( class.is_a(f2, aprilio.stream.file) )
check.TRUE( class.is_a(f1, aprilio.stream.file) )
check.errored(function() assert(cast.to(f, dataset)) end)
f:close()
os.remove(tmp)
end) | gpl-3.0 |
rpetit3/darkstar | scripts/zones/Selbina/npcs/Tilala.lua | 13 | 1151 | -----------------------------------
-- Area: Selbina
-- NPC: Tilala
-- Guild Merchant NPC: Clothcrafting Guild
-- @pos 14.344 -7.912 10.276 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Selbina/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(516,6,21,0)) then
player:showText(npc,CLOTHCRAFT_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
rpetit3/darkstar | scripts/globals/items/plate_of_patlican_salata_+1.lua | 18 | 1203 | -----------------------------------------
-- ID: 5583
-- Item: plate_of_patlican_salata_+1
-- Food Effect: 4Hrs, All Races
-----------------------------------------
-- Agility 4
-- Vitality -1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5583);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 4);
target:addMod(MOD_VIT, -1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 4);
target:delMod(MOD_VIT, -1);
end;
| gpl-3.0 |
rpetit3/darkstar | scripts/globals/items/dish_of_spag_nero_di_seppia_+1.lua | 18 | 1799 | -----------------------------------------
-- ID: 5202
-- Item: dish_of_spag_nero_di_seppia_+1
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP % 17 (cap 140)
-- Dexterity 3
-- Vitality 2
-- Agility -1
-- Mind -2
-- Charisma -1
-- Double Attack 1
-- Store TP 6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5202);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 17);
target:addMod(MOD_FOOD_HP_CAP, 140);
target:addMod(MOD_DEX, 3);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_AGI, -1);
target:addMod(MOD_MND, -2);
target:addMod(MOD_CHR, -1);
target:addMod(MOD_DOUBLE_ATTACK, 1);
target:addMod(MOD_STORETP, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 17);
target:delMod(MOD_FOOD_HP_CAP, 140);
target:delMod(MOD_DEX, 3);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_AGI, -1);
target:delMod(MOD_MND, -2);
target:delMod(MOD_CHR, -1);
target:delMod(MOD_DOUBLE_ATTACK, 1);
target:delMod(MOD_STORETP, 6);
end;
| gpl-3.0 |
esguk811/DarkRP | gamemode/modules/fadmin/fadmin/playeractions/teleport/cl_init.lua | 6 | 2349 |
FAdmin.StartHooks["zz_Teleport"] = function()
FAdmin.Messages.RegisterNotification{
name = "goto",
hasTarget = true,
message = {"instigator", " teleported to ", "targets"}
}
FAdmin.Messages.RegisterNotification{
name = "bring",
hasTarget = true,
message = {"instigator", " brought ", "targets", " to them"}
}
FAdmin.Access.AddPrivilege("Teleport", 2)
FAdmin.Commands.AddCommand("Teleport", nil, "[Player]")
FAdmin.Commands.AddCommand("TP", nil, "[Player]")
FAdmin.Commands.AddCommand("Bring", nil, "<Player>", "[Player]")
FAdmin.Commands.AddCommand("goto", nil, "<Player>")
FAdmin.ScoreBoard.Player:AddActionButton("Teleport", "fadmin/icons/teleport", Color(0, 200, 0, 255),
function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "Teleport") end,
function(ply, button)
RunConsoleCommand("_FAdmin", "Teleport", ply:UserID())
end)
FAdmin.ScoreBoard.Player:AddActionButton("Goto", "fadmin/icons/teleport", Color(0, 200, 0, 255),
function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "Teleport") and ply ~= LocalPlayer() end,
function(ply, button)
RunConsoleCommand("_FAdmin", "goto", ply:UserID())
end)
FAdmin.ScoreBoard.Player:AddActionButton("Bring", "fadmin/icons/teleport", Color(0, 200, 0, 255),
function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "Teleport") and ply ~= LocalPlayer() end,
function(ply, button)
local menu = DermaMenu()
local Padding = vgui.Create("DPanel")
Padding:SetPaintBackgroundEnabled(false)
Padding:SetSize(1,5)
menu:AddPanel(Padding)
local Title = vgui.Create("DLabel")
Title:SetText(" Bring to:\n")
Title:SetFont("UiBold")
Title:SizeToContents()
Title:SetTextColor(color_black)
menu:AddPanel(Title)
local uid = ply:UserID()
menu:AddOption("Yourself", function() RunConsoleCommand("_FAdmin", "bring", uid) end)
for k, v in pairs(DarkRP.nickSortedPlayers()) do
if v ~= LocalPlayer() then
local vUid = v:UserID()
menu:AddOption(v:Nick(), function() RunConsoleCommand("_FAdmin", "bring", uid, vUid) end)
end
end
menu:Open()
end)
end
| mit |
MinetestForFun/server-minetestforfun-creative | mods/xdecor/enchanting.lua | 1 | 9171 | local enchanting = {}
screwdriver = screwdriver or {}
-- Cost in Mese crystal(s) for enchanting.
local mese_cost = 1
-- Force of the enchantments.
enchanting.uses = 1.2 -- Durability
enchanting.times = 0.1 -- Efficiency
enchanting.damages = 1 -- Sharpness
enchanting.strength = 1.2 -- Armor strength (3d_armor only)
enchanting.speed = 0.2 -- Player speed (3d_armor only)
enchanting.jump = 0.2 -- Player jumping (3d_armor only)
function enchanting.formspec(pos, num)
local meta = minetest.get_meta(pos)
local formspec = [[ size[9,9;]
bgcolor[#080808BB;true]
background[0,0;9,9;ench_ui.png]
list[context;tool;0.9,2.9;1,1;]
list[context;mese;2,2.9;1,1;]
list[current_player;main;0.5,4.5;8,4;]
image[2,2.9;1,1;mese_layout.png]
tooltip[sharp;Your weapon inflicts more damages]
tooltip[durable;Your tool last longer]
tooltip[fast;Your tool digs faster]
tooltip[strong;Your armor is more resistant]
tooltip[speed;Your speed is increased] ]]
..default.gui_slots..default.get_hotbar_bg(0.5,4.5)
local enchant_buttons = {
[[ image_button[3.9,0.85;4,0.92;bg_btn.png;fast;Efficiency]
image_button[3.9,1.77;4,1.12;bg_btn.png;durable;Durability] ]],
"image_button[3.9,0.85;4,0.92;bg_btn.png;strong;Strength]",
"image_button[3.9,2.9;4,0.92;bg_btn.png;sharp;Sharpness]",
[[ image_button[3.9,0.85;4,0.92;bg_btn.png;strong;Strength]
image_button[3.9,1.77;4,1.12;bg_btn.png;speed;Speed] ]]
}
formspec = formspec..(enchant_buttons[num] or "")
meta:set_string("formspec", formspec)
end
function enchanting.on_put(pos, listname, _, stack)
if listname == "tool" then
local stackname = stack:get_name()
local tool_groups = {
"axe, pick, shovel",
"chestplate, leggings, helmet",
"sword", "boots"
}
for idx, tools in pairs(tool_groups) do
if tools:find(stackname:match(":(%w+)")) then
enchanting.formspec(pos, idx)
end
end
end
end
function enchanting.fields(pos, _, fields, sender)
if fields.quit then return end
local inv = minetest.get_meta(pos):get_inventory()
local tool = inv:get_stack("tool", 1)
local mese = inv:get_stack("mese", 1)
local orig_wear = tool:get_wear()
local mod, name = tool:get_name():match("(.*):(.*)")
local enchanted_tool = (mod or "")..":enchanted_"..(name or "").."_"..next(fields)
if mese:get_count() >= mese_cost and minetest.registered_tools[enchanted_tool] then
minetest.sound_play("xdecor_enchanting", {to_player=sender:get_player_name(), gain=0.8})
tool:replace(enchanted_tool)
tool:add_wear(orig_wear)
mese:take_item(mese_cost)
inv:set_stack("mese", 1, mese)
inv:set_stack("tool", 1, tool)
end
end
function enchanting.dig(pos)
local inv = minetest.get_meta(pos):get_inventory()
return inv:is_empty("tool") and inv:is_empty("mese")
end
local function allowed(tool)
for item in pairs(minetest.registered_tools) do
if item:find("enchanted_"..tool) then return true end
end
return false
end
function enchanting.put(_, listname, _, stack)
local item = stack:get_name():match("[^:]+$")
if listname == "mese" and item == "mese_crystal" then
return stack:get_count()
elseif listname == "tool" and item and allowed(item) then
return 1
end
return 0
end
function enchanting.on_take(pos, listname)
if listname == "tool" then enchanting.formspec(pos, nil) end
end
function enchanting.construct(pos)
local meta = minetest.get_meta(pos)
meta:set_string("infotext", "Enchantment Table")
enchanting.formspec(pos, nil)
local inv = meta:get_inventory()
inv:set_size("tool", 1)
inv:set_size("mese", 1)
minetest.add_entity({x=pos.x, y=pos.y+0.85, z=pos.z}, "xdecor:book_open")
local timer = minetest.get_node_timer(pos)
timer:start(5.0)
end
function enchanting.destruct(pos)
for _, obj in pairs(minetest.get_objects_inside_radius(pos, 0.9)) do
if obj and obj:get_luaentity() and
obj:get_luaentity().name == "xdecor:book_open" then
obj:remove() break
end
end
end
function enchanting.timer(pos)
local node = minetest.get_node(pos)
local num = #minetest.get_objects_inside_radius(pos, 0.9)
if num == 0 then
minetest.add_entity({x=pos.x, y=pos.y+0.85, z=pos.z}, "xdecor:book_open")
end
local minp = {x=pos.x-2, y=pos.y, z=pos.z-2}
local maxp = {x=pos.x+2, y=pos.y+1, z=pos.z+2}
local bookshelves = minetest.find_nodes_in_area(minp, maxp, "default:bookshelf")
if #bookshelves == 0 then return true end
local bookshelf_pos = bookshelves[math.random(1, #bookshelves)]
local x = pos.x - bookshelf_pos.x
local y = bookshelf_pos.y - pos.y
local z = pos.z - bookshelf_pos.z
if tostring(x..z):find(2) then
minetest.add_particle({
pos = bookshelf_pos,
velocity = {x=x, y=2-y, z=z},
acceleration = {x=0, y=-2.2, z=0},
expirationtime = 1,
size = 2,
texture = "xdecor_glyph"..math.random(1,18)..".png"
})
end
return true
end
xdecor.register("enchantment_table", {
description = "Enchantment Table",
tiles = {"xdecor_enchantment_top.png", "xdecor_enchantment_bottom.png",
"xdecor_enchantment_side.png", "xdecor_enchantment_side.png",
"xdecor_enchantment_side.png", "xdecor_enchantment_side.png"},
groups = {cracky=1, level=1},
sounds = default.node_sound_stone_defaults(),
on_rotate = screwdriver.rotate_simple,
can_dig = enchanting.dig,
on_timer = enchanting.timer,
on_construct = enchanting.construct,
on_destruct = enchanting.destruct,
on_receive_fields = enchanting.fields,
on_metadata_inventory_put = enchanting.on_put,
on_metadata_inventory_take = enchanting.on_take,
allow_metadata_inventory_put = enchanting.put,
allow_metadata_inventory_move = function() return 0 end
})
minetest.register_entity("xdecor:book_open", {
visual = "sprite",
visual_size = {x=0.75, y=0.75},
collisionbox = {0},
physical = false,
textures = {"xdecor_book_open.png"},
on_activate = function(self)
local pos = self.object:getpos()
local pos_under = {x=pos.x, y=pos.y-1, z=pos.z}
if minetest.get_node(pos_under).name ~= "xdecor:enchantment_table" then
self.object:remove()
end
end
})
local function cap(S) return S:gsub("^%l", string.upper) end
function enchanting:register_tools(mod, def)
for tool in pairs(def.tools) do
for material in def.materials:gmatch("[%w_]+") do
for enchant in def.tools[tool].enchants:gmatch("[%w_]+") do
local original_tool = minetest.registered_tools[mod..":"..tool.."_"..material]
if not original_tool then break end
if original_tool.tool_capabilities then
local original_damage_groups = original_tool.tool_capabilities.damage_groups
local original_groupcaps = original_tool.tool_capabilities.groupcaps
local groupcaps = table.copy(original_groupcaps)
local fleshy = original_damage_groups.fleshy
local full_punch_interval = original_tool.tool_capabilities.full_punch_interval
local max_drop_level = original_tool.tool_capabilities.max_drop_level
local group = next(original_groupcaps)
if enchant == "durable" then
groupcaps[group].uses = math.ceil(original_groupcaps[group].uses * enchanting.uses)
elseif enchant == "fast" then
for i, time in pairs(original_groupcaps[group].times) do
groupcaps[group].times[i] = time - enchanting.times
end
elseif enchant == "sharp" then
fleshy = fleshy + enchanting.damages
end
minetest.register_tool(":"..mod..":enchanted_"..tool.."_"..material.."_"..enchant, {
description = "Enchanted "..cap(material).." "..cap(tool).." ("..cap(enchant)..")",
inventory_image = original_tool.inventory_image.."^[colorize:violet:50",
wield_image = original_tool.wield_image,
groups = {not_in_creative_inventory=1},
tool_capabilities = {
groupcaps = groupcaps, damage_groups = {fleshy = fleshy},
full_punch_interval = full_punch_interval, max_drop_level = max_drop_level
}
})
end
if mod == "3d_armor" then
local original_armor_groups = original_tool.groups
local armorcaps = {}
armorcaps.not_in_creative_inventory = 1
for armor_group, value in pairs(original_armor_groups) do
if enchant == "strong" then
armorcaps[armor_group] = math.ceil(value * enchanting.strength)
elseif enchant == "speed" then
armorcaps[armor_group] = value
armorcaps.physics_speed = enchanting.speed
armorcaps.physics_jump = enchanting.jump
end
end
minetest.register_tool(":"..mod..":enchanted_"..tool.."_"..material.."_"..enchant, {
description = "Enchanted "..cap(material).." "..cap(tool).." ("..cap(enchant)..")",
inventory_image = original_tool.inventory_image,
texture = "3d_armor_"..tool.."_"..material,
wield_image = original_tool.wield_image,
groups = armorcaps,
wear = 0
})
end
end
end
end
end
enchanting:register_tools("default", {
materials = "steel, bronze, mese, diamond",
tools = {
axe = {enchants = "durable, fast"},
pick = {enchants = "durable, fast"},
shovel = {enchants = "durable, fast"},
sword = {enchants = "sharp"}
}
})
enchanting:register_tools("3d_armor", {
materials = "steel, bronze, gold, diamond",
tools = {
boots = {enchants = "strong, speed"},
chestplate = {enchants = "strong"},
helmet = {enchants = "strong"},
leggings = {enchants = "strong"}
}
})
| unlicense |
ench0/external_chromium_org_third_party_skia | tools/lua/paths.lua | 92 | 3129 | --
-- Copyright 2014 Google Inc.
--
-- Use of this source code is governed by a BSD-style license that can be
-- found in the LICENSE file.
--
-- Path scraping script.
-- This script is designed to count the number of times we fall back to software
-- rendering for a path in a given SKP. However, this script does not count an exact
-- number of uploads, since there is some overlap with clipping: e.g. two clipped paths
-- may cause three uploads to the GPU (set clip 1, set clip 2, unset clip 2/reset clip 1),
-- but these cases are rare.
draws = 0
drawPaths = 0
drawPathsAnti = 0
drawPathsConvexAnti = 0
clips = 0
clipPaths = 0
clipPathsAnti = 0
clipPathsConvexAnti = 0
usedPath = false
usedSWPath = false
skpsTotal = 0
skpsWithPath = 0
skpsWithSWPath = 0
function sk_scrape_startcanvas(c, fileName)
usedPath = false
usedSWPath = false
end
function sk_scrape_endcanvas(c, fileName)
skpsTotal = skpsTotal + 1
if usedPath then
skpsWithPath = skpsWithPath + 1
if usedSWPath then
skpsWithSWPath = skpsWithSWPath + 1
end
end
end
function string.starts(String,Start)
return string.sub(String,1,string.len(Start))==Start
end
function isPathValid(path)
if not path then
return false
end
if path:isEmpty() then
return false
end
if path:isRect() then
return false
end
return true
end
function sk_scrape_accumulate(t)
if (string.starts(t.verb, "draw")) then
draws = draws + 1
end
if (string.starts(t.verb, "clip")) then
clips = clips + 1
end
if t.verb == "clipPath" then
local path = t.path
if isPathValid(path) then
clipPaths = clipPaths + 1
usedPath = true
if t.aa then
clipPathsAnti = clipPathsAnti + 1
if path:isConvex() then
clipPathsConvexAnti = clipPathsConvexAnti + 1
else
usedSWPath = true
end
end
end
end
if t.verb == "drawPath" then
local path = t.path
local paint = t.paint
if paint and isPathValid(path) then
drawPaths = drawPaths + 1
usedPath = true
if paint:isAntiAlias() then
drawPathsAnti = drawPathsAnti + 1
if path:isConvex() then
drawPathsConvexAnti = drawPathsConvexAnti + 1
else
usedSWPath = true
end
end
end
end
end
function sk_scrape_summarize()
local swDrawPaths = drawPathsAnti - drawPathsConvexAnti
local swClipPaths = clipPathsAnti - clipPathsConvexAnti
io.write("clips = clips + ", clips, "\n");
io.write("draws = draws + ", draws, "\n");
io.write("clipPaths = clipPaths + ", clipPaths, "\n");
io.write("drawPaths = drawPaths + ", drawPaths, "\n");
io.write("swClipPaths = swClipPaths + ", swClipPaths, "\n");
io.write("swDrawPaths = swDrawPaths + ", swDrawPaths, "\n");
io.write("skpsTotal = skpsTotal + ", skpsTotal, "\n");
io.write("skpsWithPath = skpsWithPath + ", skpsWithPath, "\n");
io.write("skpsWithSWPath = skpsWithSWPath + ", skpsWithSWPath, "\n");
end
| bsd-3-clause |
sys4-fr/server-minetestforfun | mods/u_skins/u_skins/init.lua | 10 | 4926 | -- Unified Skins for Minetest - based modified Bags from unfied_inventory and skins from inventory_plus
-- Copyright (c) 2012 cornernote, Dean Montgomery
-- License: GPLv3
u_skins = {}
u_skins.modpath = minetest.get_modpath("u_skins")
u_skins.file = minetest.get_worldpath().."/u_skins.mt"
u_skins.default = "character_1"
u_skins.pages = {}
u_skins.u_skins = {}
u_skins.file_save = false
-- ( Deprecated
u_skins.type = { SPRITE=0, MODEL=1, ERROR=99 }
u_skins.get_type = function(texture)
if not u_skins.is_skin(texture) then
return u_skins.type.ERROR
end
return u_skins.type.MODEL
end
-- )
u_skins.is_skin = function(texture)
if not texture then
return false
end
if not u_skins.meta[texture] then
return false
end
return true
end
dofile(u_skins.modpath.."/skinlist.lua")
dofile(u_skins.modpath.."/players.lua")
u_skins.update_player_skin = function(player)
local name = player:get_player_name()
if not u_skins.is_skin(u_skins.u_skins[name]) then
u_skins.u_skins[name] = u_skins.default
end
player:set_properties({
textures = {u_skins.u_skins[name]..".png"},
})
u_skins.file_save = true
end
-- Display Current Skin
unified_inventory.register_page("u_skins", {
get_formspec = function(player)
local name = player:get_player_name()
if not u_skins.is_skin(u_skins.u_skins[name]) then
u_skins.u_skins[name] = u_skins.default
end
local formspec = ("background[0.06,0.99;7.92,7.52;ui_misc_form.png]"
.."image[0,.75;1,2;"..u_skins.u_skins[name].."_preview.png]"
.."label[6,.5;Raw texture:]"
.."image[6,1;2,1;"..u_skins.u_skins[name]..".png]")
local meta = u_skins.meta[u_skins.u_skins[name]]
if meta then
if meta.name ~= "" then
formspec = formspec.."label[2,.5;Name: "..minetest.formspec_escape(meta.name).."]"
end
if meta.author ~= "" then
formspec = formspec.."label[2,1;Author: "..minetest.formspec_escape(meta.author).."]"
end
if meta.license ~= "" then
formspec = formspec.."label[2,1.5;License: "..minetest.formspec_escape(meta.license).."]"
end
if meta.description ~= "" then --what's that??
formspec = formspec.."label[2,2;Description: "..minetest.formspec_escape(meta.description).."]"
end
end
local page = 0
if u_skins.pages[name] then
page = u_skins.pages[name]
end
formspec = formspec .. "button[.75,3;6.5,.5;u_skins_page$"..page..";Change]"
return {formspec=formspec}
end,
})
unified_inventory.register_button("u_skins", {
type = "image",
image = "u_skins_button.png",
tooltip = "Skin inventory",
show_with = false, -- modif MFF (Crabman 30/06/2015)
})
-- Create all of the skin-picker pages.
u_skins.generate_pages = function(texture)
local page = 0
local pages = {}
for i, skin in ipairs(u_skins.list) do
local p_index = (i - 1) % 16
if p_index == 0 then
page = page + 1
pages[page] = {}
end
pages[page][p_index + 1] = {i, skin}
end
local total_pages = page
page = 1
for page, arr in ipairs(pages) do
local formspec = "background[0.06,0.99;7.92,7.52;ui_misc_form.png]"
local y = -0.1
for i, skin in ipairs(arr) do
local x = (i - 1) % 8
if i > 1 and x == 0 then
y = 1.8
end
formspec = (formspec.."image_button["..x..","..y..";1,2;"..
skin[2].."_preview.png;u_skins_set$"..skin[1]..";]"..
"tooltip[u_skins_set$"..skin[1]..";"..u_skins.meta[skin[2]].name.."]")
end
local page_prev = page - 2
local page_next = page
if page_prev < 0 then
page_prev = total_pages - 1
end
if page_next >= total_pages then
page_next = 0
end
formspec = (formspec
.."button[0,3.8;1,.5;u_skins_page$"..page_prev..";<<]"
.."button[.75,3.8;6.5,.5;u_skins_null;Page "..page.."/"..total_pages.."]"
.."button[7,3.8;1,.5;u_skins_page$"..page_next..";>>]")
unified_inventory.register_page("u_skins_page$"..(page - 1), {
get_formspec = function(player)
return {formspec=formspec}
end
})
end
end
-- click button handlers
minetest.register_on_player_receive_fields(function(player, formname, fields)
if fields.u_skins then
unified_inventory.set_inventory_formspec(player, "craft")
return
end
for field, _ in pairs(fields) do
local current = string.split(field, "$", 2)
if current[1] == "u_skins_set" then
u_skins.u_skins[player:get_player_name()] = u_skins.list[tonumber(current[2])]
u_skins.update_player_skin(player)
unified_inventory.set_inventory_formspec(player, "u_skins")
elseif current[1] == "u_skins_page" then
u_skins.pages[player:get_player_name()] = current[2]
unified_inventory.set_inventory_formspec(player, "u_skins_page$"..current[2])
end
end
end)
-- Change skin on join - reset if invalid
minetest.register_on_joinplayer(function(player)
local player_name = player:get_player_name()
if not u_skins.is_skin(u_skins.u_skins[player_name]) then
u_skins.u_skins[player_name] = u_skins.default
end
u_skins.update_player_skin(player)
end)
u_skins.generate_pages()
u_skins.load_players()
| unlicense |
MinetestForFun/server-minetestforfun-creative | mods/plantlife_modpack/bushes_classic/init.lua | 1 | 1304 | -- Bushes classic mod originally by unknown
-- now maintained by VanessaE
--
-- License: WTFPL
local S = biome_lib.intllib
bushes_classic = {}
bushes_classic.bushes = {
"strawberry",
"blackberry",
"blueberry",
"raspberry",
"gooseberry",
"mixed_berry"
}
bushes_classic.bushes_descriptions = {
"Strawberry",
"Blackberry",
"Blueberry",
"Raspberry",
"Gooseberry",
"Mixed Berry"
}
bushes_classic.spawn_list = {}
local modpath = minetest.get_modpath('bushes_classic')
-- dofile(modpath..'/cooking.lua')
dofile(modpath..'/nodes.lua')
biome_lib:spawn_on_surfaces({
spawn_delay = 3600,
spawn_plants = bushes_classic.spawn_list,
avoid_radius = 10,
spawn_chance = 100,
spawn_surfaces = {
"default:dirt_with_grass",
"woodsoils:dirt_with_leaves_1",
"woodsoils:grass_with_leaves_1",
"woodsoils:grass_with_leaves_2",
"farming:soil",
"farming:soil_wet"
},
avoid_nodes = {"group:bush"},
seed_diff = 545342534, -- chosen by a fair mashing of the keyboard - guaranteed to be random :P
plantlife_limit = -0.1,
light_min = 10,
temp_min = 0.15, -- approx 20C
temp_max = -0.15, -- approx 35C
humidity_min = 0, -- 50% RH
humidity_max = -1, -- 100% RH
})
minetest.register_alias("bushes:basket_pies", "bushes:basket_strawberry")
minetest.log("action", S("[Bushes] Loaded."))
| unlicense |
rpetit3/darkstar | scripts/zones/Uleguerand_Range/npcs/HomePoint#5.lua | 27 | 1258 | -----------------------------------
-- Area: Uleguerand_Range
-- NPC: HomePoint#5
-- @pos
-----------------------------------
package.loaded["scripts/zones/Uleguerand_Range/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Uleguerand_Range/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x2200, 80);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x2200) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
sevenbot/etehadseven | plugins/invite.lua | 299 | 1025 | -- Invite other user to the chat group.
-- Use !invite name User_name or !invite id id_number
-- The User_name is the print_name (there are no spaces but _)
do
local function callback(extra, success, result)
vardump(success)
vardump(result)
end
local function run(msg, matches)
local user = matches[2]
-- User submitted a user name
if matches[1] == "name" then
user = string.gsub(user," ","_")
end
-- User submitted an id
if matches[1] == "id" then
user = 'user#id'..user
end
-- The message must come from a chat group
if msg.to.type == 'chat' then
local chat = 'chat#id'..msg.to.id
chat_add_user(chat, user, callback, false)
return "Add: "..user.." to "..chat
else
return 'This isnt a chat group!'
end
end
return {
description = "Invite other user to the chat group",
usage = {
"!invite name [user_name]",
"!invite id [user_id]" },
patterns = {
"^!invite (name) (.*)$",
"^!invite (id) (%d+)$"
},
run = run,
moderation = true
}
end | gpl-2.0 |
alireza98/y | plugins/invite.lua | 299 | 1025 | -- Invite other user to the chat group.
-- Use !invite name User_name or !invite id id_number
-- The User_name is the print_name (there are no spaces but _)
do
local function callback(extra, success, result)
vardump(success)
vardump(result)
end
local function run(msg, matches)
local user = matches[2]
-- User submitted a user name
if matches[1] == "name" then
user = string.gsub(user," ","_")
end
-- User submitted an id
if matches[1] == "id" then
user = 'user#id'..user
end
-- The message must come from a chat group
if msg.to.type == 'chat' then
local chat = 'chat#id'..msg.to.id
chat_add_user(chat, user, callback, false)
return "Add: "..user.." to "..chat
else
return 'This isnt a chat group!'
end
end
return {
description = "Invite other user to the chat group",
usage = {
"!invite name [user_name]",
"!invite id [user_id]" },
patterns = {
"^!invite (name) (.*)$",
"^!invite (id) (%d+)$"
},
run = run,
moderation = true
}
end | gpl-2.0 |
esguk811/DarkRP | gamemode/modules/fadmin/fadmin/cl_interface/cl_PlayerLists.lua | 5 | 1324 | local function SortedPairsByFunction(Table, Sorted, SortDown)
local CopyTable = {}
for k,v in pairs(Table) do
table.insert(CopyTable, {NAME = tostring(v:Nick()), PLY = v})
end
table.SortByMember(CopyTable, "NAME", SortDown)
local SortedTable = {}
for k,v in ipairs(CopyTable) do
if not IsValid(v.PLY) or not v.PLY[Sorted] then continue end
local SortBy = (Sorted ~= "Team" and v.PLY[Sorted](v.PLY)) or team.GetName(v.PLY[Sorted](v.PLY))
SortedTable[SortBy] = SortedTable[SortBy] or {}
table.insert(SortedTable[SortBy], v.PLY)
end
local SecondSort = {}
for k,v in SortedPairs(SortedTable, SortDown) do
table.insert(SecondSort, v)
end
CopyTable = {}
for k,v in pairs(SecondSort) do
for a,b in pairs(v) do
table.insert(CopyTable, b)
end
end
return ipairs(CopyTable)
end
function FAdmin.ScoreBoard.Main.PlayerListView(Sorted, SortDown)
FAdmin.ScoreBoard.Main.Controls.FAdminPanelList:Clear(true)
for k, ply in SortedPairsByFunction(player.GetAll(), Sorted, SortDown) do
local Row = vgui.Create("FadminPlayerRow")
Row:SetPlayer(ply)
Row:Dock(TOP)
Row:InvalidateLayout()
FAdmin.ScoreBoard.Main.Controls.FAdminPanelList:AddItem(Row)
end
end
| mit |
rpetit3/darkstar | scripts/zones/Hall_of_Transference/npcs/_0e8.lua | 22 | 1707 | -----------------------------------
-- Area: Hall of Transference
-- NPC: Large Apparatus (Right) - Mea
-- @pos 290.253 -81.849 -42.381 14
-----------------------------------
package.loaded["scripts/zones/Hall_of_Transference/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Hall_of_Transference/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getVar("MeaChipRegistration") == 0 and player:getVar("skyShortcut") == 1 and trade:hasItemQty(478,1) and trade:getItemCount() == 1) then
player:tradeComplete();
player:startEvent(0x00A4);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("MeaChipRegistration") == 1) then
player:messageSpecial(NO_RESPONSE_OFFSET+6); -- Device seems to be functioning correctly.
else
player:startEvent(0x00A3); -- Hexagonal Cones
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00A4) then
player:messageSpecial(NO_RESPONSE_OFFSET+4,478); -- You fit..
player:messageSpecial(NO_RESPONSE_OFFSET+5); -- Device has been repaired
player:setVar("MeaChipRegistration",1);
end
end;
| gpl-3.0 |
rpetit3/darkstar | scripts/zones/Dynamis-Valkurm/Zone.lua | 13 | 2454 | -----------------------------------
--
-- Zone: Dynamis-Valkurm
--
-----------------------------------
package.loaded["scripts/zones/Dynamis-Valkurm/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Dynamis-Valkurm/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaValkurm]UniqueID")) then
if (player:isBcnmsFull() == 1) then
if (player:hasStatusEffect(EFFECT_DYNAMIS, 0) == false) then
inst = player:addPlayerToDynamis(1286);
if (inst == 1) then
player:bcnmEnter(1286);
else
cs = 0x0065;
end
else
player:bcnmEnter(1286);
end
else
inst = player:bcnmRegister(1286);
if (inst == 1) then
player:bcnmEnter(1286);
else
cs = 0x0065;
end
end
else
cs = 0x0065;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0065) then
player:setPos(117,-9,132,162,103);
end
end;
| gpl-3.0 |
Benjamin-L/Dinosauria | external/ngplant-0.9.11/plugins/gmesh_rhomb.lua | 1 | 3092 | --[[
ngPlant-plugin : gmesh-generator
menu-name : Rhomb
--]]
--[[
====== BEGIN GPL LICENSE BLOCK =====
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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
===== END GPL LICENSE BLOCK =====
--]]
function CreateRhomb(height,width)
Rhomb = {
vattrs =
{
vertex = { { 0.0, 0.0, 0.0 },
{ width * 0.5, height * 0.5, 0.0 },
{ 0.0, height, 0.0 },
{ -width * 0.5, height * 0.5, 0.0 } },
normal = { { 0.0, 0.0, 1.0 } },
texcoord0 = { { 0.5, 0.0 },
{ 1.0, 0.5 },
{ 0.5, 1.0 },
{ 0.0, 0.5 } },
binormal = { { 0.0, 1.0, 0.0 } },
tangent = { { 1.0, 0.0, 0.0 } }
},
vindices = { {
{ 1, 1, 1, 1, 1},
{ 2, 1, 2, 1, 1},
{ 3, 1, 3, 1, 1},
{ 4, 1, 4, 1, 1}
} },
attrs =
{
vertex = { { 0.0, 0.0, 0.0 },
{ width * 0.5, height * 0.5, 0.0 },
{ -width * 0.5, height * 0.5, 0.0 },
{ 0.0, height, 0.0 } },
normal = { { 0.0, 0.0, 1.0 },
{ 0.0, 0.0, 1.0 },
{ 0.0, 0.0, 1.0 },
{ 0.0, 0.0, 1.0 } },
texcoord0 = { { 0.5, 0.0 },
{ 1.0, 0.5 },
{ 0.0, 0.5 },
{ 0.5, 1.0 } },
binormal = { { 0.0, 1.0, 0.0 },
{ 0.0, 1.0, 0.0 },
{ 0.0, 1.0, 0.0 },
{ 0.0, 1.0, 0.0 } },
tangent = { { 1.0, 0.0, 0.0 },
{ 1.0, 0.0, 0.0 },
{ 1.0, 0.0, 0.0 },
{ 1.0, 0.0, 0.0 } }
},
indices = { { 1, 2, 3 }, { 3, 2, 4} }
}
return Rhomb
end
Params = ShowParameterDialog(
{
{
label = "Height",
name = "Height",
type = "number",
default = 0.5
},
{
label = "Width",
name = "Width",
type = "number",
default = 0.5
}
})
if Params == nil then
return nil
else
return CreateRhomb(Params.Height,Params.Width)
end
| gpl-3.0 |
rpetit3/darkstar | scripts/globals/mobskills/Thermal_Pulse.lua | 34 | 1074 | ---------------------------------------------
-- Thermal Pulse
-- Family: Wamouracampa
-- Description: Deals Fire damage to enemies within area of effect. Additional effect: Blindness
-- Type: Magical
-- Utsusemi/Blink absorb: Ignores shadow
-- Range: 12.5
-- Notes: Open form only.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:AnimationSub() ~=0) then
return 1;
else
return 0;
end
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_BLINDNESS;
MobStatusEffectMove(mob, target, typeEffect, 20, 0, 60);
local dmgmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_FIRE,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_FIRE,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
martinrotter/textilosaurus | src/libtextosaurus/3rd-party/scintilla-lt/lexlua/powershell.lua | 2 | 2013 | -- Copyright 2015-2019 Mitchell mitchell.att.foicica.com. See License.txt.
-- PowerShell LPeg lexer.
-- Contributed by Jeff Stone.
local lexer = require('lexer')
local token, word_match = lexer.token, lexer.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local lex = lexer.new('powershell')
-- Whitespace.
lex:add_rule('whitespace', token(lexer.WHITESPACE, lexer.space^1))
-- Comments.
lex:add_rule('comment', token(lexer.COMMENT, '#' * lexer.nonnewline^0))
-- Keywords.
lex:add_rule('keyword', token(lexer.KEYWORD, word_match([[
Begin Break Continue Do Else End Exit For ForEach ForEach-Object Get-Date
Get-Random If Param Pause Powershell Process Read-Host Return Switch While
Write-Host
]], true)))
-- Comparison Operators.
lex:add_rule('comparison', token(lexer.KEYWORD, '-' * word_match([[
and as band bor contains eq ge gt is isnot le like lt match ne nomatch not
notcontains notlike or replace
]], true)))
-- Parameters.
lex:add_rule('parameter', token(lexer.KEYWORD, '-' * word_match([[
Confirm Debug ErrorAction ErrorVariable OutBuffer OutVariable Verbose WhatIf
]], true)))
-- Properties.
lex:add_rule('property', token(lexer.KEYWORD, '.' * word_match([[
day dayofweek dayofyear hour millisecond minute month second timeofday year
]], true)))
-- Types.
lex:add_rule('type', token(lexer.KEYWORD, '[' * word_match([[
array boolean byte char datetime decimal double hashtable int long single
string xml
]], true) * ']'))
-- Variables.
lex:add_rule('variable', token(lexer.VARIABLE,
'$' * (lexer.digit^1 + lexer.word +
lexer.delimited_range('{}', true, true))))
-- Strings.
lex:add_rule('string', token(lexer.STRING, lexer.delimited_range('"', true)))
-- Numbers.
lex:add_rule('number', token(lexer.NUMBER, lexer.float + lexer.integer))
-- Operators.
lex:add_rule('operator', token(lexer.OPERATOR, S('=!<>+-/*^&|~.,:;?()[]{}%`')))
-- Fold points.
lex:add_fold_point(lexer.OPERATOR, '{', '}')
return lex
| gpl-3.0 |
rpetit3/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Caiphimonride.lua | 13 | 1292 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Caiphimonride
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
require("scripts/zones/Tavnazian_Safehold/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,CAIPHIMONRIDE_SHOP_DIALOG);
stock = {0x4042,1867, --Dagger
0x40b6,8478, --Longsword
0x43B7,8, --Rusty Bolt
0x47C7,93240, --Falx (COP Chapter 4 Needed; not implemented yet)
0x4726,51905} --Voulge (COP Chapter 4 Needed; not implemented yet)
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
rpetit3/darkstar | scripts/globals/common.lua | 35 | 2855 | -----------------------------------
--
--
-----------------------------------
-----------------------------------
-- switch
-----------------------------------
function switch(c)
local swtbl = {
casevar = c,
caseof = function (self,code)
local f
if (self.casevar) then
f = code[self.casevar] or code.default
else
f = code.missing or code.default
end
if f then
if type(f)=="function" then
return f(self.casevar,self)
else
error("case "..tostring(self.casevar).." not a function")
end
end
end
}
return swtbl
end;
-----------------------------------
-- printf
-----------------------------------
function printf(s,...)
print(s:format(...))
end;
-----------------------------------
-- getMidnight
-- Returns midnight for the current day in epoch format
-----------------------------------
function getMidnight(day)
-- Get time, because this is going to get ugly. Using ! for UTC won't work where we're going.
local hometime = os.date("*t");
if (day ~= nil) then
hometime = os.date("*t", day);
end
-- Set to 24:00 to get end of the day.
local midnight = os.time{year=hometime.year, month=hometime.month, day=hometime.day, hour=24};
-- And determine the timezone in seconds, because we'll need that to get UTC and LUA doesn't make it easy.
local timezone = os.difftime(os.time(), os.time(os.date("!*t")));
-- Midnight adjusted for timezone, then timezone offset * 3600 to get us where we want to be.
local finaltime = midnight + timezone - (TIMEZONE_OFFSET * 3600);
-- And make sure that the offset midnight isn't already passed
if ((day ~= nil and finaltime <= day) or (day == nil and finaltime <= os.time())) then
finaltime = finaltime + 86400;
end
return finaltime;
end;
-----------------------------------
-- getConquestTally()
-- Returns the end of the current conquest tally
-----------------------------------
function getConquestTally()
-- Get time into a handy dandy table
local weekDayNumber = tonumber(os.date("%w"));
local daysToTally = 0;
-- LUA is Sun -> Sat, conquest is Mon -> Sun, so adjustments via conditional are needed.
-- If today is Sunday (0), no additional days are necessary, so keep the 0.
-- Ex: Friday = 5, 7 - 5 = 2 days to add, all of Saturday and Sunday.
if (weekDayNumber > 0) then
daysToTally = 7 - weekDayNumber;
end
-- Midnight + daysToTally * a day worth of seconds.
return (getMidnight() + (daysToTally * 86400));
end;
-----------------------------------
-- vanaDay()
-- Small function to make it easier to store the current date
-----------------------------------
function vanaDay()
return (VanadielYear() * 360) + VanadielDayOfTheYear();
end; | gpl-3.0 |
tommo/gii | template/game/lib/mock/tools/HighscoreTable.lua | 2 | 2917 | --[[
* MOCK framework for Moai
* Copyright (C) 2012 Tommo Zhou(tommo.zhou@gmail.com). All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
CLASS: HighscoreTable ()
function HighscoreTable:__init(settings)
self.records={}
self.settings=self.settings or {}
end
function HighscoreTable:report(score,userdata,sync)
if score<=0 then return 0,0 end
local rank=0
local lv=userdata and userdata.level
local records=self.records
local ctime=os.time()
local nv={
score=score,
userdata=userdata,
time=ctime,
isnew=true
}
local todayRank=0
local inserted
for i, v in ipairs(records) do
v.isnew=false
local diff=ctime-v.time
-- print(diff,24*3600)
if diff<=24*3600 then --today?
todayRank=todayRank+1
end
if not inserted and score > v.score or
lv and score ==v.score and lv > v.userdata.level then
rank=i
inserted=true
table.insert(records,i,nv)
break
end
end
if not inserted then
table.insert(records,nv)
rank=#records
todayRank=todayRank+1
end
--trim
self.records=table.sub(records,1,self.settings.recordSlotCount or 1000)
if todayRank==1 or not self.settings.onlySyncHighest then
self:doSync(score)
end
return rank,todayRank
end
function HighscoreTable:doSync(score)
if checkOS('iOS') then
if self.settings.leaderboardID then
gameCenterHelper:reportScore(score,self.settings.leaderboardID)
end
else --use other game stat service?
end
end
function HighscoreTable:fetchScore(from, count, timespan)
from=from or 1
count=count or 1
timespan=timespan or 'all'
local result={}
if timespan=='all' then
for i=from ,from+count-1 do
local v=self.records[i]
if not v then break end
result[i-from+1]=v
end
elseif timespan=='today' then --todo
end
return result
end
function HighscoreTable:fetchTopScore(timespan)
local list=self:fetchScore(1,1,timespan)
return list[1]
end | mit |
nxhack/packages | utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/hostapd_stations.lua | 17 | 7694 | local ubus = require "ubus"
local bit32 = require "bit32"
local function get_wifi_interfaces()
local conn = ubus.connect()
local ubuslist = conn:objects()
local interfaces = {}
for _,net in ipairs(ubuslist) do
if net.find(net,"hostapd.") then
local ifname = net:gsub("hostapd.", "")
table.insert(interfaces, ifname);
end
end
conn:close()
return interfaces;
end
local function is_ubus_interface(ubus_interfaces, interface)
for i=1,#ubus_interfaces do
if ubus_interfaces[i] == interface then return true end
end
return false
end
local function get_wifi_interface_labels()
local u = ubus.connect()
local status = u:call("network.wireless", "status", {})
local interfaces = {}
local ubus_interfaces = get_wifi_interfaces()
for _, dev_table in pairs(status) do
for _, intf in ipairs(dev_table['interfaces']) do
local cfg = intf['config']
if is_ubus_interface(ubus_interfaces, cfg['ifname']) then
-- Migrate this to ubus interface once it exposes all interesting labels
local handle = io.popen("hostapd_cli -i " .. cfg['ifname'] .." status")
local hostapd_status = handle:read("*a")
handle:close()
local hostapd = {}
local bss_idx = -1
for line in hostapd_status:gmatch("[^\r\n]+") do
local name, value = string.match(line, "(.+)=(.+)")
if name == "freq" then
hostapd["freq"] = value
elseif name == "channel" then
hostapd["channel"] = value
-- hostapd gives us all bss on the relevant phy, find the one we're interested in
elseif string.match(name, "bss%[%d%]") then
if value == cfg['ifname'] then
bss_idx = tonumber(string.match(name, "bss%[(%d)%]"))
end
elseif bss_idx >= 0 then
if name == "bssid[" .. bss_idx .. "]" then
hostapd["bssid"] = value
elseif name == "ssid[" .. bss_idx .. "]" then
hostapd["ssid"] = value
end
end
end
local labels = {
vif = cfg['ifname'],
ssid = hostapd['ssid'],
bssid = hostapd['bssid'],
encryption = cfg['encryption'], -- In a mixed scenario it would be good to know if A or B was used
frequency = hostapd['freq'],
channel = hostapd['channel'],
}
table.insert(interfaces, labels)
end
end
end
return interfaces
end
local function scrape()
local metric_hostapd_station_rx_packets = metric("hostapd_station_receive_packets_total", "counter")
local metric_hostapd_station_rx_bytes = metric("hostapd_station_receive_bytes_total", "counter")
local metric_hostapd_station_tx_packets = metric("hostapd_station_transmit_packets_total", "counter")
local metric_hostapd_station_tx_bytes = metric("hostapd_station_transmit_bytes_total", "counter")
local metric_hostapd_station_signal = metric("hostapd_station_signal_dbm", "gauge")
local metric_hostapd_station_connected_time = metric("hostapd_station_connected_seconds_total", "counter")
local metric_hostapd_station_inactive_msec = metric("hostapd_station_inactive_seconds", "gauge")
local metric_hostapd_station_flag_auth = metric("hostapd_station_flag_auth", "gauge")
local metric_hostapd_station_flag_assoc = metric("hostapd_station_flag_assoc", "gauge")
local metric_hostapd_station_flag_short_preamble = metric("hostapd_station_flag_short_preamble", "gauge")
local metric_hostapd_station_flag_ht = metric("hostapd_station_flag_ht", "gauge")
local metric_hostapd_station_flag_vht = metric("hostapd_station_flag_vht", "gauge")
local metric_hostapd_station_flag_he = metric("hostapd_station_flag_he", "gauge")
local metric_hostapd_station_flag_mfp = metric("hostapd_station_flag_mfp", "gauge")
local metric_hostapd_station_flag_wmm = metric("hostapd_station_flag_wmm", "gauge")
local metric_hostapd_station_sae_group = metric("hostapd_station_sae_group", "gauge")
local metric_hostapd_station_vht_capb_su_beamformee = metric("hostapd_station_vht_capb_su_beamformee", "gauge")
local metric_hostapd_station_vht_capb_mu_beamformee = metric("hostapd_station_vht_capb_mu_beamformee", "gauge")
local function evaluate_metrics(labels, kv)
values = {}
for k, v in pairs(kv) do
values[k] = v
end
-- check if values exist, they may not due to race conditions while querying
if values["flags"] then
local flags = {}
for flag in string.gmatch(values["flags"], "%u+") do
flags[flag] = true
end
metric_hostapd_station_flag_auth(labels, flags["AUTH"] and 1 or 0)
metric_hostapd_station_flag_assoc(labels, flags["ASSOC"] and 1 or 0)
metric_hostapd_station_flag_short_preamble(labels, flags["SHORT_PREAMBLE"] and 1 or 0)
metric_hostapd_station_flag_ht(labels, flags["HT"] and 1 or 0)
metric_hostapd_station_flag_vht(labels, flags["VHT"]and 1 or 0)
metric_hostapd_station_flag_he(labels, flags["HE"] and 1 or 0)
metric_hostapd_station_flag_wmm(labels, flags["WMM"] and 1 or 0)
metric_hostapd_station_flag_mfp(labels, flags["MFP"] and 1 or 0)
end
-- these metrics can reasonably default to zero, when missing
metric_hostapd_station_rx_packets(labels, values["rx_packets"] or 0)
metric_hostapd_station_rx_bytes(labels, values["rx_bytes"] or 0)
metric_hostapd_station_tx_packets(labels, values["tx_packets"] or 0)
metric_hostapd_station_tx_bytes(labels, values["tx_bytes"] or 0)
-- and these metrics can't be defaulted, so check again
if values["inactive_msec"] ~= nil then
metric_hostapd_station_inactive_msec(labels, values["inactive_msec"] / 1000)
end
if values["signal"] ~= nil then
metric_hostapd_station_signal(labels, values["signal"])
end
if values["connected_time"] ~= nil then
metric_hostapd_station_connected_time(labels, values["connected_time"])
end
if values["vht_caps_info"] ~= nil then
local caps = tonumber(string.gsub(values["vht_caps_info"], "0x", ""), 16)
metric_hostapd_station_vht_capb_su_beamformee(labels, bit32.band(bit32.lshift(1, 12), caps) > 0 and 1 or 0)
metric_hostapd_station_vht_capb_mu_beamformee(labels, bit32.band(bit32.lshift(1, 20), caps) > 0 and 1 or 0)
else
metric_hostapd_station_vht_capb_su_beamformee(labels, 0)
metric_hostapd_station_vht_capb_mu_beamformee(labels, 0)
end
if values["sae_group"] ~= nil then
metric_hostapd_station_sae_group(labels, values["sae_group"])
end
end
for _, labels in ipairs(get_wifi_interface_labels()) do
local vif = labels['vif']
local handle = io.popen("hostapd_cli -i " .. vif .." all_sta")
local all_sta = handle:read("*a")
handle:close()
local station = nil
local metrics = {}
for line in all_sta:gmatch("[^\r\n]+") do
if string.match(line, "^%x[0123456789aAbBcCdDeE]:%x%x:%x%x:%x%x:%x%x:%x%x$") then
-- the first time we see a mac we have no previous station to eval, so don't
if station ~= nil then
labels.station = station
evaluate_metrics(labels, metrics)
end
-- remember current station bssid and truncate metrics
station = line
metrics = {}
else
local key, value = string.match(line, "(.+)=(.+)")
if key ~= nil then
metrics[key] = value
end
end
end
-- the final station, check if there ever was one, will need a metrics eval as well
if station ~= nil then
labels.station = station
evaluate_metrics(labels, metrics)
end
end
end
return { scrape = scrape }
| gpl-2.0 |
MinetestForFun/server-minetestforfun-creative | mods/moreblocks/stairsplus/stairs.lua | 1 | 6036 | --[[
More Blocks: stair definitions
Copyright (c) 2011-2015 Calinou and contributors.
Licensed under the zlib license. See LICENSE.md for more information.
--]]
local S = moreblocks.intllib
-- Node will be called <modname>:stair_<subname>
function register_stair(modname, subname, recipeitem, groups, images, description, drop, light)
stairsplus:register_stair(modname, subname, recipeitem, {
groups = groups,
tiles = images,
description = description,
drop = drop,
light_source = light,
sounds = default.node_sound_stone_defaults(),
})
end
function stairsplus:register_stair(modname, subname, recipeitem, fields)
local defs = {
[""] = {
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, 0, 0.5},
{-0.5, 0, 0, 0.5, 0.5, 0.5},
},
},
},
["_half"] = {
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0, 0, 0.5},
{-0.5, 0, 0, 0, 0.5, 0.5},
},
},
},
["_right_half" ]= {
node_box = {
type = "fixed",
fixed = {
{0, -0.5, -0.5, 0.5, 0, 0.5},
{0, 0, 0, 0.5, 0.5, 0.5},
},
},
},
["_inner"] = {
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, 0, 0.5},
{-0.5, 0, 0, 0.5, 0.5, 0.5},
{-0.5, 0, -0.5, 0, 0.5, 0},
},
},
},
["_outer"] = {
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, 0, 0.5},
{-0.5, 0, 0, 0, 0.5, 0.5},
},
},
},
["_alt"] = {
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, 0, 0},
{-0.5, 0, 0, 0.5, 0.5, 0.5},
},
},
},
["_alt_1"] = {
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.0625, -0.5, 0.5, 0, 0},
{-0.5, 0.4375, 0, 0.5, 0.5, 0.5},
},
},
},
["_alt_2"] = {
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.125, -0.5, 0.5, 0, 0},
{-0.5, 0.375, 0, 0.5, 0.5, 0.5},
},
},
},
["_alt_4"] = {
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.25, -0.5, 0.5, 0, 0},
{-0.5, 0.25, 0, 0.5, 0.5, 0.5},
},
},
},
}
local desc = S("%s Stairs"):format(fields.description)
for alternate, def in pairs(defs) do
for k, v in pairs(fields) do
def[k] = v
end
def.drawtype = "nodebox"
def.paramtype = "light"
def.paramtype2 = "facedir"
def.on_place = minetest.rotate_node
def.description = desc
def.groups = stairsplus:prepare_groups(fields.groups)
if fields.drop then
def.drop = modname .. ":stair_" .. fields.drop .. alternate
end
minetest.register_node(":" .. modname .. ":stair_" .. subname .. alternate, def)
end
minetest.register_alias("stairs:stair_" .. subname, modname .. ":stair_" .. subname)
circular_saw.known_nodes[recipeitem] = {modname, subname}
-- Some saw-less recipes:
minetest.register_craft({
output = modname .. ":stair_" .. subname .. " 8",
recipe = {
{recipeitem, "", ""},
{recipeitem, recipeitem, ""},
{recipeitem, recipeitem, recipeitem},
},
})
minetest.register_craft({
output = modname .. ":stair_" .. subname .. " 8",
recipe = {
{"", "", recipeitem},
{"", recipeitem, recipeitem},
{recipeitem, recipeitem, recipeitem},
},
})
minetest.register_craft({
type = "shapeless",
output = modname .. ":stair_" .. subname,
recipe = {modname .. ":panel_" .. subname, modname .. ":slab_" .. subname},
})
minetest.register_craft({
type = "shapeless",
output = modname .. ":stair_" .. subname,
recipe = {modname .. ":panel_" .. subname, modname .. ":panel_" .. subname, modname .. ":panel_" .. subname},
})
minetest.register_craft({
type = "shapeless",
output = modname .. ":stair_" .. subname .. "_outer",
recipe = {modname .. ":micro_" .. subname, modname .. ":slab_" .. subname},
})
minetest.register_craft({
type = "shapeless",
output = modname .. ":stair_" .. subname .. "_half",
recipe = {modname .. ":micro_" .. subname, modname .. ":micro_" .. subname, modname .. ":micro_" .. subname},
})
minetest.register_craft({
type = "shapeless",
output = modname .. ":stair_" .. subname .. "_half",
recipe = {modname .. ":panel_" .. subname, modname .. ":micro_" .. subname},
})
minetest.register_craft({
type = "shapeless",
output = modname .. ":stair_" .. subname .. "_right_half",
recipe = {modname .. ":stair_" .. subname .. "_half"},
})
minetest.register_craft({
type = "shapeless",
output = modname .. ":stair_" .. subname,
recipe = {modname .. ":micro_" .. subname, modname .. ":micro_" .. subname, modname .. ":micro_" .. subname, modname .. ":micro_" .. subname, modname .. ":micro_" .. subname, modname .. ":micro_" .. subname},
})
minetest.register_craft({
type = "shapeless",
output = modname .. ":stair_" .. subname .. "_inner",
recipe = {modname .. ":micro_" .. subname, modname .. ":micro_" .. subname, modname .. ":micro_" .. subname, modname .. ":micro_" .. subname, modname .. ":micro_" .. subname, modname .. ":micro_" .. subname, modname .. ":micro_" .. subname},
})
minetest.register_craft({
type = "shapeless",
output = modname .. ":stair_" .. subname .. "_outer",
recipe = {modname .. ":micro_" .. subname, modname .. ":micro_" .. subname, modname .. ":micro_" .. subname, modname .. ":micro_" .. subname, modname .. ":micro_" .. subname},
})
minetest.register_craft({
type = "shapeless",
output = modname .. ":stair_" .. subname,
recipe = {modname .. ":panel_" .. subname, modname .. ":panel_" .. subname, modname .. ":panel_" .. subname},
})
minetest.register_craft({ -- See mirrored variation of the recipe below.
output = modname .. ":stair_" .. subname .. "_alt",
recipe = {
{modname .. ":panel_" .. subname, ""},
{"" , modname .. ":panel_" .. subname},
},
})
minetest.register_craft({ -- Mirrored variation of the recipe above.
output = modname .. ":stair_" .. subname .. "_alt",
recipe = {
{"" , modname .. ":panel_" .. subname},
{modname .. ":panel_" .. subname, ""},
},
})
end
| unlicense |
Endika/Algorithm-Implementations | Monty_Hall_Problem/Lua/Yonaba/monty_hall.lua | 26 | 1033 | -- Monty-Hall problem implementation
-- See : http://en.wikipedia.org/wiki/Monty_Hall_problem
-- Create a range of values as a list
local function range(n)
local t = {}
for i = 1,n do t[i] = i end
return t
end
-- Simulates Monty Hall problem
-- ndoors : number of doors
-- switch : whether or not the player wants to switch his initial choice
-- return : true if the player won, false otherwise
local function simulate(ndoors, switch)
local winning_door = math.random(1,ndoors)
local choice = math.random(1,ndoors)
local doors = range(ndoors)
while #doors>2 do
local door_to_open_index = math.random(1,#doors)
local door_to_open = doors[door_to_open_index]
if (door_to_open ~= winning_door
and door_to_open ~= choice) then
table.remove(doors, door_to_open_index)
end
end
if switch then
choice = (doors[1] == choice and doors[2] or doors[1])
end
return (choice == winning_door)
end
math.randomseed(os.time())
local r = simulate(5,true)
print('won',r)
return simulate
| mit |
TakingInitiative/wesnoth | data/ai/micro_ais/cas/ca_herding_herd_sheep.lua | 7 | 3249 | local H = wesnoth.require "lua/helper.lua"
local AH = wesnoth.require "ai/lua/ai_helper.lua"
local herding_area = wesnoth.require "ai/micro_ais/cas/ca_herding_f_herding_area.lua"
local function get_dogs(cfg)
local dogs = AH.get_units_with_moves {
side = wesnoth.current.side,
{ "and", H.get_child(cfg, "filter") }
}
return dogs
end
local function get_sheep_to_herd(cfg)
local all_sheep = wesnoth.get_units {
side = wesnoth.current.side,
{ "and", H.get_child(cfg, "filter_second") },
{ "not", { { "filter_adjacent", { side = wesnoth.current.side, { "and", H.get_child(cfg, "filter") } } } } }
}
local sheep_to_herd = {}
local herding_area = herding_area(cfg)
for _,single_sheep in ipairs(all_sheep) do
if (not herding_area:get(single_sheep.x, single_sheep.y)) then
table.insert(sheep_to_herd, single_sheep)
end
end
return sheep_to_herd
end
local ca_herding_herd_sheep = {}
function ca_herding_herd_sheep:evaluation(cfg)
-- If dogs have moves left, and there is a sheep with moves left outside the
-- herding area, chase it back
if (not get_dogs(cfg)[1]) then return 0 end
if (not get_sheep_to_herd(cfg)[1]) then return 0 end
return cfg.ca_score
end
function ca_herding_herd_sheep:execution(cfg)
local dogs = get_dogs(cfg)
local sheep_to_herd = get_sheep_to_herd(cfg)
local max_rating, best_dog, best_hex = -9e99
local c_x, c_y = cfg.herd_x, cfg.herd_y
for _,single_sheep in ipairs(sheep_to_herd) do
-- Farthest sheep goes first
local sheep_rating = H.distance_between(c_x, c_y, single_sheep.x, single_sheep.y) / 10.
-- Sheep with no movement left gets big hit
if (single_sheep.moves == 0) then sheep_rating = sheep_rating - 100. end
for _,dog in ipairs(dogs) do
local reach_map = AH.get_reachable_unocc(dog)
reach_map:iter( function(x, y, v)
local dist = H.distance_between(x, y, single_sheep.x, single_sheep.y)
local rating = sheep_rating - dist
-- Needs to be on "far side" of sheep, wrt center for adjacent hexes
if (H.distance_between(x, y, c_x, c_y) <= H.distance_between(single_sheep.x, single_sheep.y, c_x, c_y))
and (dist == 1)
then rating = rating - 1000 end
-- And the closer dog goes first (so that it might be able to chase another sheep afterward)
rating = rating - H.distance_between(x, y, dog.x, dog.y) / 100.
-- Finally, prefer to stay on path, if possible
if (wesnoth.match_location(x, y, H.get_child(cfg, "filter_location")) ) then rating = rating + 0.001 end
reach_map:insert(x, y, rating)
if (rating > max_rating) then
max_rating, best_dog, best_hex = rating, dog, { x, y }
end
end)
end
end
if (best_hex[1] == best_dog.x) and (best_hex[2] == best_dog.y) then
AH.checked_stopunit_moves(ai, best_dog)
else
AH.checked_move(ai, best_dog, best_hex[1], best_hex[2]) -- partial move only!
end
end
return ca_herding_herd_sheep
| gpl-2.0 |
rpetit3/darkstar | scripts/zones/Giddeus/npcs/Harvesting_Point.lua | 13 | 1059 | -----------------------------------
-- Area: Giddeus
-- NPC: Harvesting Point
-----------------------------------
package.loaded["scripts/zones/Giddeus/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/harvesting");
require("scripts/zones/Giddeus/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startHarvesting(player,player:getZoneID(),npc,trade,0x0046);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(HARVESTING_IS_POSSIBLE_HERE,1020);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
lukego/snabbswitch | src/core/link.lua | 13 | 3092 | module(...,package.seeall)
local debug = _G.developer_debug
local shm = require("core.shm")
local ffi = require("ffi")
local C = ffi.C
local packet = require("core.packet")
require("core.packet_h")
local counter = require("core.counter")
require("core.counter_h")
require("core.link_h")
local band = require("bit").band
local size = C.LINK_RING_SIZE -- NB: Huge slow-down if this is not local
max = C.LINK_MAX_PACKETS
local counternames = {"rxpackets", "txpackets", "rxbytes", "txbytes", "txdrop"}
function new (name)
local r = shm.map("links/"..name, "struct link")
for _, c in ipairs(counternames) do
r.stats[c] = counter.open("counters/"..name.."/"..c)
end
return r
end
function free (r, name)
for _, c in ipairs(counternames) do
counter.delete("counters/"..name.."/"..c)
end
shm.unmap(r)
shm.unlink("links/"..name)
end
function receive (r)
-- if debug then assert(not empty(r), "receive on empty link") end
local p = r.packets[r.read]
r.read = band(r.read + 1, size - 1)
counter.add(r.stats.rxpackets)
counter.add(r.stats.rxbytes, p.length)
return p
end
function front (r)
return (r.read ~= r.write) and r.packets[r.read] or nil
end
function transmit (r, p)
-- assert(p)
if full(r) then
counter.add(r.stats.txdrop)
packet.free(p)
else
r.packets[r.write] = p
r.write = band(r.write + 1, size - 1)
counter.add(r.stats.txpackets)
counter.add(r.stats.txbytes, p.length)
r.has_new_data = true
end
end
-- Return true if the ring is empty.
function empty (r)
return r.read == r.write
end
-- Return true if the ring is full.
function full (r)
return band(r.write + 1, size - 1) == r.read
end
-- Return the number of packets that are ready for read.
function nreadable (r)
if r.read > r.write then
return r.write + size - r.read
else
return r.write - r.read
end
end
function nwritable (r)
return max - nreadable(r)
end
function stats (r)
local stats = {}
for _, c
in ipairs(counternames) do
stats[c] = tonumber(counter.read(r.stats[c]))
end
return stats
end
function selftest ()
print("selftest: link")
local r = new("test")
local p = packet.allocate()
assert(counter.read(r.stats.txpackets) == 0 and empty(r) == true and full(r) == false)
assert(nreadable(r) == 0)
transmit(r, p)
assert(counter.read(r.stats.txpackets) == 1 and empty(r) == false and full(r) == false)
for i = 1, max-2 do
transmit(r, p)
end
assert(counter.read(r.stats.txpackets) == max-1 and empty(r) == false and full(r) == false)
assert(nreadable(r) == counter.read(r.stats.txpackets))
transmit(r, p)
assert(counter.read(r.stats.txpackets) == max and empty(r) == false and full(r) == true)
transmit(r, p)
assert(counter.read(r.stats.txpackets) == max and counter.read(r.stats.txdrop) == 1)
assert(not empty(r) and full(r))
while not empty(r) do
receive(r)
end
assert(counter.read(r.stats.rxpackets) == max)
link.free(r, "test")
print("selftest OK")
end
| apache-2.0 |
rpetit3/darkstar | scripts/globals/items/plate_of_homemade_salad.lua | 18 | 1107 | -----------------------------------------
-- ID: 5227
-- Item: plate_of_homemade_salad
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Magic 10
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5227);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 10);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 10);
end;
| gpl-3.0 |
esguk811/DarkRP | gamemode/modules/fadmin/fadmin/cleanup/sv_init.lua | 5 | 1782 | local function ClearDecals(ply, cmd, args)
if not FAdmin.Access.PlayerHasPrivilege(ply, "CleanUp") then FAdmin.Messages.SendMessage(ply, 5, "No access!") return false end
for k,v in pairs(player.GetAll()) do
v:ConCommand("r_cleardecals")
end
FAdmin.Messages.ActionMessage(ply, player.GetAll(), "You have removed all decals. NOTE: this does NOT make the server ANY less laggy!", "All decals have been removed. NOTE: this does NOT make the server ANY less laggy!", "Removed all decals.")
return true
end
local function StopSounds(ply, cmd, args)
if not FAdmin.Access.PlayerHasPrivilege(ply, "CleanUp") then FAdmin.Messages.SendMessage(ply, 5, "No access!") return false end
umsg.Start("FAdmin_StopSounds")
umsg.End()
FAdmin.Messages.ActionMessage(ply, player.GetAll(), "You have stopped all sounds", "All sounds have been stopped", "Stopped all sounds")
return true
end
local function CleanUp(ply, cmd, args)
if not FAdmin.Access.PlayerHasPrivilege(ply, "CleanUp") then FAdmin.Messages.SendMessage(ply, 5, "No access!") return false end
game.CleanUpMap()
FAdmin.Messages.ActionMessage(ply, player.GetAll(), "You have cleaned up the map", "The map has been cleaned up", "Cleaned up the map")
return true
end
FAdmin.StartHooks["CleanUp"] = function()
FAdmin.Commands.AddCommand("ClearDecals", ClearDecals)
FAdmin.Commands.AddCommand("StopSounds", StopSounds)
FAdmin.Commands.AddCommand("CleanUp", CleanUp)
local oldCleanup = concommand.GetTable()["gmod_admin_cleanup"]
concommand.Add("gmod_admin_cleanup", function(ply, cmd, args)
if args[1] then return oldCleanup(ply, cmd, args) end
return CleanUp(ply, cmd, args)
end)
FAdmin.Access.AddPrivilege("CleanUp", 2)
end
| mit |
rpetit3/darkstar | scripts/zones/Grand_Palace_of_HuXzoi/npcs/_iya.lua | 12 | 1611 | -----------------------------------
-- Area: Grand Palace of Hu'Xzoi
-- NPC: Gate of the Gods
-- @pos -20 0.1 -283 34
-----------------------------------
package.loaded["scripts/zones/Grand_Palace_of_HuXzoi/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Grand_Palace_of_HuXzoi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and player:getVar("PromathiaStatus") == 3) then
player:startEvent(0x0001);
else
player:startEvent(0x0034);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0034 and option == 1) then
player:setPos(-419.995,0,248.483,191,35); -- To The Garden of RuHmet {R}
elseif (csid == 0x0001) then
player:setVar("PromathiaStatus",0);
player:completeMission(COP, GARDEN_OF_ANTIQUITY);
player:addMission(COP, A_FATE_DECIDED);
player:addItem(14672);
player:messageSpecial(ITEM_OBTAINED, 14672);
end
end; | gpl-3.0 |
rpetit3/darkstar | scripts/zones/Metalworks/npcs/Tomasa.lua | 13 | 1512 | -----------------------------------
-- Area: Metalworks
-- NPC: Tomasa
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,TOMASA_SHOP_DIALOG);
stock = {0x112C,257,1, -- Sausage Roll
0x1139,73,1, -- Hard-Boiled Egg
0x1141,3036,1, -- Egg Soup
0x115A,368,1, -- Pineapple Juice
0x1127,22,2, -- Bretzel
0x11E2,143,2, -- Sausage
0x1148,1012,2, -- Melon Juice
0x1193,92,3, -- Iron Bread
0x1154,294,3, -- Baked Popoto
0x1167,184,3, -- Pebble Soup
0x119D,10,3} -- Distilled Water
showNationShop(player, BASTOK, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
EntranceJew/poopsmith.lua | poopsmith.lua | 1 | 2766 | local poopsmith = {
_VERSION = 'poopsmith 1.0.0',
_DESCRIPTION = 'The much less useful alternative to strict.lua',
_URL = 'https://github.com/EntranceJew/poopsmith.lua',
_LICENSE = [[
The MIT License (MIT)
Copyright (c) 2015 EntranceJew
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.
]]
}
-- to share, with the lazy
poopsmith.unipoop = "๐ฉ"
poopsmith.safepoop = "\240\159\146\169"
-- all the valid modes
poopsmith.modes = {
bobSaget = {
__newindex = function(g, name, value)
rawset(_G, poopsmith.unipoop, value)
return rawset(_G, name, poopsmith.unipoop)
end
},
janitor = {
__smithSetup = function()
rawset(_G, poopsmith.unipoop, {})
end,
__newindex = function(g, name, value)
return rawset(_G[poopsmith.unipoop], name, value)
end
},
tamagotchi = {
__smithSetup = function()
rawset(_G, poopsmith.unipoop, 1)
end,
__newindex = function(g, name, value)
rawset(_G, poopsmith.unipoop, rawget(_G, poopsmith.unipoop)+1)
return rawset(_G, poopsmith.unipoop:rep(_G[poopsmith.unipoop]), value)
end
},
beanCounter = {
__smithSetup = function()
rawset(_G, poopsmith.unipoop, 0)
end,
__newindex = function(g, name, value)
rawset(_G, poopsmith.unipoop, rawget(_G, poopsmith.unipoop)+1)
return rawset(_G, poopsmith.unipoop .. _G[poopsmith.unipoop], value)
end
},
}
function poopsmith.setMode(mode)
if not poopsmith.modes[mode] then
return false
end
if poopsmith.modes[mode].__smithSetup then
poopsmith.modes[mode].__smithSetup()
end
setmetatable(_G, poopsmith.modes[mode])
return true
end
return setmetatable(poopsmith, {__call = function(_, mode) poopsmith.setMode(mode) end}) | mit |
rpetit3/darkstar | scripts/zones/Dynamis-Beaucedine/mobs/Goblin_Statue.lua | 22 | 1841 | -----------------------------------
-- Area: Dynamis Beaucedine
-- MOB: Goblin Statue
-- Map Position: http://images1.wikia.nocookie.net/__cb20090312005233/ffxi/images/thumb/b/b6/Bea.jpg/375px-Bea.jpg
-----------------------------------
package.loaded["scripts/zones/Dynamis-Beaucedine/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Beaucedine/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
dynamis.spawnGroup(mob, beaucedineGoblinList, 2);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
local mobID = mob:getID();
-- Time Bonus: 031 046
if (mobID == 17326860 and mob:isInBattlefieldList() == false) then
player:addTimeToDynamis(15);
mob:addInBattlefieldList();
elseif (mobID == 17326875 and mob:isInBattlefieldList() == false) then
player:addTimeToDynamis(15);
mob:addInBattlefieldList();
-- HP Bonus: 037 041 044 051 053
elseif (mobID == 17326866 or mobID == 17326870 or mobID == 17326873 or mobID == 17326880 or mobID == 17326882) then
player:restoreHP(2000);
player:messageBasic(024,(player:getMaxHP()-player:getHP()));
-- MP Bonus: 038 040 045 049 052 104
elseif (mobID == 17326867 or mobID == 17326869 or mobID == 17326874 or mobID == 17326878 or mobID == 17326881 or mobID == 17326933) then
player:restoreMP(2000);
player:messageBasic(025,(player:getMaxMP()-player:getMP()));
end
end;
| gpl-3.0 |
rpetit3/darkstar | scripts/zones/Kazham/npcs/Kocho_Phunakcham.lua | 15 | 1056 | -----------------------------------
-- Area: Kazham
-- NPC: Kocho Phunakcham
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("BathedInScent") == 1) then
player:startEvent(0x00AA); -- scent from Blue Rafflesias
else
player:startEvent(0x0041);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
rpetit3/darkstar | scripts/zones/East_Ronfaure/npcs/Cheval_River.lua | 13 | 1679 | -----------------------------------
-- Area: East Ronfaure
-- NPC: Cheval_River
-- @pos 223 -58 426 101
-- Involved in Quest: Waters of Cheval
-----------------------------------
package.loaded["scripts/zones/East_Ronfaure/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/East_Ronfaure/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,WATER_OF_THE_CHEVAL) == QUEST_ACCEPTED and trade:hasItemQty(602, 1)) then
if (trade:getItemCount() == 1 and player:getFreeSlotsCount() > 0) then
player:tradeComplete();
player:addItem(603);
player:messageSpecial(CHEVAL_RIVER_WATER, 603);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 603);
end;
end;
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasItem(602) == true) then
player:messageSpecial(BLESSED_WATERSKIN);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
lukego/snabbswitch | lib/ljsyscall/syscall/osx/types.lua | 18 | 9044 | -- OSX types
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
local function init(types)
local abi = require "syscall.abi"
local t, pt, s, ctypes = types.t, types.pt, types.s, types.ctypes
local ffi = require "ffi"
local bit = require "syscall.bit"
local h = require "syscall.helpers"
local addtype, addtype_var, addtype_fn, addraw2 = h.addtype, h.addtype_var, h.addtype_fn, h.addraw2
local ptt, reviter, mktype, istype, lenfn, lenmt, getfd, newfn
= h.ptt, h.reviter, h.mktype, h.istype, h.lenfn, h.lenmt, h.getfd, h.newfn
local ntohl, ntohl, ntohs, htons, octal = h.ntohl, h.ntohl, h.ntohs, h.htons, h.octal
local c = require "syscall.osx.constants"
local mt = {} -- metatables
local addtypes = {
fdset = "fd_set",
clock_serv = "clock_serv_t",
}
local addstructs = {
mach_timespec = "struct mach_timespec",
}
for k, v in pairs(addtypes) do addtype(types, k, v) end
for k, v in pairs(addstructs) do addtype(types, k, v, lenmt) end
t.clock_serv1 = ffi.typeof("clock_serv_t[1]")
-- 32 bit dev_t, 24 bit minor, 8 bit major
local function makedev(major, minor)
if type(major) == "table" then major, minor = major[1], major[2] end
local dev = major or 0
if minor then dev = bit.bor(minor, bit.lshift(major, 24)) end
return dev
end
mt.device = {
index = {
major = function(dev) return bit.bor(bit.band(bit.rshift(dev.dev, 24), 0xff)) end,
minor = function(dev) return bit.band(dev.dev, 0xffffff) end,
device = function(dev) return tonumber(dev.dev) end,
},
newindex = {
device = function(dev, major, minor) dev.dev = makedev(major, minor) end,
},
__new = function(tp, major, minor)
return ffi.new(tp, makedev(major, minor))
end,
}
addtype(types, "device", "struct {dev_t dev;}", mt.device)
function t.sa(addr, addrlen) return addr end -- non Linux is trivial, Linux has odd unix handling
mt.stat = {
index = {
dev = function(st) return t.device(st.st_dev) end,
mode = function(st) return st.st_mode end,
ino = function(st) return tonumber(st.st_ino) end,
nlink = function(st) return st.st_nlink end,
uid = function(st) return st.st_uid end,
gid = function(st) return st.st_gid end,
rdev = function(st) return t.device(st.st_rdev) end,
atime = function(st) return st.st_atimespec.time end,
ctime = function(st) return st.st_ctimespec.time end,
mtime = function(st) return st.st_mtimespec.time end,
birthtime = function(st) return st.st_birthtimespec.time end,
size = function(st) return tonumber(st.st_size) end,
blocks = function(st) return tonumber(st.st_blocks) end,
blksize = function(st) return tonumber(st.st_blksize) end,
flags = function(st) return st.st_flags end,
gen = function(st) return st.st_gen end,
type = function(st) return bit.band(st.st_mode, c.S_I.FMT) end,
todt = function(st) return bit.rshift(st.type, 12) end,
isreg = function(st) return st.type == c.S_I.FREG end,
isdir = function(st) return st.type == c.S_I.FDIR end,
ischr = function(st) return st.type == c.S_I.FCHR end,
isblk = function(st) return st.type == c.S_I.FBLK end,
isfifo = function(st) return st.type == c.S_I.FIFO end,
islnk = function(st) return st.type == c.S_I.FLNK end,
issock = function(st) return st.type == c.S_I.FSOCK end,
},
}
-- add some friendlier names to stat, also for luafilesystem compatibility
mt.stat.index.access = mt.stat.index.atime
mt.stat.index.modification = mt.stat.index.mtime
mt.stat.index.change = mt.stat.index.ctime
local namemap = {
file = mt.stat.index.isreg,
directory = mt.stat.index.isdir,
link = mt.stat.index.islnk,
socket = mt.stat.index.issock,
["char device"] = mt.stat.index.ischr,
["block device"] = mt.stat.index.isblk,
["named pipe"] = mt.stat.index.isfifo,
}
mt.stat.index.typename = function(st)
for k, v in pairs(namemap) do if v(st) then return k end end
return "other"
end
addtype(types, "stat", "struct stat", mt.stat)
local signames = {}
local duplicates = {LWT = true, IOT = true, CLD = true, POLL = true}
for k, v in pairs(c.SIG) do
if not duplicates[k] then signames[v] = k end
end
mt.siginfo = {
index = {
signo = function(s) return s.si_signo end,
errno = function(s) return s.si_errno end,
code = function(s) return s.si_code end,
pid = function(s) return s.si_pid end,
uid = function(s) return s.si_uid end,
status = function(s) return s.si_status end,
addr = function(s) return s.si_addr end,
value = function(s) return s.si_value end,
band = function(s) return s.si_band end,
signame = function(s) return signames[s.signo] end,
},
newindex = {
signo = function(s, v) s.si_signo = v end,
errno = function(s, v) s.si_errno = v end,
code = function(s, v) s.si_code = v end,
pid = function(s, v) s.si_pid = v end,
uid = function(s, v) s.si_uid = v end,
status = function(s, v) s.si_status = v end,
addr = function(s, v) s.si_addr = v end,
value = function(s, v) s.si_value = v end,
band = function(s, v) s.si_band = v end,
},
__len = lenfn,
}
addtype(types, "siginfo", "siginfo_t", mt.siginfo)
mt.dirent = {
index = {
ino = function(self) return self.d_ino end,
--seekoff = function(self) return self.d_seekoff end, -- not in legacy dirent
reclen = function(self) return self.d_reclen end,
namlen = function(self) return self.d_namlen end,
type = function(self) return self.d_type end,
name = function(self) return ffi.string(self.d_name, self.d_namlen) end,
toif = function(self) return bit.lshift(self.d_type, 12) end, -- convert to stat types
},
__len = function(self) return self.d_reclen end,
}
for k, v in pairs(c.DT) do
mt.dirent.index[k] = function(self) return self.type == v end
end
addtype(types, "dirent", "struct legacy_dirent", mt.dirent)
mt.flock = {
index = {
type = function(self) return self.l_type end,
whence = function(self) return self.l_whence end,
start = function(self) return self.l_start end,
len = function(self) return self.l_len end,
pid = function(self) return self.l_pid end,
},
newindex = {
type = function(self, v) self.l_type = c.FCNTL_LOCK[v] end,
whence = function(self, v) self.l_whence = c.SEEK[v] end,
start = function(self, v) self.l_start = v end,
len = function(self, v) self.l_len = v end,
pid = function(self, v) self.l_pid = v end,
},
__new = newfn,
}
addtype(types, "flock", "struct flock", mt.flock)
-- TODO see Linux notes. Also maybe can be shared with BSDs, have not checked properly
mt.wait = {
__index = function(w, k)
local _WSTATUS = bit.band(w.status, octal("0177"))
local _WSTOPPED = octal("0177")
local WTERMSIG = _WSTATUS
local EXITSTATUS = bit.band(bit.rshift(w.status, 8), 0xff)
local WIFEXITED = (_WSTATUS == 0)
local tab = {
WIFEXITED = WIFEXITED,
WIFSTOPPED = bit.band(w.status, 0xff) == _WSTOPPED,
WIFSIGNALED = _WSTATUS ~= _WSTOPPED and _WSTATUS ~= 0
}
if tab.WIFEXITED then tab.EXITSTATUS = EXITSTATUS end
if tab.WIFSTOPPED then tab.WSTOPSIG = EXITSTATUS end
if tab.WIFSIGNALED then tab.WTERMSIG = WTERMSIG end
if tab[k] then return tab[k] end
local uc = 'W' .. k:upper()
if tab[uc] then return tab[uc] end
end
}
function t.waitstatus(status)
return setmetatable({status = status}, mt.wait)
end
-- sigaction, standard POSIX behaviour with union of handler and sigaction
addtype_fn(types, "sa_sigaction", "void (*)(int, siginfo_t *, void *)")
mt.sigaction = {
index = {
handler = function(sa) return sa.__sigaction_u.__sa_handler end,
sigaction = function(sa) return sa.__sigaction_u.__sa_sigaction end,
mask = function(sa) return sa.sa_mask end,
flags = function(sa) return tonumber(sa.sa_flags) end,
},
newindex = {
handler = function(sa, v)
if type(v) == "string" then v = pt.void(c.SIGACT[v]) end
if type(v) == "number" then v = pt.void(v) end
sa.__sigaction_u.__sa_handler = v
end,
sigaction = function(sa, v)
if type(v) == "string" then v = pt.void(c.SIGACT[v]) end
if type(v) == "number" then v = pt.void(v) end
sa.__sigaction_u.__sa_sigaction = v
end,
mask = function(sa, v)
if not ffi.istype(t.sigset, v) then v = t.sigset(v) end
sa.sa_mask = v
end,
flags = function(sa, v) sa.sa_flags = c.SA[v] end,
},
__new = function(tp, tab)
local sa = ffi.new(tp)
if tab then for k, v in pairs(tab) do sa[k] = v end end
if tab and tab.sigaction then sa.sa_flags = bit.bor(sa.flags, c.SA.SIGINFO) end -- this flag must be set if sigaction set
return sa
end,
}
addtype(types, "sigaction", "struct sigaction", mt.sigaction)
return types
end
return {init = init}
| apache-2.0 |
iRGBit/Dato-Core | src/unity/python/graphlab/lua/pl/stringio.lua | 28 | 3821 | --- Reading and writing strings using file-like objects. <br>
--
-- f = stringio.open(text)
-- l1 = f:read() -- read first line
-- n,m = f:read ('*n','*n') -- read two numbers
-- for line in f:lines() do print(line) end -- iterate over all lines
-- f = stringio.create()
-- f:write('hello')
-- f:write('dolly')
-- assert(f:value(),'hellodolly')
--
-- See @{03-strings.md.File_style_I_O_on_Strings|the Guide}.
-- @module pl.stringio
local unpack = rawget(_G,'unpack') or rawget(table,'unpack')
local getmetatable,tostring,tonumber = getmetatable,tostring,tonumber
local concat,append = table.concat,table.insert
local stringio = {}
-- Writer class
local SW = {}
SW.__index = SW
local function xwrite(self,...)
local args = {...} --arguments may not be nil!
for i = 1, #args do
append(self.tbl,args[i])
end
end
function SW:write(arg1,arg2,...)
if arg2 then
xwrite(self,arg1,arg2,...)
else
append(self.tbl,arg1)
end
end
function SW:writef(fmt,...)
self:write(fmt:format(...))
end
function SW:value()
return concat(self.tbl)
end
function SW:__tostring()
return self:value()
end
function SW:close() -- for compatibility only
end
function SW:seek()
end
-- Reader class
local SR = {}
SR.__index = SR
function SR:_read(fmt)
local i,str = self.i,self.str
local sz = #str
if i > sz then return nil end
local res
if fmt == '*l' or fmt == '*L' then
local idx = str:find('\n',i) or (sz+1)
res = str:sub(i,fmt == '*l' and idx-1 or idx)
self.i = idx+1
elseif fmt == '*a' then
res = str:sub(i)
self.i = sz
elseif fmt == '*n' then
local _,i2,i2,idx
_,idx = str:find ('%s*%d+',i)
_,i2 = str:find ('^%.%d+',idx+1)
if i2 then idx = i2 end
_,i2 = str:find ('^[eE][%+%-]*%d+',idx+1)
if i2 then idx = i2 end
local val = str:sub(i,idx)
res = tonumber(val)
self.i = idx+1
elseif type(fmt) == 'number' then
res = str:sub(i,i+fmt-1)
self.i = i + fmt
else
error("bad read format",2)
end
return res
end
function SR:read(...)
if select('#',...) == 0 then
return self:_read('*l')
else
local res, fmts = {},{...}
for i = 1, #fmts do
res[i] = self:_read(fmts[i])
end
return unpack(res)
end
end
function SR:seek(whence,offset)
local base
whence = whence or 'cur'
offset = offset or 0
if whence == 'set' then
base = 1
elseif whence == 'cur' then
base = self.i
elseif whence == 'end' then
base = #self.str
end
self.i = base + offset
return self.i
end
function SR:lines(...)
local n, args = select('#',...)
if n > 0 then
args = {...}
end
return function()
if n == 0 then
return self:_read '*l'
else
return self:read(unpack(args))
end
end
end
function SR:close() -- for compatibility only
end
--- create a file-like object which can be used to construct a string.
-- The resulting object has an extra `value()` method for
-- retrieving the string value. Implements `file:write`, `file:seek`, `file:lines`,
-- plus an extra `writef` method which works like `utils.printf`.
-- @usage f = create(); f:write('hello, dolly\n'); print(f:value())
function stringio.create()
return setmetatable({tbl={}},SW)
end
--- create a file-like object for reading from a given string.
-- Implements `file:read`.
-- @string s The input string.
-- @usage fs = open '20 10'; x,y = f:read ('*n','*n'); assert(x == 20 and y == 10)
function stringio.open(s)
return setmetatable({str=s,i=1},SR)
end
function stringio.lines(s,...)
return stringio.open(s):lines(...)
end
return stringio
| agpl-3.0 |
thehunmonkgroup/luchia | tests/unit/core_document.lua | 3 | 8780 | local lunatest = require "lunatest"
local assert_equal = lunatest.assert_equal
local assert_table = lunatest.assert_table
local common = require "common_test_functions"
local document = require "luchia.core.document"
local attachment = require "luchia.core.attachment"
local tests = {}
local id = "id"
local rev = "rev"
local doc_key = "key"
local doc_value = "value"
local content_type = "application/json"
local text_file_content_type = "text/plain"
local attachment_file_name = "attachment.txt"
local custom_loader_file_path = "/tmp/textfile1.txt"
local custom_loader_file_data = "foo."
function tests.test_new_no_params_returns_empty_document()
local doc = document:new()
assert_table(doc, "doc")
assert_equal(0, common.table_length(doc.document), "doc.document length")
end
function tests.test_new_no_params_returns_only_document()
local doc = document:new()
assert_equal(1, common.table_length(doc), "doc length")
end
local function document_only_id()
local params = {
id = id,
}
local doc = document:new(params)
assert_table(doc, "doc")
return doc, id
end
function tests.test_new_only_id_param_returns_id()
local doc, id = document_only_id()
assert_equal(id, doc.id)
end
function tests.test_new_only_id_param_returns_document()
local doc = document_only_id()
assert_table(doc.document, "doc.document")
end
function tests.test_new_only_id_param_returns_only_id_and_document()
local doc = document_only_id()
assert_equal(2, common.table_length(doc), "doc length")
end
function tests.test_new_only_id_param_returns_id_in_document()
local doc, id = document_only_id()
assert_equal(id, doc.document._id, "doc.document._id")
end
function tests.test_new_only_id_param_returns_only_id_in_document()
local doc = document_only_id()
assert_equal(1, common.table_length(doc.document), "doc.document length")
end
function tests.test_new_no_id_with_rev_param_returns_nil()
local params = {
rev = rev,
}
local doc = document:new(params)
assert_equal(nil, doc)
end
local function document_only_document()
local params = {
document = {
[doc_key] = doc_value,
},
}
local doc = document:new(params)
assert_table(doc, "doc")
return doc
end
function tests.test_new_only_document_param_returns_document()
local doc = document_only_document()
assert_table(doc.document, "doc.document")
end
function tests.test_new_only_document_param_returns_only_document()
local doc = document_only_document()
assert_equal(1, common.table_length(doc), "doc length")
end
function tests.test_new_only_document_param_returns_correct_document_key_value()
local doc = document_only_document()
assert_equal(doc_value, doc.document[doc_key])
end
function tests.test_new_only_document_param_returns_only_correct_document_key_value()
local doc = document_only_document()
assert_equal(1, common.table_length(doc.document), "doc.document length")
end
local function document_all_params()
local params = {
id = id,
rev = rev,
document = {
[doc_key] = doc_value,
},
}
local doc = document:new(params)
assert_table(doc, "doc")
return doc
end
function tests.test_new_all_params_returns_id()
local doc = document_all_params()
assert_equal(id, doc.id)
end
function tests.test_new_all_params_returns_rev()
local doc = document_all_params()
assert_equal(rev, doc.rev)
end
function tests.test_new_all_params_returns_document()
local doc = document_all_params()
assert_table(doc.document, "doc.document")
end
function tests.test_new_all_params_returns_only_id_rev_document()
local doc = document_all_params()
assert_equal(3, common.table_length(doc), "doc length")
end
function tests.test_new_all_params_returns_id_in_document()
local doc = document_all_params()
assert_equal(id, doc.document._id)
end
function tests.test_new_all_params_returns_rev_in_document()
local doc = document_all_params()
assert_equal(rev, doc.document._rev)
end
function tests.test_new_all_params_returns_correct_document_key_value()
local doc = document_all_params()
assert_equal(doc_value, doc.document[doc_key])
end
function tests.test_new_all_params_returns_only_id_rev_correct_document_key_value()
local doc = document_all_params()
assert_equal(3, common.table_length(doc.document), "doc.document length")
end
local function custom_loader_function()
return custom_loader_file_data
end
local function build_new_attachment()
local params = {
file_path = custom_loader_file_path,
content_type = text_file_content_type,
custom_loader_function = custom_loader_function,
file_name = attachment_file_name,
}
local att = attachment:new(params)
assert_table(att, "att")
return att
end
local function document_with_attachment(att)
att = att or build_new_attachment()
local doc = document:new()
assert_table(doc, "doc")
local return_document = doc:add_attachment(att)
return doc, return_document
end
function tests.test_add_attachment_valid_att_empty_document_valid_document()
local doc = document_with_attachment()
assert_table(doc.document, "doc.document")
end
function tests.test_add_attachment_valid_att_empty_document_only_document()
local doc = document_with_attachment()
assert_equal(1, common.table_length(doc), "doc length")
end
function tests.test_add_attachment_valid_att_empty_document_valid_attachments()
local doc = document_with_attachment()
assert_table(doc.document._attachments, "doc.document._attachments")
end
function tests.test_add_attachment_valid_att_empty_document_only_attachments()
local doc = document_with_attachment()
assert_equal(1, common.table_length(doc.document), "doc.document length")
end
function tests.test_add_attachment_valid_att_empty_document_valid_attachment_file_name()
local doc = document_with_attachment()
assert_table(doc.document._attachments[attachment_file_name], "doc.document._attachments[attachment_file_name]")
end
function tests.test_add_attachment_valid_att_empty_document_only_attachment_file_name()
local doc = document_with_attachment()
assert_equal(1, common.table_length(doc.document._attachments), "doc.document._attachments length")
end
function tests.test_add_attachment_valid_att_empty_document_valid_attachment_content_type()
local doc = document_with_attachment()
assert_equal(text_file_content_type, doc.document._attachments[attachment_file_name].content_type, "doc.document._attachments[attachment_file_name].content_type")
end
function tests.test_add_attachment_valid_att_empty_document_valid_attachment_data()
local mime = require "mime"
local doc = document_with_attachment()
assert_equal(mime.b64(custom_loader_file_data), doc.document._attachments[attachment_file_name].data, "doc.document._attachments[attachment_file_name].data")
end
function tests.test_add_attachment_valid_att_empty_document_only_attachment_content_type_data()
local doc = document_with_attachment()
assert_equal(2, common.table_length(doc.document._attachments[attachment_file_name]), "doc.document._attachments[file_name] length")
end
function tests.test_add_attachment_valid_att_empty_document_doc_document_matches_return_document()
local doc, return_document = document_with_attachment()
assert_equal(doc.document, return_document)
end
function tests.test_add_attachment_invalid_att_empty_document_returns_nil_return_document()
local doc, return_document = document_with_attachment({})
assert_equal(nil, return_document, "return doc.document")
end
function tests.test_add_attachment_invalid_file_data_returns_nil()
local att = build_new_attachment()
att.file_data = nil
local doc = document:new()
local return_document = doc:add_attachment(att)
assert_equal(nil, return_document, "return doc.document")
end
function tests.test_add_attachment_no_att_empty_document_returns_nil_return_document()
local doc = document:new()
local return_document = document:add_attachment()
assert_equal(nil, return_document, "return doc.document")
end
function tests.test_core_document_prepare_request_data_content_type()
local json = require "cjson"
local server = {}
local params = {
id = id,
rev = rev,
document = {
[doc_key] = doc_value,
},
}
local doc = document:new(params)
doc:prepare_request_data(server)
assert_equal(content_type, server.content_type, "server.content_type")
end
function tests.test_core_document_prepare_request_data_request_data()
local json = require "cjson"
local server = {}
local params = {
id = id,
rev = rev,
document = {
[doc_key] = doc_value,
},
}
local doc = document:new(params)
doc:prepare_request_data(server)
assert_equal(json.encode(doc.document), server.request_data, "server.request_data")
end
return tests
| bsd-3-clause |
rpetit3/darkstar | scripts/zones/Kazham/npcs/Bhukka_Sahbeo.lua | 15 | 1053 | -----------------------------------
-- Area: Kazham
-- NPC: Bhukka Sahbeo
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("BathedInScent") == 1) then
player:startEvent(0x00BC); -- scent from Blue Rafflesias
else
player:startEvent(0x007A);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
esguk811/DarkRP | gamemode/modules/hitmenu/sh_init.lua | 5 | 3198 | local plyMeta = FindMetaTable("Player")
local hitmanTeams = {}
local minHitDistanceSqr = GM.Config.minHitDistance * GM.Config.minHitDistance
function plyMeta:isHitman()
return hitmanTeams[self:Team()]
end
function plyMeta:hasHit()
return self:getDarkRPVar("hasHit") or false
end
function plyMeta:getHitTarget()
return self:getDarkRPVar("hitTarget")
end
function plyMeta:getHitPrice()
return self:getDarkRPVar("hitPrice") or GAMEMODE.Config.minHitPrice
end
function DarkRP.addHitmanTeam(job)
if not job or not RPExtraTeams[job] then return end
if DarkRP.DARKRP_LOADING and DarkRP.disabledDefaults["hitmen"][RPExtraTeams[job].command] then return end
hitmanTeams[job] = true
end
DarkRP.getHitmanTeams = fp{fn.Id, hitmanTeams}
function DarkRP.hooks:canRequestHit(hitman, customer, target, price)
if not hitman:isHitman() then return false, DarkRP.getPhrase("player_not_hitman") end
if customer:GetPos():DistToSqr(hitman:GetPos()) > minHitDistanceSqr then return false, DarkRP.getPhrase("distance_too_big") end
if hitman == target then return false, DarkRP.getPhrase("hitman_no_suicide") end
if hitman == customer then return false, DarkRP.getPhrase("hitman_no_self_order") end
if not customer:canAfford(price) then return false, DarkRP.getPhrase("cant_afford", DarkRP.getPhrase("hit")) end
if price < GAMEMODE.Config.minHitPrice then return false, DarkRP.getPhrase("price_too_low") end
if hitman:hasHit() then return false, DarkRP.getPhrase("hitman_already_has_hit") end
if IsValid(target) and ((target:getDarkRPVar("lastHitTime") or -GAMEMODE.Config.hitTargetCooldown) > CurTime() - GAMEMODE.Config.hitTargetCooldown) then return false, DarkRP.getPhrase("hit_target_recently_killed_by_hit") end
if IsValid(customer) and ((customer.lastHitAccepted or -GAMEMODE.Config.hitCustomerCooldown) > CurTime() - GAMEMODE.Config.hitCustomerCooldown) then return false, DarkRP.getPhrase("customer_recently_bought_hit") end
return true
end
hook.Add("onJobRemoved", "hitmenuUpdate", function(i, job)
hitmanTeams[i] = nil
end)
--[[---------------------------------------------------------------------------
DarkRPVars
---------------------------------------------------------------------------]]
DarkRP.registerDarkRPVar("hasHit", net.WriteBit, fn.Compose{tobool, net.ReadBit})
DarkRP.registerDarkRPVar("hitTarget", net.WriteEntity, net.ReadEntity)
DarkRP.registerDarkRPVar("hitPrice", fn.Curry(fn.Flip(net.WriteInt), 2)(32), fn.Partial(net.ReadInt, 32))
DarkRP.registerDarkRPVar("lastHitTime", fn.Curry(fn.Flip(net.WriteInt), 2)(32), fn.Partial(net.ReadInt, 32))
--[[---------------------------------------------------------------------------
Chat commands
---------------------------------------------------------------------------]]
DarkRP.declareChatCommand{
command = "hitprice",
description = "Set the price of your hits",
condition = plyMeta.isHitman,
delay = 10
}
DarkRP.declareChatCommand{
command = "requesthit",
description = "Request a hit from the player you're looking at",
delay = 5,
condition = fn.Compose{fn.Not, fn.Null, fn.Curry(fn.Filter, 2)(plyMeta.isHitman), player.GetAll}
}
| mit |
rpetit3/darkstar | scripts/globals/bluemagic.lua | 8 | 14343 | require("scripts/globals/status")
require("scripts/globals/magic")
BLUE_SKILL = 43;
-- The type of spell.
SPELLTYPE_PHYSICAL = 0;
SPELLTYPE_MAGICAL = 1;
SPELLTYPE_RANGED = 2;
SPELLTYPE_BREATH = 3;
SPELLTYPE_DRAIN = 4;
SPELLTYPE_SPECIAL = 5;
-- The TP modifier
TPMOD_NONE = 0;
TPMOD_CRITICAL = 1;
TPMOD_DAMAGE = 2;
TPMOD_ACC = 3;
TPMOD_ATTACK = 4;
-- The damage type for the spell
DMGTYPE_BLUNT = 0;
DMGTYPE_PIERCE = 1;
DMGTYPE_SLASH = 2;
DMGTYPE_H2H = 3;
-- The SC the spell makes
SC_IMPACTION = 0;
SC_TRANSFIXION = 1;
SC_DETONATION = 2;
SC_REVERBERATION = 3;
SC_SCISSION = 4;
SC_INDURATION = 5;
SC_LIQUEFACTION = 6;
SC_COMPRESSION = 7;
SC_FUSION = 8;
SC_FRAGMENTATION = 9;
SC_DISTORTION = 10;
SC_GRAVITATION = 11;
SC_DARK = 12;
SC_LIGHT = 13;
INT_BASED = 1;
CHR_BASED = 2;
MND_BASED = 3;
-- Get the damage for a blue magic physical spell.
-- caster - The entity casting the spell.
-- target - The target of the spell.
-- spell - The blue magic spell itself.
-- params - The parameters for the spell. Broken down into:
-- .tpmod - The TP modifier for the spell (e.g. damage varies, critical varies with TP, etc). Should be a TPMOD_xxx enum.
-- .numHits - The number of hits in the spell.
-- .multiplier - The base multiplier for the spell (not under Chain Affinity) - Every spell must specify this. (equivalent to TP 0%)
-- .tp150 - The TP modifier @ 150% TP (damage multiplier, crit chance, etc. 1.0 = 100%, 2.0 = 200% NOT 100=100%).
-- This value is interpreted as crit chance or dmg multiplier depending on the TP modifier (tpmod).
-- .tp300 - The TP modifier @ 300% TP (damage multiplier, crit chance, etc. 1.0 = 100%, 2.0 = 200% NOT 100=100%)
-- This value is interpreted as crit chance or dmg multiplier depending on the TP modifier (tpmod).
-- .azuretp - The TP modifier under Azure Lore (damage multiplier, crit chance, etc. 1.0 = 100%, 2.0 = 200% NOT 100=100%)
-- This value is interpreted as crit chance or dmg multiplier depending on the TP modifier (tpmod).
-- .duppercap - The upper cap for D for this spell.
-- .str_wsc - The decimal % value for STR % (e.g. STR 20% becomes 0.2)
-- .dex_wsc - Same as above.
-- .vit_wsc - Same as above.
-- .int_wsc - Same as above.
-- .mnd_wsc - Same as above.
-- .chr_wsc - Same as above.
-- .agi_wsc - Same as above.
function BluePhysicalSpell(caster, target, spell, params)
-- store related values
local magicskill = caster:getSkillLevel(BLUE_SKILL) + caster:getMod(79 + BLUE_SKILL); -- Base skill + equip mods
-- TODO: Under Chain affinity?
-- TODO: Under Efflux?
-- TODO: Merits.
-- TODO: Under Azure Lore.
---------------------------------
-- Calculate the final D value -
---------------------------------
-- worked out from http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
-- Final D value ??= floor(D+fSTR+WSC) * Multiplier
local D = math.floor((magicskill * 0.11)) * 2 + 3;
-- cap D
if (D > params.duppercap) then
D = params.duppercap;
end
-- print("D val is ".. D);
local fStr = BluefSTR(caster:getStat(MOD_STR) - target:getStat(MOD_VIT));
if (fStr > 22) then
fStr = 22; -- TODO: Smite of Rage doesn't have this cap applied.
end
-- print("fStr val is ".. fStr);
local WSC = BlueGetWsc(caster, params);
-- print("wsc val is ".. WSC);
local multiplier = params.multiplier;
-- If under CA, replace multiplier with fTP(multiplier, tp150, tp300)
local chainAffinity = caster:getStatusEffect(EFFECT_CHAIN_AFFINITY);
if chainAffinity ~= nil then
-- Calculate the total TP available for the fTP multiplier.
local tp = caster:getTP() + caster:getMerit(MERIT_ENCHAINMENT);
if tp > 3000 then
tp = 3000;
end;
multiplier = BluefTP(tp, multiplier, params.tp150, params.tp300);
end;
-- TODO: Modify multiplier to account for family bonus/penalty
local finalD = math.floor(D + fStr + WSC) * multiplier;
-- print("Final D is ".. finalD);
----------------------------------------------
-- Get the possible pDIF range and hit rate --
----------------------------------------------
if (params.offcratiomod == nil) then -- default to attack. Pretty much every physical spell will use this, Cannonball being the exception.
params.offcratiomod = caster:getStat(MOD_ATT)
end;
-- print(params.offcratiomod)
local cratio = BluecRatio(params.offcratiomod / target:getStat(MOD_DEF), caster:getMainLvl(), target:getMainLvl());
local hitrate = BlueGetHitRate(caster,target,true);
-- print("Hit rate "..hitrate);
-- print("pdifmin "..cratio[1].." pdifmax "..cratio[2]);
-------------------------
-- Perform the attacks --
-------------------------
local hitsdone = 0;
local hitslanded = 0;
local finaldmg = 0;
while (hitsdone < params.numhits) do
local chance = math.random();
if (chance <= hitrate) then -- it hit
-- TODO: Check for shadow absorbs.
-- Generate a random pDIF between min and max
local pdif = math.random((cratio[1]*1000),(cratio[2]*1000));
pdif = pdif/1000;
-- Apply it to our final D
if (hitsdone == 0) then -- only the first hit benefits from multiplier
finaldmg = finaldmg + (finalD * pdif);
else
finaldmg = finaldmg + ((math.floor(D + fStr + WSC)) * pdif); -- same as finalD but without multiplier (it should be 1.0)
end
hitslanded = hitslanded + 1;
-- increment target's TP (100TP per hit landed)
target:addTP(100);
end
hitsdone = hitsdone + 1;
end
-- print("Hits landed "..hitslanded.."/"..hitsdone.." for total damage: "..finaldmg);
return finaldmg;
end;
-- Blue Magical type spells
function BlueMagicalSpell(caster, target, spell, params, statMod)
local D = caster:getMainLvl() + 2;
if (D > params.duppercap) then
D = params.duppercap;
end
local ST = BlueGetWsc(caster, params); -- According to Wiki ST is the same as WSC, essentially Blue mage spells that are magical use the dmg formula of Magical type Weapon skills
if (caster:hasStatusEffect(EFFECT_BURST_AFFINITY)) then
ST = ST * 2;
end
local convergenceBonus = 1.0;
if (caster:hasStatusEffect(EFFECT_CONVERGENCE)) then
convergenceEffect = getStatusEffect(EFFECT_CONVERGENCE);
local convLvl = convergenceEffect:getPower();
if (convLvl == 1) then
convergenceBonus = 1.05;
elseif (convLvl == 2) then
convergenceBonus = 1.1;
elseif (convLvl == 3) then
convergenceBonus = 1.15;
end
end
local statBonus = 0;
local dStat = 0; -- Please make sure to add an additional stat check if there is to be a spell that uses neither INT, MND, or CHR. None currently exist.
if (statMod == INT_BASED) then -- Stat mod is INT
dStat = caster:getStat(MOD_INT) - target:getStat(MOD_INT)
statBonus = (dStat)* params.tMultiplier;
elseif (statMod == CHR_BASED) then -- Stat mod is CHR
dStat = caster:getStat(MOD_CHR) - target:getStat(MOD_CHR)
statBonus = (dStat)* params.tMultiplier;
elseif (statMod == MND_BASED) then -- Stat mod is MND
dStat = caster:getStat(MOD_MND) - target:getStat(MOD_MND)
statBonus = (dStat)* params.tMultiplier;
end
D =(((D + ST) * params.multiplier * convergenceBonus) + statBonus);
-- At this point according to wiki we apply standard magic attack calculations
local magicAttack = 1.0;
local multTargetReduction = 1.0; -- TODO: Make this dynamically change, temp static till implemented.
magicAttack = math.floor(D * multTargetReduction);
magicAttack = math.floor(magicAttack * applyResistance(caster,spell,target,dStat,BLUE_SKILL,0));
dmg = math.floor(addBonuses(caster, spell, target, magicAttack));
caster:delStatusEffectSilent(EFFECT_BURST_AFFINITY);
return dmg;
end;
function BlueFinalAdjustments(caster, target, spell, dmg, params)
if (dmg < 0) then
dmg = 0;
end
dmg = dmg * BLUE_POWER;
dmg = dmg - target:getMod(MOD_PHALANX);
if (dmg < 0) then
dmg = 0;
end
-- handling stoneskin
dmg = utils.stoneskin(target, dmg);
target:delHP(dmg);
target:updateEnmityFromDamage(caster,dmg);
target:handleAfflatusMiseryDamage(dmg);
-- TP has already been dealt with.
return dmg;
end;
------------------------------
-- Utility functions below ---
------------------------------
function BlueGetWsc(attacker, params)
wsc = (attacker:getStat(MOD_STR) * params.str_wsc + attacker:getStat(MOD_DEX) * params.dex_wsc +
attacker:getStat(MOD_VIT) * params.vit_wsc + attacker:getStat(MOD_AGI) * params.agi_wsc +
attacker:getStat(MOD_INT) * params.int_wsc + attacker:getStat(MOD_MND) * params.mnd_wsc +
attacker:getStat(MOD_CHR) * params.chr_wsc) * BlueGetAlpha(attacker:getMainLvl());
return wsc;
end;
-- Given the raw ratio value (atk/def) and levels, returns the cRatio (min then max)
function BluecRatio(ratio,atk_lvl,def_lvl)
-- Level penalty...
local levelcor = 0;
if (atk_lvl < def_lvl) then
levelcor = 0.05 * (def_lvl - atk_lvl);
end
ratio = ratio - levelcor;
-- apply caps
if (ratio<0) then
ratio = 0;
elseif (ratio>2) then
ratio = 2;
end
-- Obtaining cRatio_MIN
local cratiomin = 0;
if (ratio<1.25) then
cratiomin = 1.2 * ratio - 0.5;
elseif (ratio>=1.25 and ratio<=1.5) then
cratiomin = 1;
elseif (ratio>1.5 and ratio<=2) then
cratiomin = 1.2 * ratio - 0.8;
end
-- Obtaining cRatio_MAX
local cratiomax = 0;
if (ratio<0.5) then
cratiomax = 0.4 + 1.2 * ratio;
elseif (ratio<=0.833 and ratio>=0.5) then
cratiomax = 1;
elseif (ratio<=2 and ratio>0.833) then
cratiomax = 1.2 * ratio;
end
cratio = {};
if (cratiomin < 0) then
cratiomin = 0;
end
cratio[1] = cratiomin;
cratio[2] = cratiomax;
return cratio;
end;
-- Gets the fTP multiplier by applying 2 straight lines between ftp1-ftp2 and ftp2-ftp3
-- tp - The current TP
-- ftp1 - The TP 0% value
-- ftp2 - The TP 150% value
-- ftp3 - The TP 300% value
function BluefTP(tp,ftp1,ftp2,ftp3)
if (tp>=0 and tp<1500) then
return ftp1 + ( ((ftp2-ftp1)/100) * (tp / 10));
elseif (tp>=1500 and tp<=3000) then
-- generate a straight line between ftp2 and ftp3 and find point @ tp
return ftp2 + ( ((ftp3-ftp2)/100) * ((tp-1500) / 10));
else
print("blue fTP error: TP value is not between 0-3000!");
end
return 1; -- no ftp mod
end;
function BluefSTR(dSTR)
local fSTR2 = nil;
if (dSTR >= 12) then
fSTR2 = ((dSTR+4)/2);
elseif (dSTR >= 6) then
fSTR2 = ((dSTR+6)/2);
elseif (dSTR >= 1) then
fSTR2 = ((dSTR+7)/2);
elseif (dSTR >= -2) then
fSTR2 = ((dSTR+8)/2);
elseif (dSTR >= -7) then
fSTR2 = ((dSTR+9)/2);
elseif (dSTR >= -15) then
fSTR2 = ((dSTR+10)/2);
elseif (dSTR >= -21) then
fSTR2 = ((dSTR+12)/2);
else
fSTR2 = ((dSTR+13)/2);
end
return fSTR2;
end;
function BlueGetHitRate(attacker,target,capHitRate)
local acc = attacker:getACC();
local eva = target:getEVA();
if (attacker:getMainLvl() > target:getMainLvl()) then -- acc bonus!
acc = acc + ((attacker:getMainLvl()-target:getMainLvl())*4);
elseif (attacker:getMainLvl() < target:getMainLvl()) then -- acc penalty :(
acc = acc - ((target:getMainLvl()-attacker:getMainLvl())*4);
end
local hitdiff = 0;
local hitrate = 75;
if (acc>eva) then
hitdiff = (acc-eva)/2;
end
if (eva>acc) then
hitdiff = ((-1)*(eva-acc))/2;
end
hitrate = hitrate+hitdiff;
hitrate = hitrate/100;
-- Applying hitrate caps
if (capHitRate) then -- this isn't capped for when acc varies with tp, as more penalties are due
if (hitrate>0.95) then
hitrate = 0.95;
end
if (hitrate<0.2) then
hitrate = 0.2;
end
end
return hitrate;
end;
-- Function to stagger duration of effects by using the resistance to change the value
function getBlueEffectDuration(caster,resist,effect)
local duration = 0;
if (resist == 0.125) then
resist = 1;
elseif (resist == 0.25) then
resist = 2;
elseif (resist == 0.5) then
resist = 3;
else
resist = 4;
end
if (effect == EFFECT_BIND) then
duration = math.random(0,5) + resist * 5;
elseif (effect == EFFECT_STUN) then
duration = math.random(2,3) + resist;
-- printf("Duration of stun is %i",duration);
elseif (effect == EFFECT_WEIGHT) then
duration = math.random(20,24) + resist * 9; -- 30-60
elseif (effect == EFFECT_PARALYSIS) then
duration = math.random(50,60) + resist * 15; -- 60- 120
end
return duration;
end;
-- obtains alpha, used for working out WSC
function BlueGetAlpha(level)
local alpha = 1.00;
if (level <= 5) then
alpha = 1.00;
elseif (level <= 11) then
alpha = 0.99;
elseif (level <= 17) then
alpha = 0.98;
elseif (level <= 23) then
alpha = 0.97;
elseif (level <= 29) then
alpha = 0.96;
elseif (level <= 35) then
alpha = 0.95;
elseif (level <= 41) then
alpha = 0.94;
elseif (level <= 47) then
alpha = 0.93;
elseif (level <= 53) then
alpha = 0.92;
elseif (level <= 59) then
alpha = 0.91;
elseif (level <= 61) then
alpha = 0.90;
elseif (level <= 63) then
alpha = 0.89;
elseif (level <= 65) then
alpha = 0.88;
elseif (level <= 67) then
alpha = 0.87;
elseif (level <= 69) then
alpha = 0.86;
elseif (level <= 71) then
alpha = 0.85;
elseif (level <= 73) then
alpha = 0.84;
elseif (level <= 75) then
alpha = 0.83;
elseif (level <= 99) then
alpha = 0.85;
end
return alpha;
end;
| gpl-3.0 |
nokizorque/ucd | UCDaccounts/misc.lua | 1 | 1237 | function isNickAllowed(plr, nick)
if (nick:match("#%x%x%x%x%x%x")) then
return false
end
if (type(nick:lower():find("[ucd]", 1, true)) == "number") then
if (exports.UCDadmin:isPlayerAdmin(plr)) then
return true
end
return false
end
return true
end
addEventHandler("onPlayerChangeNick", root,
function (old, new)
if (not isPlayerLoggedIn(source)) then
cancelEvent()
return
end
if (not isNickAllowed(source, new)) then
exports.UCDdx:new(source, "You cannot use this nick as it contains forbidden characters", 255, 0, 0)
cancelEvent()
return
end
if (not wasEventCancelled() and new and type(new) == "string" and isPlayerLoggedIn(source)) then
exports.UCDdx:new(source, "You nick has been changed to: "..tostring(new), 0, 255, 0)
SAD(source.account.name, "lastUsedName", new)
exports.UCDlogging:new(source, "nick", tostring(old).." > "..tostring(new))
end
end
)
addEventHandler("onPlayerJoin", root,
function ()
source.name = source.name:gsub("#%x%x%x%x%x%x", "")
end
)
addEventHandler("onPlayerLogin", root,
function ()
if (not isNickAllowed(source, source.name)) then
source.name = source.name:gsub("[ucd]", ""):gsub("[UCD]", ""):gsub("#%x%x%x%x%x%x", "")
end
end
)
| mit |
lukego/snabbswitch | src/apps/intel/intel1g.lua | 5 | 31132 | -- intel1g: Device driver app for Intel 1G network cards
--
-- This is a device driver for Intel i210, i350 families of 1G network cards.
--
-- The driver aims to be fairly flexible about how it can be used. The
-- user can specify whether to initialize the NIC, which hardware TX
-- and RX queue should be used (or none), and the size of the TX/RX
-- descriptor rings. This should accomodate users who want to
-- initialize the NIC in an exotic way (e.g. with Linux igbe/ethtool),
-- or to dispatch packets across input queues in a specific way
-- (e.g. RSS and FlowDirector), or want to create many transmit-only
-- apps with private TX queues as a fast-path to get packets onto the
-- wire. The driver does not directly support these use cases but it
-- avoids abstractions that would potentially come into conflict with
-- them.
--
-- This flexibility does require more work from the user. For contrast
-- consider the intel10g driver: its VMDq mode automatically selects
-- available transmit/receive queues from a pool and initializes the
-- NIC to dispatch traffic to them based on MAC/VLAN. This is very
-- convenient but it also assumes that the NIC will only be used by
-- one driver in one process. This driver on the other hand does not
-- perform automatic queue assignment and so that must be done
-- separately (for example when constructing the app network with a
-- suitable configuration). The notion is that people constructing app
-- networks will have creative ideas that we are not able to
-- anticipate and so it is important to avoid assumptions about how
-- the driver will be used.
--
-- Data sheets (reference documentation):
-- http://www.intel.com/content/dam/www/public/us/en/documents/datasheets/ethernet-controller-i350-datasheet.pdf
-- http://www.intel.com/content/dam/www/public/us/en/documents/datasheets/i210-ethernet-controller-datasheet.pdf
-- Note: section and page numbers in the comments below refer to the i210 data sheet
-- run selftest() on APU2's second/middle NIC:
-- sudo SNABB_SELFTEST_INTEL1G_0="0000:02:00.0" ./snabb snsh -t apps.intel.intel1g
-- Note: rxqueue >0 not working yet!
module(..., package.seeall)
local ffi = require("ffi")
local C = ffi.C
local pci = require("lib.hardware.pci")
local band, bor, bnot, lshift = bit.band, bit.bor, bit.bnot, bit.lshift
local lib = require("core.lib")
local bits, bitset = lib.bits, lib.bitset
local compiler_barrier = lib.compiler_barrier
local tophysical = core.memory.virtual_to_physical
Intel1g = {}
function Intel1g:new(conf)
local self = {}
local pciaddress = conf.pciaddr
local attach = conf.attach
local txq = conf.txqueue or 0
local rxq = conf.rxqueue or 0
local ndesc = conf.ndescriptors or 512
local rxburst = conf.rxburst or 128
-- 8.1.3 Register Summary, p.359
local r = {}
r.CTRL = 0x00000 -- Device Control - RW
--r.CTRL = 0x00004 -- alias: Device Control - RW
r.STATUS = 0x00008 -- Device Status - RO
r.CTRL_EXT = 0x00018 -- Extended Device Control - RW
r.MDIC = 0x00020 -- MDI Control - RW
r.RCTL = 0x00100 -- RX Control - RW
r.TCTL = 0x00400 -- TX Control - RW
r.TCTL_EXT = 0x00404 -- Extended TX Control - RW
r.MDICNFG = 0x00E04 -- MDI Configuration - RW
r.EEER = 0x00E30 -- Energy Efficient Ethernet (EEE) Register
r.EIMC = 0x01528 --
--r.RXDCTL = 0x02828 -- legacy alias: RX Descriptor Control queue 0 - RW
--r.TXDCTL = 0x03828 -- legacy alias: TX Descriptor Control queue 0 - RW
r.GPRC = 0x04074 -- Good Packets Receive Count - R/clr
r.RNBC = 0x040A0 -- Receive No Buffers Count - R/clr
r.TORL = 0x040C0 -- Total Octets Received - R/clr
r.TORH = 0x040C4 -- Total Octets Received - R/clr
r.TOTL = 0x040C8 -- Total Octets Transmitted - R/clr
r.TOTH = 0x040CC -- Total Octets Transmitted - R/clr
r.TPR = 0x040D0 -- Total Packets Received - R/clr
r.TPT = 0x040D4 -- Total Packets Transmitted - R/clr
r.RPTHC = 0x04104 -- Rx Packets to Host Count - R/clr
r.MANC = 0x05820 --
r.SWSM = 0x05b50 --
r.SW_FW_SYNC=0x05b5c -- Software Firmware Synchronization
r.EEMNGCTL= 0x12030 -- Management EEPROM Control Register
-- checks
local deviceInfo= pci.device_info(pciaddress)
assert(pci.is_usable(deviceInfo), "NIC is in use")
assert(deviceInfo.driver == 'apps.intel.intel1g', "intel1g does not support this NIC")
local ringSize= 1
if deviceInfo.device == "0x1521" then -- i350
ringSize= 8
elseif deviceInfo.device == "0x157b" then -- i210
ringSize= 4
end
assert((txq >=0) and (txq <ringSize), "txqueue must be in 0.." .. ringSize-1 .. " for " .. deviceInfo.model)
assert((rxq >=0) and (rxq <ringSize), "rxqueue must be in 0.." .. ringSize-1 .. " for " .. deviceInfo.model)
assert((ndesc %128) ==0, "ndesc must be a multiple of 128 (for Rx only)") -- see 7.1.4.5
-- Setup device access
pci.unbind_device_from_linux(pciaddress)
pci.set_bus_master(pciaddress, true)
local regs, mmiofd = pci.map_pci_memory(pciaddress, 0)
-- Common utilities, see snabbswitch/src/lib/hardware/register.lua
local function bitvalue (value)
-- bitvalue(0x42) => 0x42
-- bitvalue({a=7,b=2}) => 0x42
return (type(value) == 'table') and bits(value) or tonumber(value)
end
local function poke32 (offset, value)
value = bitvalue(value)
compiler_barrier()
regs[offset/4] = value
end
local function peek32 (offset)
compiler_barrier()
return regs[offset/4]
end
local function set32 (offset, value)
value = bitvalue(value)
poke32(offset, bor(peek32(offset), value))
end
local function clear32 (offset, value)
value = bitvalue(value)
poke32(offset, band(peek32(offset), bnot(value)))
end
local function wait32 (offset, mask, value)
-- Block until applying `bitmask` to the register value gives `value`.
-- if `value` is not given then block until all bits in the mask are set.
mask = bitvalue(mask)
value = bitvalue(value)
repeat until band(peek32(offset), mask) == (value or mask)
end
-- 3.7.4.4.4 Using PHY Registers,
local MDIOpage= -1 -- 8.27.3.21 HW resets to 0, but persists with SW reset!
poke32(r.MDICNFG, 0) -- 8.2.5 MDC/MDIO Config: 0x0000 = internal PHY
local function writePHY(page, register, data) -- 8.2.4 Media Dependent Interface Control
if page ~= MDIOpage then
MDIOpage= page
writePHY(page, 22, (page %256)) -- select page by writing page to register 22 (from any page)
end
poke32(r.MDIC, 1 *2^26 + (register %2^5)*2^16 + (data %2^16)) -- OpCode 01b = MDI write
wait32(r.MDIC, {Ready=28})
assert(band(peek32(r.MDIC), bitvalue({Error=30})) ==0, "writePHY(): error")
end
local function readPHY(page, register)
if page ~= MDIOpage then
MDIOpage= page
writePHY(page, 22, (page %256)) -- select page by writing page to register 22 (from any page)
end
poke32(r.MDIC, 2 *2^26 + (register %2^5)*2^16) -- OpCode 10b = MDI read
wait32(r.MDIC, {Ready=28})
assert(band(peek32(r.MDIC), bitvalue({Error=30})) ==0, "readPHY(): error")
return peek32(r.MDIC) %2^16
end
local function yesno (value, bit)
return bitset(value, bit) and 'yes' or 'no'
end
local function printMACstatus()
print("MAC Status:")
local status= peek32(r.STATUS) -- p.372, 8.2.2
print(" STATUS = " .. bit.tohex(status))
print(" Full Duplex = " .. yesno(status, 0))
print(" Link Up = " .. yesno(status, 1))
print(" TxOFF Paused = " .. yesno(status, 4))
local speed = (({10,100,1000,1000})[1+bit.band(bit.rshift(status, 6),3)])
print(" Speed = " .. speed .. ' Mb/s')
local autoSpeed = (({10,100,1000,1000})[1+bit.band(bit.rshift(status, 8),3)])
print(" Auto Speed = " .. autoSpeed .. ' Mb/s') -- Auto-Speed Detection Value (ASDV), result after setting CTRL_EXT.ASDCHK
print(" PHY Reset = " .. yesno(status, 10))
print(" RxFlowCtrl = " .. yesno(status, 27)) -- should be set by SW driver to auto-neg. from PHY
print(" TxFlowCtrl = " .. yesno(status, 28)) -- should be set by SW driver to auto-neg. from PHY
end
local function printPHYstatus()
print("PHY Status:")
print(" PHYREG(0,0) = " .. bit.tohex(readPHY(0,0)) .. " Copper Control") -- p.545,
print(" PHYREG(0,1) = " .. bit.tohex(readPHY(0,1)) .. " Copper Status") -- p.546,
local phyID1= readPHY(0,2)
print(" PHYREG(0,2) = " .. bit.tohex(phyID1) .. " PHY ID 1") -- p.547, 8.27.3.3 PHY Identifier 1
assert((phyID1 == 0x0141) or (phyID1 == 0x0154), "PHY ID1 is not 0x0141 (i210) or 0x0154 (i350)")
print(" PHYREG(0,4) = " .. bit.tohex(readPHY(0,4)) .. " Copper Auto-Neg Adv") -- p.548, p.114, auto-neg. flow control (bits 10, 11)
print(" PHYREG(0,5) = " .. bit.tohex(readPHY(0,5)) .. " Copper Link Partner Ability") -- p.549, p.115, auto-neg. flow control (bits 10, 11) of partner
print(" PHYREG(0,6) = " .. bit.tohex(readPHY(0,6)) .. " Copper Auto-Neg Expansion") -- p.550
print(" PHYREG(0,9) = " .. bit.tohex(readPHY(0,9)) .. " 1000BASE-T Control") -- p.552
print(" PHYREG(0,10) = " .. bit.tohex(readPHY(0,10)) .. " 1000BASE-T Status") -- p.553
print(" PHYREG(0,15) = " .. bit.tohex(readPHY(0,15)) .. " Extended Status") -- p.554
print(" PHYREG(0,16) = " .. bit.tohex(readPHY(0,16)) .. " Copper Specific Control 1") -- p.554
local phyStatus= readPHY(0, 17)
print(" PHYREG(0,17) = " .. bit.tohex(phyStatus) .. " Copper Specific Status 1") -- p.556, 8.27.3.16
local speed = (({10,100,1000,1000})[1+bit.band(bit.rshift(phyStatus, 14),3)])
print(" Speed = " .. speed .. ' Mb/s')
print(" Full Duplex = " .. yesno(phyStatus, 13))
print(" Page Rx = " .. yesno(phyStatus, 12))
print(" Spd Dplx Resolved = " .. yesno(phyStatus, 11))
print(" Copper Link = " .. yesno(phyStatus, 10))
print(" Tx Pause = " .. yesno(phyStatus, 9))
print(" Rx Pause = " .. yesno(phyStatus, 8))
print(" MDI-X = " .. yesno(phyStatus, 6))
print(" Downshift = " .. yesno(phyStatus, 5))
print(" Copper Sleep = " .. yesno(phyStatus, 4)) -- Copper Energy Detect Status
print(" Glabal Link = " .. yesno(phyStatus, 3))
print(" Polarity Rev = " .. yesno(phyStatus, 1))
print(" Jabber = " .. yesno(phyStatus, 0))
print(" PHYREG(0,20) = " .. bit.tohex(readPHY(0,20)) .. " Copper Specific Control 2") -- p.559
print(" PHYREG(0,21) = " .. bit.tohex(readPHY(0,21)) .. " Copper Specific Rx Errors") -- p.559
print(" PHYREG(0,22) = " .. bit.tohex(readPHY(0,22)) .. " Page Addres") -- p.559
print(" PHYREG(0,23) = " .. bit.tohex(readPHY(0,23)) .. " Copper Specific Control 3") -- p.560
print(" PHYREG(2,16) = " .. bit.tohex(readPHY(2,16)) .. " MAC Specific Control 1") -- p.561
print(" PHYREG(2,19) = " .. bit.tohex(readPHY(2,19)) .. " MAC Specific Status") -- p.561
print(" PHYREG(2,21) = " .. bit.tohex(readPHY(2,21)) .. " MAC Specific Control 2") -- p.563
end
local function printTxStatus()
print("Tx status")
local tctl= peek32(r.TCTL)
print(" TCTL = " .. bit.tohex(tctl))
print(" TXDCTL = " .. bit.tohex(peek32(r.TXDCTL)))
print(" TX Enable = " .. yesno(tctl, 1))
end
local function printRxStatus()
print("Rx status")
local rctl= peek32(r.RCTL)
print(" RCTL = " .. bit.tohex(rctl))
print(" RXDCTL = " .. bit.tohex(peek32(r.RXDCTL)))
print(" RX Enable = " .. yesno(rctl, 1))
print(" RX Loopback = " .. yesno(rctl, 6))
end
local function printNICstatus(r, title)
print(title)
printMACstatus()
printPHYstatus()
printTxStatus()
printRxStatus()
end
local counters= {rxPackets=0, rxBytes=0, txPackets=0, txBytes=0, pull=0, push=0,
pullTxLinkFull=0, pullNoTxLink=0, pushRxLinkEmpty=0, pushTxRingFull=0}
local function printStats(r)
print("Stats from NIC registers:")
print(" Rx Packets= " .. peek32(r.TPR) .. " Octets= " .. peek32(r.TORH) *2^32 +peek32(r.TORL))
print(" Tx Packets= " .. peek32(r.TPT) .. " Octets= " .. peek32(r.TOTH) *2^32 +peek32(r.TOTL))
print(" Rx Good Packets= " .. peek32(r.GPRC))
print(" Rx No Buffers= " .. peek32(r.RNBC))
print(" Rx Packets to Host=" .. peek32(r.RPTHC))
print("Stats from counters:")
self:report()
end
-- Return the next index into a ring buffer.
-- (ndesc is a power of 2 and the ring wraps after ndesc-1.)
local function ringnext (index)
return band(index+1, ndesc-1)
end
local stop_nic, stop_transmit, stop_receive
local function initPHY()
-- 4.3.1.4 PHY Reset, p.131
wait32(r.MANC, {BLK_Phy_Rst_On_IDE=18}, 0) -- wait untill IDE link stable
-- 4.6.1 Acquiring Ownership over a Shared Resource, p.147
-- and 4.6.2 Releasing Ownership
-- XXX to do: write wrappers for both software/software (SWSM.SMBI)
-- software/firmware (SWSM.SWESMBI) semamphores, then apply them...
set32(r.SWSM, {SWESMBI= 1}) -- a. get software/firmware semaphore
while band(peek32(r.SWSM), 0x02) ==0 do
set32(r.SWSM, {SWESMBI= 1})
end
wait32(r.SW_FW_SYNC, {SW_PHY_SM=1}, 0) -- b. wait until firmware releases PHY
set32(r.SW_FW_SYNC, {SW_PHY_SM=1}) -- set semaphore bit to own PHY
clear32(r.SWSM, {SWESMBI= 1}) -- c. release software/firmware semaphore
set32(r.CTRL, {PHYreset= 31}) -- 3. set PHY reset
C.usleep(1*100) -- 4. wait 100 us
clear32(r.CTRL, {PHYreset= 31}) -- 5. release PHY reset
set32(r.SWSM, {SWESMBI= 1}) -- 6. release ownership
while band(peek32(r.SWSM), 0x02) ==0 do
set32(r.SWSM, {SWESMBI= 1})
end
clear32(r.SW_FW_SYNC, {SW_PHY_SM=1}) -- release PHY
clear32(r.SWSM, {SWESMBI= 1}) -- release software/firmware semaphore
wait32(r.EEMNGCTL, {CFG_DONE0=18}) -- 7. wait for CFG_DONE
set32(r.SWSM, {SWESMBI= 1}) -- 8. a. get software/firmware semaphore
while band(peek32(r.SWSM), 0x02) ==0 do
set32(r.SWSM, {SWESMBI= 1})
end
wait32(r.SW_FW_SYNC, {SW_PHY_SM=1}, 0) -- b. wait until firmware releases PHY
clear32(r.SWSM, {SWESMBI= 1}) -- c. release software/firmware semaphore
--XXX to do... -- 9. configure PHY
--XXX to do... -- 10. release ownership, see 4.6.2, p.148
clear32(r.SW_FW_SYNC, {SW_PHY_SM=1}) -- release PHY
clear32(r.SWSM, {SWESMBI= 1}) -- release software/firmware semaphore
end
-- Device setup and initialization
--printNICstatus(r, "Status before Init: ")
--printStats(r)
if not attach then -- Initialize device
poke32(r.EIMC, 0xffffffff) -- disable interrupts
poke32(r.CTRL, {RST = 26}) -- software / global reset, self clearing
--poke32(r.CTRL, {DEV_RST = 29}) -- device reset (incl. DMA), self clearing
C.usleep(4*1000) -- wait at least 3 ms before reading, see 7.6.1.1
wait32(r.CTRL, {RST = 26}, 0) -- wait port reset complete
--wait32(r.CTRL, {DEV_RST = 29}, 0) -- wait device reset complete
poke32(r.EIMC, 0xffffffff) -- re-disable interrupts
if conf.loopback == "MAC" then -- 3.7.6.2.1 Setting the I210 to MAC Loopback Mode
set32(r.CTRL, {SETLINKUP = 6}) -- Set CTRL.SLU (bit 6, should be set by default)
set32(r.RCTL, {LOOPBACKMODE0 = 6}) -- Set RCTL.LBM to 01b (bits 7:6)
set32(r.CTRL, {FRCSPD=11, FRCDPLX=12}) -- Set CTRL.FRCSPD and FRCDPLX (bits 11 and 12)
set32(r.CTRL, {FD=0, SPEED1=9}) -- Set the CTRL.FD bit and program the CTRL.SPEED field to 10b (1 GbE)
set32(r.EEER, {EEE_FRC_AN=24}) -- Set EEER.EEE_FRC_AN to 1b to enable checking EEE operation in MAC loopback mode
print("MAC Loopback set")
elseif conf.loopback == "PHY" then -- 3.7.6.3.1 Setting the I210 to Internal PHY Loopback Mode
set32(r.CTRL, {SETLINKUP = 6}) -- Set CTRL.SLU (bit 6, should be set by default)
clear32(r.CTRL_EXT, {LinkMode1=23,LinkMode0=22}) -- set Link mode to internal PHY
writePHY(0, 0, bitvalue({Duplex=8, SpeedMSB=6})) -- PHYREG 8.27.3 Copper Control
writePHY(2, 21, 0x06) -- MAC interface speed 1GE, 8.27.3.27 MAC Specific Control 2, p.563
--writePHY(0, 0, bitvalue({Duplex=8, SpeedMSB=6, CopperReset=15})) -- Copper Reset: not required, so don't!
writePHY(0, 0, bitvalue({Duplex=8, SpeedMSB=6, Loopback=14})) -- Loopback
print("PHY Loopback set")
else -- 3.7.4.4 Copper (Internal) PHY Link Config
-- PHY tells MAC after auto-neg. (PCS and 802.3 clauses 28 (extensions) & 40 (.3ab)
-- config generally determined by PHY auto-neg. (speed, duplex, flow control)
-- PHY asserts link indication (LINK) to MAC
-- SW driver must Set Link Up (CTRL.SLU) before MAC recognizes LINK from PHY and consider link up
initPHY() -- 4.5.7.2.1 Full Duplx, Speed auto neg. by PHY
C.usleep(1*1000*1000) -- wait 1s for init to settle
print("initPHY() done")
clear32(r.STATUS, {PHYReset=10}) -- p.373
set32(r.CTRL, {SETLINKUP = 6}) -- Set CTRL.SLU (bit 6, should be set by default)
clear32(r.CTRL_EXT, {LinkMode1=23,LinkMode0=22}) -- set Link mode to direct copper / internal PHY
clear32(r.CTRL_EXT, {PowerDown=20}) -- disable power down
set32(r.CTRL_EXT, {AutoSpeedDetect = 12}) -- p.373
--set32(r.CTRL_EXT, {DriverLoaded = 28}) -- signal Device Driver Loaded
io.write("Waiting for link...")
io.flush()
wait32(r.STATUS, {LinkUp=1}) -- wait for auto-neg. to complete
print(" We have link-up!")
--printMACstatus()
end
stop_nic = function ()
-- XXX Are these the right actions?
clear32(r.CTRL, {SETLINKUP = 6}) -- take the link down
pci.set_bus_master(pciaddress, false) -- disable DMA
end
function self:report() -- from SolarFlareNic:report() for snabbmark, etc.
io.write("Intel1g device " .. pciaddress .. ": ")
for name,value in pairs(counters) do
io.write(string.format('%s: %d ', name, value))
end
print("")
end
end -- if not attach then
if txq then -- Transmitter
-- Define registers for the transmit queue that we are using
r.TDBAL = 0xe000 + txq*0x40
r.TDBAH = 0xe004 + txq*0x40
r.TDLEN = 0xe008 + txq*0x40
r.TDH = 0xe010 + txq*0x40 -- Tx Descriptor Head - RO!
r.TDT = 0xe018 + txq*0x40 -- Tx Descriptor Head - RW
r.TXDCTL = 0xe028 + txq*0x40
r.TXCTL = 0xe014 + txq*0x40
-- Setup transmit descriptor memory
local txdesc_t = ffi.typeof("struct { uint64_t address, flags; }")
local txdesc_ring_t = ffi.typeof("$[$]", txdesc_t, ndesc)
local txdesc = ffi.cast(ffi.typeof("$&", txdesc_ring_t),
memory.dma_alloc(ffi.sizeof(txdesc_ring_t)))
-- Transmit state variables
local txpackets = {} -- packets currently queued
local tdh, tdt = 0, 0 -- Cache of DMA head/tail indexes
local txdesc_flags = bits({ifcs=25, dext=29, dtyp0=20, dtyp1=21, eop=24})
-- Initialize transmit queue
poke32(r.TDBAL, tophysical(txdesc) % 2^32)
poke32(r.TDBAH, tophysical(txdesc) / 2^32)
poke32(r.TDLEN, ndesc * ffi.sizeof(txdesc_t))
set32(r.TCTL, {TxEnable=1})
poke32(r.TXDCTL, {WTHRESH=16, ENABLE=25})
poke32(r.EIMC, 0xffffffff) -- re-disable interrupts
--printNICstatus(r, "Status after init transmit: ")
-- Return true if we can enqueue another packet for transmission.
local function can_transmit ()
return ringnext(tdt) ~= tdh
end
-- Queue a packet for transmission
-- Precondition: can_transmit() => true
local function transmit (p)
txdesc[tdt].address = tophysical(p.data)
txdesc[tdt].flags = bor(p.length, txdesc_flags, lshift(p.length+0ULL, 46))
txpackets[tdt] = p
tdt = ringnext(tdt)
counters.txPackets= counters.txPackets +1
counters.txBytes= counters.txBytes +p.length
end
-- Synchronize DMA ring state with hardware
-- Free packets that have been transmitted
local function sync_transmit ()
local cursor = tdh
tdh = peek32(r.TDH) -- possible race condition, see 7.1.4.4, 7.2.3
while cursor ~= tdh do
if txpackets[cursor] then
packet.free(txpackets[cursor])
txpackets[cursor] = nil
end
cursor = ringnext(cursor)
end
poke32(r.TDT, tdt)
end
function self:push () -- move frames from link.rx to NIC.txQueue for transmission
counters.push= counters.push +1
--local li = self.input[1]
local li = self.input["rx"] -- same-same as [1]
assert(li, "intel1g:push: no input link")
if link.empty(li) then -- from SolarFlareNic:push()
counters.pushRxLinkEmpty= counters.pushRxLinkEmpty +1
elseif not can_transmit() then
counters.pushTxRingFull= counters.pushTxRingFull +1
end
while not link.empty(li) and can_transmit() do
transmit(link.receive(li))
end
sync_transmit()
end
stop_transmit = function ()
poke32(r.TXDCTL, 0)
wait32(r.TXDCTL, {ENABLE=25}, 0)
for i = 0, ndesc-1 do
if txpackets[i] then
packet.free(txpackets[i])
txpackets[i] = nil
end
end
end
end -- if txq then
if rxq then -- Receiver
r.RDBAL = 0xc000 + rxq*0x40
r.RDBAH = 0xc004 + rxq*0x40
r.RDLEN = 0xc008 + rxq*0x40
r.SRRCTL = 0xc00c + rxq*0x40 -- Split and Replication Receive Control
r.RDH = 0xc010 + rxq*0x40 -- Rx Descriptor Head - RO
r.RXCTL = 0xc014 + rxq*0x40 -- Rx DCA Control Registers
r.RDT = 0xc018 + rxq*0x40 -- Rx Descriptor Tail - RW
r.RXDCTL = 0xc028 + rxq*0x40 -- Receive Descriptor Control
local rxdesc_t = ffi.typeof([[
struct {
uint64_t address;
uint16_t length, cksum;
uint8_t status, errors;
uint16_t vlan;
} __attribute__((packed))
]])
assert(ffi.sizeof(rxdesc_t), "sizeof(rxdesc_t)= ".. ffi.sizeof(rxdesc_t) .. ", but must be 16 Byte")
local rxdesc_ring_t = ffi.typeof("$[$]", rxdesc_t, ndesc)
local rxdesc = ffi.cast(ffi.typeof("$&", rxdesc_ring_t),
memory.dma_alloc(ffi.sizeof(rxdesc_ring_t)))
-- Receive state
local rxpackets = {}
local rdh, rdt= 0, 0
-- Initialize receive queue
-- see em_initialize_receive_unit() in http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/sys/dev/pci/if_em.c
clear32(r.RCTL, {rxen = 1}) -- disable receiver while setting up descriptor ring
--poke32(r.RDTR, ) -- set Receive Delay Timer Register (only for interrupt ops?)
poke32(r.RDBAL, tophysical(rxdesc) % 2^32)
poke32(r.RDBAH, tophysical(rxdesc) / 2^32)
poke32(r.RDLEN, ndesc * ffi.sizeof(rxdesc_t))
for i = 0, ndesc-1 do
local p= packet.allocate()
rxpackets[i]= p
rxdesc[i].address= tophysical(p.data)
rxdesc[i].status= 0
end
local rctl= {}
rctl.RXEN= 1 -- enable receiver
rctl.SBP= 2 -- store bad packet
rctl.RCTL_UPE= 3 -- unicast promiscuous enable
rctl.RCTL_MPE= 4 -- multicast promiscuous enable
rctl.LPE= 5 -- Long Packet Enable
rctl.BAM= 15 -- broadcast enable
--rctl.SZ_512= 17 -- buffer size: use SRRCTL for larger buffer sizes
--rctl.RCTL_RDMTS_HALF= -- rx desc min threshold size
rctl.SECRC= 26 -- i350 has a bug where it always strips the CRC, so strip CRC and cope in rxeof
poke32(r.SRRCTL, 10) -- buffer size in 1 KB increments
set32(r.SRRCTL, {Drop_En= 31}) -- drop packets when no descriptors available
set32(r.RXDCTL, {ENABLE= 25}) -- enable the RX queue
wait32(r.RXDCTL, {ENABLE=25}) -- wait until enabled
--poke32(r.RCTL, rctl) -- enable receiver only once Rx queue/descriptors are setup
set32(r.RCTL, rctl) -- enable receiver only once Rx queue/descriptors are setup
--poke32(r.RDH, 0) -- Rx descriptor Head (RO)
--poke32(r.RDT, 0) -- Rx descriptor Tail
poke32(r.RDT, ndesc-1) -- Rx descriptor Tail, trigger NIC to cache descriptors with index ~=0
--printNICstatus(r, "Status after init receive: ")
-- Return true if there is a DMA-completed packet ready to be received.
local function can_receive ()
local r= (rdt ~= rdh) and (band(rxdesc[rdt].status, 0x01) ~= 0)
--print("can_receive(): r=",r, " rdh=",rdh, " rdt=",rdt)
return r
end
local lostSeq, lastSeqNo = 0, -1
local function receive () -- Receive a packet
assert(can_receive()) -- precondition
local desc = rxdesc[rdt]
local p = rxpackets[rdt]
p.length = desc.length
counters.rxPackets= counters.rxPackets +1
counters.rxBytes= counters.rxBytes +p.length
local np= packet.allocate() -- get empty packet buffer
rxpackets[rdt] = np -- disconnect received packet, connect new buffer
rxdesc[rdt].address= tophysical(np.data)
rxdesc[rdt].status= 0 -- see 7.1.4.5: zero status before bumping tail pointer
rdt = ringnext(rdt)
--print("receive(): p.length= ", p.length)
rxSeqNo= p.data[3] *2^24 + p.data[2] *2^16 + p.data[1] *2^8 + p.data[0]
--print("receive(): txFrame= ", rxSeqNo)
lastSeqNo= lastSeqNo +1
while lastSeqNo < rxSeqNo do
--print("receive(): lastSeqNo , rxSeqNo= ", lastSeqNo, rxSeqNo)
--print("receive(): missing ", lastSeqNo)
lostSeq= lostSeq +1
lastSeqNo= lastSeqNo +1
end
return p
end
local function sync_receive () -- Synchronize receive registers with hardware
rdh = peek32(r.RDH) -- possible race condition, see 7.1.4.4, 7.2.3
--rdh = band(peek32(r.RDH), ndesc-1) -- from intel1g: Luke observed (RDH == ndesc) !?
--rdh = math.min(peek32(r.RDH), ndesc-1) -- from intel10g
assert(rdh <ndesc) -- from intel1g: Luke observed (RDH == ndesc) !?
--C.full_memory_barrier() -- from intel10g, why???
poke32(r.RDT, rdt)
--print("sync_receive(): rdh=",rdh, " rdt=",rdt)
end
function self:pull () -- move received frames from NIC.rxQueue to link.tx
counters.pull= counters.pull +1
--local lo = self.output[1]
local lo = self.output["tx"] -- same-same as [1]
--assert(lo, "intel1g: no output link")
local limit = rxburst
while limit > 0 and can_receive() do
limit = limit - 1
if lo then -- a link connects NIC to a sink
if not link.full(lo) then -- from SolarFlareNic:pull()
link.transmit(lo, receive())
else
counters.pullTxLinkFull= counters.pullTxLinkFull +1
packet.free(receive())
end
else
counters.pullNoTxLink= counters.pullNoTxLink +1
packet.free(receive())
end
end
sync_receive()
end
stop_receive = function () -- stop receiver, see 4.5.9.2
--poke32(r.RXDCTL, 0)
clear32(r.RXDCTL, {ENABLE=25})
wait32(r.RXDCTL, {ENABLE=25}, 0)
for i = 0, ndesc-1 do
if rxpackets[i] then
packet.free(rxpackets[i])
rxpackets[i] = nil
end
end
-- XXX return dma memory of Rx descriptor ring
print("stop_receive(): lostSeq ", lostSeq)
end
end -- if rxq then
function self:stop () -- Stop all functions that are running
if stop_receive then stop_receive() end
if stop_transmit then stop_transmit() end
if stop_nic then stop_nic() end
--printNICstatus(r, "Status after Stop: ")
printStats(r)
end
return self
--return setmetatable(self, {__index = Intel1g})
end -- function Intel1g:new()
function selftest ()
print("selftest: Intel1g")
local pciaddr = os.getenv("SNABB_SELFTEST_INTEL1G_0")
if not pciaddr then
print("SNABB_SELFTEST_INTEL1G_0 not set")
os.exit(engine.test_skipped_code)
end
local c = config.new()
local basic = require("apps.basic.basic_apps")
config.app(c, "source", basic.Source)
config.app(c, "sink", basic.Sink)
-- try MAC loopback with i210 or i350 NIC
--config.app(c, "nic", Intel1g, {pciaddr=pciaddr, loopback="MAC", rxburst=512})
config.app(c, "nic", Intel1g, {pciaddr=pciaddr, loopback="PHY", rxburst=512})
--config.app(c, "nic", Intel1g, {pciaddr=pciaddr, loopback="MAC", txqueue=1})
--config.app(c, "nic", Intel1g, {pciaddr=pciaddr, loopback="MAC", txqueue=1, rxqueue=1})
config.link(c, "source.tx -> nic.rx")
config.link(c, "nic.tx -> sink.rx")
-- replace intel1g by Repeater
--config.app(c, "repeater", basic.Repeater)
--config.link(c, "source.tx -> repeater.input")
--config.link(c, "repeater.output -> sink.rx")
engine.configure(c)
-- showlinks: src/core/app.lua calls report_links()
local startTime = C.get_monotonic_time()
engine.main({duration = 1, report = {showapps = true, showlinks = true, showload= true}})
local endTime = C.get_monotonic_time()
print("selftest: ok")
local runtime = endTime - startTime
engine.app_table.nic.stop() -- outputs :report()
local source= engine.app_table.source.output.tx
assert(source, "Intel1g: no source?")
local s= link.stats(source)
print("source: txpackets= ", s.txpackets, " rxpackets= ", s.rxpackets, " txdrop= ", s.txdrop)
local txpackets= s.txpackets
--local li = engine.app_table.nic.input[1]
local li = engine.app_table.nic.input["rx"] -- same-same as [1]
assert(li, "Intel1g: no input link?")
local s= link.stats(li)
print("input link: txpackets= ", s.txpackets, " rxpackets= ", s.rxpackets, " txdrop= ", s.txdrop)
--local lo = engine.app_table.nic.output[1]
local lo = engine.app_table.nic.output["tx"] -- same-same as [1]
assert(lo, "Intel1g: no output link?")
local s= link.stats(lo)
print("output link: txpackets= ", s.txpackets, " rxpackets= ", s.rxpackets, " txdrop= ", s.txdrop)
local sink= engine.app_table.sink.input.rx
assert(sink, "Intel1g: no sink?")
local s= link.stats(sink)
print("sink: txpackets= ", s.txpackets, " rxpackets= ", s.rxpackets, " txdrop= ", s.txdrop)
local rxpackets= s.rxpackets
print(("Processed %.1f M 60 Byte packets in %.2f s (rate: %.1f Mpps, %.2f Gbit/s, %.2f %% packet loss).")
:format(
txpackets / 1e6, runtime,
txpackets / runtime / 1e6,
((txpackets * 60 * 8) / runtime) / (1024*1024*1024),
(txpackets - rxpackets) *100 / txpackets
))
end
| apache-2.0 |
nokizorque/ucd | guieditor/client/util.lua | 2 | 16014 | --[[--------------------------------------------------
GUI Editor
client
util.lua
common utility functions
--]]--------------------------------------------------
function isBool(b)
return b == true or b == false
end
function toBool(b)
return b == "true" or b == "True" or b == true
end
function asString(v)
if type(v) == "userdata" then
local t = getElementType(v)
if t == "player" then
return tostring(t) .. "["..tostring(getPlayerName(v)).."]"
end
return tostring(t) .. " ["..tostring(v).."]"
end
return tostring(v)
end
--[[--------------------------------------------------
return the absolute position of an element, regardless of its parents
--]]--------------------------------------------------
function guiGetAbsolutePosition(element)
local x, y = guiGetPosition(element, false)
if getElementType(element) == "gui-tab" then
y = y + guiGetProperty(guiGetParent(element), "AbsoluteTabHeight")
end
local parent = guiGetParent(element)
while parent do
local tempX, tempY = guiGetPosition(parent, false)
x = x + tempX
y = y + tempY
if getElementType(parent) == "gui-tab" then
y = y + guiGetProperty(guiGetParent(parent), "AbsoluteTabHeight")
end
parent = guiGetParent(parent)
end
return x, y
end
--[[--------------------------------------------------
return the gui parent of a gui element
--]]--------------------------------------------------
function guiGetParent(element)
local parent = getElementParent(element)
if parent then
local t = getElementType(parent)
if t and t:find('gui-...') and t ~= 'guiroot' then
return parent
end
end
return nil
end
--[[--------------------------------------------------
return the width/height of the parent of a gui element,
regardless of whether the parent is a gui element or the screen
--]]--------------------------------------------------
function guiGetParentSize(element)
local parent = guiGetParent(element)
if parent then
return guiGetSize(parent, false)
else
return guiGetScreenSize()
end
end
--[[--------------------------------------------------
get all gui elements with the same parent as the given element
--]]--------------------------------------------------
function guiGetSiblings(element)
if exists(element) and guiGetParent(element) then
return getElementChildren(guiGetParent(element))
else
return guiGetScreenElements()
end
end
--[[--------------------------------------------------
get all direct children of guiroot
--]]--------------------------------------------------
function guiGetScreenElements(all)
-- put all existing child gui elements of guiroot into a table
local guiElements = {}
for _,guiType in ipairs(gGUITypes) do
for _,element in ipairs(getElementsByType(guiType)) do
if getElementType(getElementParent(element))=="guiroot" then
if all or relevant(element) then
--if getElementType(element) ~= "gui-scrollbar" and getElementType(element) ~= "gui-scrollpane" then
table.insert(guiElements, element)
--end
end
end
end
end
return guiElements
end
--[[--------------------------------------------------
easy way to set the rollover colour of a label
--]]--------------------------------------------------
function setRolloverColour(element, rollover, rolloff)
setElementData(element, "guieditor:rollonColour", rollover)
setElementData(element, "guieditor:rolloffColour", rolloff)
addEventHandler("onClientMouseEnter", element, rollover_on, false)
addEventHandler("onClientMouseLeave", element, rollover_off, false)
end
function rollover_on()
guiSetColour(source, unpack(getElementData(source, "guieditor:rollonColour")))
end
function rollover_off()
guiSetColour(source, unpack(getElementData(source, "guieditor:rolloffColour")))
end
--[[--------------------------------------------------
patch getCursorPosition to return both relative and absolute position types
--]]--------------------------------------------------
getCursorPosition_ = getCursorPosition
function getCursorPosition(absolute)
if not absolute then
return getCursorPosition_()
else
local x, y = getCursorPosition_()
if x and y then
x = x * gScreen.x
y = y * gScreen.y
return x, y
end
end
return false
end
--[[--------------------------------------------------
patch getElementData to have inherit = false by default
--]]--------------------------------------------------
getElementData_ = getElementData
function getElementData(element, data, inherit)
if not exists(element) then
outputDebugString("Bad element at getElementData(_, " .. tostring(data) .. ", " .. tostring(inherit) .. ")")
return
end
if getElementInvalidData(element, data) then
return getElementInvalidData(element, data)
end
if inherit == nil then
inherit = false
end
return getElementData_(element, data, inherit)
end
--[[--------------------------------------------------
patch setElementData to divert data with invalid types to
setElementInvalidData automatically
--]]--------------------------------------------------
setElementData_ = setElementData
function setElementData(element, key, value)
if not exists(element) then
outputDebugString("Bad element at setElementData(_, " .. tostring(key) .. ", " .. tostring(value) .. ")")
return
end
if type(value) == "function" then
return setElementInvalidData(element, key, value)
end
if type(value) == "table" then
if table.find(value, "function", type) then
return setElementInvalidData(element, key, value)
end
end
if getElementInvalidData(element, key) then
return setElementInvalidData(element, key, value)
end
return setElementData_(element, key, value)
end
--[[--------------------------------------------------
a data cache for saving information that is not allowed in normal element data
eg: function pointers
--]]--------------------------------------------------
__invalidData = {}
function setElementInvalidData(element, key, value)
outputDebug("set data '"..tostring(key).."' = "..tostring(value), "INVALID_DATA")
if not __invalidData[element] then
__invalidData[element] = {}
end
__invalidData[element][key] = value
return true
end
function getElementInvalidData(element, key)
outputDebug("get data '"..tostring(key).."' from "..asString(element), "INVALID_DATA")
if __invalidData[element] and __invalidData[element][key] then
return __invalidData[element][key]
end
return nil
end
--[[--------------------------------------------------
patch guiSetVisible to block changing the visibility of 'dead' elements
ie: those that have been 'deleted', but still exist in the undo buffer
--]]--------------------------------------------------
guiSetVisible_ = guiSetVisible
function guiSetVisible(element, visible)
if getElementData(element, "guieditor:removed") then
return
end
return guiSetVisible_(element, visible)
end
--[[--------------------------------------------------
patch guiGetPosition to account for code positions
--]]--------------------------------------------------
guiGetPosition_ = guiGetPosition
function guiGetPosition(element, relative, checkCode, parentW, parentH)
if checkCode and getElementData(element, "guieditor:positionCode") then
local output = split(getElementData(element, "guieditor:positionCode"), ",")
local sX, sY = PositionCoder.formatOutput(element, output[1], output[2], parentW, parentH)
local ranX, resultX = pcall(loadstring(sX))
local ranY, resultY = pcall(loadstring(sY))
if ranX and ranY then
return resultX, resultY
end
end
return guiGetPosition_(element, relative)
end
--[[--------------------------------------------------
patch guiSetAlpha to auto convert 0-100 to 0-1
--]]--------------------------------------------------
guiSetAlpha_ = guiSetAlpha
function guiSetAlpha(element, alpha, convert)
if exists(element) then
if convert then
alpha = alpha / 100
end
return guiSetAlpha_(element, alpha)
end
end
guiProgressBarSetProgress_ = guiProgressBarSetProgress
function guiProgressBarSetProgress(element, progress)
if exists(element) then
guiProgressBarSetProgress_(element, progress)
end
end
--[[--------------------------------------------------
patch guiSetSize to fix tab sizes
--]]--------------------------------------------------
guiSetSize_ = guiSetSize
function guiSetSize(element, w, h, relative)
if getElementType(element) == "gui-tabpanel" then
-- the size of the tab button changes depending on the size of the tab panel when the tab is added
-- eg: add a tab to a 20x20 tab panel and the button will be sized to ~80% of the parent
-- add a tab to a 500x500 tab panel and the button will be closer to ~20% of the parent
-- once this has been set at creation time it never changes again, even if the tab panel is resized
-- so we have to change it manually
local h2 = h
-- if it is relative, transform back into absolute
if relative then
local pH = gScreen.y
if guiGetParent(element) then
_, pH = guiGetSize(guiGetParent(element), false)
end
h2 = h * pH
end
guiSetProperty(element, "TabHeight", 25 / h2)
--guiSetProperty(element, "AbsoluteTabHeight", 25)
end
return guiSetSize_(element, w, h, relative)
end
--[[--------------------------------------------------
table extensions
--]]--------------------------------------------------
function table.create(keys, value)
local result = {}
for _,k in ipairs(keys) do
result[k] = value
end
return result
end
function table.find(t, target, func)
if type(t) == "table" then
for key, value in pairs(t) do
if (func and func(value) or value) == target then
return true
end
if type(value) == "table" then
if table.find(value, target, func) then
return true
end
end
end
end
return false
end
function table.copy(theTable)
local t = {}
for k, v in pairs(theTable) do
if type(v) == "table" then
t[k] = table.copy(v)
else
t[k] = v
end
end
return t
end
function table.count(t)
local c = 0
for v in pairs(t) do
c = c + 1
end
return c
end
function table.merge(a, b)
local t = {}
for i,v in ipairs(a) do
t[i] = v
end
for k,v in ipairs(b) do
t[#t + 1] = v
end
return t
end
function rgbToHex(r, g, b)
return string.format("%02X%02X%02X", r, g, b)
end
function rgbaToHex(r, g, b, a)
return string.format("%02X%02X%02X%02X", a, r, g, b)
end
function string.insert(s, insert, pos)
return string.sub(s, 0, pos) .. tostring(insert) .. string.sub(s, pos + 1)
end
function string.overwrite(s, insert, startPos, endPos)
return string.sub(s, 0, startPos) .. tostring(insert) .. string.sub(s, endPos + 1)
end
function string.trim(s)
return s:match('^()%s*$') and '' or s:match('^%s*(.*%S)')
end
function string.contains(str, match, plain)
local s, e = str:find(match, 0, plain == true or plain == nil)
return (s and e and s ~= -1 and e ~= -1)
end
function string.gsubIgnoreCase(str, match, rep)
match = string.gsub(match, "%a",
function(c)
return string.format("[%s%s]", string.lower(c), string.upper(c))
end
)
str = str:gsub(match, rep)
return str
end
function string.cleanSpace(str)
return str:gsub(" ", "")
end
function string.limit(str, length)
local limited = false
while dxGetTextWidth(str, 1, "default") > length do
str = str:sub(1, -2)
if not limited then
limited = true
end
end
return str, limited
end
function string.firstToUpper(str)
return (str:gsub("^%l", string.upper))
end
function string.lines(str)
local t = {}
local function helper(line)
table.insert(t, line)
return ""
end
helper((str:gsub("(.-)\r?\n", helper)))
return t
end
function math.lerp(from, to, t)
return from + (to - from) * t
end
function stripGUIPrefix(s)
if type(s) == "string" then
return s:sub(5)
else
--outputDebug("Invalid type "..type(s).." in stripGUIPrefix", "GENERAL")
return ""
end
end
function guiGetFriendlyName(element)
return string.firstToUpper(stripGUIPrefix(getElementType(element)))
end
function exists(e)
return e and isElement(e)
end
--[[--------------------------------------------------
check if an element should be included in regular operations
ie: was it created by the editor, does it exist outside the undo buffer
--]]--------------------------------------------------
function relevant(e)
if managed(e) and
not getElementData(e, "guieditor:removed") and
not getElementData(e, "guieditor.internal:noLoad") then
return true
end
return
end
function removed(e)
return exists(e) and getElementData(e, "guieditor:removed")
end
function managed(e)
return getElementData(e, "guieditor:managed")
end
function hasText(e)
if exists(e) and managed(e) then
local elementType = stripGUIPrefix(getElementType(e))
if elementType == "edit" or elementType == "memo" then
return true
end
end
return false
end
function hasColour(e)
if exists(e) --[[and managed(e)]] then
local elementType = stripGUIPrefix(getElementType(e))
if elementType == "window" or
elementType == "button" or
elementType == "label" or
elementType == "checkbox" or
elementType == "combobox" or
elementType == "edit" or
elementType == "radiobutton" or
elementType == "staticimage" or
elementType == "memo" or
elementType == "combobox" then
return true
end
end
return false
end
function doOnChildren(element, func, ...)
func(element, ...)
for _,e in ipairs(getElementChildren(element)) do
doOnChildren(e, func, ...)
end
end
function valueInRange(value, minimum, maximum)
return (value >= minimum) and (value <= maximum)
end
function valueInRangeUnordered(value, range1, range2)
return (value >= math.min(range1, range2)) and (value <= math.max(range1, range2))
end
function elementOverlap(a, b)
local aX, aY = guiGetPosition(a, false)
local aW, aH = guiGetSize(a, false)
local bX, bY = guiGetPosition(b, false)
local bW, bH = guiGetSize(b, false)
return rectangleOverlap(aX, aY, aW, aH, bX, bY, bW, bH)
end
function rectangleOverlap(aX, aY, aW, aH, bX, bY, bW, bH)
local xOverlap = valueInRange(aX, bX, bX + bW) or valueInRange(bX, aX, aX + aW)
local yOverlap = valueInRange(aY, bY, bY + bH) or valueInRange(bY, aY, aY + aH)
return xOverlap, yOverlap
end
function pointOverlap(element, x, y)
local ex, ey = guiGetAbsolutePosition(element)
local w, h = guiGetSize(element, false)
return valueInRange(x, ex, ex + w) or valueInRange(y, ey, ey + h)
end
--[[
function fromcolor(colour)
a = math.floor(colour / 16777216)
local a_ = a
if (colour < 0) then
a = 256 + a
end
colour = colour - (16777216 * a_)
r = math.floor(colour / 65536)
colour = colour - (65536 * r)
g = math.floor(colour / 256)
colour = colour - (256 * g)
b = colour
return r, g, b, a
end
]]
function fromcolor(colour)
if colour then
local hex = string.format("%08X", colour)
local a, r, g, b = getColorFromString("#"..hex)
return r, g, b, a
end
return 255,255,255,255
end
function math.round(value)
return math.floor(value + 0.5)
end
Group = {}
Group.__index = Group
Group.addOrCreate =
function(groups, item, value)
local placed = false
for _, group in ipairs(groups) do
if group:add(item, value) then
placed = true
break
end
end
if not placed then
groups[#groups + 1] = Group:create(item, value)
end
end
function Group:create(item, value)
local new = setmetatable(
{
items = {}
},
Group
)
if item ~= nil and value ~= nil then
new:add(item, value)
end
return new
end
function Group:add(item, value)
if not self.items[item] then
self.items[item] = value
return true
end
return false
end
function Group:contains(item, value)
for i, v in pairs(self.items) do
if (item ~= nil and item == i) then
return true
end
if (value ~= nil and value == v) then
return true
end
end
end
function Group:count()
return table.count(self.items)
end | mit |
omid1212/wez | plugins/quotes.lua | 651 | 1630 | local quotes_file = './data/quotes.lua'
local quotes_table
function read_quotes_file()
local f = io.open(quotes_file, "r+")
if f == nil then
print ('Created a new quotes file on '..quotes_file)
serialize_to_file({}, quotes_file)
else
print ('Quotes loaded: '..quotes_file)
f:close()
end
return loadfile (quotes_file)()
end
function save_quote(msg)
local to_id = tostring(msg.to.id)
if msg.text:sub(11):isempty() then
return "Usage: !addquote quote"
end
if quotes_table == nil then
quotes_table = {}
end
if quotes_table[to_id] == nil then
print ('New quote key to_id: '..to_id)
quotes_table[to_id] = {}
end
local quotes = quotes_table[to_id]
quotes[#quotes+1] = msg.text:sub(11)
serialize_to_file(quotes_table, quotes_file)
return "done!"
end
function get_quote(msg)
local to_id = tostring(msg.to.id)
local quotes_phrases
quotes_table = read_quotes_file()
quotes_phrases = quotes_table[to_id]
return quotes_phrases[math.random(1,#quotes_phrases)]
end
function run(msg, matches)
if string.match(msg.text, "!quote$") then
return get_quote(msg)
elseif string.match(msg.text, "!addquote (.+)$") then
quotes_table = read_quotes_file()
return save_quote(msg)
end
end
return {
description = "Save quote",
description = "Quote plugin, you can create and retrieve random quotes",
usage = {
"!addquote [msg]",
"!quote",
},
patterns = {
"^!addquote (.+)$",
"^!quote$",
},
run = run
}
| gpl-2.0 |
disslove7777/Mj.Dl-Bot | plugins/quotes.lua | 651 | 1630 | local quotes_file = './data/quotes.lua'
local quotes_table
function read_quotes_file()
local f = io.open(quotes_file, "r+")
if f == nil then
print ('Created a new quotes file on '..quotes_file)
serialize_to_file({}, quotes_file)
else
print ('Quotes loaded: '..quotes_file)
f:close()
end
return loadfile (quotes_file)()
end
function save_quote(msg)
local to_id = tostring(msg.to.id)
if msg.text:sub(11):isempty() then
return "Usage: !addquote quote"
end
if quotes_table == nil then
quotes_table = {}
end
if quotes_table[to_id] == nil then
print ('New quote key to_id: '..to_id)
quotes_table[to_id] = {}
end
local quotes = quotes_table[to_id]
quotes[#quotes+1] = msg.text:sub(11)
serialize_to_file(quotes_table, quotes_file)
return "done!"
end
function get_quote(msg)
local to_id = tostring(msg.to.id)
local quotes_phrases
quotes_table = read_quotes_file()
quotes_phrases = quotes_table[to_id]
return quotes_phrases[math.random(1,#quotes_phrases)]
end
function run(msg, matches)
if string.match(msg.text, "!quote$") then
return get_quote(msg)
elseif string.match(msg.text, "!addquote (.+)$") then
quotes_table = read_quotes_file()
return save_quote(msg)
end
end
return {
description = "Save quote",
description = "Quote plugin, you can create and retrieve random quotes",
usage = {
"!addquote [msg]",
"!quote",
},
patterns = {
"^!addquote (.+)$",
"^!quote$",
},
run = run
}
| gpl-2.0 |
mrbangi/yagop | plugins/quotes.lua | 651 | 1630 | local quotes_file = './data/quotes.lua'
local quotes_table
function read_quotes_file()
local f = io.open(quotes_file, "r+")
if f == nil then
print ('Created a new quotes file on '..quotes_file)
serialize_to_file({}, quotes_file)
else
print ('Quotes loaded: '..quotes_file)
f:close()
end
return loadfile (quotes_file)()
end
function save_quote(msg)
local to_id = tostring(msg.to.id)
if msg.text:sub(11):isempty() then
return "Usage: !addquote quote"
end
if quotes_table == nil then
quotes_table = {}
end
if quotes_table[to_id] == nil then
print ('New quote key to_id: '..to_id)
quotes_table[to_id] = {}
end
local quotes = quotes_table[to_id]
quotes[#quotes+1] = msg.text:sub(11)
serialize_to_file(quotes_table, quotes_file)
return "done!"
end
function get_quote(msg)
local to_id = tostring(msg.to.id)
local quotes_phrases
quotes_table = read_quotes_file()
quotes_phrases = quotes_table[to_id]
return quotes_phrases[math.random(1,#quotes_phrases)]
end
function run(msg, matches)
if string.match(msg.text, "!quote$") then
return get_quote(msg)
elseif string.match(msg.text, "!addquote (.+)$") then
quotes_table = read_quotes_file()
return save_quote(msg)
end
end
return {
description = "Save quote",
description = "Quote plugin, you can create and retrieve random quotes",
usage = {
"!addquote [msg]",
"!quote",
},
patterns = {
"^!addquote (.+)$",
"^!quote$",
},
run = run
}
| gpl-2.0 |
wissam23/alahvaz.bot | plugins/soper.lua | 3 | 80806 | --[[
โโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโ โโ โโ โโ
โโ โโ BY SAJJAD NOORI โโ โโ
โโ โโ BY SAJAD NOORI (@SAJJADNOORI) โโ โโ
โโ โโ JUST WRITED BY SAJJAD NOORI โโ โโ
โโ โโ Orders : ุงูุงูุงู
ุฑ โโ โโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
--]]
local function check_member_super(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
if success == 0 then
send_large_msg(receiver, "๐๐ปู
ูุดุบฺูช ุงุจูู ูุงุชูุนุจ๐โ๏ธ")
end
for k,v in pairs(result) do
local member_id = v.peer_id
if member_id ~= our_id then
-- SuperGroup configuration
data[tostring(msg.to.id)] = {
group_type = 'SuperGroup',
long_id = msg.to.peer_id,
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.title, '_', ' '),
lock_arabic = 'no',
lock_link = "no",
flood = 'yes',
lock_spam = 'yes',
lock_sticker = 'no',
member = 'no',
public = 'no',
lock_rtl = 'no',
lock_contacts = 'no',
strict = 'no'
}
}
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)
local text = 'โ๏ธ ุชู
ุชูุนูู ุงูู
ุฌู
ูุนู ููุญุจูุจ๐ โ๏ธ.'
return reply_msg(msg.id, text, ok_cb, false)
end
end
end
--Check Members #rem supergroup
local function check_member_superrem(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) 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)
local text = 'โ๏ธ ุชู
ุชุนุทูู ุงูู
ุฌู
ูุนู๐ โ๏ธ.'
return reply_msg(msg.id, text, ok_cb, false)
end
end
end
--Function to Add supergroup
local function superadd(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
channel_get_users(receiver, check_member_super,{receiver = receiver, data = data, msg = msg})
end
--Function to remove supergroup
local function superrem(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
channel_get_users(receiver, check_member_superrem,{receiver = receiver, data = data, msg = msg})
end
--Get and output admins and bots in supergroup
local function callback(cb_extra, success, result)
local i = 1
local chat_name = string.gsub(cb_extra.msg.to.print_name, "_", " ")
local member_type = cb_extra.member_type
local text = member_type.." for "..chat_name..":\n"
for k,v in pairsByKeys(result) do
if not v.first_name then
name = " "
else
vname = v.first_name:gsub("โฎ", "")
name = vname:gsub("_", " ")
end
text = text.."\n"..i.." - "..name.."["..v.peer_id.."]"
i = i + 1
end
send_large_msg(cb_extra.receiver, text)
end
--Get and output info about supergroup
local function callback_info(cb_extra, success, result)
local title ="โจ๏ธ ู
ุนููู
ุงุช ุนู ู
ุฌู
ูุนุฉโ๏ธ: ["..result.title.."]\n\n"
local admin_num = "โฃ ุนุฏุฏ ุงูุงุฏู
ููู: "..result.admins_count.."\n"
local user_num = "โฃ ุนุฏุฏ ุงูุงุนุถุงุก: "..result.participants_count.."\n"
local kicked_num = "โฃ ุงูุงุนุถุงุก ุงูุงูุซุฑ ุชูุงุนู: "..result.kicked_count.."\n"
local channel_id = "โฃ ุงูุฏู ุงูู
ุฌู
ูุนู: "..result.peer_id.."\n"
if result.username then
channel_username = "โฃ ู
ุนุฑู ุงูู
ุฌู
ูุนู : @"..result.username
else
channel_username = ""
end
local text = title..admin_num..user_num..kicked_num..channel_id..channel_username
send_large_msg(cb_extra.receiver, text)
end
--Get and output members of supergroup
local function callback_who(cb_extra, success, result)
local text = "โ๏ธ ุงุนุถุงุก ุงูู
ุฌู
ูุนู โจ๏ธ "..cb_extra.receiver
local i = 1
for k,v in pairsByKeys(result) do
if not v.print_name then
name = " "
else
vname = v.print_name:gsub("โฎ", "")
name = vname:gsub("_", " ")
end
if v.username then
username = " @"..v.username
else
username = ""
end
text = text.."\n"..i.." - "..name.." "..username.." [ "..v.peer_id.." ]\n"
--text = text.."\n"..username
i = i + 1
end
local file = io.open("./groups/lists/supergroups/"..cb_extra.receiver..".txt", "w")
file:write(text)
file:flush()
file:close()
send_document(cb_extra.receiver,"./groups/lists/supergroups/"..cb_extra.receiver..".txt", ok_cb, false)
post_msg(cb_extra.receiver, text, ok_cb, false)
end
--Get and output list of kicked users for supergroup
local function callback_kicked(cb_extra, success, result)
--vardump(result)
local text = "โ๏ธ ูุงุฆู
ู ุงูุฏูุงุช ุงูุงุนุถุงุก โจ๏ธ "..cb_extra.receiver.."\n\n"
local i = 1
for k,v in pairsByKeys(result) do
if not v.print_name then
name = " "
else
vname = v.print_name:gsub("โฎ", "")
name = vname:gsub("_", " ")
end
if v.username then
name = name.." @"..v.username
end
text = text.."\n"..i.." - "..name.." [ "..v.peer_id.." ]\n"
i = i + 1
end
local file = io.open("./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", "w")
file:write(text)
file:flush()
file:close()
send_document(cb_extra.receiver,"./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", ok_cb, false)
--send_large_msg(cb_extra.receiver, text)
end
--Begin supergroup locks
local function lock_group_links(msg, data, target)
if not is_momod(msg) then
return
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'yes' then
return '๐ ุงูุฑูุงุจุท ุจุงููุนู ู
ููููู ูู ุงูู
ุฌู
ูุนู ๐'
else
data[tostring(target)]['settings']['lock_link'] = 'yes'
save_data(_config.moderation.data, data)
return ' ุชู
๐โ๏ธ ููู ุงูุฑูุงุจุท ูู ุงูู
ุฌู
ูุนู ๐'
end
end
local function unlock_group_links(msg, data, target)
if not is_momod(msg) then
return
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'no' then
return '๐ ุงูุฑูุงุจุท ุจุงููุนู ู
ูุชูุญู ูู ุงูู
ุฌู
ูุนู ๐โ๏ธ'
else
data[tostring(target)]['settings']['lock_link'] = 'no'
save_data(_config.moderation.data, data)
return ' ุชู
โ๏ธ ูุชุญ ุงูุฑูุงุจุท ูู ุงูู
ุฌู
ูุนู ูู
ููู ุงูุงุฑุณุงู ุงูุงู ๐'
end
end
local function lock_group_spam(msg, data, target)
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "โ๐ป ูุง ุชูุนุจ ุจูููู ููุท ุงูู
ุฏูุฑ ูุงูุงุฏู
ู ููุนู ุฐุงูู๐ "
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'yes' then
return '๐ ู
ุถุงุฏ ุงูุณุจุงู
ุจุงููุนู ู
ูุชูุญ ๐๐'
else
data[tostring(target)]['settings']['lock_spam'] = 'yes'
save_data(_config.moderation.data, data)
return 'ุชู
โ๏ธ ูุชุญ ู
ุถุงุฏ ุงูุณุจุงู
๐ ๐'
end
end
local function unlock_group_spam(msg, data, target)
if not is_momod(msg) then
return
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'no' then
return '๐ ู
ุถุงุฏ ุงูุณุจุงู
ุจุงููุนูู ู
ูููู ๐ โ๏ธ'
else
data[tostring(target)]['settings']['lock_spam'] = 'no'
save_data(_config.moderation.data, data)
return 'ุชู
โ๏ธ ููู ู
ุถุงุฏ ุงูุณุจุงู
๐ ๐'
end
end
local function lock_group_flood(msg, data, target)
if not is_momod(msg) then
return
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return '๐ ุงูุชูุฑุงุฑ ุจุงููุนู ู
ููู ๐โ๏ธ'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'ุชู
โ๏ธ ููู ุงูุชูุฑุงุฑ ๐'
end
end
local function unlock_group_flood(msg, data, target)
if not is_momod(msg) then
return
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return '๐ ุงูุชูุฑุงุฑ ุจุงููุนู ู
ูุชูุญ ๐โ๏ธ'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'ุชู
โ๏ธ ูุชุญ ุงูุชูุฑุงุฑ ๐'
end
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return '๐ ุงูุบู ุงูุนุฑุจูู ุจุงููุนู ู
ููููู ๐โ๏ธ'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'ุชู
โ๏ธ ููู ุงููุบู ุงูุนุฑุจูู ๐'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return '๐ ุงููุบู ุงูุนุฑุจูู ุจุงููุนู ู
ูุชูุญู ๐โ๏ธ'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'ุชู
โ๏ธ ูุชุญ ุงููุบู ุงูุนุฑุจูู ๐'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return '๐ ุงูุงุถุงูู ุจุงููุนู ู
ููููู ๐โ๐ป'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'ุชู
โ๏ธ ููู ุงูุงุถุงูู ๐โ๐ป'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return '๐ ุงูุงุถุงูู ุจุงููุนู ู
ูุชูุญู ๐โ๏ธ'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'ุชู
โ๏ธ ูุชุญ ุงูุงุถุงูู ๐๐น'
end
end
local function lock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'yes' then
return '๐ ุงูุงุถุงูู ุงูุฌู
ุงุนูู ุจุงููุนู ู
ููููู ๐ โ๐ป'
else
data[tostring(target)]['settings']['lock_rtl'] = 'yes'
save_data(_config.moderation.data, data)
return 'ุชู
โ๏ธ ููู ุงูุงุถุงูู ุงูุฌู
ุงุนูู ๐ โ๐ป'
end
end
local function unlock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'no' then
return '๐ ุงูุงุถุงูู ุงูุฌู
ุงุนูู ุจุงููุนู ู
ูุชูุญู ๐โ๏ธ'
else
data[tostring(target)]['settings']['lock_rtl'] = 'no'
save_data(_config.moderation.data, data)
return 'ุชู
โ๏ธ ูุชุญ ุงูุงุถุงูู ุงูุฌู
ุงุนูู ๐๐น'
end
end
local function lock_group_sticker(msg, data, target)
if not is_momod(msg) then
return
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'yes' then
return '๐ ุงูู
ูุตูุงุช ุจุงููุนู ู
ููููู ๐โ๐ป'
else
data[tostring(target)]['settings']['lock_sticker'] = 'yes'
save_data(_config.moderation.data, data)
return 'ุชู
โ๏ธ ููู ุงูู
ูุตูุงุช ๐โ๐ป'
end
end
local function unlock_group_sticker(msg, data, target)
if not is_momod(msg) then
return
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'no' then
return '๐ ุงูู
ูุตูุงุช ุจุงููุนู ู
ูุชูุญู ๐โ๏ธ'
else
data[tostring(target)]['settings']['lock_sticker'] = 'no'
save_data(_config.moderation.data, data)
return 'ุชู
โ๏ธ ูุชุญ ุงูู
ูุตูุงุช ๐โ๏ธ'
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 '๐ ุฌูุงุช ุงูุงุชุตุงู ุจุงููุนู ู
ููููู ๐โ๐ป'
else
data[tostring(target)]['settings']['lock_contacts'] = 'yes'
save_data(_config.moderation.data, data)
return 'ุชู
โ๏ธ ููู ุฌูุงุช ุงูุงุชุตุงู ๐โ๐ป'
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 '๐ ุฌูุงุช ุงูุงุชุตุงู ุจุงููุนู ู
ูุชูุญู ๐โ๏ธ'
else
data[tostring(target)]['settings']['lock_contacts'] = 'no'
save_data(_config.moderation.data, data)
return 'ุชู
โ๏ธ ูุชุญ ุฌูุงุช ุงูุงุชุตุงู ๐โญ๏ธ'
end
end
local function enable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_strict_lock = data[tostring(target)]['settings']['strict']
if group_strict_lock == 'yes' then
return '๐ ุงูุชุญุฐูุฑ ุจุงููุนู ู
ูููู ๐โ๐ป'
else
data[tostring(target)]['settings']['strict'] = 'yes'
save_data(_config.moderation.data, data)
return 'ุชู
โ๏ธ ููู ุงูุชุญุฐูุฑ ๐โ๐ป'
end
end
local function disable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_strict_lock = data[tostring(target)]['settings']['strict']
if group_strict_lock == 'no' then
return '๐ ุงูุชุญุฐูุฑ ุจุงููุนู ู
ูุชูุญ ๐โ๏ธ'
else
data[tostring(target)]['settings']['strict'] = 'no'
save_data(_config.moderation.data, data)
return 'โ๏ธ ุชู
ูุชุญ ุงูุชุญุฐูุฑ ๐โญ๏ธ'
end
end
--End supergroup locks
--'Set supergroup rules' function
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'ุชู
โ๏ธ ูุถุน ุงูููุงููู ๐ ูู ุงูู
ุฌู
ูุนุฉ ๐ฅ'
end
--'Get supergroup rules' function
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'ููุณ ๐ ููุงู ููุงููู ๐ ูู ุงูู
ุฌู
ูุนุฉ ๐ฅ'
end
local rules = data[tostring(msg.to.id)][data_cat]
local group_name = data[tostring(msg.to.id)]['settings']['set_name']
local rules = group_name..' ๐ ููุงููู ู
ุฌู
ูุนุฉ ๐๏ธ\n\n'..rules:gsub("/n", " ")
return rules
end
--Set supergroup to public or not public function
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "๐ ๐ ูุง ุชูุนุจ ุจูููู ููุท ุงูู
ุฏูุฑ ูุงูุงุฏู
ู ููุนู ุฐุงููโ๏ธโ๐ป"
end
local group_public_lock = data[tostring(target)]['settings']['public']
local long_id = data[tostring(target)]['long_id']
if not long_id then
data[tostring(target)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
end
if group_public_lock == 'yes' then
return '๐ ุงูู
ุฌู
ูุนู ุนุงู
ู ุจุงููุนู โ๏ธ'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return '๐ฅ ุงูู
ุฌู
ูุนู ุงูุงู ุงุตุจุญุช ุนุงู
ู โจ๏ธโ๏ธ'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_public_lock = data[tostring(target)]['settings']['public']
local long_id = data[tostring(target)]['long_id']
if not long_id then
data[tostring(target)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
end
if group_public_lock == 'no' then
return '๐ฅุงูู
ุฌู
ูุนู ๐ ููุณุช ุนุงู
ู โ๏ธ'
else
data[tostring(target)]['settings']['public'] = 'no'
data[tostring(target)]['long_id'] = msg.to.long_id
save_data(_config.moderation.data, data)
return '๐ฅ ุงูู
ุฌู
ูุนู ุงูุงู ููุณุช ุนุงู
ู โ๏ธ'
end
end
--Show supergroup settings; function
function show_supergroup_settingsmod(msg, target)
if not is_momod(msg) then
return
end
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
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 = "โ ุงุนุฏุงุฏุงุช ุงูู
ุฌู
ูุนู ๐ฅ\nโฃ ููู ุงูุฑูุงุจุท : "..settings.lock_link.."\nโฃ ููู ุงูุชูุฑุงุฑ: "..settings.flood.."\nโฃ ุนุฏุฏ ุงูุชูุฑุงุฑ : "..NUM_MSG_MAX.."\nโฃ ููู ุงูููุงูุด ุงูุทูููู: "..settings.lock_spam.."\nโฃ ููู ุงููุบู ุงูุนุฑุจูู: "..settings.lock_arabic.."\nโฃ ููู ุงูุงุถุงูู: "..settings.lock_member.."\nโฃ ููู ุงูู
ุบุงุฏุฑู: "..settings.lock_rtl.."\nโฃ ููู ุงูู
ูุตูุงุช: "..settings.lock_sticker.."\nโฃ ุงูู
ุฑุงูุจู: "..settings.public.."\nโฃ ููู ุฌู
ูุน ุงูุงุนุฏุงุฏุงุช: "..settings.strict
return text
end
local function promote_admin(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
local member_tag_username = string.gsub(member_username, '@', '(at)')
if not data[group] then
return
end
if data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_username..' ๐ ูุชูุญ ููู ุจุงููุนู ุถู
ู ุงูุงุฏุงุฑู ๐.')
end
data[group]['moderators'][tostring(user_id)] = member_tag_username
save_data(_config.moderation.data, data)
end
local function demote_admin(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
if not data[group] then
return
end
if not data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_tag_username..' ๐ โ๐ป ููุชููุญู ูููููู ุจุฃูููุนูู ุถู
ููู ุฃูุขูุนุถุฃุก ๐ฟ.')
end
data[group]['moderators'][tostring(user_id)] = nil
save_data(_config.moderation.data, data)
end
local function promote2(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
local member_tag_username = string.gsub(member_username, '@', '(at)')
if not data[group] then
return send_large_msg(receiver, 'โ๐ป๐ ุงููู
ูุฌู
ููุนูู ููุณุชู ูุนุฃูููู โ๏ธ.')
end
if data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_username..' ๐ ูุชููุญู ูููููู ุจุฃููุนูู ุถู
ูููู ุฃููุขูุฏู
ูููููููู ๐.')
end
data[group]['moderators'][tostring(user_id)] = member_tag_username
save_data(_config.moderation.data, data)
send_large_msg(receiver, member_username..' ุฑููุนููููู ุฃุฏู
ูู ๐๐ ุดุฏู ุญููููู ูุงุดุงุทุฑ๐ช๐
.')
end
local function demote2(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
if not data[group] then
return send_large_msg(receiver, 'โ๐ป๐ ุงููู
ูุฌู
ููุนูู ููุณุชู ูุนุฃูููู โ๏ธ.')
end
if not data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_tag_username..' ๐ โ๐ป ููุชููุญู ูููููู ุจุฃูููุนูู ุถู
ููู ุฃูุขูุนุถุฃุก ๐ฟ.')
end
data[group]['moderators'][tostring(user_id)] = nil
save_data(_config.moderation.data, data)
send_large_msg(receiver, member_username..' ุฎูุทูููู ููุฒูููู ู
ูู ุฃูุขูุฏู
ูููููู ๐ ูุชูุจุฌู ููููุฃ ูู
ูุนูู ุนูููู๐๐ข.')
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 'โ๐ป๐ ุงููู
ูุฌู
ููุนูู ููุณุชู ูุนุฃูููู โ๏ธ.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then
return '๐ ูุขู ูููููุฌูุฏู ุฃูุฏู
ูููููู ุญูุฃูููุฃู ๐โ๏ธ.'
end
local i = 1
local message = '\n๐ข ูุฃุฆู
ููู ุฃูุขูุฏู
ููููููู โ๏ธ ' .. 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
-- Start by reply actions
function get_message_callback(extra, success, result)
local get_cmd = extra.get_cmd
local msg = extra.msg
local data = load_data(_config.moderation.data)
local print_name = user_print_name(msg.from):gsub("โฎ", "")
local name_log = print_name:gsub("_", " ")
if get_cmd == "ุงูุฏู" and not result.action then
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for: ["..result.from.peer_id.."]")
id1 = send_large_msg(channel, result.from.peer_id)
elseif get_cmd == 'ุงูุฏู' and result.action then
local action = result.action.type
if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then
if result.action.user then
user_id = result.action.user.peer_id
else
user_id = result.peer_id
end
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id by service msg for: ["..user_id.."]")
id1 = send_large_msg(channel, user_id)
end
elseif get_cmd == "idfrom" then
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for msg fwd from: ["..result.fwd_from.peer_id.."]")
id2 = send_large_msg(channel, result.fwd_from.peer_id)
elseif get_cmd == 'channel_block' and not result.action then
local member_id = result.from.peer_id
local channel_id = result.to.peer_id
if member_id == msg.from.id then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then
return send_large_msg("channel#id"..channel_id, "๐ก๐ ูุงุชู
ุณูุช ุจูููู ูุงูู
ููู ุทุฑุฏ ุงูุงุฏู
ู ุฃู ุงูู
ุฏูุฑูโ๏ธ")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "๐ก๐ ูุง ุชู
ุณูุช ุจูููู ูุงูู
ููู ุทุฑุฏ ุงูุงุฏุงุฑูโ๏ธ")
end
--savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply")
kick_user(member_id, channel_id)
elseif get_cmd == 'channel_block' and result.action and result.action.type == 'chat_add_user' then
local user_id = result.action.user.peer_id
local channel_id = result.to.peer_id
if member_id == msg.from.id then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then
return send_large_msg("channel#id"..channel_id, "๐ก๐ ูุงุชู
ุณูุช ุจูููู ูุงูู
ููู ุทุฑุฏ ุงูุงุฏู
ู ุฃู ุงูู
ุฏูุฑูโ๏ธ")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "๐ก๐ ูุง ุชู
ุณูุช ุจูููู ูุงูู
ููู ุทุฑุฏ ุงูุงุฏุงุฑูโ๏ธ")
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply to sev. msg.")
kick_user(user_id, channel_id)
elseif get_cmd == "ู
ุณุญ" then
delete_msg(result.id, ok_cb, false)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted a message by reply")
elseif get_cmd == "ุฑูุน ุงุฏุงุฑู" then
local user_id = result.from.peer_id
local channel_id = "channel#id"..result.to.peer_id
channel_set_admin(channel_id, "user#id"..user_id, ok_cb, false)
if result.from.username then
text = "@"..result.from.username.." ุจูุนูุฏู ุดูุชุฑููุฏู ๐ ู
ููู ุฑุจูููู ุชูู
ู ุฑูุนููู ููู ุฃูุขูุฏุฑูู ๐ช"
else
text = "[ "..user_id.." ]ุจูุนูุฏู ุดูุชุฑููุฏู ๐ ู
ููู ุฑุจูููู ุชูู
ู ุฑูุนููู ููู ุฃูุขูุฏุฑูู ๐ช"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..user_id.."] as admin by reply")
send_large_msg(channel_id, text)
elseif get_cmd == "ุชูุฒูู ุงุฏุงุฑู" then
local user_id = result.from.peer_id
local channel_id = "channel#id"..result.to.peer_id
if is_admin2(result.from.peer_id) then
return send_large_msg(channel_id, "โ๐ป๐ก๐ ูุข ุชู
ุณููุช ุจูููููู ูุขู ูู
ูููููู ุชูุฒููู ุฃุฏุฃุฑูู ๐")
end
channel_demote(channel_id, "user#id"..user_id, ok_cb, false)
if result.from.username then
text = "@"..result.from.username.." ุฎุทูููู ุชู
ู ุชูุฒููู ๐ข ู
ููู ุฃูุขูุฏุฃุฑูู ูุชุจุฌู ุฌุฑูุฃูุฑูู ูููุจูู ๐"
else
text = "[ "..user_id.." ] ุฎุทูููู ุชู
ู ุชูุฒููู ๐ข ู
ููู ุฃูุขูุฏุฃุฑูู ูุชุจุฌู ุฌุฑูุฃูุฑูู ูููุจูู ๐"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted: ["..user_id.."] from admin by reply")
send_large_msg(channel_id, text)
elseif get_cmd == "ุฑูุน ุงูู
ุฏูุฑ" then
local group_owner = data[tostring(result.to.peer_id)]['set_owner']
if group_owner then
local channel_id = 'channel#id'..result.to.peer_id
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(channel_id, user, ok_cb, false)
end
local user_id = "user#id"..result.from.peer_id
channel_set_admin(channel_id, user_id, ok_cb, false)
data[tostring(result.to.peer_id)]['set_owner'] = tostring(result.from.peer_id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..result.from.peer_id.."] as owner by reply")
if result.from.username then
text = "@"..result.from.username.." [ "..result.from.peer_id.." ] ููุขู ูููู
ููู ุชู
ู โ๏ธ ุฑูุนููู ู
ูุฏููุฑ ๐๐ ุณููุฌูู ูููุจูู ๐"
else
text = "[ "..result.from.peer_id.." ] ููุขู ูููู
ููู ุชู
ู โ๏ธ ุฑูุนููู ู
ูุฏููุฑ ๐๐ ุณููุฌูู ูููุจูู ๐"
end
send_large_msg(channel_id, text)
end
elseif get_cmd == "ุฑูุน ุงุฏู
ู" then
local receiver = result.to.peer_id
local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '')
local member_name = full_name:gsub("โฎ", "")
local member_username = member_name:gsub("_", " ")
if result.from.username then
member_username = '@'.. result.from.username
end
local member_id = result.from.peer_id
if result.to.peer_type == 'channel' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted mod: @"..member_username.."["..result.from.peer_id.."] by reply")
promote2("channel#id"..result.to.peer_id, member_username, member_id)
--channel_set_mod(channel_id, user, ok_cb, false)
end
elseif get_cmd == "ุชูุฒูู ุงุฏู
ู" then
local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '')
local member_name = full_name:gsub("โฎ", "")
local member_username = member_name:gsub("_", " ")
if result.from.username then
member_username = '@'.. result.from.username
end
local member_id = result.from.peer_id
--local user = "user#id"..result.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ุชูุฒูู ุงุฏู
ู: @"..member_username.."["..user_id.."] by reply")
demote2("channel#id"..result.to.peer_id, member_username, member_id)
--channel_demote(channel_id, user, ok_cb, false)
elseif get_cmd == 'mute_user' then
if result.service then
local action = result.action.type
if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then
if result.action.user then
user_id = result.action.user.peer_id
end
end
if action == 'chat_add_user_link' then
if result.from then
user_id = result.from.peer_id
end
end
else
user_id = result.from.peer_id
end
local receiver = extra.receiver
local chat_id = msg.to.id
print(user_id)
print(chat_id)
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
send_large_msg(receiver, "["..user_id.."] ๐ ุฌุฑุงุฑู โค๏ธ ุฑุงุญ ุงููุชู
ู
ูู ููุง ุฏุฑุฏุด ๐")
elseif is_admin1(msg) then
mute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] โ๐ปุนู
ูุช ุนูู ููุณู ุชู
ูุชู
ู ๐ค")
end
end
end
-- End by reply actions
--By ID actions
local function cb_user_info(extra, success, result)
local receiver = extra.receiver
local user_id = result.peer_id
local get_cmd = extra.get_cmd
local data = load_data(_config.moderation.data)
--[[if get_cmd == "setadmin" then
local user_id = "user#id"..result.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been set as an admin"
else
text = "[ "..result.peer_id.." ] has been set as an admin"
end
send_large_msg(receiver, text)]]
if get_cmd == "ุชูุฒูู ุงุฏุงุฑู" then
if is_admin2(result.peer_id) then
return send_large_msg(receiver, "๐ก๐ูุข ุชู
ุณููุช ุจูููููู ูุขู ูู
ูููููู ุชูุฒููู ุฃุฏุฃุฑูู ๐")
end
local user_id = "user#id"..result.peer_id
channel_demote(receiver, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." ุฎุทูููู ุชู
ู ุชูุฒููู ๐ข ู
ูู ุฃูุขูุฏุฃุฑูู ูุชุจุฌู ุฌุฑูุฃูุฑูู ูููุจูู ๐"
send_large_msg(receiver, text)
else
text = "[ "..result.peer_id.." ] ุฎุทูููู ุชู
ู ุชูุฒููู ๐ข ู
ูู ุฃูุขูุฏุฃุฑูู ูุชุจุฌู ุฌุฑูุฃูุฑูู ูููุจูู ๐"
send_large_msg(receiver, text)
end
elseif get_cmd == "ุฑูุน ุงุฏู
ู" then
if result.username then
member_username = "@"..result.username
else
member_username = string.gsub(result.print_name, '_', ' ')
end
promote2(receiver, member_username, user_id)
elseif get_cmd == "ุชูุฒูู ุงุฏู
ู" then
if result.username then
member_username = "@"..result.username
else
member_username = string.gsub(result.print_name, '_', ' ')
end
demote2(receiver, member_username, user_id)
end
end
-- Begin resolve username actions
local function callbackres(extra, success, result)
local member_id = result.peer_id
local member_username = "@"..result.username
local get_cmd = extra.get_cmd
if get_cmd == "ุงูุงูุฏู" then
local user = result.peer_id
local name = string.gsub(result.print_name, "_", " ")
local channel = 'channel#id'..extra.channelid
send_large_msg(channel, user..'\n'..name)
return user
elseif get_cmd == "ุงูุฏู" then
local user = result.peer_id
local channel = 'channel#id'..extra.channelid
send_large_msg(channel, user)
return user
elseif get_cmd == "invite" then
local receiver = extra.channel
local user_id = "user#id"..result.peer_id
channel_invite(receiver, user_id, ok_cb, false)
--[[elseif get_cmd == "channel_block" then
local user_id = result.peer_id
local channel_id = extra.channelid
local sender = extra.sender
if member_id == sender then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(sender) then
return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "You can't kick other admins")
end
kick_user(user_id, channel_id)
elseif get_cmd == "setadmin" then
local user_id = "user#id"..result.peer_id
local channel_id = extra.channel
channel_set_admin(channel_id, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been set as an admin"
send_large_msg(channel_id, text)
else
text = "@"..result.peer_id.." has been set as an admin"
send_large_msg(channel_id, text)
end
elseif get_cmd == "setowner" then
local receiver = extra.channel
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = extra.from_id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
local user = "user#id"..group_owner
if not is_admin2(group_owner) and not is_support(group_owner) then
channel_demote(receiver, user, ok_cb, false)
end
local user_id = "user#id"..result.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
data[tostring(channel)]['set_owner'] = tostring(result.peer_id)
save_data(_config.moderation.data, data)
savelog(channel, name_log.." ["..from_id.."] set ["..result.peer_id.."] as owner by username")
if result.username then
text = member_username.." [ "..result.peer_id.." ] added as owner"
else
text = "[ "..result.peer_id.." ] added as owner"
end
send_large_msg(receiver, text)
end]]
elseif get_cmd == "ุฑูุน ุงุฏู
ู" then
local receiver = extra.channel
local user_id = result.peer_id
--local user = "user#id"..result.peer_id
promote2(receiver, member_username, user_id)
--channel_set_mod(receiver, user, ok_cb, false)
elseif get_cmd == "ุชูุฒูู ุงุฏู
ู" then
local receiver = extra.channel
local user_id = result.peer_id
local user = "user#id"..result.peer_id
demote2(receiver, member_username, user_id)
elseif get_cmd == "ุชูุฒูู ุงุฏุงุฑู" then
local user_id = "user#id"..result.peer_id
local channel_id = extra.channel
if is_admin2(result.peer_id) then
return send_large_msg(channel_id, "๐ก๐ูุข ุชู
ุณููุช ุจูููููู ูุขู ูู
ูููููู ุชูุฒููู ุฃุฏุฃุฑูู ๐")
end
channel_demote(channel_id, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." ุฎุทูููู ุชู
ู ุชูุฒููู ๐ข ู
ูู ุฃูุขูุฏุฃุฑูู ูุชุจุฌู ุฌุฑูุฃูุฑูู ูููุจูู ๐"
send_large_msg(channel_id, text)
else
text = "@"..result.peer_id.." ุฎุทูููู ุชู
ู ุชูุฒููู ๐ข ู
ูู ุฃูุขูุฏุฃุฑูู ูุชุจุฌู ุฌุฑูุฃูุฑูู ูููุจูู ๐"
send_large_msg(channel_id, text)
end
local receiver = extra.channel
local user_id = result.peer_id
demote_admin(receiver, member_username, user_id)
elseif get_cmd == 'mute_user' then
local user_id = result.peer_id
local receiver = extra.receiver
local chat_id = string.gsub(receiver, 'channel#id', '')
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] removed from muted user list")
elseif is_owner(extra.msg) then
mute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] added to muted user list")
end
end
end
--End resolve username actions
--Begin non-channel_invite username actions
local function in_channel_cb(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local msg = cb_extra.msg
local data = load_data(_config.moderation.data)
local print_name = user_print_name(cb_extra.msg.from):gsub("โฎ", "")
local name_log = print_name:gsub("_", " ")
local member = cb_extra.username
local memberid = cb_extra.user_id
if member then
text = 'ูุงููุฌุฏ ุนุถู @'..member..' ูู ูุงุฐู ุงูู
ุฌู
ูุนู.'
else
text = 'ูุงููุฌุฏ ุนุถู ['..memberid..'] ูู ูุงุฐู ุงูู
ุฌู
ูุนู.'
end
if get_cmd == "channel_block" then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local user_id = v.peer_id
local channel_id = cb_extra.msg.to.id
local sender = cb_extra.msg.from.id
if user_id == sender then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(user_id, channel_id) and not is_admin2(sender) then
return send_large_msg("channel#id"..channel_id, "๐ก๐ ูุงุชู
ุณูุช ุจูููู ูุงูู
ููู ุทุฑุฏ ุงูุงุฏู
ู ุฃู ุงูู
ุฏูุฑูโ๏ธ")
end
if is_admin2(user_id) then
return send_large_msg("channel#id"..channel_id, "๐ก๐ ูุง ุชู
ุณูุช ุจูููู ูุงูู
ููู ุทุฑุฏ ุงูุงุฏุงุฑูโ๏ธ")
end
if v.username then
text = ""
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..v.username.." ["..v.peer_id.."]")
else
text = ""
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..v.peer_id.."]")
end
kick_user(user_id, channel_id)
return
end
end
elseif get_cmd == "ุฑูุน ุงุฏุงุฑู" then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local user_id = "user#id"..v.peer_id
local channel_id = "channel#id"..cb_extra.msg.to.id
channel_set_admin(channel_id, user_id, ok_cb, false)
if v.username then
text = "@"..v.username.." ["..v.peer_id.."] ุจูุนูุฏู ุดูุชุฑููุฏู ๐ ู
ูู ุฑุจูููู ุชูู
ู ุฑูุนููู ููู ุฃูุขูุฏุฑูู ๐ช"
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..v.username.." ["..v.peer_id.."]")
else
text = "["..v.peer_id.."] ุจูุนูุฏู ุดูุชุฑููุฏู ๐ ู
ูู ุฑุจูููู ุชูู
ู ุฑูุนููู ููู ุฃูุขูุฏุฑูู ๐ช"
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin "..v.peer_id)
end
if v.username then
member_username = "@"..v.username
else
member_username = string.gsub(v.print_name, '_', ' ')
end
local receiver = channel_id
local user_id = v.peer_id
promote_admin(receiver, member_username, user_id)
end
send_large_msg(channel_id, text)
return
end
elseif get_cmd == 'ุฑูุน ุงูู
ุฏูุฑ' then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = cb_extra.msg.from.id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(receiver, user, ok_cb, false)
end
local user_id = "user#id"..v.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
data[tostring(channel)]['set_owner'] = tostring(v.peer_id)
save_data(_config.moderation.data, data)
savelog(channel, name_log.."["..from_id.."] set ["..v.peer_id.."] as owner by username")
if result.username then
text = member_username.." ["..v.peer_id.."] ููุขู ูููู
ููู ุชู
ู โ๏ธ ุฑูุนููู ู
ูุฏููุฑ ๐ ุณููุฌูู ูููุจูู ๐"
else
text = "["..v.peer_id.."] ููุขู ูููู
ููู ุชู
ู โ๏ธ ุฑูุนููู ู
ูุฏููุฑ ๐ ุณููุฌูู ูููุจูู ๐"
end
end
elseif memberid and vusername ~= member and vpeer_id ~= memberid then
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = cb_extra.msg.from.id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(receiver, user, ok_cb, false)
end
data[tostring(channel)]['set_owner'] = tostring(memberid)
save_data(_config.moderation.data, data)
savelog(channel, name_log.."["..from_id.."] set ["..memberid.."] as owner by username")
text = "["..memberid.."] ููุขู ูููู
ููู ุชู
ู โ๏ธ ุฑูุนููู ู
ูุฏููุฑ ๐ ุณููุฌูู ูููุจูู ๐"
end
end
end
end
send_large_msg(receiver, text)
end
--End non-channel_invite username actions
--'Set supergroup photo' function
local function set_supergroup_photo(msg, success, result)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return
end
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/channel_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
channel_set_photo(receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
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
--Run function
local function run(msg, matches)
if msg.to.type == 'chat' then
if matches[1] == 'ุชุฑููู ุณูุจุฑ' then
if not is_admin1(msg) then
return
end
local receiver = get_receiver(msg)
chat_upgrade(receiver, ok_cb, false)
end
elseif msg.to.type == 'channel'then
if matches[1] == 'ุชุฑููู ุณูุจุฑ' then
if not is_admin1(msg) then
return
end
return "ุงูู
ุฌู
ูุนุฉ ๐ฅ ุฎุงุฑูุฉ โป๏ธ ุจุงููุนู โ๏ธ"
end
end
if msg.to.type == 'channel' then
local support_id = msg.from.id
local receiver = get_receiver(msg)
local print_name = user_print_name(msg.from):gsub("โฎ", "")
local name_log = print_name:gsub("_", " ")
local data = load_data(_config.moderation.data)
if matches[1] == 'ุชูุนูู' and not matches[2] then
if not is_admin1(msg) and not is_support(support_id) then
return
end
if is_super_group(msg) then
return reply_msg(msg.id, '๐ ุฃูู
ูุฌู
ูููุนูููู ุจุฃูููุชุฃูููุฏู ู
ูุนูููู โ๏ธ..', ok_cb, false)
end
print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") added")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added SuperGroup")
superadd(msg)
set_mutes(msg.to.id)
channel_set_admin(receiver, 'user#id'..msg.from.id, ok_cb, false)
end
if matches[1] == 'ุชุนุทูู ุงูู
ุฌู
ูุนู' and is_admin1(msg) and not matches[2] then
if not is_super_group(msg) then
return reply_msg(msg.id, '๐ ุฃูู
ูุฌู
ูููุนูููู ุจุฃูููุชุฃูููุฏู ุชูู
ู ุชูุนูุทูููููุฃู โ๏ธ..', ok_cb, false)
end
print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed")
superrem(msg)
rem_mutes(msg.to.id)
end
if not data[tostring(msg.to.id)] then
return
end
if matches[1] == "ู
ุนููู
ุงุช ุงูู
ุฌู
ูุนู" then
if not is_owner(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup info")
channel_info(receiver, callback_info, {receiver = receiver, msg = msg})
end
if matches[1] == "ุงูุงุฏุงุฑููู" then
if not is_owner(msg) and not is_support(msg.from.id) then
return
end
member_type = 'โค๏ธ ููุฃุฆูู
ููู ุฃููุฃุฏุฑูููููู โค๏ธ'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup Admins list")
admins = channel_get_admins(receiver,callback, {receiver = receiver, msg = msg, member_type = member_type})
end
if matches[1] == "ู
ุฏูุฑ ุงูู
ุฌู
ูุนู" then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "โ๐ปโ ูุง ููุฌุฏ ู
ุฏูุฑ ูู ุงูู
ุฌู
ูุนู ููุชุธุฑ ุงูุชุฎุงุจุงุชูู
ูุชุนูู ุงูู
ุฏูุฑ ๐๐"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "โค๏ธ ู
ุฏูุฑ ุงูู
ุฌู
ูุนุฉ ุงูู
ุญุชุฑู
โค๏ธ ["..group_owner..']'
end
if matches[1] == "ุงูุงุฏู
ููู" then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
-- channel_get_admins(receiver,callback, {receiver = receiver})
end
if matches[1] == "ูุดู ุจูุช" and is_momod(msg) then
member_type = 'ูุดู ุงูุจูุชุงุช ุจ ุงูู
ุฌู
ูุนู'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup bots list")
channel_get_bots(receiver, callback, {receiver = receiver, msg = msg, member_type = member_type})
end
if matches[1] == "ุงูุฏู ุงูุงุนุถุงุก" and not matches[2] and is_momod(msg) then
local user_id = msg.from.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup users list")
channel_get_users(receiver, callback_who, {receiver = receiver})
end
if matches[1] == "kicked" and is_momod(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested Kicked users list")
channel_get_kicked(receiver, callback_kicked, {receiver = receiver})
end
if matches[1] == 'ู
ุณุญ' and is_momod(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'ู
ุณุญ',
msg = msg
}
delete_msg(msg.id, ok_cb, false)
get_message(msg.reply_id, get_message_callback, cbreply_extra)
end
end
if matches[1] == 'ุจููู' and is_momod(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'channel_block',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'ุจููู' and string.match(matches[2], '^%d+$') then
--[[local user_id = matches[2]
local channel_id = msg.to.id
if is_momod2(user_id, channel_id) and not is_admin2(user_id) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: [ user#id"..user_id.." ]")
kick_user(user_id, channel_id)]]
local get_cmd = 'channel_block'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif msg.text:match("@[%a%d]") then
--[[local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'channel_block',
sender = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..username)
resolve_username(username, callbackres, cbres_extra)]]
local get_cmd = 'channel_block'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'ุงูุฏู' then
if type(msg.reply_id) ~= "nil" and is_momod(msg) and not matches[2] then
local cbreply_extra = {
get_cmd = 'ุงูุฏู',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif type(msg.reply_id) ~= "nil" and matches[2] == "from" and is_momod(msg) then
local cbreply_extra = {
get_cmd = 'idfrom',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif msg.text:match("@[%a%d]") then
local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'ุงูุฏู'
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested ID for: @"..username)
resolve_username(username, callbackres, cbres_extra)
else
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup ID")
return "โฃ ุงูุฏู ู
ุฌู
ูุนุฉ "..string.gsub(msg.to.print_name, "_", " ")..": "..msg.to.id
end
end
if matches[1] == 'ู
ุบุงุฏุฑู' then
if msg.to.type == 'channel' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] left via kickme")
channel_kick("channel#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if matches[1] == 'ุชุบูุฑ ุงูุฑุงุจุท' and is_momod(msg)then
local function callback_link (extra , success, result)
local receiver = get_receiver(msg)
if success == 0 then
send_large_msg(receiver, '*โ๐ปโ ุนุฐุฑุง ูุง ูู
ูู ุชุบูุฑ ุฑุงุจุท ูุงุฐู ุงูู
ุฌู
ูุนู ๐* \nุงูู
ุฌู
ูุนู ููุณุช ู
ู ุตูุน ุงูุจูุช.\n\nูุฑุฌุฆ ุงุณุชุฎุฏุงู
ุงูุฑุงุจุท ุงูุฎุงุต ุจูุง ูู ุงุนุฏุงุฏุงุช ุงูู
ุฌู
ูุนู')
data[tostring(msg.to.id)]['settings']['set_link'] = nil
save_data(_config.moderation.data, data)
else
send_large_msg(receiver, "ุชู
โ๏ธ ุชุบูุฑ ุงูุฑุงุจุท ๐ฅ ")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to create a new SuperGroup link")
export_channel_link(receiver, callback_link, false)
end
if matches[1] == 'ุถุน ุฑุงุจุท' and is_owner(msg) then
data[tostring(msg.to.id)]['settings']['set_link'] = 'waiting'
save_data(_config.moderation.data, data)
return 'โ๐ป ูุฑุฌุฆ ุงุฑุณุงู ุฑุงุจุท ุงูู
ุฌู
ูุนู ุฎุงุต ุจู ๐ฅ'
end
if msg.text then
if msg.text:match("^(https://telegram.me/joinchat/%S+)$") and data[tostring(msg.to.id)]['settings']['set_link'] == 'waiting' and is_owner(msg) then
data[tostring(msg.to.id)]['settings']['set_link'] = msg.text
save_data(_config.moderation.data, data)
return "ุชู
โ๏ธ ุญูุธ ุงูุฑุงุจุท ๐"
end
end
if matches[1] == 'ุงูุฑุงุจุท' then
if not is_momod(msg) then
return
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "โูุฑุฌุฆ ุงุฑุณุงู [/ุชุบูุฑ ุงูุฑุงุจุท] ูุงูุดุงุก ุฑุงุจุท ุงูู
ุฌู
ูุนู๐๐ปโ๏ธ"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "โ๏ธ ุฑุงุจุท ุงูู
ุฌู
ูุนู ๐ฅ:\n"..group_link
end
if matches[1] == "invite" and is_sudo(msg) then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = "invite"
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] invited @"..username)
resolve_username(username, callbackres, cbres_extra)
end
if matches[1] == 'ุงูุงูุฏู' and is_owner(msg) then
local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'ุงูุงูุฏู'
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] resolved username: @"..username)
resolve_username(username, callbackres, cbres_extra)
end
--[[if matches[1] == 'kick' and is_momod(msg) then
local receiver = channel..matches[3]
local user = "user#id"..matches[2]
chaannel_kick(receiver, user, ok_cb, false)
end]]
if matches[1] == 'ุฑูุน ุงุฏุงุฑู' then
if not is_support(msg.from.id) and not is_owner(msg) then
return
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'ุฑูุน ุงุฏุงุฑู',
msg = msg
}
setadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'ุฑูุน ุงุฏุงุฑู' and string.match(matches[2], '^%d+$') then
--[[] local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'setadmin'
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})]]
local get_cmd = 'ุฑูุน ุงุฏุงุฑู'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif matches[1] == 'ุฑูุน ุงุฏุงุฑู' and not string.match(matches[2], '^%d+$') then
--[[local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'setadmin'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..username)
resolve_username(username, callbackres, cbres_extra)]]
local get_cmd = 'ุฑูุน ุงุฏุงุฑู'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'ุชูุฒูู ุงุฏุงุฑู' then
if not is_support(msg.from.id) and not is_owner(msg) then
return
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'ุชูุฒูู ุงุฏุงุฑู',
msg = msg
}
demoteadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'ุชูุฒูู ุงุฏุงุฑู' and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'ุชูุฒูู ุงุฏุงุฑู'
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif matches[1] == 'ุชูุฒูู ุงุฏุงุฑู' and not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'ุชูุฒูู ุงุฏุงุฑู'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted admin @"..username)
resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == 'ุฑูุน ุงูู
ุฏูุฑ' and is_owner(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'ุฑูุน ุงูู
ุฏูุฑ',
msg = msg
}
setowner = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'ุฑูุน ุงูู
ุฏูุฑ' and string.match(matches[2], '^%d+$') then
--[[ local group_owner = data[tostring(msg.to.id)]['set_owner']
if group_owner then
local receiver = get_receiver(msg)
local user_id = "user#id"..group_owner
if not is_admin2(group_owner) and not is_support(group_owner) then
channel_demote(receiver, user_id, ok_cb, false)
end
local user = "user#id"..matches[2]
channel_set_admin(receiver, user, ok_cb, false)
data[tostring(msg.to.id)]['set_owner'] = tostring(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]]
local get_cmd = 'ุฑูุน ุงูู
ุฏูุฑ'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif matches[1] == 'ุฑูุน ุงูู
ุฏูุฑ' and not string.match(matches[2], '^%d+$') then
local get_cmd = 'ุฑูุน ุงูู
ุฏูุฑ'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'ุฑูุน ุงุฏู
ู' then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "๐๐ปู
ููุดุบฺูููช ุขุจููู ูููุทู ุงูู
ุฏูุฑ ุงู ุงูุงุฏุงุฑู ูุญูู ูููโ๏ธ"
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'ุฑูุน ุงุฏู
ู',
msg = msg
}
promote = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'ุฑูุน ุงุฏู
ู' and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'ุฑูุน ุงุฏู
ู'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted user#id"..matches[2])
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif matches[1] == 'ุฑูุน ุงุฏู
ู' and not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'ุฑูุน ุงุฏู
ู',
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @"..username)
return resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == 'mp' and is_sudo(msg) then
channel = get_receiver(msg)
user_id = 'user#id'..matches[2]
channel_set_mod(channel, user_id, ok_cb, false)
return "ok"
end
if matches[1] == 'md' and is_sudo(msg) then
channel = get_receiver(msg)
user_id = 'user#id'..matches[2]
channel_demote(channel, user_id, ok_cb, false)
return "ok"
end
if matches[1] == 'ุชูุฒูู ุงุฏู
ู' then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "๐๐ปู
ููุดุบฺูููช ุขุจููู ูููุทู ุงูู
ุฏูุฑ ุงู ุงูุงุฏุงุฑู ูุญูู ูููโ๏ธ"
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'ุชูุฒูู ุงุฏู
ู',
msg = msg
}
demote = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'ุชูุฒูู ุงุฏู
ู' and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'ุชูุฒูู ุงุฏู
ู'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted user#id"..matches[2])
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'ุชูุฒูู ุงุฏู
ู'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @"..username)
return resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == "ุถุน ุงุณู
" and is_momod(msg) then
local receiver = get_receiver(msg)
local set_name = string.gsub(matches[2], '_', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..matches[2])
rename_channel(receiver, set_name, ok_cb, false)
end
if msg.service and msg.action.type == 'chat_rename' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..msg.to.title)
data[tostring(msg.to.id)]['settings']['set_name'] = msg.to.title
save_data(_config.moderation.data, data)
end
if matches[1] == "ุถุน ูุตู" and is_momod(msg) then
local receiver = get_receiver(msg)
local about_text = matches[2]
local data_cat = 'description'
local target = msg.to.id
data[tostring(target)][data_cat] = about_text
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup description to: "..about_text)
channel_set_about(receiver, about_text, ok_cb, false)
return "ุชู
โ๏ธ ูุถุน ูุตู ุงูู
ุฌู
ูุนู ๐ฅ\n\nโ๐ป ุงูุถุฑ ุงูุฆ ุงูุญูู ูุชุดุงูุฏ ุงููุตู ุงูุฌุฏูุฏ ๐ฅ"
end
if matches[1] == "ุถุน ู
ุนุฑู" and is_admin1(msg) then
local function ok_username_cb (extra, success, result)
local receiver = extra.receiver
if success == 1 then
send_large_msg(receiver, "ุชู
โ๏ธ ูุถุน ู
ุนุฑู ููู
ุฌู
ูุนู ๐ฅโ๏ธ\n\nโ๐ป ุงูุถุฑ ุงูุฆ ุงูุญูู ูุชุดุงูุฏ ุชุบูุฑุงุช ุงูู
ุฌู
ูุนู ๐ฅ")
elseif success == 0 then
send_large_msg(receiver, "๐ข ูุดู ุชุนููู ู
ุนุฑู ุงูู
ุฌู
ูุนู ๐ฅโ๏ธ\nUsername may already be taken.\n\nNote: Username can use a-z, 0-9 and underscores.\nMinimum length is 5 characters.")
end
end
local username = string.gsub(matches[2], '@', '')
channel_set_username(receiver, username, ok_username_cb, {receiver=receiver})
end
if matches[1] == 'ุถุน ููุงููู' and is_momod(msg) then
rules = matches[2]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[2].."]")
return set_rulesmod(msg, data, target)
end
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_momod(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set new SuperGroup photo")
load_photo(msg.id, set_supergroup_photo, msg)
return
end
end
if matches[1] == 'ุถุน ุตูุฑู' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] started setting new SuperGroup photo")
return 'โ๐ปุงุฑุณู ูู ุตูุฑู ุงูุงู โ๏ธ๐'
end
if matches[1] == 'ู
ุณุญ' then
if not is_momod(msg) then
return
end
if not is_momod(msg) then
return "๐๐ปู
ููุดุบฺูููช ุขุจููู ูููุทู ุงูู
ุฏูุฑ ูุญูู ูููโ๏ธ"
end
if matches[2] == 'ุงูุงุฏู
ููู' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then
return 'โ๏ธ ุนุฐุฑุง ูุง ููุฌุฏ ุงุฏู
ููู ูู ุงูู
ุฌู
ูุนู ููุชู
ู
ุณุญูู
๐'
end
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")
return '๐ ุชู
ู
ุณุญ ูุงุฆู
ู ุงูุงุฏู
ููู โ๏ธ'
end
if matches[2] == 'ุงูููุงููู' then
local data_cat = 'rules'
if data[tostring(msg.to.id)][data_cat] == nil then
return "โ๏ธุนุฐุฑุง ูุง ููุฌุฏ ููุงููู ูู ุงูู
ุฌู
ูุนู ููุชู
ู
ุณุญูุง ๐"
end
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")
return '๐ ุชู
ู
ุณุญ ููุงููู ุงูู
ุฌู
ูุนู โ๏ธ'
end
if matches[2] == 'ุงููุตู' then
local receiver = get_receiver(msg)
local about_text = ' '
local data_cat = 'description'
if data[tostring(msg.to.id)][data_cat] == nil then
return 'โ๏ธุนุฐุฑุง ูุง ููุฌุฏ ูุตู ูู ุงูู
ุฌู
ูุนู ููุชู
ู
ุณุญู ๐'
end
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")
channel_set_about(receiver, about_text, ok_cb, false)
return "๐ ุชู
ู
ุณุญ ูุตู ุงูู
ุฌู
ูุนู โ๏ธ"
end
if matches[2] == 'ุงูู
ูุชูู
ูู' then
chat_id = msg.to.id
local hash = 'mute_user:'..chat_id
redis:del(hash)
return "๐ ุชู
ู
ุณุญ ูุงุฆู
ู ุงูู
ูุชูู
ูู โ๏ธ"
end
if matches[2] == 'ุงูู
ุนุฑู' and is_admin1(msg) then
local function ok_username_cb (extra, success, result)
local receiver = extra.receiver
if success == 1 then
send_large_msg(receiver, "๐ ุชู
ู
ุณุญ ู
ุนุฑู ุงูู
ุฌู
ูุนู โ๏ธ")
elseif success == 0 then
send_large_msg(receiver, "โ๏ธุบุฐุฑุง ูุดู ู
ุณุญ ู
ุนุฑู ุงูู
ุฌู
ูุนู ๐")
end
end
local username = ""
channel_set_username(receiver, username, ok_username_cb, {receiver=receiver})
end
end
if matches[1] == 'ููู' and is_momod(msg) then
local target = msg.to.id
if matches[2] == 'ุงูุฑูุงุจุท' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ")
return lock_group_links(msg, data, target)
end
if matches[2] == 'ุงูููุงูุด' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked spam ")
return lock_group_spam(msg, data, target)
end
if matches[2] == 'ุงูุชูุฑุงุฑ' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_flood(msg, data, target)
end
if matches[2] == 'ุงูุนุฑุจูู' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'ุงูุงุถุงูู' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2]:lower() == 'ุงูุงุถุงูู ุงูุฌู
ุงุนูู' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked rtl chars. in names")
return lock_group_rtl(msg, data, target)
end
if matches[2] == 'ุงูู
ูุตูุงุช' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting")
return lock_group_sticker(msg, data, target)
end
if matches[2] == 'ุฌูุงุช ุงูุงุชุตุงู' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting")
return lock_group_contacts(msg, data, target)
end
if matches[2] == 'ุงููู' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked enabled strict settings")
return enable_strict_rules(msg, data, target)
end
end
if matches[1] == 'ูุชุญ' and is_momod(msg) then
local target = msg.to.id
if matches[2] == 'ุงูุฑูุงุจุท' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting")
return unlock_group_links(msg, data, target)
end
if matches[2] == 'ุงูููุงูุด' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked spam")
return unlock_group_spam(msg, data, target)
end
if matches[2] == 'ุงูุชูุฑุงุฑ' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood")
return unlock_group_flood(msg, data, target)
end
if matches[2] == 'ุงูุนุฑุจูู' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked Arabic")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'ุงูุงุถุงูู' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2]:lower() == 'ุงูุงุถุงูู ุงูุฌู
ุงุนูู' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked RTL chars. in names")
return unlock_group_rtl(msg, data, target)
end
if matches[2] == 'ุงูู
ูุตูุงุช' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting")
return unlock_group_sticker(msg, data, target)
end
if matches[2] == 'ุฌูุงุช ุงูุงุชุตุงู' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting")
return unlock_group_contacts(msg, data, target)
end
if matches[2] == 'ุงูุชุญุฐูุฑ' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled strict settings")
return disable_strict_rules(msg, data, target)
end
end
if matches[1] == 'ุถุน ุชูุฑุงุฑ' then
if not is_momod(msg) then
return
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "๐ ุถุน ุชูุฑุงุฑ ู
ู 5 ุงูุฆ 20 โ๏ธ"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'ุชู
โ๏ธ ุชุนููู ุงูุชูุฑุงุฑ โผ๏ธโ ููุนุฏุฏ ๐๐ฟ: '..matches[2]
end
if matches[1] == 'ุงูู
ุฑุงูุจู' and is_momod(msg) then
local target = msg.to.id
if matches[2] == 'ูุนู
' 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] == 'ูุง' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: not public")
return unset_public_membermod(msg, data, target)
end
end
if matches[1] == 'ููู' and is_momod(msg) then
local chat_id = msg.to.id
if matches[2] == 'ุงูุตูุช' then
local msg_type = 'Audio'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." has been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'ุงูุตูุฑ' then
local msg_type = 'Photo'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." has been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'ุงูููุฏูู' then
local msg_type = 'Video'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." has been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'ุงูุตูุฑ ุงูู
ุชุญุฑูู' then
local msg_type = 'Gifs'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." have been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'ุงููุงููุงุช' then
local msg_type = 'Documents'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." have been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'ุงูุฏุฑุฏุดู' then
local msg_type = 'Text'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." has been muted"
else
return "Mute "..msg_type.." is already on"
end
end
if matches[2] == 'ุงูู
ุฌู
ูุนู' then
local msg_type = 'All'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return "Mute "..msg_type.." has been enabled"
else
return "Mute "..msg_type.." is already on"
end
end
end
if matches[1] == 'ูุชุญ' and is_momod(msg) then
local chat_id = msg.to.id
if matches[2] == 'ุงูุตูุช' then
local msg_type = 'Audio'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." has been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'ุงูุตูุฑ' then
local msg_type = 'Photo'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." has been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'ุงูููุฏูู' then
local msg_type = 'Video'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." has been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'ุงูุตูุฑ ุงูู
ุชุญุฑูู' then
local msg_type = 'Gifs'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." have been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'ุงููุงููุงุช' then
local msg_type = 'Documents'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." have been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'ุงูุฏุฑุฏุดู' then
local msg_type = 'Text'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute message")
unmute(chat_id, msg_type)
return msg_type.." has been unmuted"
else
return "Mute text is already off"
end
end
if matches[2] == 'ุงูู
ุฌู
ูุนู' then
local msg_type = 'All'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return "Mute "..msg_type.." has been disabled"
else
return "Mute "..msg_type.." is already disabled"
end
end
end
if matches[1] == "ูุชู
" and is_momod(msg) then
local chat_id = msg.to.id
local hash = "mute_user"..chat_id
local user_id = ""
if type(msg.reply_id) ~= "nil" then
local receiver = get_receiver(msg)
local get_cmd = "mute_user"
muteuser = get_message(msg.reply_id, get_message_callback, {receiver = receiver, get_cmd = get_cmd, msg = msg})
elseif matches[1] == "ูุชู
" and string.match(matches[2], '^%d+$') then
local user_id = matches[2]
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed ["..user_id.."] from the muted users list")
return "["..user_id.."] removed from the muted users list"
elseif is_momod(msg) then
mute_user(chat_id, user_id)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."] to the muted users list")
return "["..user_id.."] added to the muted user list"
end
elseif matches[1] == "ูุชู
" and not string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local get_cmd = "mute_user"
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
resolve_username(username, callbackres, {receiver = receiver, get_cmd = get_cmd, msg=msg})
end
end
if matches[1] == "ุงุนุฏุงุฏุงุช ุงููุณุงุฆุท" and is_momod(msg) then
local chat_id = msg.to.id
if not has_mutes(chat_id) then
set_mutes(chat_id)
return mutes_list(chat_id)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist")
return mutes_list(chat_id)
end
if matches[1] == "ุงูู
ูุชูู
ูู" and is_momod(msg) then
local chat_id = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist")
return muted_user_list(chat_id)
end
if matches[1] == 'ุงูุงุนุฏุงุฏุงุช' and is_momod(msg) then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup settings ")
return show_supergroup_settingsmod(msg, target)
end
if matches[1] == 'ุงูููุงููู' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'help' and not is_owner(msg) then
text = "Message /superhelp to @Teleseed in private for SuperGroup help"
reply_msg(msg.id, text, ok_cb, false)
elseif matches[1] == 'help' and is_owner(msg) then
local name_log = user_print_name(msg.from)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp")
return super_help()
end
if matches[1] == 'peer_id' and is_admin1(msg)then
text = msg.to.peer_id
reply_msg(msg.id, text, ok_cb, false)
post_large_msg(receiver, text)
end
if matches[1] == 'msg.to.id' and is_admin1(msg) then
text = msg.to.id
reply_msg(msg.id, text, ok_cb, false)
post_large_msg(receiver, text)
end
--Admin Join Service Message
if msg.service then
local action = msg.action.type
if action == 'chat_add_user_link' then
if is_owner2(msg.from.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.from.id
savelog(msg.to.id, name_log.." Admin ["..msg.from.id.."] joined the SuperGroup via link")
channel_set_admin(receiver, user, ok_cb, false)
end
if is_support(msg.from.id) and not is_owner2(msg.from.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.from.id
savelog(msg.to.id, name_log.." Support member ["..msg.from.id.."] joined the SuperGroup")
channel_set_mod(receiver, user, ok_cb, false)
end
end
if action == 'chat_add_user' then
if is_owner2(msg.action.user.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.action.user.id
savelog(msg.to.id, name_log.." Admin ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]")
channel_set_admin(receiver, user, ok_cb, false)
end
if is_support(msg.action.user.id) and not is_owner2(msg.action.user.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.action.user.id
savelog(msg.to.id, name_log.." Support member ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]")
channel_set_mod(receiver, user, ok_cb, false)
end
end
end
if matches[1] == 'msg.to.peer_id' then
post_large_msg(receiver, msg.to.peer_id)
end
end
end
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '['..msg.media.type..']'
end
return msg
end
return {
patterns = {
"^(ุชูุนูู)$",
"^(ุชุนุทูู ุงูู
ุฌู
ูุนู)$",
"^([Mm]ove) (.*)$",
"^(ู
ุนููู
ุงุช ุงูู
ุฌู
ูุนู)$",
"^(ุงูุงุฏุงุฑููู)$",
"^(ู
ุฏูุฑ ุงูู
ุฌู
ูุนู)$",
"^(ุงูุงุฏู
ููู)$",
"^(ูุดู ุจูุช)$",
"^(ุงูุฏู ุงูุงุนุถุงุก)$",
"^([Kk]icked)$",
"^(ุจููู) (.*)",
"^(ุจููู)",
"^(ุชุฑููู ุณูุจุฑ)$",
"^(ุงูุฏู)$",
"^(ุงูุฏู) (.*)$",
"^(ู
ุบุงุฏุฑู)$",
"^[#!/]([Kk]ick) (.*)$",
"^(ุชุบูุฑ ุงูุฑุงุจุท)$",
"^(ุถุน ุฑุงุจุท)$",
"^(ุงูุฑุงุจุท)$",
"^(ุงูุงูุฏู) (.*)$",
"^(ุฑูุน ุงุฏุงุฑู) (.*)$",
"^(ุฑูุน ุงุฏุงุฑู)",
"^(ุชูุฒูู ุงุฏุงุฑู) (.*)$",
"^(ุชูุฒูู ุงุฏุงุฑู)",
"^(ุฑูุน ุงูู
ุฏูุฑ) (.*)$",
"^(ุฑูุน ุงูู
ุฏูุฑ)$",
"^(ุฑูุน ุงุฏู
ู) (.*)$",
"^(ุฑูุน ุงุฏู
ู)",
"^(ุชูุฒูู ุงุฏู
ู) (.*)$",
"^(ุชูุฒูู ุงุฏู
ู)",
"^(ุถุน ุงุณู
) (.*)$",
"^(ุถุน ูุตู) (.*)$",
"^(ุถุน ููุงููู) (.*)$",
"^(ุถุน ุตูุฑู)$",
"^(ุถุน ู
ุนุฑู) (.*)$",
"^(ู
ุณุญ)$",
"^(ููู) (.*)$",
"^(ูุชุญ) (.*)$",
"^(ููู) ([^%s]+)$",
"^(ูุชุญ) ([^%s]+)$",
"^(ูุชู
)$",
"^(ูุชู
) (.*)$",
"^(ุงูู
ุฑุงูุจู) (.*)$",
"^(ุงูุงุนุฏุงุฏุงุช)$",
"^(ุงูููุงููู)$",
"^(ุถุน ุชูุฑุงุฑ) (%d+)$",
"^(ู
ุณุญ) (.*)$",
"^[#!/]([Hh]elpp)$",
"^(ุงุนุฏุงุฏุงุช ุงููุณุงุฆุท)$",
"^(ุงูู
ูุชูู
ูู)$",
"[#!/](mp) (.*)",
"[#!/](md) (.*)",
"^(https://telegram.me/joinchat/%S+)$",
"msg.to.peer_id",
"%[(document)%]",
"%[(photo)%]",
"%[(video)%]",
"%[(audio)%]",
"%[(contact)%]",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
}
--End supergrpup.lua
--By @SAJJADNOORI | gpl-3.0 |
DorotheeLaugwitz/intergalacticgolf | conf.lua | 2 | 2335 | function love.conf(t)
-- The name of the save directory (string)
t.identity = nil
-- The LรVE version this game was made for (string)
t.version = "0.9.1"
-- Attach a console (boolean, Windows only)
t.console = false
-- The window title (string)
t.window.title = "YOUR_PRODUCT (c) 2345 by YOUR_NAME"
-- Filepath to an image to use as the window's icon (string)
t.window.icon = nil
-- The window width (number)
t.window.width = 1280
-- The window height (number)
t.window.height = 920
-- Remove all border visuals from the window (boolean)
t.window.borderless = false
-- Let the window be user-resizable (boolean)
t.window.resizable = false
-- Minimum window width if the window is resizable (number)
t.window.minwidth = 1
-- Minimum window height if the window is resizable (number)
t.window.minheight = 1
-- Enable fullscreen (boolean)
t.window.fullscreen = false
-- Standard fullscreen or desktop fullscreen mode (string)
t.window.fullscreentype = "desktop"
-- Enable vertical sync (boolean)
t.window.vsync = true
-- The number of samples to use with multi-sampled antialiasing (number)
t.window.fsaa = 0
-- Index of the monitor to show the window in (number)
t.window.display = 1
-- Enable high-dpi mode for the window on a Retina display (boolean). Added in 0.9.1
t.window.highdpi = false
-- Enable sRGB gamma correction when drawing to the screen (boolean). Added in 0.9.1
t.window.srgb = false
-- Enable the audio module (boolean)
t.modules.audio = true
-- Enable the event module (boolean)
t.modules.event = true
-- Enable the graphics module (boolean)
t.modules.graphics = true
-- Enable the image module (boolean)
t.modules.image = true
-- Enable the joystick module (boolean)
t.modules.joystick = true
-- Enable the keyboard module (boolean)
t.modules.keyboard = true
-- Enable the math module (boolean)
t.modules.math = true
-- Enable the mouse module (boolean)
t.modules.mouse = true
-- Enable the physics module (boolean)
t.modules.physics = true
-- Enable the sound module (boolean)
t.modules.sound = true
-- Enable the system module (boolean)
t.modules.system = true
-- Enable the timer module (boolean)
t.modules.timer = true
-- Enable the window module (boolean)
t.modules.window = true
-- Enable the thread module (boolean)
t.modules.thread = true
end
| mit |
rpetit3/darkstar | scripts/zones/Giddeus/npcs/Ghoo_Pakya.lua | 13 | 2141 | -----------------------------------
-- Area: Giddeus
-- NPC: Ghoo Pakya
-- Involved in Mission 1-3
-- @pos -139 0 147 145
-----------------------------------
package.loaded["scripts/zones/Giddeus/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/globals/keyitems");
require("scripts/zones/Giddeus/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(WINDURST) == THE_PRICE_OF_PEACE) then
if (player:hasKeyItem(DRINK_OFFERINGS)) then
-- We have the offerings
player:startEvent(0x0031);
else
if (player:getVar("ghoo_talk") == 1) then
-- npc: You want your offering back?
player:startEvent(0x0032);
elseif (player:getVar("ghoo_talk") == 2) then
-- npc: You'll have to crawl back to treasure chamber, etc
player:startEvent(0x0033);
else
-- We don't have the offerings yet or anymore
player:startEvent(0x0034);
end
end
else
player:startEvent(0x0034);
end
end
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0031) then
player:delKeyItem(DRINK_OFFERINGS);
player:setVar("ghoo_talk",1);
if (player:hasKeyItem(FOOD_OFFERINGS) == false) then
player:setVar("MissionStatus",2);
end
elseif (csid == 0x0032) then
player:setVar("ghoo_talk",2);
end
end; | gpl-3.0 |
rpetit3/darkstar | scripts/zones/Horlais_Peak/npcs/relic.lua | 13 | 1842 | -----------------------------------
-- Area: Horlais Peak
-- NPC: <this space intentionally left blank>
-- @pos 450 -40 -31 139
-----------------------------------
package.loaded["scripts/zones/Horlais_Peak/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Horlais_Peak/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece
if (player:getVar("RELIC_IN_PROGRESS") == 18317 and trade:getItemCount() == 4 and trade:hasItemQty(18317,1) and
trade:hasItemQty(1580,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1454,1)) then
player:startEvent(13,18318);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 13) then
if (player:getFreeSlotsCount() < 2) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18318);
player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1453);
else
player:tradeComplete();
player:addItem(18318);
player:addItem(1453,30);
player:messageSpecial(ITEM_OBTAINED,18318);
player:messageSpecial(ITEMS_OBTAINED,1453,30);
player:setVar("RELIC_IN_PROGRESS",0);
end
end
end; | gpl-3.0 |
opentechinstitute/luci-commotion-linux | libs/lucid-rpc/luasrc/lucid/rpc/server.lua | 52 | 8197 | --[[
LuCI - Lua Development Framework
Copyright 2009 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]
local ipairs, pairs = ipairs, pairs
local tostring, tonumber = tostring, tonumber
local pcall, assert, type, unpack = pcall, assert, type, unpack
local nixio = require "nixio"
local json = require "luci.json"
local util = require "luci.util"
local table = require "table"
local ltn12 = require "luci.ltn12"
--- RPC daemom.
-- @cstyle instance
module "luci.lucid.rpc.server"
RQLIMIT = 32 * nixio.const.buffersize
VERSION = "1.0"
ERRNO_PARSE = -32700
ERRNO_INVALID = -32600
ERRNO_UNKNOWN = -32001
ERRNO_TIMEOUT = -32000
ERRNO_NOTFOUND = -32601
ERRNO_NOACCESS = -32002
ERRNO_INTERNAL = -32603
ERRNO_NOSUPPORT = -32003
ERRMSG = {
[ERRNO_PARSE] = "Parse error.",
[ERRNO_INVALID] = "Invalid request.",
[ERRNO_TIMEOUT] = "Connection timeout.",
[ERRNO_UNKNOWN] = "Unknown error.",
[ERRNO_NOTFOUND] = "Method not found.",
[ERRNO_NOACCESS] = "Access denied.",
[ERRNO_INTERNAL] = "Internal error.",
[ERRNO_NOSUPPORT] = "Operation not supported."
}
--- Create an RPC method wrapper.
-- @class function
-- @param method Lua function
-- @param description Method description
-- @return Wrapped RPC method
Method = util.class()
--- Create an extended wrapped RPC method.
-- @class function
-- @param method Lua function
-- @param description Method description
-- @return Wrapped RPC method
function Method.extended(...)
local m = Method(...)
m.call = m.xcall
return m
end
function Method.__init__(self, method, description)
self.description = description
self.method = method
end
--- Extended call the associated function.
-- @param session Session storage
-- @param argv Request parameters
-- @return function call response
function Method.xcall(self, session, argv)
return self.method(session, unpack(argv))
end
--- Standard call the associated function.
-- @param session Session storage
-- @param argv Request parameters
-- @return function call response
function Method.call(self, session, argv)
return self.method(unpack(argv))
end
--- Process a given request and create a JSON response.
-- @param session Session storage
-- @param request Requested method
-- @param argv Request parameters
function Method.process(self, session, request, argv)
local stat, result = pcall(self.call, self, session, argv)
if stat then
return { result=result }
else
return { error={
code=ERRNO_UNKNOWN,
message=ERRMSG[ERRNO_UNKNOWN],
data=result
} }
end
end
-- Remap IPv6-IPv4-compatibility addresses to IPv4 addresses
local function remapipv6(adr)
local map = "::ffff:"
if adr:sub(1, #map) == map then
return adr:sub(#map+1)
else
return adr
end
end
--- Create an RPC module.
-- @class function
-- @param description Method description
-- @return RPC module
Module = util.class()
function Module.__init__(self, description)
self.description = description
self.handler = {}
end
--- Add a handler.
-- @param k key
-- @param v handler
function Module.add(self, k, v)
self.handler[k] = v
end
--- Add an access restriction.
-- @param restriction Restriction specification
function Module.restrict(self, restriction)
if not self.restrictions then
self.restrictions = {restriction}
else
self.restrictions[#self.restrictions+1] = restriction
end
end
--- Enforce access restrictions.
-- @param request Request object
-- @return nil or HTTP statuscode, table of headers, response source
function Module.checkrestricted(self, session, request, argv)
if not self.restrictions then
return
end
for _, r in ipairs(self.restrictions) do
local stat = true
if stat and r.interface then -- Interface restriction
if not session.localif then
for _, v in ipairs(session.env.interfaces) do
if v.addr == session.localaddr then
session.localif = v.name
break
end
end
end
if r.interface ~= session.localif then
stat = false
end
end
if stat and r.user and session.user ~= r.user then -- User restriction
stat = false
end
if stat then
return
end
end
return {error={code=ERRNO_NOACCESS, message=ERRMSG[ERRNO_NOACCESS]}}
end
--- Register a handler, submodule or function.
-- @param m entity
-- @param descr description
-- @return Module (self)
function Module.register(self, m, descr)
descr = descr or {}
for k, v in pairs(m) do
if util.instanceof(v, Method) then
self.handler[k] = v
elseif type(v) == "table" then
self.handler[k] = Module()
self.handler[k]:register(v, descr[k])
elseif type(v) == "function" then
self.handler[k] = Method(v, descr[k])
end
end
return self
end
--- Process a request.
-- @param session Session storage
-- @param request Request object
-- @param argv Request parameters
-- @return JSON response object
function Module.process(self, session, request, argv)
local first, last = request:match("^([^.]+).?(.*)$")
local stat = self:checkrestricted(session, request, argv)
if stat then -- Access Denied
return stat
end
local hndl = first and self.handler[first]
if not hndl then
return {error={code=ERRNO_NOTFOUND, message=ERRMSG[ERRNO_NOTFOUND]}}
end
session.chain[#session.chain+1] = self
return hndl:process(session, last, argv)
end
--- Create a server object.
-- @class function
-- @param root Root module
-- @return Server object
Server = util.class()
function Server.__init__(self, root)
self.root = root
end
--- Get the associated root module.
-- @return Root module
function Server.get_root(self)
return self.root
end
--- Set a new root module.
-- @param root Root module
function Server.set_root(self, root)
self.root = root
end
--- Create a JSON reply.
-- @param jsonrpc JSON-RPC version
-- @param id Message id
-- @param res Result
-- @param err Error
-- @reutrn JSON response source
function Server.reply(self, jsonrpc, id, res, err)
id = id or json.null
-- 1.0 compatibility
if jsonrpc ~= "2.0" then
jsonrpc = nil
res = res or json.null
err = err or json.null
end
return json.Encoder(
{id=id, result=res, error=err, jsonrpc=jsonrpc}, BUFSIZE
):source()
end
--- Handle a new client connection.
-- @param client client socket
-- @param env superserver environment
function Server.process(self, client, env)
local decoder
local sinkout = client:sink()
client:setopt("socket", "sndtimeo", 90)
client:setopt("socket", "rcvtimeo", 90)
local close = false
local session = {server = self, chain = {}, client = client, env = env,
localaddr = remapipv6(client:getsockname())}
local req, stat, response, result, cb
repeat
local oldchunk = decoder and decoder.chunk
decoder = json.ActiveDecoder(client:blocksource(nil, RQLIMIT))
decoder.chunk = oldchunk
result, response, cb = nil, nil, nil
-- Read one request
stat, req = pcall(decoder.get, decoder)
if stat then
if type(req) == "table" and type(req.method) == "string"
and (not req.params or type(req.params) == "table") then
req.params = req.params or {}
result, cb = self.root:process(session, req.method, req.params)
if type(result) == "table" then
if req.id ~= nil then
response = self:reply(req.jsonrpc, req.id,
result.result, result.error)
end
close = result.close
else
if req.id ~= nil then
response = self:reply(req.jsonrpc, req.id, nil,
{code=ERRNO_INTERNAL, message=ERRMSG[ERRNO_INTERNAL]})
end
end
else
response = self:reply(req.jsonrpc, req.id,
nil, {code=ERRNO_INVALID, message=ERRMSG[ERRNO_INVALID]})
end
else
if nixio.errno() ~= nixio.const.EAGAIN then
response = self:reply("2.0", nil,
nil, {code=ERRNO_PARSE, message=ERRMSG[ERRNO_PARSE]})
--[[else
response = self:reply("2.0", nil,
nil, {code=ERRNO_TIMEOUT, message=ERRMSG_TIMEOUT})]]
end
close = true
end
if response then
ltn12.pump.all(response, sinkout)
end
if cb then
close = cb(client, session, self) or close
end
until close
client:shutdown()
client:close()
end
| apache-2.0 |
rpetit3/darkstar | scripts/zones/Port_Windurst/npcs/Puo_Rhen.lua | 13 | 1052 | -----------------------------------
-- Area: Port Windurst
-- NPC: Puo Rhen
-- Type: Mission Starter
-- @zone: 240
-- @pos -227.964 -9 187.087
--
-- Auto-Script: Requires Verification (Verfied By Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0048);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
rpetit3/darkstar | scripts/globals/items/windurst_taco.lua | 18 | 1552 | -----------------------------------------
-- ID: 5172
-- Item: windurst_taco
-- Food Effect: 30Min, All Races
-----------------------------------------
-- MP 20
-- Vitality -1
-- Agility 5
-- MP Recovered While Healing 1
-- Ranged Accuracy % 8 (cap 10)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5172);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 20);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_AGI, 5);
target:addMod(MOD_MPHEAL, 1);
target:addMod(MOD_FOOD_RACCP, 8);
target:addMod(MOD_FOOD_RACC_CAP, 10);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 20);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_AGI, 5);
target:delMod(MOD_MPHEAL, 1);
target:delMod(MOD_FOOD_RACCP, 8);
target:delMod(MOD_FOOD_RACC_CAP, 10);
end;
| gpl-3.0 |
SnakeSVx/sbep | lua/entities/livable_module/init.lua | 2 | 22756 |
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
util.PrecacheSound( "apc_engine_start" )
util.PrecacheSound( "apc_engine_stop" )
util.PrecacheSound( "common/warning.wav" )
include('shared.lua')
function ENT:Initialize()
self.BaseClass.Initialize(self)
self.Active = 0
self.damaged = 0
self:CreateEnvironment(1, 1, 1, 0, 0, 0, 0, 0)
self.currentsize = self:BoundingRadius()
self.maxsize = self:BoundingRadius()
self.maxO2Level = 100
if not (WireAddon == nil) then
self.WireDebugName = self.PrintName
self.Inputs = Wire_CreateInputs(self, { "On", "Gravity", "Max O2 level" })
self.Outputs = Wire_CreateOutputs(self, { "On", "Oxygen-Level", "Temperature", "Gravity", "Damaged" })
else
self.Inputs = { { Name = "On" }, { Name = "Radius" }, { Name = "Gravity" }, { Name = "Max O2 level" } }
end
CAF.GetAddon("Resource Distribution").RegisterNonStorageDevice(self)
end
function ENT:TurnOn()
if (self.Active == 0) then
self:EmitSound( "apc_engine_start" )
self.Active = 1
self:UpdateSize(self.sbenvironment.size, self.currentsize) --We turn the forcefield that contains the environment on
if self.environment and not self.environment:IsSpace() then --Fill the environment with air if the surounding environment has o2, replace with CO2
self.sbenvironment.air.o2 = self.sbenvironment.air.o2 + self.environment:Convert(0, -1, math.Round(self.sbenvironment.air.max/18))
end
if not (WireAddon == nil) then Wire_TriggerOutput(self, "On", self.Active) end
self:SetOOO(1)
end
end
function ENT:TurnOff()
if (self.Active == 1) then
self:StopSound( "apc_engine_start" )
self:EmitSound( "apc_engine_stop" )
self.Active = 0
if self.environment then --flush all resources into the environment if we are in one (used for the slownes of the SB updating process, we don't want errors do we?)
if self.sbenvironment.air.o2 > 0 then
local left = self:SupplyResource("oxygen", self.sbenvironment.air.o2)
self.environment:Convert(-1, 0, left)
end
if self.sbenvironment.air.co2 > 0 then
local left = self:SupplyResource("carbon dioxide", self.sbenvironment.air.co2)
self.environment:Convert(-1, 1, left)
end
if self.sbenvironment.air.n > 0 then
local left = self:SupplyResource("nitrogen", self.sbenvironment.air.n)
self.environment:Convert(-1, 2, left)
end
if self.sbenvironment.air.h > 0 then
local left = self:SupplyResource("hydrogen", self.sbenvironment.air.h)
self.environment:Convert(-1, 3, left)
end
end
self.sbenvironment.temperature = 0
self:UpdateSize(self.sbenvironment.size, 0) --We turn the forcefield that contains the environment off!
if not (WireAddon == nil) then Wire_TriggerOutput(self, "On", self.Active) end
self:SetOOO(0)
end
end
function ENT:TriggerInput(iname, value)
if (iname == "On") then
self:SetActive(value)
elseif (iname == "Gravity") then
local gravity = value
if value <= 0 then
gravity = 0
end
self.sbenvironment.gravity = gravity
elseif (iname == "Max O2 level") then
local level = 100
level = math.Clamp(math.Round(value), 0, 100)
self.maxO2Level = level
end
end
function ENT:Damage()
if (self.damaged == 0) then
self.damaged = 1
end
if ((self.Active == 1) and (math.random(1, 10) <= 3)) then
self:TurnOff()
end
end
function ENT:Repair()
self.BaseClass.Repair(self)
self:SetColor(255, 255, 255, 255)
self.damaged = 0
end
function ENT:Destruct()
CAF.GetAddon("Spacebuild").RemoveEnvironment(self)
CAF.GetAddon("Life Support").LS_Destruct(self, true)
end
function ENT:OnRemove()
CAF.GetAddon("Spacebuild").RemoveEnvironment(self)
self.BaseClass.OnRemove(self)
self:StopSound("apc_engine_start")
end
function ENT:PreEntityCopy()
local LivableModule = {}
LivableModule.Active = self.Active
LivableModule.damaged = self.damaged
if WireAddon then
duplicator.StoreEntityModifier(self,"WireDupeInfo",WireLib.BuildDupeInfo(self.Entity))
end
duplicator.StoreEntityModifier(self, "livable_module", LivableModule)
end
function ENT:PostEntityPaste(ply, ent, createdEnts)
if WireAddon then
local emods = ent.EntityMods
if emods and emods.WireDupeInfo then
WireLib.ApplyDupeInfo(ply, ent, emods.WireDupeInfo, function(id) return createdEnts[id] end)
end
end
end
function MakeLivableModule( Player, Data )
local ent = ents.Create( Data.Class )
duplicator.DoGeneric( ent, Data )
ent:Spawn()
duplicator.DoGenericPhysics( ent, Player, Data )
ent:SetPlayer(Player)
ent.damaged = Data.EntityMods.livable_module.damaged
if CPPI then ent:CPPISetOwner(Player) end
if Data.EntityMods.livable_module.Active == 1 then
ent:TurnOn()
end
return ent
end
duplicator.RegisterEntityClass( "livable_module", MakeLivableModule, "Data" )
--[[
function ENT:CreateEnvironment(gravity, atmosphere, pressure, temperature, o2, co2, n, h)
--Msg("CreateEnvironment: "..tostring(gravity).."\n")
--set Gravity if one is given
if gravity and type(gravity) == "number" then
if gravity < 0 then
gravity = 0
end
self.sbenvironment.gravity = gravity
end
--set atmosphere if given
if atmosphere and type(atmosphere) == "number" then
if atmosphere < 0 then
atmosphere = 0
elseif atmosphere > 1 then
atmosphere = 1
end
self.sbenvironment.atmosphere = atmosphere
end
--set pressure if given
if pressure and type(pressure) == "number" and pressure >= 0 then
self.sbenvironment.pressure = pressure
else
self.sbenvironment.pressure = math.Round(self.sbenvironment.atmosphere * self.sbenvironment.gravity)
end
--set temperature if given
if temperature and type(temperature) == "number" then
self.sbenvironment.temperature = temperature
end
--set o2 if given
if o2 and type(o2) == "number" and o2 > 0 then
if o2 > 100 then o2 = 100 end
self.sbenvironment.air.o2per = o2
self.sbenvironment.air.o2 = math.Round(o2 * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere)
else
o2 = 0
self.sbenvironment.air.o2per = 0
self.sbenvironment.air.o2 = 0
end
--set co2 if given
if co2 and type(co2) == "number" and co2 > 0 then
if (100 - o2) < co2 then co2 = 100-o2 end
self.sbenvironment.air.co2per = co2
self.sbenvironment.air.co2 = 0
else
co2 = 0
self.sbenvironment.air.co2per = 0
self.sbenvironment.air.co2 = 0
end
--set n if given
if n and type(n) == "number" and n > 0 then
if ((100 - o2)-co2) < n then n = (100-o2)-co2 end
self.sbenvironment.air.nper = n
self.sbenvironment.air.n = 0
else
n = 0
self.sbenvironment.air.n = 0
self.sbenvironment.air.n = 0
end
--set h if given
if h and type(h) == "number" then
if (((100 - o2)-co2)-n) < h then h = ((100-o2)-co2)-n end
self.sbenvironment.air.hper = h
self.sbenvironment.air.h = math.Round(h * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere)
else
h = 0
self.sbenvironment.air.h = 0
self.sbenvironment.air.h = 0
end
if o2 + co2 + n + h < 100 then
local tmp = 100 - (o2 + co2 + n + h)
self.sbenvironment.air.empty = math.Round(tmp * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere)
self.sbenvironment.air.emptyper = tmp
elseif o2 + co2 + n + h > 100 then
local tmp = (o2 + co2 + n + h) - 100
if co2 > tmp then
self.sbenvironment.air.co2 = math.Round((co2 - tmp) * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere)
self.sbenvironment.air.co2per = co2 + tmp
elseif n > tmp then
self.sbenvironment.air.n = math.Round((n - tmp) * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere)
self.sbenvironment.air.nper = n + tmp
elseif h > tmp then
self.sbenvironment.air.h = math.Round((h - tmp) * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere)
self.sbenvironment.air.hper = h + tmp
elseif o2 > tmp then
self.sbenvironment.air.o2 = math.Round((o2 - tmp) * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere)
self.sbenvironment.air.o2per = o2 - tmp
end
end
self.sbenvironment.air.max = math.Round(100 * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere)
self:PrintVars()
end
-- ]]
--[[
function ENT:UpdateSize(oldsize, newsize)
if oldsize == newsize then return end
if oldsize and newsize and type(oldsize) == "number" and type(newsize) == "number" and oldsize >= 0 and newsize >= 0 then
if oldsize == 0 then
self.sbenvironment.air.o2 = 0
self.sbenvironment.air.co2 = 0
self.sbenvironment.air.n = 0
self.sbenvironment.air.h = 0
self.sbenvironment.air.empty = 0
self.sbenvironment.size = newsize
elseif newsize == 0 then
local tomuch = self.sbenvironment.air.o2
if self.environment then
tomuch = self.environment:Convert(-1, 0, tomuch)
end
tomuch = self.sbenvironment.air.co2
if self.environment then
tomuch = self.environment:Convert(-1, 1, tomuch)
end
tomuch = self.sbenvironment.air.n
if self.environment then
tomuch = self.environment:Convert(-1, 2, tomuch)
end
tomuch = self.sbenvironment.air.h
if self.environment then
tomuch = self.environment:Convert(-1, 3, tomuch)
end
self.sbenvironment.air.o2 = 0
self.sbenvironment.air.co2 = 0
self.sbenvironment.air.n = 0
self.sbenvironment.air.h = 0
self.sbenvironment.air.empty = 0
self.sbenvironment.size = 0
else
self.sbenvironment.air.o2 = (newsize/oldsize) * self.sbenvironment.air.o2
self.sbenvironment.air.co2 = (newsize/oldsize) * self.sbenvironment.air.co2
self.sbenvironment.air.n = (newsize/oldsize) * self.sbenvironment.air.n
self.sbenvironment.air.h = (newsize/oldsize) * self.sbenvironment.air.h
self.sbenvironment.air.empty = (newsize/oldsize) * self.sbenvironment.air.empty
self.sbenvironment.size = newsize
end
self.sbenvironment.air.max = math.Round(100 * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere)
if self.sbenvironment.air.o2 > self.sbenvironment.air.max then
local tomuch = self.sbenvironment.air.o2 - self.sbenvironment.air.max
if self.environment then
tomuch = self.environment:Convert(-1, 0, tomuch)
self.sbenvironment.air.o2 = self.sbenvironment.air.max + tomuch
end
end
if self.sbenvironment.air.co2 > self.sbenvironment.air.max then
local tomuch = self.sbenvironment.air.co2 - self.sbenvironment.air.max
if self.environment then
tomuch = self.environment:Convert(-1, 1, tomuch)
self.sbenvironment.air.co2 = self.sbenvironment.air.max + tomuch
end
end
if self.sbenvironment.air.n > self.sbenvironment.air.max then
local tomuch = self.sbenvironment.air.n - self.sbenvironment.air.max
if self.environment then
tomuch = self.environment:Convert(-1, 2, tomuch)
self.sbenvironment.air.n = self.sbenvironment.air.max + tomuch
end
end
if self.sbenvironment.air.h > self.sbenvironment.air.max then
local tomuch = self.sbenvironment.air.h - self.sbenvironment.air.max
if self.environment then
tomuch = self.environment:Convert(-1, 3, tomuch)
self.sbenvironment.air.h = self.sbenvironment.air.max + tomuch
end
end
end
end
--]]
function ENT:Climate_Control()
local temperature = 0
local pressure = 0
if self.environment then
temperature = self.environment:GetTemperature(self)
pressure = self.environment:GetPressure()
--Msg("Found environment, updating\n")
end
--Msg("Temperature: "..tostring(temperature)..", pressure: " ..tostring(pressure).."\n")
if self.Active == 1 then --Only do something if the device is on
self.energy = self:GetResourceAmount("energy")
if self.energy == 0 or self.energy < 3 * math.ceil(self.maxsize/1024) then --Don't have enough power to keep the controler\'s think process running, shut it all down
self:TurnOff()
return
--Msg("Turning of\n")
else
self.air = self:GetResourceAmount("oxygen")
self.coolant = self:GetResourceAmount("water")
self.coolant2 = self:GetResourceAmount("nitrogen")
self.energy = self:GetResourceAmount("energy")
--First let check our air supply and try to stabilize it if we got oxygen left in storage at a rate of 10 oxygen per second
if self.sbenvironment.air.o2 < self.sbenvironment.air.max * (self.maxO2Level/100) then
--We need some energy to fire the pump!
local energyneeded = 5 * math.ceil(self.maxsize/1024)
local mul = 1
if self.energy < energyneeded then
mul = self.energy/energyneeded
self:ConsumeResource("energy", self.energy)
else
self:ConsumeResource("energy", energyneeded)
end
local air = math.ceil(1500 * mul)
if self.air < air then air = self.air end
if self.sbenvironment.air.co2 > 0 then
local actual = self:Convert(1, 0, air)
self:ConsumeResource("oxygen", actual)
self:SupplyResource("carbon dioxide", actual)
elseif self.sbenvironment.air.n > 0 then
local actual = self:Convert(2, 0, air)
self:ConsumeResource("oxygen", actual)
self:SupplyResource("nitrogen", actual)
elseif self.sbenvironment.air.h > 0 then
local actual = self:Convert(3, 0, air)
self:ConsumeResource("oxygen", actual)
self:SupplyResource("hydrogen", actual)
else
self:ConsumeResource("oxygen", air)
self.sbenvironment.air.o2 = self.sbenvironment.air.o2 + air
end
elseif self.sbenvironment.air.o2 > self.sbenvironment.air.max then
local tmp = self.sbenvironment.air.o2 - self.sbenvironment.air.max
self:SupplyResource("oxygen", tmp)
end
--Now let's check the pressure, if pressure is larger then 1 then we need some more power to keep the climate_controls environment stable. We don\' want any leaks do we?
if pressure > 1 then
self:ConsumeResource("energy", (pressure-1) * 2 * math.ceil(self.maxsize/1024))
end
if temperature < self.sbenvironment.temperature then
local dif = self.sbenvironment.temperature - temperature
dif = math.ceil(dif/100) --Change temperature depending on the outside temperature, 5ยฐ difference does a lot less then 10000ยฐ difference
self.sbenvironment.temperature = self.sbenvironment.temperature - dif
elseif temperature > self.sbenvironment.temperature then
local dif = temperature - self.sbenvironment.temperature
dif = math.ceil(dif / 100)
self.sbenvironment.temperature = self.sbenvironment.temperature + dif
end
--Msg("Temperature: "..tostring(self.sbenvironment.temperature).."\n")
if self.sbenvironment.temperature < 288 then
--Msg("Heating up?\n")
if self.sbenvironment.temperature + 60 <= 303 then
self:ConsumeResource("energy", 24 * math.ceil(self.maxsize/1024))
self.energy = self:GetResourceAmount("energy")
if self.energy > 60 * math.ceil(self.maxsize/1024) then
--Msg("Enough energy\n")
self.sbenvironment.temperature = self.sbenvironment.temperature + 60
self:ConsumeResource("energy", 60 * math.ceil(self.maxsize/1024))
else
--Msg("not Enough energy\n")
self.sbenvironment.temperature = self.sbenvironment.temperature + math.ceil((self.energy/ 60 * math.ceil(self.maxsize/1024))*60)
self:ConsumeResource("energy", self.energy)
end
elseif self.sbenvironment.temperature + 30 <= 303 then
self:ConsumeResource("energy", 12 * math.ceil(self.maxsize/1024))
self.energy = self:GetResourceAmount("energy")
if self.energy > 30 * math.ceil(self.maxsize/1024) then
--Msg("Enough energy\n")
self.sbenvironment.temperature = self.sbenvironment.temperature + 30
self:ConsumeResource("energy", 30 * math.ceil(self.maxsize/1024))
else
--Msg("not Enough energy\n")
self.sbenvironment.temperature = self.sbenvironment.temperature + math.ceil((self.energy/ 30 * math.ceil(self.maxsize/1024))*30)
self:ConsumeResource("energy", self.energy)
end
elseif self.sbenvironment.temperature + 15 <= 303 then
self:ConsumeResource("energy", 6 * math.ceil(self.maxsize/1024))
self.energy = self:GetResourceAmount("energy")
if self.energy > 15 * math.ceil(self.maxsize/1024) then
--Msg("Enough energy\n")
self.sbenvironment.temperature = self.sbenvironment.temperature + 15
self:ConsumeResource("energy", 15 * math.ceil(self.maxsize/1024))
else
--Msg("not Enough energy\n")
self.sbenvironment.temperature = self.sbenvironment.temperature + math.ceil((self.energy/ 15 * math.ceil(self.maxsize/1024))*15)
self:ConsumeResource("energy", self.energy)
end
else
self:ConsumeResource("energy", 2 * math.ceil(self.maxsize/1024))
self.energy = self:GetResourceAmount("energy")
if self.energy > 5 * math.ceil(self.maxsize/1024) then
--Msg("Enough energy\n")
self.sbenvironment.temperature = self.sbenvironment.temperature + 5
self:ConsumeResource("energy", 5 * math.ceil(self.maxsize/1024))
else
--Msg("not Enough energy\n")
self.sbenvironment.temperature = self.sbenvironment.temperature + math.ceil((self.energy/ 5 * math.ceil(self.maxsize/1024))*5)
self:ConsumeResource("energy", self.energy)
end
end
elseif self.sbenvironment.temperature > 303 then
if self.sbenvironment.temperature - 60 >= 288 then
self:ConsumeResource("energy", 24 * math.ceil(self.maxsize/1024))
if self.coolant2 > 12 * math.ceil(self.maxsize/1024) then
self.sbenvironment.temperature = self.sbenvironment.temperature - 60
self:ConsumeResource("nitrogen", 12 * math.ceil(self.maxsize/1024))
elseif self.coolant > 60 * math.ceil(self.maxsize/1024) then
self.sbenvironment.temperature = self.sbenvironment.temperature - 60
self:ConsumeResource("water", 60 * math.ceil(self.maxsize/1024))
else
if self.coolant2 > 0 then
self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant2/ 12 * math.ceil(self.maxsize/1024))*60)
self:ConsumeResource("nitrogen", self.coolant2)
elseif self.coolant > 0 then
self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant/ 60 * math.ceil(self.maxsize/1024))*60)
self:ConsumeResource("water", self.coolant)
end
end
elseif self.sbenvironment.temperature - 30 >= 288 then
self:ConsumeResource("energy", 12 * math.ceil(self.maxsize/1024))
if self.coolant2 > 6 * math.ceil(self.maxsize/1024) then
self.sbenvironment.temperature = self.sbenvironment.temperature - 30
self:ConsumeResource("nitrogen", 6 * math.ceil(self.maxsize/1024))
elseif self.coolant > 30 * math.ceil(self.maxsize/1024) then
self.sbenvironment.temperature = self.sbenvironment.temperature - 30
self:ConsumeResource("water", 30 * math.ceil(self.maxsize/1024))
else
if self.coolant2 > 0 then
self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant2/ 6 * math.ceil(self.maxsize/1024))*30)
self:ConsumeResource("nitrogen", self.coolant2)
elseif self.coolant > 0 then
self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant/ 30 * math.ceil(self.maxsize/1024))*30)
self:ConsumeResource("water", self.coolant)
end
end
elseif self.sbenvironment.temperature - 15 >= 288 then
self:ConsumeResource("energy", 6 * math.ceil(self.maxsize/1024))
if self.coolant2 > 3 * math.ceil(self.maxsize/1024) then
self.sbenvironment.temperature = self.sbenvironment.temperature - 15
self:ConsumeResource("nitrogen", 3 * math.ceil(self.maxsize/1024))
elseif self.coolant > 15 * math.ceil(self.maxsize/1024) then
self.sbenvironment.temperature = self.sbenvironment.temperature - 15
self:ConsumeResource("water", 15 * math.ceil(self.maxsize/1024))
else
if self.coolant2 > 0 then
self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant2/ 3 * math.ceil(self.maxsize/1024))*15)
self:ConsumeResource("nitrogen", self.coolant2)
elseif self.coolant > 0 then
self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant/ 15 * math.ceil(self.maxsize/1024))*15)
self:ConsumeResource("water", self.coolant)
end
end
else
self:ConsumeResource("energy", 2 * math.ceil(self.maxsize/1024))
if self.coolant2 > 1 * math.ceil(self.maxsize/1024) then
self.sbenvironment.temperature = self.sbenvironment.temperature - 5
self:ConsumeResource("nitrogen", 1 * math.ceil(self.maxsize/1024))
elseif self.coolant > 5 * math.ceil(self.maxsize/1024) then
self.sbenvironment.temperature = self.sbenvironment.temperature - 5
self:ConsumeResource("water", 5 * math.ceil(self.maxsize/1024))
else
if self.coolant2 > 0 then
self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant2/ 1 * math.ceil(self.maxsize/1024))*5)
self:ConsumeResource("nitrogen", self.coolant2)
elseif self.coolant > 0 then
self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant/ 5 * math.ceil(self.maxsize/1024))*5)
self:ConsumeResource("water", self.coolant)
end
end
end
end
end
end
if not (WireAddon == nil) then
Wire_TriggerOutput(self, "Oxygen-Level", tonumber(self:GetO2Percentage()))
Wire_TriggerOutput(self, "Temperature", tonumber(self.sbenvironment.temperature))
Wire_TriggerOutput(self, "Gravity", tonumber(self.sbenvironment.gravity))
Wire_TriggerOutput(self, "Damaged", tonumber(self.damaged))
end
end
function ENT:Think()
self.BaseClass.Think(self)
self:Climate_Control()
self:NextThink(CurTime() + 1)
return true
end
--[[
function ENT:OnEnvironment(ent)
if not ent then return end
if ent == self then return end
local pos = ent:GetPos()
local dist = pos:Distance(self:GetPos())
if dist < self:GetSize() then
local min, max = ent:WorldSpaceAABB()
if table.HasValue(ents.FindInBox( min, max ), ent) then
if not ent.environment then
ent.environment = self
--self:UpdateGravity(ent)
else
if ent.environment:GetPriority() < self:GetPriority() then
ent.environment = self
--self:UpdateGravity(ent)
elseif ent.environment:GetPriority() == self:GetPriority() then
if ent.environment:GetSize() != 0 then
if self:GetSize() <= ent.environment:GetSize() then
ent.environment = self
--self:UpdateGravity(ent)
else
if dist < pos:Distance(ent.environment:GetPos()) then
ent.environment = self
end
end
else
ent.environment = self
--self:UpdateGravity(ent)
end
end
end
end
end
end
]]
| apache-2.0 |
tvandijck/premake-core | binmodules/luasocket/src/headers.lua | 133 | 3698 | -----------------------------------------------------------------------------
-- Canonic header field capitalization
-- LuaSocket toolkit.
-- Author: Diego Nehab
-----------------------------------------------------------------------------
local socket = require("socket")
socket.headers = {}
local _M = socket.headers
_M.canonic = {
["accept"] = "Accept",
["accept-charset"] = "Accept-Charset",
["accept-encoding"] = "Accept-Encoding",
["accept-language"] = "Accept-Language",
["accept-ranges"] = "Accept-Ranges",
["action"] = "Action",
["alternate-recipient"] = "Alternate-Recipient",
["age"] = "Age",
["allow"] = "Allow",
["arrival-date"] = "Arrival-Date",
["authorization"] = "Authorization",
["bcc"] = "Bcc",
["cache-control"] = "Cache-Control",
["cc"] = "Cc",
["comments"] = "Comments",
["connection"] = "Connection",
["content-description"] = "Content-Description",
["content-disposition"] = "Content-Disposition",
["content-encoding"] = "Content-Encoding",
["content-id"] = "Content-ID",
["content-language"] = "Content-Language",
["content-length"] = "Content-Length",
["content-location"] = "Content-Location",
["content-md5"] = "Content-MD5",
["content-range"] = "Content-Range",
["content-transfer-encoding"] = "Content-Transfer-Encoding",
["content-type"] = "Content-Type",
["cookie"] = "Cookie",
["date"] = "Date",
["diagnostic-code"] = "Diagnostic-Code",
["dsn-gateway"] = "DSN-Gateway",
["etag"] = "ETag",
["expect"] = "Expect",
["expires"] = "Expires",
["final-log-id"] = "Final-Log-ID",
["final-recipient"] = "Final-Recipient",
["from"] = "From",
["host"] = "Host",
["if-match"] = "If-Match",
["if-modified-since"] = "If-Modified-Since",
["if-none-match"] = "If-None-Match",
["if-range"] = "If-Range",
["if-unmodified-since"] = "If-Unmodified-Since",
["in-reply-to"] = "In-Reply-To",
["keywords"] = "Keywords",
["last-attempt-date"] = "Last-Attempt-Date",
["last-modified"] = "Last-Modified",
["location"] = "Location",
["max-forwards"] = "Max-Forwards",
["message-id"] = "Message-ID",
["mime-version"] = "MIME-Version",
["original-envelope-id"] = "Original-Envelope-ID",
["original-recipient"] = "Original-Recipient",
["pragma"] = "Pragma",
["proxy-authenticate"] = "Proxy-Authenticate",
["proxy-authorization"] = "Proxy-Authorization",
["range"] = "Range",
["received"] = "Received",
["received-from-mta"] = "Received-From-MTA",
["references"] = "References",
["referer"] = "Referer",
["remote-mta"] = "Remote-MTA",
["reply-to"] = "Reply-To",
["reporting-mta"] = "Reporting-MTA",
["resent-bcc"] = "Resent-Bcc",
["resent-cc"] = "Resent-Cc",
["resent-date"] = "Resent-Date",
["resent-from"] = "Resent-From",
["resent-message-id"] = "Resent-Message-ID",
["resent-reply-to"] = "Resent-Reply-To",
["resent-sender"] = "Resent-Sender",
["resent-to"] = "Resent-To",
["retry-after"] = "Retry-After",
["return-path"] = "Return-Path",
["sender"] = "Sender",
["server"] = "Server",
["smtp-remote-recipient"] = "SMTP-Remote-Recipient",
["status"] = "Status",
["subject"] = "Subject",
["te"] = "TE",
["to"] = "To",
["trailer"] = "Trailer",
["transfer-encoding"] = "Transfer-Encoding",
["upgrade"] = "Upgrade",
["user-agent"] = "User-Agent",
["vary"] = "Vary",
["via"] = "Via",
["warning"] = "Warning",
["will-retry-until"] = "Will-Retry-Until",
["www-authenticate"] = "WWW-Authenticate",
["x-mailer"] = "X-Mailer",
}
return _M | bsd-3-clause |
MinetestForFun/server-minetestforfun-creative | mods/mesecons/mesecons_pressureplates/init.lua | 10 | 3484 | local pp_box_off = {
type = "fixed",
fixed = { -7/16, -8/16, -7/16, 7/16, -7/16, 7/16 },
}
local pp_box_on = {
type = "fixed",
fixed = { -7/16, -8/16, -7/16, 7/16, -7.5/16, 7/16 },
}
pp_on_timer = function (pos, elapsed)
local node = minetest.get_node(pos)
local basename = minetest.registered_nodes[node.name].pressureplate_basename
-- This is a workaround for a strange bug that occurs when the server is started
-- For some reason the first time on_timer is called, the pos is wrong
if not basename then return end
local objs = minetest.get_objects_inside_radius(pos, 1)
local two_below = vector.add(pos, vector.new(0, -2, 0))
if objs[1] == nil and node.name == basename .. "_on" then
minetest.set_node(pos, {name = basename .. "_off"})
mesecon.receptor_off(pos, mesecon.rules.pplate)
elseif node.name == basename .. "_off" then
for k, obj in pairs(objs) do
local objpos = obj:getpos()
if objpos.y > pos.y-1 and objpos.y < pos.y then
minetest.set_node(pos, {name = basename .. "_on"})
mesecon.receptor_on(pos, mesecon.rules.pplate )
end
end
end
return true
end
-- Register a Pressure Plate
-- offstate: name of the pressure plate when inactive
-- onstate: name of the pressure plate when active
-- description: description displayed in the player's inventory
-- tiles_off: textures of the pressure plate when inactive
-- tiles_on: textures of the pressure plate when active
-- image: inventory and wield image of the pressure plate
-- recipe: crafting recipe of the pressure plate
function mesecon.register_pressure_plate(basename, description, textures_off, textures_on, image_w, image_i, recipe)
mesecon.register_node(basename, {
drawtype = "nodebox",
inventory_image = image_i,
wield_image = image_w,
paramtype = "light",
description = description,
pressureplate_basename = basename,
on_timer = pp_on_timer,
on_construct = function(pos)
minetest.get_node_timer(pos):start(mesecon.setting("pplate_interval", 0.1))
end,
},{
mesecons = {receptor = { state = mesecon.state.off, rules = mesecon.rules.pplate }},
node_box = pp_box_off,
selection_box = pp_box_off,
groups = {snappy = 2, oddly_breakable_by_hand = 3},
tiles = textures_off
},{
mesecons = {receptor = { state = mesecon.state.on, rules = mesecon.rules.pplate }},
node_box = pp_box_on,
selection_box = pp_box_on,
groups = {snappy = 2, oddly_breakable_by_hand = 3, not_in_creative_inventory = 1},
tiles = textures_on
})
minetest.register_craft({
output = basename .. "_off",
recipe = recipe,
})
end
mesecon.register_pressure_plate(
"mesecons_pressureplates:pressure_plate_wood",
"Wooden Pressure Plate",
{"jeija_pressure_plate_wood_off.png","jeija_pressure_plate_wood_off.png","jeija_pressure_plate_wood_off_edges.png"},
{"jeija_pressure_plate_wood_on.png","jeija_pressure_plate_wood_on.png","jeija_pressure_plate_wood_on_edges.png"},
"jeija_pressure_plate_wood_wield.png",
"jeija_pressure_plate_wood_inv.png",
{{"group:wood", "group:wood"}})
mesecon.register_pressure_plate(
"mesecons_pressureplates:pressure_plate_stone",
"Stone Pressure Plate",
{"jeija_pressure_plate_stone_off.png","jeija_pressure_plate_stone_off.png","jeija_pressure_plate_stone_off_edges.png"},
{"jeija_pressure_plate_stone_on.png","jeija_pressure_plate_stone_on.png","jeija_pressure_plate_stone_on_edges.png"},
"jeija_pressure_plate_stone_wield.png",
"jeija_pressure_plate_stone_inv.png",
{{"default:cobble", "default:cobble"}})
| unlicense |
lexa/awesome | lib/wibox/layout/align.lua | 2 | 9861 | ---------------------------------------------------------------------------
-- @author Uli Schlachter
-- @copyright 2010 Uli Schlachter
-- @release @AWESOME_VERSION@
-- @classmod wibox.layout.align
---------------------------------------------------------------------------
local setmetatable = setmetatable
local table = table
local pairs = pairs
local type = type
local floor = math.floor
local base = require("wibox.layout.base")
local widget_base = require("wibox.widget.base")
local align = {}
--- Draw an align layout.
-- @param wibox The wibox that this widget is drawn to.
-- @param cr The cairo context to use.
-- @param width The available width.
-- @param height The available height.
function align:draw(wibox, cr, width, height)
-- Draw will have to deal with all three align modes and should work in a
-- way that makes sense if one or two of the widgets are missing (if they
-- are all missing, it won't draw anything.) It should also handle the case
-- where the fit something that isn't set to expand (for instance the
-- outside widgets when the expand mode is "inside" or any of the widgets
-- when the expand mode is "none" wants to take up more space than is
-- allowed.
local size_first = 0
-- start with all the space given by the parent, subtract as we go along
local size_remains = self.dir == "y" and height or width
-- we will prioritize the middle widget unless the expand mode is "inside"
-- if it is, we prioritize the first widget by not doing this block also,
-- if the second widget doesn't exist, we will prioritise the first one
-- instead
if self._expand ~= "inside" and self.second then
local w, h = base.fit_widget(self.second, width, height)
local size_second = self.dir == "y" and h or w
-- if all the space is taken, skip the rest, and draw just the middle
-- widget
if size_second >= size_remains then
base.draw_widget(wibox, cr, self.second, 0, 0, width, height)
return
else
-- the middle widget is sized first, the outside widgets are given
-- the remaining space if available we will draw later
size_remains = floor((size_remains - size_second) / 2)
end
end
if self.first then
local w, h, _ = width, height, nil
-- we use the fit function for the "inside" and "none" modes, but
-- ignore it for the "outside" mode, which will force it to expand
-- into the remaining space
if self._expand ~= "outside" then
if self.dir == "y" then
_, h = base.fit_widget(self.first, width, size_remains)
size_first = h
-- for "inside", the third widget will get a chance to use the
-- remaining space, then the middle widget. For "none" we give
-- the third widget the remaining space if there was no second
-- widget to take up any space (as the first if block is skipped
-- if this is the case)
if self._expand == "inside" or not self.second then
size_remains = size_remains - h
end
else
w, _ = base.fit_widget(self.first, size_remains, height)
size_first = w
if self._expand == "inside" or not self.second then
size_remains = size_remains - w
end
end
else
if self.dir == "y" then
h = size_remains
else
w = size_remains
end
end
base.draw_widget(wibox, cr, self.first, 0, 0, w, h)
end
-- size_remains will be <= 0 if first used all the space
if self.third and size_remains > 0 then
local w, h, _ = width, height, nil
if self._expand ~= "outside" then
if self.dir == "y" then
_, h = base.fit_widget(self.third, width, size_remains)
-- give the middle widget the rest of the space for "inside" mode
if self._expand == "inside" then
size_remains = size_remains - h
end
else
w, _ = base.fit_widget(self.third, size_remains, height)
if self._expand == "inside" then
size_remains = size_remains - w
end
end
else
if self.dir == "y" then
h = size_remains
else
w = size_remains
end
end
local x, y = width - w, height - h
base.draw_widget(wibox, cr, self.third, x, y, w, h)
end
-- here we either draw the second widget in the space set aside for it
-- in the beginning, or in the remaining space, if it is "inside"
if self.second and size_remains > 0 then
local x, y, w, h = 0, 0, width, height
if self._expand == "inside" then
if self.dir == "y" then
h = size_remains
x, y = 0, size_first
else
w = size_remains
x, y = size_first, 0
end
else
if self.dir == "y" then
_, h = base.fit_widget(self.second, width, size_remains)
y = floor( (height - h)/2 )
else
w, _ = base.fit_widget(self.second, width, size_remains)
x = floor( (width -w)/2 )
end
end
base.draw_widget(wibox, cr, self.second, x, y, w, h)
end
end
local function widget_changed(layout, old_w, new_w)
if old_w then
old_w:disconnect_signal("widget::updated", layout._emit_updated)
end
if new_w then
widget_base.check_widget(new_w)
new_w:weak_connect_signal("widget::updated", layout._emit_updated)
end
layout._emit_updated()
end
--- Set the layout's first widget. This is the widget that is at the left/top
function align:set_first(widget)
widget_changed(self, self.first, widget)
self.first = widget
end
--- Set the layout's second widget. This is the centered one.
function align:set_second(widget)
widget_changed(self, self.second, widget)
self.second = widget
end
--- Set the layout's third widget. This is the widget that is at the right/bottom
function align:set_third(widget)
widget_changed(self, self.third, widget)
self.third = widget
end
--- Fit the align layout into the given space. The align layout will
-- ask for the sum of the sizes of its sub-widgets in its direction
-- and the largest sized sub widget in the other direction.
-- @param orig_width The available width.
-- @param orig_height The available height.
function align:fit(orig_width, orig_height)
local used_in_dir = 0
local used_in_other = 0
for k, v in pairs{self.first, self.second, self.third} do
local w, h = base.fit_widget(v, orig_width, orig_height)
local max = self.dir == "y" and w or h
if max > used_in_other then
used_in_other = max
end
used_in_dir = used_in_dir + (self.dir == "y" and h or w)
end
if self.dir == "y" then
return used_in_other, used_in_dir
end
return used_in_dir, used_in_other
end
--- Set the expand mode which determines how sub widgets expand to take up
-- unused space. Options are:
-- "inside" - Default option. Size of outside widgets is determined using their
-- fit function. Second, middle, or center widget expands to fill
-- remaining space.
-- "outside" - Center widget is sized using its fit function and placed in the
-- center of the allowed space. Outside widgets expand (or contract)
-- to fill remaining space on their side.
-- "none" - All widgets are sized using their fit function, drawn to only the
-- returned space, or remaining space, whichever is smaller. Center
-- widget gets priority.
-- @param mode How to use unused space. "inside" (default) "outside" or "none"
function align:set_expand(mode)
if mode == "none" or mode == "outside" then
self._expand = mode
else
self._expand = "inside"
end
self:emit_signal("widget::updated")
end
function align:reset()
for k, v in pairs({ "first", "second", "third" }) do
self[v] = nil
end
self:emit_signal("widget::updated")
end
local function get_layout(dir)
local ret = widget_base.make_widget()
ret.dir = dir
ret._emit_updated = function()
ret:emit_signal("widget::updated")
end
for k, v in pairs(align) do
if type(v) == "function" then
ret[k] = v
end
end
ret:set_expand("inside")
return ret
end
--- Returns a new horizontal align layout. An align layout can display up to
-- three widgets. The widget set via :set_left() is left-aligned. :set_right()
-- sets a widget which will be right-aligned. The remaining space between those
-- two will be given to the widget set via :set_middle().
function align.horizontal()
local ret = get_layout("x")
ret.set_left = ret.set_first
ret.set_middle = ret.set_second
ret.set_right = ret.set_third
return ret
end
--- Returns a new vertical align layout. An align layout can display up to
-- three widgets. The widget set via :set_top() is top-aligned. :set_bottom()
-- sets a widget which will be bottom-aligned. The remaining space between those
-- two will be given to the widget set via :set_middle().
function align.vertical()
local ret = get_layout("y")
ret.set_top = ret.set_first
ret.set_middle = ret.set_second
ret.set_bottom = ret.set_third
return ret
end
return align
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
hhli/redis | deps/lua/test/sort.lua | 889 | 1494 | -- two implementations of a sort function
-- this is an example only. Lua has now a built-in function "sort"
-- extracted from Programming Pearls, page 110
function qsort(x,l,u,f)
if l<u then
local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
x[l],x[m]=x[m],x[l] -- swap pivot to first position
local t=x[l] -- pivot value
m=l
local i=l+1
while i<=u do
-- invariant: x[l+1..m] < t <= x[m+1..i-1]
if f(x[i],t) then
m=m+1
x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
end
i=i+1
end
x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
-- x[l+1..m-1] < x[m] <= x[m+1..u]
qsort(x,l,m-1,f)
qsort(x,m+1,u,f)
end
end
function selectionsort(x,n,f)
local i=1
while i<=n do
local m,j=i,i+1
while j<=n do
if f(x[j],x[m]) then m=j end
j=j+1
end
x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
i=i+1
end
end
function show(m,x)
io.write(m,"\n\t")
local i=1
while x[i] do
io.write(x[i])
i=i+1
if x[i] then io.write(",") end
end
io.write("\n")
end
function testsorts(x)
local n=1
while x[n] do n=n+1 end; n=n-1 -- count elements
show("original",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort",x)
selectionsort(x,n,function (x,y) return x>y end)
show("after reverse selection sort",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort again",x)
end
-- array to be sorted
x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}
testsorts(x)
| bsd-3-clause |
tidatida/annotated_redis_source | deps/lua/test/sort.lua | 889 | 1494 | -- two implementations of a sort function
-- this is an example only. Lua has now a built-in function "sort"
-- extracted from Programming Pearls, page 110
function qsort(x,l,u,f)
if l<u then
local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
x[l],x[m]=x[m],x[l] -- swap pivot to first position
local t=x[l] -- pivot value
m=l
local i=l+1
while i<=u do
-- invariant: x[l+1..m] < t <= x[m+1..i-1]
if f(x[i],t) then
m=m+1
x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
end
i=i+1
end
x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
-- x[l+1..m-1] < x[m] <= x[m+1..u]
qsort(x,l,m-1,f)
qsort(x,m+1,u,f)
end
end
function selectionsort(x,n,f)
local i=1
while i<=n do
local m,j=i,i+1
while j<=n do
if f(x[j],x[m]) then m=j end
j=j+1
end
x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
i=i+1
end
end
function show(m,x)
io.write(m,"\n\t")
local i=1
while x[i] do
io.write(x[i])
i=i+1
if x[i] then io.write(",") end
end
io.write("\n")
end
function testsorts(x)
local n=1
while x[n] do n=n+1 end; n=n-1 -- count elements
show("original",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort",x)
selectionsort(x,n,function (x,y) return x>y end)
show("after reverse selection sort",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort again",x)
end
-- array to be sorted
x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}
testsorts(x)
| bsd-3-clause |
soloestoy/redis | deps/lua/test/sort.lua | 889 | 1494 | -- two implementations of a sort function
-- this is an example only. Lua has now a built-in function "sort"
-- extracted from Programming Pearls, page 110
function qsort(x,l,u,f)
if l<u then
local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
x[l],x[m]=x[m],x[l] -- swap pivot to first position
local t=x[l] -- pivot value
m=l
local i=l+1
while i<=u do
-- invariant: x[l+1..m] < t <= x[m+1..i-1]
if f(x[i],t) then
m=m+1
x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
end
i=i+1
end
x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
-- x[l+1..m-1] < x[m] <= x[m+1..u]
qsort(x,l,m-1,f)
qsort(x,m+1,u,f)
end
end
function selectionsort(x,n,f)
local i=1
while i<=n do
local m,j=i,i+1
while j<=n do
if f(x[j],x[m]) then m=j end
j=j+1
end
x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
i=i+1
end
end
function show(m,x)
io.write(m,"\n\t")
local i=1
while x[i] do
io.write(x[i])
i=i+1
if x[i] then io.write(",") end
end
io.write("\n")
end
function testsorts(x)
local n=1
while x[n] do n=n+1 end; n=n-1 -- count elements
show("original",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort",x)
selectionsort(x,n,function (x,y) return x>y end)
show("after reverse selection sort",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort again",x)
end
-- array to be sorted
x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}
testsorts(x)
| bsd-3-clause |
TakingInitiative/wesnoth | data/lua/helper.lua | 2 | 13217 | --! #textdomain wesnoth
local helper = {}
local wml_actions = wesnoth.wml_actions
--! Returns an iterator over all the sides matching a given filter that can be used in a for-in loop.
function helper.get_sides(cfg)
local function f(s)
local i = s.i
while i < #wesnoth.sides do
i = i + 1
if wesnoth.match_side(i, cfg) then
s.i = i
return wesnoth.sides[i], i
end
end
end
return f, { i = 0 }
end
--! Interrupts the current execution and displays a chat message that looks like a WML error.
function helper.wml_error(m)
error("~wml:" .. m, 0)
end
--! Returns an iterator over teams that can be used in a for-in loop.
function helper.all_teams()
local function f(s)
local i = s.i
local team = wesnoth.sides[i]
s.i = i + 1
return team
end
return f, { i = 1 }
end
--! Returns the first subtag of @a cfg with the given @a name.
--! If @a id is not nil, the "id" attribute of the subtag has to match too.
--! The function also returns the index of the subtag in the array.
function helper.get_child(cfg, name, id)
for i,v in ipairs(cfg) do
if v[1] == name then
local w = v[2]
if not id or w.id == id then return w, i end
end
end
end
--! Returns the nth subtag of @a cfg with the given @a name.
--! (Indices start at 1, as always with Lua.)
--! The function also returns the index of the subtag in the array.
function helper.get_nth_child(cfg, name, n)
for i,v in ipairs(cfg) do
if v[1] == name then
n = n - 1
if n == 0 then return v[2], i end
end
end
end
--! Returns the number of subtags of @a with the given @a name.
function helper.child_count(cfg, name)
local n = 0
for i,v in ipairs(cfg) do
if v[1] == name then
n = n + 1
end
end
return n
end
--! Returns an iterator over all the subtags of @a cfg with the given @a name.
function helper.child_range(cfg, tag)
local iter, state, i = ipairs(cfg)
local function f(s)
local c
repeat
i,c = iter(s,i)
if not c then return end
until c[1] == tag
return c[2]
end
return f, state
end
--! Returns an array from the subtags of @a cfg with the given @a name
function helper.child_array(cfg, tag)
local result = {}
for val in helper.child_range(cfg, tag) do
table.insert(result, val)
end
return result
end
--! Modifies all the units satisfying the given @a filter.
--! @param vars key/value pairs that need changing.
--! @note Usable only during WML actions.
function helper.modify_unit(filter, vars)
wml_actions.store_unit({
[1] = { "filter", filter },
variable = "LUA_modify_unit",
kill = true
})
for i = 0, wesnoth.get_variable("LUA_modify_unit.length") - 1 do
local u = string.format("LUA_modify_unit[%d]", i)
for k, v in pairs(vars) do
wesnoth.set_variable(u .. '.' .. k, v)
end
wml_actions.unstore_unit({
variable = u,
find_vacant = false
})
end
wesnoth.set_variable("LUA_modify_unit")
end
--! Fakes the move of a unit satisfying the given @a filter to position @a x, @a y.
--! @note Usable only during WML actions.
function helper.move_unit_fake(filter, to_x, to_y)
wml_actions.store_unit({
[1] = { "filter", filter },
variable = "LUA_move_unit",
kill = false
})
local from_x = wesnoth.get_variable("LUA_move_unit.x")
local from_y = wesnoth.get_variable("LUA_move_unit.y")
wml_actions.scroll_to({ x=from_x, y=from_y })
if to_x < from_x then
wesnoth.set_variable("LUA_move_unit.facing", "sw")
elseif to_x > from_x then
wesnoth.set_variable("LUA_move_unit.facing", "se")
end
wesnoth.set_variable("LUA_move_unit.x", to_x)
wesnoth.set_variable("LUA_move_unit.y", to_y)
wml_actions.kill({
x = from_x,
y = from_y,
animate = false,
fire_event = false
})
wml_actions.move_unit_fake({
type = "$LUA_move_unit.type",
gender = "$LUA_move_unit.gender",
variation = "$LUA_move_unit.variation",
side = "$LUA_move_unit.side",
x = from_x .. ',' .. to_x,
y = from_y .. ',' .. to_y
})
wml_actions.unstore_unit({ variable="LUA_move_unit", find_vacant=true })
wml_actions.redraw({})
wesnoth.set_variable("LUA_move_unit")
end
local variable_mt = {
__metatable = "WML variable proxy"
}
local function get_variable_proxy(k)
local v = wesnoth.get_variable(k, true)
if type(v) == "table" then
v = setmetatable({ __varname = k }, variable_mt)
end
return v
end
local function set_variable_proxy(k, v)
if getmetatable(v) == variable_mt then
v = wesnoth.get_variable(v.__varname)
end
wesnoth.set_variable(k, v)
end
function variable_mt.__index(t, k)
local i = tonumber(k)
if i then
k = t.__varname .. '[' .. i .. ']'
else
k = t.__varname .. '.' .. k
end
return get_variable_proxy(k)
end
function variable_mt.__newindex(t, k, v)
local i = tonumber(k)
if i then
k = t.__varname .. '[' .. i .. ']'
else
k = t.__varname .. '.' .. k
end
set_variable_proxy(k, v)
end
local root_variable_mt = {
__metatable = "WML variables",
__index = function(t, k) return get_variable_proxy(k) end,
__newindex = function(t, k, v)
if type(v) == "function" then
-- User-friendliness when _G is overloaded early.
-- FIXME: It should be disabled outside the "preload" event.
rawset(t, k, v)
else
set_variable_proxy(k, v)
end
end
}
--! Sets the metatable of @a t so that it can be used to access WML variables.
--! @return @a t.
--! @code
--! helper.set_wml_var_metatable(_G)
--! my_persistent_variable = 42
--! @endcode
function helper.set_wml_var_metatable(t)
return setmetatable(t, root_variable_mt)
end
local fire_action_mt = {
__metatable = "WML actions",
__index = function(t, n)
return function(cfg) wesnoth.fire(n, cfg) end
end
}
--! Sets the metatable of @a t so that it can be used to fire WML actions.
--! @return @a t.
--! @code
--! W = helper.set_wml_action_metatable {}
--! W.message { speaker = "narrator", message = "?" }
--! @endcode
function helper.set_wml_action_metatable(t)
return setmetatable(t, fire_action_mt)
end
local create_tag_mt = {
__metatable = "WML tag builder",
__index = function(t, n)
return function(cfg) return { n, cfg } end
end
}
--! Sets the metatable of @a t so that it can be used to create subtags with less brackets.
--! @return @a t.
--! @code
--! T = helper.set_wml_tag_metatable {}
--! W.event { name = "new turn", T.message { speaker = "narrator", message = "?" } }
--! @endcode
function helper.set_wml_tag_metatable(t)
return setmetatable(t, create_tag_mt)
end
--! Fetches all the WML container variables with name @a var.
--! @returns a table containing all the variables (starting at index 1).
function helper.get_variable_array(var)
local result = {}
for i = 1, wesnoth.get_variable(var .. ".length") do
result[i] = wesnoth.get_variable(string.format("%s[%d]", var, i - 1))
end
return result
end
--! Puts all the elements of table @a t inside a WML container with name @a var.
function helper.set_variable_array(var, t)
wesnoth.set_variable(var)
for i, v in ipairs(t) do
wesnoth.set_variable(string.format("%s[%d]", var, i - 1), v)
end
end
--! Creates proxies for all the WML container variables with name @a var.
--! This is similar to helper.get_variable_array, except that the elements
--! can be used for writing too.
--! @returns a table containing all the variable proxies (starting at index 1).
function helper.get_variable_proxy_array(var)
local result = {}
for i = 1, wesnoth.get_variable(var .. ".length") do
result[i] = get_variable_proxy(string.format("%s[%d]", var, i - 1))
end
return result
end
--! Displays a WML message box with attributes from table @attr and options
--! from table @options.
--! @return the index of the selected option.
--! @code
--! local result = helper.get_user_choice({ speaker = "narrator" },
--! { "Choice 1", "Choice 2" })
--! @endcode
function helper.get_user_choice(attr, options)
local result = 0
function wesnoth.__user_choice_helper(i)
result = i
end
local msg = {}
for k,v in pairs(attr) do
msg[k] = attr[k]
end
for k,v in ipairs(options) do
table.insert(msg, { "option", { message = v,
{ "command", { { "lua", {
code = string.format("wesnoth.__user_choice_helper(%d)", k)
}}}}}})
end
wml_actions.message(msg)
wesnoth.__user_choice_helper = nil
return result
end
local function is_even(v) return v % 2 == 0 end
--! Returns the distance between two tiles given by their WML coordinates.
function helper.distance_between(x1, y1, x2, y2)
local hdist = math.abs(x1 - x2)
local vdist = math.abs(y1 - y2)
if (y1 < y2 and not is_even(x1) and is_even(x2)) or
(y2 < y1 and not is_even(x2) and is_even(x1))
then vdist = vdist + 1 end
return math.max(hdist, vdist + math.floor(hdist / 2))
end
local adjacent_offset = {
[false] = { {0,-1}, {1,-1}, {1,0}, {0,1}, {-1,0}, {-1,-1} },
[true] = { {0,-1}, {1,0}, {1,1}, {0,1}, {-1,1}, {-1,0} }
}
--! Returns an iterator over adjacent locations that can be used in a for-in loop.
function helper.adjacent_tiles(x, y, with_borders)
local x1,y1,x2,y2,b = 1,1,wesnoth.get_map_size()
if with_borders then
x1 = x1 - b
y1 = y1 - b
x2 = x2 + b
y2 = y2 + b
end
local offset = adjacent_offset[is_even(x)]
local i = 1
return function()
while i <= 6 do
local o = offset[i]
i = i + 1
local u, v = o[1] + x, o[2] + y
if u >= x1 and u <= x2 and v >= y1 and v <= y2 then
return u, v
end
end
return nil
end
end
function helper.literal(cfg)
if type(cfg) == "userdata" then
return cfg.__literal
else
return cfg or {}
end
end
function helper.parsed(cfg)
if type(cfg) == "userdata" then
return cfg.__parsed
else
return cfg or {}
end
end
function helper.shallow_literal(cfg)
if type(cfg) == "userdata" then
return cfg.__shallow_literal
else
return cfg or {}
end
end
function helper.shallow_parsed(cfg)
if type(cfg) == "userdata" then
return cfg.__shallow_parsed
else
return cfg or {}
end
end
function helper.rand (possible_values)
assert(type(possible_values) == "table" or type(possible_values) == "string", string.format("helper.rand expects a string or table as parameter, got %s instead", type(possible_values)))
local items = {}
local num_choices = 0
if type(possible_values) == "string" then
-- split on commas
for word in possible_values:gmatch("[^,]+") do
-- does the word contain two dots? If yes, that's a range
local dots_start, dots_end = word:find("%.%.")
if dots_start then
-- split on the dots if so and cast as numbers
local low = tonumber(word:sub(1, dots_start-1))
local high = tonumber(word:sub(dots_end+1))
-- perhaps someone passed a string as part of the range, intercept the issue
if not (low and high) then
wesnoth.message("Malformed range: " .. possible_values)
table.insert(items, word)
num_choices = num_choices + 1
else
if low > high then
-- low is greater than high, swap them
low, high = high, low
end
-- if both ends represent the same number, then just use that number
if low == high then
table.insert(items, low)
num_choices = num_choices + 1
else
-- insert a table representing the range
table.insert(items, {low, high})
-- how many items does the range contain? Increase difference by 1 because we include both ends
num_choices = num_choices + (high - low) + 1
end
end
else
-- handle as a string
table.insert(items, word)
num_choices = num_choices + 1
end
end
else
num_choices = #possible_values
items = possible_values
-- We need to parse ranges separately anyway
for i, val in ipairs(possible_values) do
if type(val) == "table" then
assert(#val == 2 and type(val[1]) == "number" and type(val[2]) == "number", "Malformed range for helper.rand")
if val[1] > val[2] then
val = {val[2], val[1]}
end
num_choices = num_choices + (val[2] - val[1])
end
end
end
local idx = wesnoth.random(1, num_choices)
for i, item in ipairs(items) do
if type(item) == "table" then -- that's a range
local elems = item[2] - item[1] + 1 -- amount of elements in the range, both ends included
if elems >= idx then
return item[1] + elems - idx
else
idx = idx - elems
end
else -- that's a single element
idx = idx - 1
if idx == 0 then
return item
end
end
end
return nil
end
function helper.deprecate(msg, f)
return function(...)
if msg then
wesnoth.message("warning", msg)
-- trigger the message only once
msg = nil
end
return f(...)
end
end
function helper.round( number )
-- code converted from util.hpp, round_portable function
-- round half away from zero method
if number >= 0 then
number = math.floor( number + 0.5 )
else
number = math.ceil ( number - 0.5 )
end
return number
end
function helper.shuffle( t, random_func)
random_func = random_func or wesnoth.random
-- since tables are passed by reference, this is an in-place shuffle
-- it uses the Fisher-Yates algorithm, also known as Knuth shuffle
assert( type( t ) == "table", string.format( "helper.shuffle expects a table as parameter, got %s instead", type( t ) ) )
local length = #t
for index = length, 2, -1 do
local random = random_func( 1, index )
t[index], t[random] = t[random], t[index]
end
end
return helper
| gpl-2.0 |
vseledkin/april-ann | profile_build_scripts/build_debug_mkl.lua | 3 | 3144 | dofile("luapkg/formiga.lua")
local postprocess = dofile("luapkg/postprocess.lua")
formiga.build_dir = "build_debug_mkl"
local packages = dofile "profile_build_scripts/package_list.lua"
-- table.insert(packages, "rlcompleter") -- AUTOCOMPLETION => needs READLINE
local metadata = dofile "profile_build_scripts/METADATA.lua"
luapkg{
program_name = "april-ann.debug",
description = metadata.description,
version = metadata.version,
url = metadata.url,
verbosity_level = 0, -- 0 => NONE, 1 => ONLY TARGETS, 2 => ALL
packages = packages,
version_flags = metadata.version_flags,
disclaimer_strings = metadata.disclaimer_strings,
prefix = metadata.prefix,
global_flags = {
debug="yes",
use_lstrip = "no",
use_readline="yes",
optimization = "no",
add_git_metadata = "yes",
platform = "unix",
extra_flags={
-- For Intel MKL :)
"-DUSE_MKL",
"-I/opt/MKL/include",
--------------------
"-march=native",
"-msse",
"-pg",
"-fopenmp",
"-fPIC",
},
extra_libs={
"-fPIC",
"-pg",
"-lpthread",
"-rdynamic",
-- For Intel MKL :)
"-L/opt/MKL/lib",
"-lmkl_intel_lp64",
"-Wl,--start-group",
"-lmkl_intel_thread",
"-lmkl_def",
"-lmkl_core",
"-Wl,--end-group",
"-liomp5"
},
shared_extra_libs={
"-shared",
"-llua5.2",
"-I/usr/include/lua5.2",
},
},
main_package = package{
name = "main_package",
default_target = "build",
target{
name = "init",
mkdir{ dir = "bin" },
mkdir{ dir = "build" },
mkdir{ dir = "include" },
},
target{
name = "provide",
depends = "init",
copy{ file = formiga.os.compose_dir(formiga.os.cwd,"lua","include","*.h"), dest_dir = "include" }
},
target{ name = "clean_all",
exec{ command = [[find . -name "*~" -exec rm {} ';']] },
delete{ dir = "bin" },
delete{ dir = "build" },
delete{ dir = "build_doc" },
delete{ dir = "doxygen_doc" },
},
target{ name = "clean",
delete{ dir = "bin" },
delete{ dir = "build" },
delete{ dir = "build_doc" },
},
target{ name = "document_clean",
delete{ dir = "build_doc" },
delete{ dir = "doxygen_doc" },
},
target{
name = "build",
depends = "provide",
compile_luapkg_utils{},
link_main_program{},
create_static_library{},
create_shared_library{},
copy_header_files{},
dot_graph{
file_name = "dep_graph.dot"
},
use_timestamp = true,
},
target{
name = "test",
depends = "build",
},
target{ name = "document",
echo{"this is documentation"},
main_documentation{
dev_documentation = {
main_documentation_file = formiga.os.compose_dir("docs","april_dev.dox"),
doxygen_options = {
GENERATE_LATEX = 'NO',
},
},
user_documentation = {
main_documentation_file = formiga.os.compose_dir("docs","april_user_ref.dox"),
doxygen_options = {
GENERATE_LATEX = 'NO',
},
}
},
},
},
}
postprocess(arg, formiga)
| gpl-3.0 |
ddouglascarr/rooset | lfframework/framework/env/ui/form_element.lua | 3 | 2498 | --[[--
ui.form_element(
args, -- external arguments
{ -- options for this function call
fetch_value = fetch_value_flag, -- true causes automatic determination of args.value, if nil
fetch_record = fetch_record_flag, -- true causes automatic determination of args.record, if nil
disable_label_for_id = disable_label_for_id_flag, -- true suppresses automatic setting of args.attr.id for a HTML label_for reference
},
function(args)
... -- program code
end
)
This function helps other form helpers by preprocessing arguments passed to the helper, e.g. fetching a value from a record stored in a state-table of the currently active slot.
--]]--
-- TODO: better documentation
function ui.form_element(args, extra_args, func)
local args = table.new(args)
if extra_args then
for key, value in pairs(extra_args) do
args[key] = value
end
end
local slot_state = slot.get_state_table()
args.html_name = args.html_name or args.name
if args.fetch_value then
if args.value == nil then
if not args.record and slot_state then
args.record = slot_state.form_record
end
if args.record then
args.value = args.record[args.name]
end
else
args.value = nihil.lower(args.value)
end
elseif args.fetch_record then
if not args.record and slot_state then
args.record = slot_state.form_record
end
end
if
args.html_name and
not args.readonly and
slot_state.form_readonly == false
then
args.readonly = false
local prefix
if args.html_name_prefix == nil then
prefix = slot_state.html_name_prefix
else
prefix = args.html_name_prefix
end
if prefix then
args.html_name = prefix .. args.html_name
end
else
args.readonly = true
end
if args.label then
if not args.disable_label_for_id then
if not args.attr then
args.attr = { id = ui.create_unique_id() }
elseif not args.attr.id then
args.attr.id = ui.create_unique_id()
end
end
if not args.label_attr then
args.label_attr = { class = "ui_field_label" }
elseif not args.label_attr.class then
args.label_attr.class = "ui_field_label"
end
end
ui.container{
auto_args = args,
content = function() return func(args) end
}
end
| mit |
rpetit3/darkstar | scripts/zones/Qufim_Island/npcs/qm3.lua | 29 | 4306 | -----------------------------------
-- Area: Qufim Island
-- NPC: ??? (qm3)
-- Mission: ACP - The Echo Awakens
-- @zone 126
-- @pos -120.342 -19.471 306.661
-----------------------------------
package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil;
-------------------------------------
require("scripts/zones/Qufim_Island/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
-- Trade Seedspall's Lux, Luna, Astrum
if (player:getCurrentMission(ACP) == THE_ECHO_AWAKENS and trade:getItemCount() == 3
and trade:hasItemQty(2740,1) and trade:hasItemQty(2741,1) and trade:hasItemQty(2742,1)) then
player:tradeComplete();
player:startEvent(0x001F);
end
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local ACPm = player:getCurrentMission(ACP);
local now = tonumber(os.date("%j"));
local SR = player:hasKeyItem(SEEDSPALL_ROSEUM)
local SC = player:hasKeyItem(SEEDSPALL_CAERULUM)
local SV = player:hasKeyItem(SEEDSPALL_VIRIDIS)
local AmberKey = player:hasKeyItem(AMBER_KEY);
local LastAmber = player:getVar("LastAmberKey"); -- When last Amber key was obtained
local LastViridian = player:getVar("LastViridianKey"); -- When last Viridian key was obtained
if (ENABLE_ACP == 1 and player:hasKeyItem(AMBER_KEY) == false) then
if (ACPm == GATHERER_OF_LIGHT_I and SR and SC and SV and now ~= LastViridian) then
player:startEvent(0x0020);
elseif (ACPm == GATHERER_OF_LIGHT_II and player:getVar("SEED_MANDY") == 0) then
-- Spawn Seed mandragora's
player:setVar("SEED_MANDY",1); -- This will need moved into Seed mandies onDeath script later.
player:PrintToPlayer( "Confrontation Battles are not working yet." );
-- EFFECT_CONFRONTATION for 30 min
elseif (ACPm == GATHERER_OF_LIGHT_II and player:getVar("SEED_MANDY") == 1) then -- change SEED_MANDY var number later when battle actually works (intended purpose is to track number of slain mandies).
player:setVar("SEED_MANDY",0);
player:startEvent(0x0022);
-- elseif (ACPm >= THOSE_WHO_LURK_IN_SHADOWS_I and AmberKey == false and now ~= LastAmber and now ~= LastViridian and SR and SC and SV and player:getVar("SEED_MANDY") == 0) then
-- This is for repeats to get amber keys.
-- Spawn Seed mandragora's with EFFECT_CONFRONTATION for 30 min
-- elseif (SR and SC and SV and ACPm >= THOSE_WHO_LURK_IN_SHADOWS_I and player:getVar("SEED_MANDY") == 1) then
-- player:addKeyItem(AMBER_KEY);
-- player:setVar("LastAmberKey", os.date("%j"));
-- player:messageSpecial(KEYITEM_OBTAINED,AMBER_KEY);
-- player:setVar("SEED_MANDY",0);
-- player:delKeyItem(SEEDSPALL_ROSEUM)
-- player:delKeyItem(SEEDSPALL_CAERULUM)
-- player:delKeyItem(SEEDSPALL_VIRIDIS)
else
-- Todo: find retail message (if any) and text its ID
end
else
-- Todo: find retail message (if any) and text its ID
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x001F) then
player:completeMission(ACP,THE_ECHO_AWAKENS);
player:addMission(ACP,GATHERER_OF_LIGHT_I);
elseif (csid == 0x0020) then
player:completeMission(ACP,GATHERER_OF_LIGHT_I);
player:addMission(ACP,GATHERER_OF_LIGHT_II);
player:delKeyItem(SEEDSPALL_ROSEUM)
player:delKeyItem(SEEDSPALL_CAERULUM)
player:delKeyItem(SEEDSPALL_VIRIDIS)
elseif (csid == 0x0022) then
player:completeMission(ACP,GATHERER_OF_LIGHT_II);
player:addMission(ACP,THOSE_WHO_LURK_IN_SHADOWS_I);
end
end; | gpl-3.0 |
rpetit3/darkstar | scripts/zones/Eastern_Altepa_Desert/npcs/Eulaclaire.lua | 27 | 1698 | -----------------------------------
-- Area: Eastern Altepa Desert
-- NPC: Eulaclaire
-- Type: Chocobo Renter
-----------------------------------
require("scripts/globals/chocobo");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
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(0x0006,price,gil);
else
player:startEvent(0x0007);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local price = player:getLocalVar("chocoboPriceOffer");
if (csid == 0x0006 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_CHOCOBO,EFFECT_CHOCOBO,1,0,duration,true);
end
end
end; | gpl-3.0 |
lthall/Leonard_ardupilot | libraries/AP_Scripting/applets/SmartAudio.lua | 24 | 3510 | --------------------------------------------------
--------------------------------------------------
--------- VTX LUA for SMARTAUDIO 2.0 -------------
------------based on work by----------------------
---------Craig Fitches 07/07/2020 ----------------
-------------Mods by H. Wurzburg -----------------
------------clean up by Peter Hall----------------
-----------------HARDWARE------------------
-- tested on CUAVv5Nano and TX8111 VTX
-- Prerequisites ----------------------------------
-- 1. Only works in Ardupilot 4.1dev or later
-- 2. FC with 2MB cache for LUA Scripting
-- 3. Currently only works with SmartAudio 2.0
------------ Instructions ------------------------
-- 1. Set an unused Serial port in Ardupilot to protocol 28 (scripting) and option 4 (half-duplex)
-- 2. Setup an rc channel's RXc_OPTION to 300 for changing power and SCR_USER1 parameter for initial power upon boot
---------and set to -1 for unchanged, 0 (PitMode),1,2,3, or 4 for power level (1 lowest,4 maximum)
-- 3. Attach the UART's TX for the Serial port chosen above to the VTX's SmartAudio input
-- init local variables
local startup_pwr = param:get('SCR_USER1')
local scripting_rc = rc:find_channel_for_option(300)
local port = serial:find_serial(0)
local _current_power = -1
-- hexadecimal smart audio 2.0 commands
local power_commands = {}
power_commands[1] = { {0x00,0x00,0xAA,0x55,0x0B,0x01,0x01,0xF8,0x00}, "VTX Pit Mode" }
power_commands[2] = { {0x00,0x00,0xAA,0x55,0x05,0x01,0x00,0x6B,0x00}, "VTX PWR LOW" } -- SMARTAUDIO_V2_COMMAND_POWER_0
power_commands[3] = { {0x00,0x00,0xAA,0x55,0x05,0x01,0x01,0xBE,0x00}, "VTX PWR MED" } -- SMARTAUDIO_V2_COMMAND_POWER_1
power_commands[4] = { {0x00,0x00,0xAA,0x55,0x05,0x01,0x02,0x14,0x00}, "VTX PWR HIGH" } -- SMARTAUDIO_V2_COMMAND_POWER_2
power_commands[5] = { {0x00,0x00,0xAA,0x55,0x05,0x01,0x03,0xC1,0x00}, "VTX PWR MAX" } -- SMARTAUDIO_V2_COMMAND_POWER_3
-- return a power level from 1 to 5 as set with a switch
function get_power()
input = scripting_rc:norm_input() -- - 1 to 1
input = (input + 1) * 2 -- 0 to 4
return math.floor(input+0.5) + 1 -- integer 1 to 5
end
-- set the power in the range 1 to 5
function setPower(power)
if power == _current_power then
return
end
updateSerial(power_commands[power][1])
gcs:send_text(4, power_commands[power][2])
_current_power = power
end
-- write output to the serial port
function updateSerial(value)
for count = 1, #value do
port:write(value[count])
end
end
---- main update ---
function update()
setPower(get_power())
return update, 500
end
-- initialization
function init()
-- check if setup properly
if not port then
gcs:send_text(0, "SmartAudio: No Scripting Serial Port")
return
end
if not scripting_rc then
gcs:send_text(0, "SmartAudio: No RC option for scripting")
return
end
port:begin(4800)
-- Set initial power after boot based on SCR_USER1
if startup_pwr then -- make sure we found the param
if startup_pwr >= 0 and startup_pwr < 5 then
setPower(math.floor(startup_pwr) + 1)
-- set the current power local to that requested by the rc in
-- this prevents instantly changing the power from the startup value
_current_power = get_power()
end
end
return update, 500
end
return init, 2000 --Wait 2 sec before initializing, gives time for RC in to come good in SITL, also gives a better chance to see errors
| gpl-3.0 |
Tieske/date | src/date.lua | 1 | 32158 | ---------------------------------------------------------------------------------------
-- Module for date and time calculations
--
-- Version 2.2
-- Copyright (C) 2005-2006, by Jas Latrix (jastejada@yahoo.com)
-- Copyright (C) 2013-2021, by Thijs Schreijer
-- Licensed under MIT, http://opensource.org/licenses/MIT
--[[ CONSTANTS ]]--
local HOURPERDAY = 24
local MINPERHOUR = 60
local MINPERDAY = 1440 -- 24*60
local SECPERMIN = 60
local SECPERHOUR = 3600 -- 60*60
local SECPERDAY = 86400 -- 24*60*60
local TICKSPERSEC = 1000000
local TICKSPERDAY = 86400000000
local TICKSPERHOUR = 3600000000
local TICKSPERMIN = 60000000
local DAYNUM_MAX = 365242500 -- Sat Jan 01 1000000 00:00:00
local DAYNUM_MIN = -365242500 -- Mon Jan 01 1000000 BCE 00:00:00
local DAYNUM_DEF = 0 -- Mon Jan 01 0001 00:00:00
local _;
--[[ GLOBAL SETTINGS ]]--
local centuryflip = 0 -- year >= centuryflip == 1900, < centuryflip == 2000
--[[ LOCAL ARE FASTER ]]--
local type = type
local pairs = pairs
local error = error
local assert = assert
local tonumber = tonumber
local tostring = tostring
local string = string
local math = math
local os = os
local unpack = unpack or table.unpack
local setmetatable = setmetatable
local getmetatable = getmetatable
--[[ EXTRA FUNCTIONS ]]--
local fmt = string.format
local lwr = string.lower
local rep = string.rep
local len = string.len -- luacheck: ignore
local sub = string.sub
local gsub = string.gsub
local gmatch = string.gmatch or string.gfind
local find = string.find
local ostime = os.time
local osdate = os.date
local floor = math.floor
local ceil = math.ceil
local abs = math.abs
-- removes the decimal part of a number
local function fix(n) n = tonumber(n) return n and ((n > 0 and floor or ceil)(n)) end
-- returns the modulo n % d;
local function mod(n,d) return n - d*floor(n/d) end
-- is `str` in string list `tbl`, `ml` is the minimun len
local function inlist(str, tbl, ml, tn)
local sl = len(str)
if sl < (ml or 0) then return nil end
str = lwr(str)
for k, v in pairs(tbl) do
if str == lwr(sub(v, 1, sl)) then
if tn then tn[0] = k end
return k
end
end
end
local function fnil() end
--[[ DATE FUNCTIONS ]]--
local DATE_EPOCH -- to be set later
local sl_weekdays = {
[0]="Sunday",[1]="Monday",[2]="Tuesday",[3]="Wednesday",[4]="Thursday",[5]="Friday",[6]="Saturday",
[7]="Sun",[8]="Mon",[9]="Tue",[10]="Wed",[11]="Thu",[12]="Fri",[13]="Sat",
}
local sl_meridian = {[-1]="AM", [1]="PM"}
local sl_months = {
[00]="January", [01]="February", [02]="March",
[03]="April", [04]="May", [05]="June",
[06]="July", [07]="August", [08]="September",
[09]="October", [10]="November", [11]="December",
[12]="Jan", [13]="Feb", [14]="Mar",
[15]="Apr", [16]="May", [17]="Jun",
[18]="Jul", [19]="Aug", [20]="Sep",
[21]="Oct", [22]="Nov", [23]="Dec",
}
-- added the '.2' to avoid collision, use `fix` to remove
local sl_timezone = {
[000]="utc", [0.2]="gmt",
[300]="est", [240]="edt",
[360]="cst", [300.2]="cdt",
[420]="mst", [360.2]="mdt",
[480]="pst", [420.2]="pdt",
}
-- set the day fraction resolution
local function setticks(t)
TICKSPERSEC = t;
TICKSPERDAY = SECPERDAY*TICKSPERSEC
TICKSPERHOUR= SECPERHOUR*TICKSPERSEC
TICKSPERMIN = SECPERMIN*TICKSPERSEC
end
-- is year y leap year?
local function isleapyear(y) -- y must be int!
return (mod(y, 4) == 0 and (mod(y, 100) ~= 0 or mod(y, 400) == 0))
end
-- day since year 0
local function dayfromyear(y) -- y must be int!
return 365*y + floor(y/4) - floor(y/100) + floor(y/400)
end
-- day number from date, month is zero base
local function makedaynum(y, m, d)
local mm = mod(mod(m,12) + 10, 12)
return dayfromyear(y + floor(m/12) - floor(mm/10)) + floor((mm*306 + 5)/10) + d - 307
--local yy = y + floor(m/12) - floor(mm/10)
--return dayfromyear(yy) + floor((mm*306 + 5)/10) + (d - 1)
end
-- date from day number, month is zero base
local function breakdaynum(g)
local g = g + 306
local y = floor((10000*g + 14780)/3652425)
local d = g - dayfromyear(y)
if d < 0 then y = y - 1; d = g - dayfromyear(y) end
local mi = floor((100*d + 52)/3060)
return (floor((mi + 2)/12) + y), mod(mi + 2,12), (d - floor((mi*306 + 5)/10) + 1)
end
--[[ for floats or int32 Lua Number data type
local function breakdaynum2(g)
local g, n = g + 306;
local n400 = floor(g/DI400Y);n = mod(g,DI400Y);
local n100 = floor(n/DI100Y);n = mod(n,DI100Y);
local n004 = floor(n/DI4Y); n = mod(n,DI4Y);
local n001 = floor(n/365); n = mod(n,365);
local y = (n400*400) + (n100*100) + (n004*4) + n001 - ((n001 == 4 or n100 == 4) and 1 or 0)
local d = g - dayfromyear(y)
local mi = floor((100*d + 52)/3060)
return (floor((mi + 2)/12) + y), mod(mi + 2,12), (d - floor((mi*306 + 5)/10) + 1)
end
]]
-- day fraction from time
local function makedayfrc(h,r,s,t)
return ((h*60 + r)*60 + s)*TICKSPERSEC + t
end
-- time from day fraction
local function breakdayfrc(df)
return
mod(floor(df/TICKSPERHOUR),HOURPERDAY),
mod(floor(df/TICKSPERMIN ),MINPERHOUR),
mod(floor(df/TICKSPERSEC ),SECPERMIN),
mod(df,TICKSPERSEC)
end
-- weekday sunday = 0, monday = 1 ...
local function weekday(dn) return mod(dn + 1, 7) end
-- yearday 0 based ...
local function yearday(dn)
return dn - dayfromyear((breakdaynum(dn))-1)
end
-- parse v as a month
local function getmontharg(v)
local m = tonumber(v);
return (m and fix(m - 1)) or inlist(tostring(v) or "", sl_months, 2)
end
-- get daynum of isoweek one of year y
local function isow1(y)
local f = makedaynum(y, 0, 4) -- get the date for the 4-Jan of year `y`
local d = weekday(f)
d = d == 0 and 7 or d -- get the ISO day number, 1 == Monday, 7 == Sunday
return f + (1 - d)
end
local function isowy(dn)
local w1;
local y = (breakdaynum(dn))
if dn >= makedaynum(y, 11, 29) then
w1 = isow1(y + 1);
if dn < w1 then
w1 = isow1(y);
else
y = y + 1;
end
else
w1 = isow1(y);
if dn < w1 then
w1 = isow1(y-1)
y = y - 1
end
end
return floor((dn-w1)/7)+1, y
end
local function isoy(dn)
local y = (breakdaynum(dn))
return y + (((dn >= makedaynum(y, 11, 29)) and (dn >= isow1(y + 1))) and 1 or (dn < isow1(y) and -1 or 0))
end
local function makedaynum_isoywd(y,w,d)
return isow1(y) + 7*w + d - 8 -- simplified: isow1(y) + ((w-1)*7) + (d-1)
end
--[[ THE DATE MODULE ]]--
local fmtstr = "%x %X";
--#if not DATE_OBJECT_AFX then
local date = {}
setmetatable(date, date)
-- Version: VMMMRRRR; V-Major, M-Minor, R-Revision; e.g. 5.45.321 == 50450321
do
local major = 2
local minor = 2
local revision = 0
date.version = major * 10000000 + minor * 10000 + revision
end
--#end -- not DATE_OBJECT_AFX
--[[ THE DATE OBJECT ]]--
local dobj = {}
dobj.__index = dobj
dobj.__metatable = dobj
-- shout invalid arg
local function date_error_arg() return error("invalid argument(s)",0) end
-- create new date object
local function date_new(dn, df)
return setmetatable({daynum=dn, dayfrc=df}, dobj)
end
--#if not NO_LOCAL_TIME_SUPPORT then
-- magic year table
local date_epoch, yt;
local function getequivyear(y)
assert(not yt)
yt = {}
local de = date_epoch:copy()
local dw, dy
for _ = 0, 3000 do
de:setyear(de:getyear() + 1, 1, 1)
dy = de:getyear()
dw = de:getweekday() * (isleapyear(dy) and -1 or 1)
if not yt[dw] then yt[dw] = dy end --print(de)
if yt[1] and yt[2] and yt[3] and yt[4] and yt[5] and yt[6] and yt[7] and yt[-1] and yt[-2] and yt[-3] and yt[-4] and yt[-5] and yt[-6] and yt[-7] then
getequivyear = function(y) return yt[ (weekday(makedaynum(y, 0, 1)) + 1) * (isleapyear(y) and -1 or 1) ] end
return getequivyear(y)
end
end
end
-- TimeValue from date and time
local function totv(y,m,d,h,r,s)
return (makedaynum(y, m, d) - DATE_EPOCH) * SECPERDAY + ((h*60 + r)*60 + s)
end
-- TimeValue from TimeTable
local function tmtotv(tm)
return tm and totv(tm.year, tm.month - 1, tm.day, tm.hour, tm.min, tm.sec)
end
-- Returns the bias in seconds of utc time daynum and dayfrc
local function getbiasutc2(self)
local y,m,d = breakdaynum(self.daynum)
local h,r,s = breakdayfrc(self.dayfrc)
local tvu = totv(y,m,d,h,r,s) -- get the utc TimeValue of date and time
local tml = osdate("*t", tvu) -- get the local TimeTable of tvu
if (not tml) or (tml.year > (y+1) or tml.year < (y-1)) then -- failed try the magic
y = getequivyear(y)
tvu = totv(y,m,d,h,r,s)
tml = osdate("*t", tvu)
end
local tvl = tmtotv(tml)
if tvu and tvl then
return tvu - tvl, tvu, tvl
else
return error("failed to get bias from utc time")
end
end
-- Returns the bias in seconds of local time daynum and dayfrc
local function getbiasloc2(daynum, dayfrc)
local tvu
-- extract date and time
local y,m,d = breakdaynum(daynum)
local h,r,s = breakdayfrc(dayfrc)
-- get equivalent TimeTable
local tml = {year=y, month=m+1, day=d, hour=h, min=r, sec=s}
-- get equivalent TimeValue
local tvl = tmtotv(tml)
local function chkutc()
tml.isdst = nil; local tvug = ostime(tml) if tvug and (tvl == tmtotv(osdate("*t", tvug))) then tvu = tvug return end
tml.isdst = true; local tvud = ostime(tml) if tvud and (tvl == tmtotv(osdate("*t", tvud))) then tvu = tvud return end
tvu = tvud or tvug
end
chkutc()
if not tvu then
tml.year = getequivyear(y)
tvl = tmtotv(tml)
chkutc()
end
return ((tvu and tvl) and (tvu - tvl)) or error("failed to get bias from local time"), tvu, tvl
end
--#end -- not NO_LOCAL_TIME_SUPPORT
--#if not DATE_OBJECT_AFX then
-- the date parser
local strwalker = {} -- ^Lua regular expression is not as powerful as Perl$
strwalker.__index = strwalker
local function newstrwalker(s)return setmetatable({s=s, i=1, e=1, c=len(s)}, strwalker) end
function strwalker:aimchr() return "\n" .. self.s .. "\n" .. rep(".",self.e-1) .. "^" end
function strwalker:finish() return self.i > self.c end
function strwalker:back() self.i = self.e return self end
function strwalker:restart() self.i, self.e = 1, 1 return self end
function strwalker:match(s) return (find(self.s, s, self.i)) end
function strwalker:__call(s, f)-- print("strwalker:__call "..s..self:aimchr())
local is, ie; is, ie, self[1], self[2], self[3], self[4], self[5] = find(self.s, s, self.i)
if is then self.e, self.i = self.i, 1+ie; if f then f(unpack(self)) end return self end
end
local function date_parse(str)
local y,m,d, h,r,s, z, w,u, j, e, x,c, dn,df
local sw = newstrwalker(gsub(gsub(str, "(%b())", ""),"^(%s*)","")) -- remove comment, trim leading space
--local function error_out() print(y,m,d,h,r,s) end
local function error_dup(q) --[[error_out()]] error("duplicate value: " .. (q or "") .. sw:aimchr()) end
local function error_syn(q) --[[error_out()]] error("syntax error: " .. (q or "") .. sw:aimchr()) end
local function error_inv(q) --[[error_out()]] error("invalid date: " .. (q or "") .. sw:aimchr()) end
local function sety(q) y = y and error_dup() or tonumber(q); end
local function setm(q) m = (m or w or j) and error_dup(m or w or j) or tonumber(q) end
local function setd(q) d = d and error_dup() or tonumber(q) end
local function seth(q) h = h and error_dup() or tonumber(q) end
local function setr(q) r = r and error_dup() or tonumber(q) end
local function sets(q) s = s and error_dup() or tonumber(q) end
local function adds(q) s = s + tonumber(q) end
local function setj(q) j = (m or w or j) and error_dup() or tonumber(q); end
local function setz(q) z = (z ~= 0 and z) and error_dup() or q end
local function setzn(zs,zn) zn = tonumber(zn); setz( ((zn<24) and (zn*60) or (mod(zn,100) + floor(zn/100) * 60))*( zs=='+' and -1 or 1) ) end
local function setzc(zs,zh,zm) setz( ((tonumber(zh)*60) + tonumber(zm))*( zs=='+' and -1 or 1) ) end
if not (sw("^(%d%d%d%d)",sety) and (sw("^(%-?)(%d%d)%1(%d%d)",function(_,a,b) setm(tonumber(a)); setd(tonumber(b)) end) or sw("^(%-?)[Ww](%d%d)%1(%d?)",function(_,a,b) w, u = tonumber(a), tonumber(b or 1) end) or sw("^%-?(%d%d%d)",setj) or sw("^%-?(%d%d)",function(a) setm(a);setd(1) end))
and ((sw("^%s*[Tt]?(%d%d):?",seth) and sw("^(%d%d):?",setr) and sw("^(%d%d)",sets) and sw("^(%.%d+)",adds))
or sw:finish() or (sw"^%s*$" or sw"^%s*[Zz]%s*$" or sw("^%s-([%+%-])(%d%d):?(%d%d)%s*$",setzc) or sw("^%s*([%+%-])(%d%d)%s*$",setzn))
) )
then --print(y,m,d,h,r,s,z,w,u,j)
sw:restart(); y,m,d,h,r,s,z,w,u,j = nil,nil,nil,nil,nil,nil,nil,nil,nil,nil
repeat -- print(sw:aimchr())
if sw("^[tT:]?%s*(%d%d?):",seth) then --print("$Time")
_ = sw("^%s*(%d%d?)",setr) and sw("^%s*:%s*(%d%d?)",sets) and sw("^(%.%d+)",adds)
elseif sw("^(%d+)[/\\%s,-]?%s*") then --print("$Digits")
x, c = tonumber(sw[1]), len(sw[1])
if (x >= 70) or (m and d and (not y)) or (c > 3) then
sety( x + ((x >= 100 or c>3) and 0 or x<centuryflip and 2000 or 1900) )
else
if m then setd(x) else m = x end
end
elseif sw("^(%a+)[/\\%s,-]?%s*") then --print("$Words")
x = sw[1]
if inlist(x, sl_months, 2, sw) then
if m and (not d) and (not y) then d, m = m, false end
setm(mod(sw[0],12)+1)
elseif inlist(x, sl_timezone, 2, sw) then
c = fix(sw[0]) -- ignore gmt and utc
if c ~= 0 then setz(c, x) end
elseif not inlist(x, sl_weekdays, 2, sw) then
sw:back()
-- am pm bce ad ce bc
if sw("^([bB])%s*(%.?)%s*[Cc]%s*(%2)%s*[Ee]%s*(%2)%s*") or sw("^([bB])%s*(%.?)%s*[Cc]%s*(%2)%s*") then
e = e and error_dup() or -1
elseif sw("^([aA])%s*(%.?)%s*[Dd]%s*(%2)%s*") or sw("^([cC])%s*(%.?)%s*[Ee]%s*(%2)%s*") then
e = e and error_dup() or 1
elseif sw("^([PApa])%s*(%.?)%s*[Mm]?%s*(%2)%s*") then
x = lwr(sw[1]) -- there should be hour and it must be correct
if (not h) or (h > 12) or (h < 0) then return error_inv() end
if x == 'a' and h == 12 then h = 0 end -- am
if x == 'p' and h ~= 12 then h = h + 12 end -- pm
else error_syn() end
end
elseif not(sw("^([+-])(%d%d?):(%d%d)",setzc) or sw("^([+-])(%d+)",setzn) or sw("^[Zz]%s*$")) then -- sw{"([+-])",{"(%d%d?):(%d%d)","(%d+)"}}
error_syn("?")
end
sw("^%s*") until sw:finish()
--else print("$Iso(Date|Time|Zone)")
end
-- if date is given, it must be complete year, month & day
if (not y and not h) or ((m and not d) or (d and not m)) or ((m and w) or (m and j) or (j and w)) then return error_inv("!") end
-- fix month
if m then m = m - 1 end
-- fix year if we are on BCE
if e and e < 0 and y > 0 then y = 1 - y end
-- create date object
dn = (y and ((w and makedaynum_isoywd(y,w,u)) or (j and makedaynum(y, 0, j)) or makedaynum(y, m, d))) or DAYNUM_DEF
df = makedayfrc(h or 0, r or 0, s or 0, 0) + ((z or 0)*TICKSPERMIN)
--print("Zone",h,r,s,z,m,d,y,df)
return date_new(dn, df) -- no need to :normalize();
end
local function date_fromtable(v)
local y, m, d = fix(v.year), getmontharg(v.month), fix(v.day)
local h, r, s, t = tonumber(v.hour), tonumber(v.min), tonumber(v.sec), tonumber(v.ticks)
-- atleast there is time or complete date
if (y or m or d) and (not(y and m and d)) then return error("incomplete table") end
return (y or h or r or s or t) and date_new(y and makedaynum(y, m, d) or DAYNUM_DEF, makedayfrc(h or 0, r or 0, s or 0, t or 0))
end
local tmap = {
['number'] = function(v) return date_epoch:copy():addseconds(v) end,
['string'] = function(v) return date_parse(v) end,
['boolean']= function(v) return date_fromtable(osdate(v and "!*t" or "*t")) end,
['table'] = function(v) local ref = getmetatable(v) == dobj; return ref and v or date_fromtable(v), ref end
}
local function date_getdobj(v)
local o, r = (tmap[type(v)] or fnil)(v);
return (o and o:normalize() or error"invalid date time value"), r -- if r is true then o is a reference to a date obj
end
--#end -- not DATE_OBJECT_AFX
local function date_from(arg1, arg2, arg3, arg4, arg5, arg6, arg7)
local y, m, d = fix(arg1), getmontharg(arg2), fix(arg3)
local h, r, s, t = tonumber(arg4 or 0), tonumber(arg5 or 0), tonumber(arg6 or 0), tonumber(arg7 or 0)
if y and m and d and h and r and s and t then
return date_new(makedaynum(y, m, d), makedayfrc(h, r, s, t)):normalize()
else
return date_error_arg()
end
end
--[[ THE DATE OBJECT METHODS ]]--
function dobj:normalize()
local dn, df = fix(self.daynum), self.dayfrc
self.daynum, self.dayfrc = dn + floor(df/TICKSPERDAY), mod(df, TICKSPERDAY)
return (dn >= DAYNUM_MIN and dn <= DAYNUM_MAX) and self or error("date beyond imposed limits:"..self)
end
function dobj:getdate() local y, m, d = breakdaynum(self.daynum) return y, m+1, d end
function dobj:gettime() return breakdayfrc(self.dayfrc) end
function dobj:getclockhour() local h = self:gethours() return h>12 and mod(h,12) or (h==0 and 12 or h) end
function dobj:getyearday() return yearday(self.daynum) + 1 end
function dobj:getweekday() return weekday(self.daynum) + 1 end -- in lua weekday is sunday = 1, monday = 2 ...
function dobj:getyear() local r,_,_ = breakdaynum(self.daynum) return r end
function dobj:getmonth() local _,r,_ = breakdaynum(self.daynum) return r+1 end-- in lua month is 1 base
function dobj:getday() local _,_,r = breakdaynum(self.daynum) return r end
function dobj:gethours() return mod(floor(self.dayfrc/TICKSPERHOUR),HOURPERDAY) end
function dobj:getminutes() return mod(floor(self.dayfrc/TICKSPERMIN), MINPERHOUR) end
function dobj:getseconds() return mod(floor(self.dayfrc/TICKSPERSEC ),SECPERMIN) end
function dobj:getfracsec() return mod(floor(self.dayfrc/TICKSPERSEC ),SECPERMIN)+(mod(self.dayfrc,TICKSPERSEC)/TICKSPERSEC) end
function dobj:getticks(u) local x = mod(self.dayfrc,TICKSPERSEC) return u and ((x*u)/TICKSPERSEC) or x end
function dobj:getweeknumber(wdb)
local wd, yd = weekday(self.daynum), yearday(self.daynum)
if wdb then
wdb = tonumber(wdb)
if wdb then
wd = mod(wd-(wdb-1),7)-- shift the week day base
else
return date_error_arg()
end
end
return (yd < wd and 0) or (floor(yd/7) + ((mod(yd, 7)>=wd) and 1 or 0))
end
function dobj:getisoweekday() return mod(weekday(self.daynum)-1,7)+1 end -- sunday = 7, monday = 1 ...
function dobj:getisoweeknumber() return (isowy(self.daynum)) end
function dobj:getisoyear() return isoy(self.daynum) end
function dobj:getisodate()
local w, y = isowy(self.daynum)
return y, w, self:getisoweekday()
end
function dobj:setisoyear(y, w, d)
local cy, cw, cd = self:getisodate()
if y then cy = fix(tonumber(y))end
if w then cw = fix(tonumber(w))end
if d then cd = fix(tonumber(d))end
if cy and cw and cd then
self.daynum = makedaynum_isoywd(cy, cw, cd)
return self:normalize()
else
return date_error_arg()
end
end
function dobj:setisoweekday(d) return self:setisoyear(nil, nil, d) end
function dobj:setisoweeknumber(w,d) return self:setisoyear(nil, w, d) end
function dobj:setyear(y, m, d)
local cy, cm, cd = breakdaynum(self.daynum)
if y then cy = fix(tonumber(y))end
if m then cm = getmontharg(m) end
if d then cd = fix(tonumber(d))end
if cy and cm and cd then
self.daynum = makedaynum(cy, cm, cd)
return self:normalize()
else
return date_error_arg()
end
end
function dobj:setmonth(m, d)return self:setyear(nil, m, d) end
function dobj:setday(d) return self:setyear(nil, nil, d) end
function dobj:sethours(h, m, s, t)
local ch,cm,cs,ck = breakdayfrc(self.dayfrc)
ch, cm, cs, ck = tonumber(h or ch), tonumber(m or cm), tonumber(s or cs), tonumber(t or ck)
if ch and cm and cs and ck then
self.dayfrc = makedayfrc(ch, cm, cs, ck)
return self:normalize()
else
return date_error_arg()
end
end
function dobj:setminutes(m,s,t) return self:sethours(nil, m, s, t) end
function dobj:setseconds(s, t) return self:sethours(nil, nil, s, t) end
function dobj:setticks(t) return self:sethours(nil, nil, nil, t) end
function dobj:spanticks() return (self.daynum*TICKSPERDAY + self.dayfrc) end
function dobj:spanseconds() return (self.daynum*TICKSPERDAY + self.dayfrc)/TICKSPERSEC end
function dobj:spanminutes() return (self.daynum*TICKSPERDAY + self.dayfrc)/TICKSPERMIN end
function dobj:spanhours() return (self.daynum*TICKSPERDAY + self.dayfrc)/TICKSPERHOUR end
function dobj:spandays() return (self.daynum*TICKSPERDAY + self.dayfrc)/TICKSPERDAY end
function dobj:addyears(y, m, d)
local cy, cm, cd = breakdaynum(self.daynum)
if y then y = fix(tonumber(y))else y = 0 end
if m then m = fix(tonumber(m))else m = 0 end
if d then d = fix(tonumber(d))else d = 0 end
if y and m and d then
self.daynum = makedaynum(cy+y, cm+m, cd+d)
return self:normalize()
else
return date_error_arg()
end
end
function dobj:addmonths(m, d)
return self:addyears(nil, m, d)
end
local function dobj_adddayfrc(self,n,pt,pd)
n = tonumber(n)
if n then
local x = floor(n/pd);
self.daynum = self.daynum + x;
self.dayfrc = self.dayfrc + (n-x*pd)*pt;
return self:normalize()
else
return date_error_arg()
end
end
function dobj:adddays(n) return dobj_adddayfrc(self,n,TICKSPERDAY,1) end
function dobj:addhours(n) return dobj_adddayfrc(self,n,TICKSPERHOUR,HOURPERDAY) end
function dobj:addminutes(n) return dobj_adddayfrc(self,n,TICKSPERMIN,MINPERDAY) end
function dobj:addseconds(n) return dobj_adddayfrc(self,n,TICKSPERSEC,SECPERDAY) end
function dobj:addticks(n) return dobj_adddayfrc(self,n,1,TICKSPERDAY) end
local tvspec = {
-- Abbreviated weekday name (Sun)
['%a']=function(self) return sl_weekdays[weekday(self.daynum) + 7] end,
-- Full weekday name (Sunday)
['%A']=function(self) return sl_weekdays[weekday(self.daynum)] end,
-- Abbreviated month name (Dec)
['%b']=function(self) return sl_months[self:getmonth() - 1 + 12] end,
-- Full month name (December)
['%B']=function(self) return sl_months[self:getmonth() - 1] end,
-- Year/100 (19, 20, 30)
['%C']=function(self) return fmt("%.2d", fix(self:getyear()/100)) end,
-- The day of the month as a number (range 1 - 31)
['%d']=function(self) return fmt("%.2d", self:getday()) end,
-- year for ISO 8601 week, from 00 (79)
['%g']=function(self) return fmt("%.2d", mod(self:getisoyear() ,100)) end,
-- year for ISO 8601 week, from 0000 (1979)
['%G']=function(self) return fmt("%.4d", self:getisoyear()) end,
-- same as %b
['%h']=function(self) return self:fmt0("%b") end,
-- hour of the 24-hour day, from 00 (06)
['%H']=function(self) return fmt("%.2d", self:gethours()) end,
-- The hour as a number using a 12-hour clock (01 - 12)
['%I']=function(self) return fmt("%.2d", self:getclockhour()) end,
-- The day of the year as a number (001 - 366)
['%j']=function(self) return fmt("%.3d", self:getyearday()) end,
-- Month of the year, from 01 to 12
['%m']=function(self) return fmt("%.2d", self:getmonth()) end,
-- Minutes after the hour 55
['%M']=function(self) return fmt("%.2d", self:getminutes())end,
-- AM/PM indicator (AM)
['%p']=function(self) return sl_meridian[self:gethours() > 11 and 1 or -1] end, --AM/PM indicator (AM)
-- The second as a number (59, 20 , 01)
['%S']=function(self) return fmt("%.2d", self:getseconds()) end,
-- ISO 8601 day of the week, to 7 for Sunday (7, 1)
['%u']=function(self) return self:getisoweekday() end,
-- Sunday week of the year, from 00 (48)
['%U']=function(self) return fmt("%.2d", self:getweeknumber()) end,
-- ISO 8601 week of the year, from 01 (48)
['%V']=function(self) return fmt("%.2d", self:getisoweeknumber()) end,
-- The day of the week as a decimal, Sunday being 0
['%w']=function(self) return self:getweekday() - 1 end,
-- Monday week of the year, from 00 (48)
['%W']=function(self) return fmt("%.2d", self:getweeknumber(2)) end,
-- The year as a number without a century (range 00 to 99)
['%y']=function(self) return fmt("%.2d", mod(self:getyear() ,100)) end,
-- Year with century (2000, 1914, 0325, 0001)
['%Y']=function(self) return fmt("%.4d", self:getyear()) end,
-- Time zone offset, the date object is assumed local time (+1000, -0230)
['%z']=function(self) local b = -self:getbias(); local x = abs(b); return fmt("%s%.4d", b < 0 and "-" or "+", fix(x/60)*100 + floor(mod(x,60))) end,
-- Time zone name, the date object is assumed local time
['%Z']=function(self) return self:gettzname() end,
-- Misc --
-- Year, if year is in BCE, prints the BCE Year representation, otherwise result is similar to "%Y" (1 BCE, 40 BCE)
['%\b']=function(self) local x = self:getyear() return fmt("%.4d%s", x>0 and x or (-x+1), x>0 and "" or " BCE") end,
-- Seconds including fraction (59.998, 01.123)
['%\f']=function(self) local x = self:getfracsec() return fmt("%s%.9f",x >= 10 and "" or "0", x) end,
-- percent character %
['%%']=function(self) return "%" end,
-- Group Spec --
-- 12-hour time, from 01:00:00 AM (06:55:15 AM); same as "%I:%M:%S %p"
['%r']=function(self) return self:fmt0("%I:%M:%S %p") end,
-- hour:minute, from 01:00 (06:55); same as "%I:%M"
['%R']=function(self) return self:fmt0("%I:%M") end,
-- 24-hour time, from 00:00:00 (06:55:15); same as "%H:%M:%S"
['%T']=function(self) return self:fmt0("%H:%M:%S") end,
-- month/day/year from 01/01/00 (12/02/79); same as "%m/%d/%y"
['%D']=function(self) return self:fmt0("%m/%d/%y") end,
-- year-month-day (1979-12-02); same as "%Y-%m-%d"
['%F']=function(self) return self:fmt0("%Y-%m-%d") end,
-- The preferred date and time representation; same as "%x %X"
['%c']=function(self) return self:fmt0("%x %X") end,
-- The preferred date representation, same as "%a %b %d %\b"
['%x']=function(self) return self:fmt0("%a %b %d %\b") end,
-- The preferred time representation, same as "%H:%M:%\f"
['%X']=function(self) return self:fmt0("%H:%M:%\f") end,
-- GroupSpec --
-- Iso format, same as "%Y-%m-%dT%T"
['${iso}'] = function(self) return self:fmt0("%Y-%m-%dT%T") end,
-- http format, same as "%a, %d %b %Y %T GMT"
['${http}'] = function(self) return self:fmt0("%a, %d %b %Y %T GMT") end,
-- ctime format, same as "%a %b %d %T GMT %Y"
['${ctime}'] = function(self) return self:fmt0("%a %b %d %T GMT %Y") end,
-- RFC850 format, same as "%A, %d-%b-%y %T GMT"
['${rfc850}'] = function(self) return self:fmt0("%A, %d-%b-%y %T GMT") end,
-- RFC1123 format, same as "%a, %d %b %Y %T GMT"
['${rfc1123}'] = function(self) return self:fmt0("%a, %d %b %Y %T GMT") end,
-- asctime format, same as "%a %b %d %T %Y"
['${asctime}'] = function(self) return self:fmt0("%a %b %d %T %Y") end,
}
function dobj:fmt0(str) return (gsub(str, "%%[%a%%\b\f]", function(x) local f = tvspec[x];return (f and f(self)) or x end)) end
function dobj:fmt(str)
str = str or self.fmtstr or fmtstr
return self:fmt0((gmatch(str, "${%w+}")) and (gsub(str, "${%w+}", function(x)local f=tvspec[x];return (f and f(self)) or x end)) or str)
end
function dobj.__lt(a, b) if (a.daynum == b.daynum) then return (a.dayfrc < b.dayfrc) else return (a.daynum < b.daynum) end end
function dobj.__le(a, b) if (a.daynum == b.daynum) then return (a.dayfrc <= b.dayfrc) else return (a.daynum <= b.daynum) end end
function dobj.__eq(a, b)return (a.daynum == b.daynum) and (a.dayfrc == b.dayfrc) end
function dobj.__sub(a,b)
local d1, d2 = date_getdobj(a), date_getdobj(b)
local d0 = d1 and d2 and date_new(d1.daynum - d2.daynum, d1.dayfrc - d2.dayfrc)
return d0 and d0:normalize()
end
function dobj.__add(a,b)
local d1, d2 = date_getdobj(a), date_getdobj(b)
local d0 = d1 and d2 and date_new(d1.daynum + d2.daynum, d1.dayfrc + d2.dayfrc)
return d0 and d0:normalize()
end
function dobj.__concat(a, b) return tostring(a) .. tostring(b) end
function dobj:__tostring() return self:fmt() end
function dobj:copy() return date_new(self.daynum, self.dayfrc) end
--[[ THE LOCAL DATE OBJECT METHODS ]]--
function dobj:tolocal()
local dn,df = self.daynum, self.dayfrc
local bias = getbiasutc2(self)
if bias then
-- utc = local + bias; local = utc - bias
self.daynum = dn
self.dayfrc = df - bias*TICKSPERSEC
return self:normalize()
else
return nil
end
end
function dobj:toutc()
local dn,df = self.daynum, self.dayfrc
local bias = getbiasloc2(dn, df)
if bias then
-- utc = local + bias;
self.daynum = dn
self.dayfrc = df + bias*TICKSPERSEC
return self:normalize()
else
return nil
end
end
function dobj:getbias() return (getbiasloc2(self.daynum, self.dayfrc))/SECPERMIN end
function dobj:gettzname()
local _, tvu, _ = getbiasloc2(self.daynum, self.dayfrc)
return tvu and osdate("%Z",tvu) or ""
end
--#if not DATE_OBJECT_AFX then
function date.time(h, r, s, t)
h, r, s, t = tonumber(h or 0), tonumber(r or 0), tonumber(s or 0), tonumber(t or 0)
if h and r and s and t then
return date_new(DAYNUM_DEF, makedayfrc(h, r, s, t))
else
return date_error_arg()
end
end
function date:__call(arg1, ...)
local arg_count = select("#", ...) + (arg1 == nil and 0 or 1)
if arg_count > 1 then return (date_from(arg1, ...))
elseif arg_count == 0 then return (date_getdobj(false))
else local o, r = date_getdobj(arg1); return r and o:copy() or o end
end
date.diff = dobj.__sub
function date.isleapyear(v)
local y = fix(v);
if not y then
y = date_getdobj(v)
y = y and y:getyear()
end
return isleapyear(y+0)
end
function date.epoch() return date_epoch:copy() end
function date.isodate(y,w,d) return date_new(makedaynum_isoywd(y + 0, w and (w+0) or 1, d and (d+0) or 1), 0) end
function date.setcenturyflip(y)
if y ~= floor(y) or y < 0 or y > 100 then date_error_arg() end
centuryflip = y
end
function date.getcenturyflip() return centuryflip end
-- Internal functions
function date.fmt(str) if str then fmtstr = str end; return fmtstr end
function date.daynummin(n) DAYNUM_MIN = (n and n < DAYNUM_MAX) and n or DAYNUM_MIN return n and DAYNUM_MIN or date_new(DAYNUM_MIN, 0):normalize()end
function date.daynummax(n) DAYNUM_MAX = (n and n > DAYNUM_MIN) and n or DAYNUM_MAX return n and DAYNUM_MAX or date_new(DAYNUM_MAX, 0):normalize()end
function date.ticks(t) if t then setticks(t) end return TICKSPERSEC end
--#end -- not DATE_OBJECT_AFX
local tm = osdate("!*t", 0);
if tm then
date_epoch = date_new(makedaynum(tm.year, tm.month - 1, tm.day), makedayfrc(tm.hour, tm.min, tm.sec, 0))
-- the distance from our epoch to os epoch in daynum
DATE_EPOCH = date_epoch and date_epoch:spandays()
else -- error will be raise only if called!
date_epoch = setmetatable({},{__index = function() error("failed to get the epoch date") end})
end
--#if not DATE_OBJECT_AFX then
return date
--#else
--$return date_from
--#end
| mit |
rpetit3/darkstar | scripts/zones/Nashmau/npcs/Yohj_Dukonlhy.lua | 15 | 1397 | -----------------------------------
-- Area: Nashmau
-- NPC: Yohj Dukonlhy
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Nashmau/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Based on scripts/zones/Mhaura/Dieh_Yamilsiah.lua
local timer = 1152 - ((os.time() - 1009810800)%1152);
local direction = 0; -- Arrive, 1 for depart
local waiting = 431; -- Offset for Nashmau
if (timer <= waiting) then
direction = 1; -- Ship arrived, switch dialog from "arrive" to "depart"
else
timer = timer - waiting; -- Ship hasn't arrived, subtract waiting time to get time to arrival
end
player:startEvent(231,timer,direction);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
rpetit3/darkstar | scripts/zones/Southern_San_dOria/npcs/Well.lua | 13 | 1395 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Well
-- Involved in Quest: Grave Concerns
-- @zone 230
-- @pos -129 -6 92
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,GRAVE_CONCERNS) == QUEST_ACCEPTED) then
if (trade:hasItemQty(547,1) and trade:getItemCount() == 1) then
player:tradeComplete();
player:addItem(567);
player:messageSpecial(ITEM_OBTAINED,567); -- Tomb Waterskin
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
opentechinstitute/luci-commotion-linux | libs/core/luasrc/model/network.lua | 10 | 33420 | --[[
LuCI - Network model
Copyright 2009-2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local type, next, pairs, ipairs, loadfile, table
= type, next, pairs, ipairs, loadfile, table
local tonumber, tostring, math = tonumber, tostring, math
local require = require
local bus = require "ubus"
local nxo = require "nixio"
local nfs = require "nixio.fs"
local ipc = require "luci.ip"
local sys = require "luci.sys"
local utl = require "luci.util"
local dsp = require "luci.dispatcher"
local uci = require "luci.model.uci"
local lng = require "luci.i18n"
module "luci.model.network"
IFACE_PATTERNS_VIRTUAL = { }
IFACE_PATTERNS_IGNORE = { "^wmaster%d", "^wifi%d", "^hwsim%d", "^imq%d", "^ifb%d", "^mon%.wlan%d", "^sit%d", "^gre%d", "^lo$" }
IFACE_PATTERNS_WIRELESS = { "^wlan%d", "^wl%d", "^ath%d", "^%w+%.network%d" }
protocol = utl.class()
local _protocols = { }
local _interfaces, _bridge, _switch, _tunnel
local _ubus, _ubusnetcache, _ubusdevcache
local _uci_real, _uci_state
function _filter(c, s, o, r)
local val = _uci_real:get(c, s, o)
if val then
local l = { }
if type(val) == "string" then
for val in val:gmatch("%S+") do
if val ~= r then
l[#l+1] = val
end
end
if #l > 0 then
_uci_real:set(c, s, o, table.concat(l, " "))
else
_uci_real:delete(c, s, o)
end
elseif type(val) == "table" then
for _, val in ipairs(val) do
if val ~= r then
l[#l+1] = val
end
end
if #l > 0 then
_uci_real:set(c, s, o, l)
else
_uci_real:delete(c, s, o)
end
end
end
end
function _append(c, s, o, a)
local val = _uci_real:get(c, s, o) or ""
if type(val) == "string" then
local l = { }
for val in val:gmatch("%S+") do
if val ~= a then
l[#l+1] = val
end
end
l[#l+1] = a
_uci_real:set(c, s, o, table.concat(l, " "))
elseif type(val) == "table" then
local l = { }
for _, val in ipairs(val) do
if val ~= a then
l[#l+1] = val
end
end
l[#l+1] = a
_uci_real:set(c, s, o, l)
end
end
function _stror(s1, s2)
if not s1 or #s1 == 0 then
return s2 and #s2 > 0 and s2
else
return s1
end
end
function _get(c, s, o)
return _uci_real:get(c, s, o)
end
function _set(c, s, o, v)
if v ~= nil then
if type(v) == "boolean" then v = v and "1" or "0" end
return _uci_real:set(c, s, o, v)
else
return _uci_real:delete(c, s, o)
end
end
function _wifi_iface(x)
local _, p
for _, p in ipairs(IFACE_PATTERNS_WIRELESS) do
if x:match(p) then
return true
end
end
return false
end
function _wifi_lookup(ifn)
-- got a radio#.network# pseudo iface, locate the corresponding section
local radio, ifnidx = ifn:match("^(%w+)%.network(%d+)$")
if radio and ifnidx then
local sid = nil
local num = 0
ifnidx = tonumber(ifnidx)
_uci_real:foreach("wireless", "wifi-iface",
function(s)
if s.device == radio then
num = num + 1
if num == ifnidx then
sid = s['.name']
return false
end
end
end)
return sid
-- looks like wifi, try to locate the section via state vars
elseif _wifi_iface(ifn) then
local sid = nil
_uci_state:foreach("wireless", "wifi-iface",
function(s)
if s.ifname == ifn then
sid = s['.name']
return false
end
end)
return sid
end
end
function _iface_virtual(x)
local _, p
for _, p in ipairs(IFACE_PATTERNS_VIRTUAL) do
if x:match(p) then
return true
end
end
return false
end
function _iface_ignore(x)
local _, p
for _, p in ipairs(IFACE_PATTERNS_IGNORE) do
if x:match(p) then
return true
end
end
return _iface_virtual(x)
end
function init(cursor)
_uci_real = cursor or _uci_real or uci.cursor()
_uci_state = _uci_real:substate()
_interfaces = { }
_bridge = { }
_switch = { }
_tunnel = { }
_ubus = bus.connect()
_ubusnetcache = { }
_ubusdevcache = { }
-- read interface information
local n, i
for n, i in ipairs(nxo.getifaddrs()) do
local name = i.name:match("[^:]+")
local prnt = name:match("^([^%.]+)%.")
if _iface_virtual(name) then
_tunnel[name] = true
end
if _tunnel[name] or not _iface_ignore(name) then
_interfaces[name] = _interfaces[name] or {
idx = i.ifindex or n,
name = name,
rawname = i.name,
flags = { },
ipaddrs = { },
ip6addrs = { }
}
if prnt then
_switch[name] = true
_switch[prnt] = true
end
if i.family == "packet" then
_interfaces[name].flags = i.flags
_interfaces[name].stats = i.data
_interfaces[name].macaddr = i.addr
elseif i.family == "inet" then
_interfaces[name].ipaddrs[#_interfaces[name].ipaddrs+1] = ipc.IPv4(i.addr, i.netmask)
elseif i.family == "inet6" then
_interfaces[name].ip6addrs[#_interfaces[name].ip6addrs+1] = ipc.IPv6(i.addr, i.netmask)
end
end
end
-- read bridge informaton
local b, l
for l in utl.execi("brctl show") do
if not l:match("STP") then
local r = utl.split(l, "%s+", nil, true)
if #r == 4 then
b = {
name = r[1],
id = r[2],
stp = r[3] == "yes",
ifnames = { _interfaces[r[4]] }
}
if b.ifnames[1] then
b.ifnames[1].bridge = b
end
_bridge[r[1]] = b
elseif b then
b.ifnames[#b.ifnames+1] = _interfaces[r[2]]
b.ifnames[#b.ifnames].bridge = b
end
end
end
return _M
end
function save(self, ...)
_uci_real:save(...)
_uci_real:load(...)
end
function commit(self, ...)
_uci_real:commit(...)
_uci_real:load(...)
end
function ifnameof(self, x)
if utl.instanceof(x, interface) then
return x:name()
elseif utl.instanceof(x, protocol) then
return x:ifname()
elseif type(x) == "string" then
return x:match("^[^:]+")
end
end
function get_protocol(self, protoname, netname)
local v = _protocols[protoname]
if v then
return v(netname or "__dummy__")
end
end
function get_protocols(self)
local p = { }
local _, v
for _, v in ipairs(_protocols) do
p[#p+1] = v("__dummy__")
end
return p
end
function register_protocol(self, protoname)
local proto = utl.class(protocol)
function proto.__init__(self, name)
self.sid = name
end
function proto.proto(self)
return protoname
end
_protocols[#_protocols+1] = proto
_protocols[protoname] = proto
return proto
end
function register_pattern_virtual(self, pat)
IFACE_PATTERNS_VIRTUAL[#IFACE_PATTERNS_VIRTUAL+1] = pat
end
function has_ipv6(self)
return nfs.access("/proc/net/ipv6_route")
end
function add_network(self, n, options)
local oldnet = self:get_network(n)
if n and #n > 0 and n:match("^[a-zA-Z0-9_]+$") and not oldnet then
if _uci_real:section("network", "interface", n, options) then
return network(n)
end
elseif oldnet and oldnet:is_empty() then
if options then
local k, v
for k, v in pairs(options) do
oldnet:set(k, v)
end
end
return oldnet
end
end
function get_network(self, n)
if n and _uci_real:get("network", n) == "interface" then
return network(n)
end
end
function get_networks(self)
local nets = { }
local nls = { }
_uci_real:foreach("network", "interface",
function(s)
nls[s['.name']] = network(s['.name'])
end)
local n
for n in utl.kspairs(nls) do
nets[#nets+1] = nls[n]
end
return nets
end
function del_network(self, n)
local r = _uci_real:delete("network", n)
if r then
_uci_real:delete_all("network", "alias",
function(s) return (s.interface == n) end)
_uci_real:delete_all("network", "route",
function(s) return (s.interface == n) end)
_uci_real:delete_all("network", "route6",
function(s) return (s.interface == n) end)
_uci_real:foreach("wireless", "wifi-iface",
function(s)
local net
local rest = { }
for net in utl.imatch(s.network) do
if net ~= n then
rest[#rest+1] = net
end
end
if #rest > 0 then
_uci_real:set("wireless", s['.name'], "network",
table.concat(rest, " "))
else
_uci_real:delete("wireless", s['.name'], "network")
end
end)
end
return r
end
function rename_network(self, old, new)
local r
if new and #new > 0 and new:match("^[a-zA-Z0-9_]+$") and not self:get_network(new) then
r = _uci_real:section("network", "interface", new, _uci_real:get_all("network", old))
if r then
_uci_real:foreach("network", "alias",
function(s)
if s.interface == old then
_uci_real:set("network", s['.name'], "interface", new)
end
end)
_uci_real:foreach("network", "route",
function(s)
if s.interface == old then
_uci_real:set("network", s['.name'], "interface", new)
end
end)
_uci_real:foreach("network", "route6",
function(s)
if s.interface == old then
_uci_real:set("network", s['.name'], "interface", new)
end
end)
_uci_real:foreach("wireless", "wifi-iface",
function(s)
local net
local list = { }
for net in utl.imatch(s.network) do
if net == old then
list[#list+1] = new
else
list[#list+1] = net
end
end
if #list > 0 then
_uci_real:set("wireless", s['.name'], "network",
table.concat(list, " "))
end
end)
_uci_real:delete("network", old)
end
end
return r or false
end
function get_interface(self, i)
if _interfaces[i] or _wifi_iface(i) then
return interface(i)
else
local ifc
local num = { }
_uci_real:foreach("wireless", "wifi-iface",
function(s)
if s.device then
num[s.device] = num[s.device] and num[s.device] + 1 or 1
if s['.name'] == i then
ifc = interface(
"%s.network%d" %{s.device, num[s.device] })
return false
end
end
end)
return ifc
end
end
function get_interfaces(self)
local iface
local ifaces = { }
local seen = { }
local nfs = { }
local baseof = { }
-- find normal interfaces
_uci_real:foreach("network", "interface",
function(s)
for iface in utl.imatch(s.ifname) do
if not _iface_ignore(iface) and not _wifi_iface(iface) then
seen[iface] = true
nfs[iface] = interface(iface)
end
end
end)
for iface in utl.kspairs(_interfaces) do
if not (seen[iface] or _iface_ignore(iface) or _wifi_iface(iface)) then
nfs[iface] = interface(iface)
end
end
-- find vlan interfaces
_uci_real:foreach("network", "switch_vlan",
function(s)
if not s.device then
return
end
local base = baseof[s.device]
if not base then
if not s.device:match("^eth%d") then
local l
for l in utl.execi("swconfig dev %q help 2>/dev/null" % s.device) do
if not base then
base = l:match("^%w+: (%w+)")
end
end
if not base or not base:match("^eth%d") then
base = "eth0"
end
else
base = s.device
end
baseof[s.device] = base
end
local vid = tonumber(s.vid or s.vlan)
if vid ~= nil and vid >= 0 and vid <= 4095 then
local iface = "%s.%d" %{ base, vid }
if not seen[iface] then
seen[iface] = true
nfs[iface] = interface(iface)
end
end
end)
for iface in utl.kspairs(nfs) do
ifaces[#ifaces+1] = nfs[iface]
end
-- find wifi interfaces
local num = { }
local wfs = { }
_uci_real:foreach("wireless", "wifi-iface",
function(s)
if s.device then
num[s.device] = num[s.device] and num[s.device] + 1 or 1
local i = "%s.network%d" %{ s.device, num[s.device] }
wfs[i] = interface(i)
end
end)
for iface in utl.kspairs(wfs) do
ifaces[#ifaces+1] = wfs[iface]
end
return ifaces
end
function ignore_interface(self, x)
return _iface_ignore(x)
end
function get_wifidev(self, dev)
if _uci_real:get("wireless", dev) == "wifi-device" then
return wifidev(dev)
end
end
function get_wifidevs(self)
local devs = { }
local wfd = { }
_uci_real:foreach("wireless", "wifi-device",
function(s) wfd[#wfd+1] = s['.name'] end)
local dev
for _, dev in utl.vspairs(wfd) do
devs[#devs+1] = wifidev(dev)
end
return devs
end
function get_wifinet(self, net)
local wnet = _wifi_lookup(net)
if wnet then
return wifinet(wnet)
end
end
function add_wifinet(self, net, options)
if type(options) == "table" and options.device and
_uci_real:get("wireless", options.device) == "wifi-device"
then
local wnet = _uci_real:section("wireless", "wifi-iface", nil, options)
return wifinet(wnet)
end
end
function del_wifinet(self, net)
local wnet = _wifi_lookup(net)
if wnet then
_uci_real:delete("wireless", wnet)
return true
end
return false
end
function get_status_by_route(self, addr, mask)
local _, object
for _, object in ipairs(_ubus:objects()) do
local net = object:match("^network%.interface%.(.+)")
if net then
local s = _ubus:call(object, "status", {})
if s and s.route then
local rt
for _, rt in ipairs(s.route) do
if rt.target == addr and rt.mask == mask then
return net, s
end
end
end
end
end
end
function get_status_by_address(self, addr)
local _, object
for _, object in ipairs(_ubus:objects()) do
local net = object:match("^network%.interface%.(.+)")
if net then
local s = _ubus:call(object, "status", {})
if s and s['ipv4-address'] then
local a
for _, a in ipairs(s['ipv4-address']) do
if a.address == addr then
return net, s
end
end
end
if s and s['ipv6-address'] then
local a
for _, a in ipairs(s['ipv6-address']) do
if a.address == addr then
return net, s
end
end
end
end
end
end
function get_wannet(self)
local net = self:get_status_by_route("0.0.0.0", 0)
return net and network(net)
end
function get_wandev(self)
local _, stat = self:get_status_by_route("0.0.0.0", 0)
return stat and interface(stat.l3_device or stat.device)
end
function get_wan6net(self)
local net = self:get_status_by_route("::", 0)
return net and network(net)
end
function get_wan6dev(self)
local _, stat = self:get_status_by_route("::", 0)
return stat and interface(stat.l3_device or stat.device)
end
function network(name, proto)
if name then
local p = proto or _uci_real:get("network", name, "proto")
local c = p and _protocols[p] or protocol
return c(name)
end
end
function protocol.__init__(self, name)
self.sid = name
end
function protocol._get(self, opt)
local v = _uci_real:get("network", self.sid, opt)
if type(v) == "table" then
return table.concat(v, " ")
end
return v or ""
end
function protocol._ubus(self, field)
if not _ubusnetcache[self.sid] then
_ubusnetcache[self.sid] = _ubus:call("network.interface.%s" % self.sid,
"status", { })
end
if _ubusnetcache[self.sid] and field then
return _ubusnetcache[self.sid][field]
end
return _ubusnetcache[self.sid]
end
function protocol.get(self, opt)
return _get("network", self.sid, opt)
end
function protocol.set(self, opt, val)
return _set("network", self.sid, opt, val)
end
function protocol.ifname(self)
local ifname
if self:is_floating() then
ifname = self:_ubus("l3_device")
else
ifname = self:_ubus("device")
end
if not ifname then
local num = { }
_uci_real:foreach("wireless", "wifi-iface",
function(s)
if s.device then
num[s.device] = num[s.device]
and num[s.device] + 1 or 1
local net
for net in utl.imatch(s.network) do
if net == self.sid then
ifname = "%s.network%d" %{ s.device, num[s.device] }
return false
end
end
end
end)
end
return ifname
end
function protocol.proto(self)
return "none"
end
function protocol.get_i18n(self)
local p = self:proto()
if p == "none" then
return lng.translate("Unmanaged")
elseif p == "static" then
return lng.translate("Static address")
elseif p == "dhcp" then
return lng.translate("DHCP client")
else
return lng.translate("Unknown")
end
end
function protocol.type(self)
return self:_get("type")
end
function protocol.name(self)
return self.sid
end
function protocol.uptime(self)
return self:_ubus("uptime") or 0
end
function protocol.expires(self)
local a = tonumber(_uci_state:get("network", self.sid, "lease_acquired"))
local l = tonumber(_uci_state:get("network", self.sid, "lease_lifetime"))
if a and l then
l = l - (nxo.sysinfo().uptime - a)
return l > 0 and l or 0
end
return -1
end
function protocol.metric(self)
return tonumber(_uci_state:get("network", self.sid, "metric")) or 0
end
function protocol.ipaddr(self)
local addrs = self:_ubus("ipv4-address")
return addrs and #addrs > 0 and addrs[1].address
end
function protocol.netmask(self)
local addrs = self:_ubus("ipv4-address")
return addrs and #addrs > 0 and
ipc.IPv4("0.0.0.0/%d" % addrs[1].mask):mask():string()
end
function protocol.gwaddr(self)
local _, route
for _, route in ipairs(self:_ubus("route") or { }) do
if route.target == "0.0.0.0" and route.mask == 0 then
return route.nexthop
end
end
end
function protocol.dnsaddrs(self)
local dns = { }
local _, addr
for _, addr in ipairs(self:_ubus("dns-server") or { }) do
if not addr:match(":") then
dns[#dns+1] = addr
end
end
return dns
end
function protocol.ip6addr(self)
local addrs = self:_ubus("ipv6-address")
if addrs and #addrs > 0 then
return "%s/%d" %{ addrs[1].address, addrs[1].mask }
else
addrs = self:_ubus("ipv6-prefix-assignment")
if addrs and #addrs > 0 then
return "%s/%d" %{ addrs[1].address, addrs[1].mask }
end
end
end
function protocol.gw6addr(self)
local _, route
for _, route in ipairs(self:_ubus("route") or { }) do
if route.target == "::" and route.mask == 0 then
return ipc.IPv6(route.nexthop):string()
end
end
end
function protocol.dns6addrs(self)
local dns = { }
local _, addr
for _, addr in ipairs(self:_ubus("dns-server") or { }) do
if addr:match(":") then
dns[#dns+1] = addr
end
end
return dns
end
function protocol.is_bridge(self)
return (not self:is_virtual() and self:type() == "bridge")
end
function protocol.opkg_package(self)
return nil
end
function protocol.is_installed(self)
return true
end
function protocol.is_virtual(self)
return false
end
function protocol.is_floating(self)
return false
end
function protocol.is_empty(self)
if self:is_floating() then
return false
else
local rv = true
if (self:_get("ifname") or ""):match("%S+") then
rv = false
end
_uci_real:foreach("wireless", "wifi-iface",
function(s)
local n
for n in utl.imatch(s.network) do
if n == self.sid then
rv = false
return false
end
end
end)
return rv
end
end
function protocol.add_interface(self, ifname)
ifname = _M:ifnameof(ifname)
if ifname and not self:is_floating() then
-- if its a wifi interface, change its network option
local wif = _wifi_lookup(ifname)
if wif then
_append("wireless", wif, "network", self.sid)
-- add iface to our iface list
else
_append("network", self.sid, "ifname", ifname)
end
end
end
function protocol.del_interface(self, ifname)
ifname = _M:ifnameof(ifname)
if ifname and not self:is_floating() then
-- if its a wireless interface, clear its network option
local wif = _wifi_lookup(ifname)
if wif then _filter("wireless", wif, "network", self.sid) end
-- remove the interface
_filter("network", self.sid, "ifname", ifname)
end
end
function protocol.get_interface(self)
if self:is_virtual() then
_tunnel[self:proto() .. "-" .. self.sid] = true
return interface(self:proto() .. "-" .. self.sid, self)
elseif self:is_bridge() then
_bridge["br-" .. self.sid] = true
return interface("br-" .. self.sid, self)
else
local ifn = nil
local num = { }
for ifn in utl.imatch(_uci_real:get("network", self.sid, "ifname")) do
ifn = ifn:match("^[^:/]+")
return ifn and interface(ifn, self)
end
ifn = nil
_uci_real:foreach("wireless", "wifi-iface",
function(s)
if s.device then
num[s.device] = num[s.device] and num[s.device] + 1 or 1
local net
for net in utl.imatch(s.network) do
if net == self.sid then
ifn = "%s.network%d" %{ s.device, num[s.device] }
return false
end
end
end
end)
return ifn and interface(ifn, self)
end
end
function protocol.get_interfaces(self)
if self:is_bridge() or (self:is_virtual() and not self:is_floating()) then
local ifaces = { }
local ifn
local nfs = { }
for ifn in utl.imatch(self:get("ifname")) do
ifn = ifn:match("^[^:/]+")
nfs[ifn] = interface(ifn, self)
end
for ifn in utl.kspairs(nfs) do
ifaces[#ifaces+1] = nfs[ifn]
end
local num = { }
local wfs = { }
_uci_real:foreach("wireless", "wifi-iface",
function(s)
if s.device then
num[s.device] = num[s.device] and num[s.device] + 1 or 1
local net
for net in utl.imatch(s.network) do
if net == self.sid then
ifn = "%s.network%d" %{ s.device, num[s.device] }
wfs[ifn] = interface(ifn, self)
end
end
end
end)
for ifn in utl.kspairs(wfs) do
ifaces[#ifaces+1] = wfs[ifn]
end
return ifaces
end
end
function protocol.contains_interface(self, ifname)
ifname = _M:ifnameof(ifname)
if not ifname then
return false
elseif self:is_virtual() and self:proto() .. "-" .. self.sid == ifname then
return true
elseif self:is_bridge() and "br-" .. self.sid == ifname then
return true
else
local ifn
for ifn in utl.imatch(self:get("ifname")) do
ifn = ifn:match("[^:]+")
if ifn == ifname then
return true
end
end
local wif = _wifi_lookup(ifname)
if wif then
local n
for n in utl.imatch(_uci_real:get("wireless", wif, "network")) do
if n == self.sid then
return true
end
end
end
end
return false
end
function protocol.adminlink(self)
return dsp.build_url("admin", "network", "network", self.sid)
end
interface = utl.class()
function interface.__init__(self, ifname, network)
local wif = _wifi_lookup(ifname)
if wif then
self.wif = wifinet(wif)
self.ifname = _uci_state:get("wireless", wif, "ifname")
end
self.ifname = self.ifname or ifname
self.dev = _interfaces[self.ifname]
self.network = network
end
function interface._ubus(self, field)
if not _ubusdevcache[self.ifname] then
_ubusdevcache[self.ifname] = _ubus:call("network.device", "status",
{ name = self.ifname })
end
if _ubusdevcache[self.ifname] and field then
return _ubusdevcache[self.ifname][field]
end
return _ubusdevcache[self.ifname]
end
function interface.name(self)
return self.wif and self.wif:ifname() or self.ifname
end
function interface.mac(self)
return (self:_ubus("macaddr") or "00:00:00:00:00:00"):upper()
end
function interface.ipaddrs(self)
return self.dev and self.dev.ipaddrs or { }
end
function interface.ip6addrs(self)
return self.dev and self.dev.ip6addrs or { }
end
function interface.type(self)
if self.wif or _wifi_iface(self.ifname) then
return "wifi"
elseif _bridge[self.ifname] then
return "bridge"
elseif _tunnel[self.ifname] then
return "tunnel"
elseif self.ifname:match("%.") then
return "vlan"
elseif _switch[self.ifname] then
return "switch"
else
return "ethernet"
end
end
function interface.shortname(self)
if self.wif then
return "%s %q" %{
self.wif:active_mode(),
self.wif:active_ssid() or self.wif:active_bssid()
}
else
return self.ifname
end
end
function interface.get_i18n(self)
if self.wif then
return "%s: %s %q" %{
lng.translate("Wireless Network"),
self.wif:active_mode(),
self.wif:active_ssid() or self.wif:active_bssid()
}
else
return "%s: %q" %{ self:get_type_i18n(), self:name() }
end
end
function interface.get_type_i18n(self)
local x = self:type()
if x == "wifi" then
return lng.translate("Wireless Adapter")
elseif x == "bridge" then
return lng.translate("Bridge")
elseif x == "switch" then
return lng.translate("Ethernet Switch")
elseif x == "vlan" then
return lng.translate("VLAN Interface")
elseif x == "tunnel" then
return lng.translate("Tunnel Interface")
else
return lng.translate("Ethernet Adapter")
end
end
function interface.adminlink(self)
if self.wif then
return self.wif:adminlink()
end
end
function interface.ports(self)
local members = self:_ubus("bridge-members")
if members then
local _, iface
local ifaces = { }
for _, iface in ipairs(members) do
ifaces[#ifaces+1] = interface(iface)
end
end
end
function interface.bridge_id(self)
if self.br then
return self.br.id
else
return nil
end
end
function interface.bridge_stp(self)
if self.br then
return self.br.stp
else
return false
end
end
function interface.is_up(self)
if self.wif then
return self.wif:is_up()
else
return self:_ubus("up") or false
end
end
function interface.is_bridge(self)
return (self:type() == "bridge")
end
function interface.is_bridgeport(self)
return self.dev and self.dev.bridge and true or false
end
function interface.tx_bytes(self)
local stat = self:_ubus("statistics")
return stat and stat.tx_bytes or 0
end
function interface.rx_bytes(self)
local stat = self:_ubus("statistics")
return stat and stat.rx_bytes or 0
end
function interface.tx_packets(self)
local stat = self:_ubus("statistics")
return stat and stat.tx_packets or 0
end
function interface.rx_packets(self)
local stat = self:_ubus("statistics")
return stat and stat.rx_packets or 0
end
function interface.get_network(self)
return self:get_networks()[1]
end
function interface.get_networks(self)
if not self.networks then
local nets = { }
local _, net
for _, net in ipairs(_M:get_networks()) do
if net:contains_interface(self.ifname) or
net:ifname() == self.ifname
then
nets[#nets+1] = net
end
end
table.sort(nets, function(a, b) return a.sid < b.sid end)
self.networks = nets
return nets
else
return self.networks
end
end
function interface.get_wifinet(self)
return self.wif
end
wifidev = utl.class()
function wifidev.__init__(self, dev)
self.sid = dev
self.iwinfo = dev and sys.wifi.getiwinfo(dev) or { }
end
function wifidev.get(self, opt)
return _get("wireless", self.sid, opt)
end
function wifidev.set(self, opt, val)
return _set("wireless", self.sid, opt, val)
end
function wifidev.name(self)
return self.sid
end
function wifidev.hwmodes(self)
local l = self.iwinfo.hwmodelist
if l and next(l) then
return l
else
return { b = true, g = true }
end
end
function wifidev.get_i18n(self)
local t = "Generic"
if self.iwinfo.type == "wl" then
t = "Broadcom"
elseif self.iwinfo.type == "madwifi" then
t = "Atheros"
end
local m = ""
local l = self:hwmodes()
if l.a then m = m .. "a" end
if l.b then m = m .. "b" end
if l.g then m = m .. "g" end
if l.n then m = m .. "n" end
return "%s 802.11%s Wireless Controller (%s)" %{ t, m, self:name() }
end
function wifidev.is_up(self)
local up = false
_uci_state:foreach("wireless", "wifi-iface",
function(s)
if s.device == self.sid then
if s.up == "1" then
up = true
return false
end
end
end)
return up
end
function wifidev.get_wifinet(self, net)
if _uci_real:get("wireless", net) == "wifi-iface" then
return wifinet(net)
else
local wnet = _wifi_lookup(net)
if wnet then
return wifinet(wnet)
end
end
end
function wifidev.get_wifinets(self)
local nets = { }
_uci_real:foreach("wireless", "wifi-iface",
function(s)
if s.device == self.sid then
nets[#nets+1] = wifinet(s['.name'])
end
end)
return nets
end
function wifidev.add_wifinet(self, options)
options = options or { }
options.device = self.sid
local wnet = _uci_real:section("wireless", "wifi-iface", nil, options)
if wnet then
return wifinet(wnet, options)
end
end
function wifidev.del_wifinet(self, net)
if utl.instanceof(net, wifinet) then
net = net.sid
elseif _uci_real:get("wireless", net) ~= "wifi-iface" then
net = _wifi_lookup(net)
end
if net and _uci_real:get("wireless", net, "device") == self.sid then
_uci_real:delete("wireless", net)
return true
end
return false
end
wifinet = utl.class()
function wifinet.__init__(self, net, data)
self.sid = net
local num = { }
local netid
_uci_real:foreach("wireless", "wifi-iface",
function(s)
if s.device then
num[s.device] = num[s.device] and num[s.device] + 1 or 1
if s['.name'] == self.sid then
netid = "%s.network%d" %{ s.device, num[s.device] }
return false
end
end
end)
local dev = _uci_state:get("wireless", self.sid, "ifname") or netid
self.netid = netid
self.wdev = dev
self.iwinfo = dev and sys.wifi.getiwinfo(dev) or { }
self.iwdata = data or _uci_state:get_all("wireless", self.sid) or
_uci_real:get_all("wireless", self.sid) or { }
end
function wifinet.get(self, opt)
return _get("wireless", self.sid, opt)
end
function wifinet.set(self, opt, val)
return _set("wireless", self.sid, opt, val)
end
function wifinet.mode(self)
return _uci_state:get("wireless", self.sid, "mode") or "ap"
end
function wifinet.ssid(self)
return _uci_state:get("wireless", self.sid, "ssid")
end
function wifinet.bssid(self)
return _uci_state:get("wireless", self.sid, "bssid")
end
function wifinet.network(self)
return _uci_state:get("wifinet", self.sid, "network")
end
function wifinet.id(self)
return self.netid
end
function wifinet.name(self)
return self.sid
end
function wifinet.ifname(self)
local ifname = self.iwinfo.ifname
if not ifname or ifname:match("^wifi%d") or ifname:match("^radio%d") then
ifname = self.wdev
end
return ifname
end
function wifinet.get_device(self)
if self.iwdata.device then
return wifidev(self.iwdata.device)
end
end
function wifinet.is_up(self)
return (self.iwdata.up == "1")
end
function wifinet.active_mode(self)
local m = _stror(self.iwinfo.mode, self.iwdata.mode) or "ap"
if m == "ap" then m = "Master"
elseif m == "sta" then m = "Client"
elseif m == "adhoc" then m = "Ad-Hoc"
elseif m == "mesh" then m = "Mesh"
elseif m == "monitor" then m = "Monitor"
end
return m
end
function wifinet.active_mode_i18n(self)
return lng.translate(self:active_mode())
end
function wifinet.active_ssid(self)
return _stror(self.iwinfo.ssid, self.iwdata.ssid)
end
function wifinet.active_bssid(self)
return _stror(self.iwinfo.bssid, self.iwdata.bssid) or "00:00:00:00:00:00"
end
function wifinet.active_encryption(self)
local enc = self.iwinfo and self.iwinfo.encryption
return enc and enc.description or "-"
end
function wifinet.assoclist(self)
return self.iwinfo.assoclist or { }
end
function wifinet.frequency(self)
local freq = self.iwinfo.frequency
if freq and freq > 0 then
return "%.03f" % (freq / 1000)
end
end
function wifinet.bitrate(self)
local rate = self.iwinfo.bitrate
if rate and rate > 0 then
return (rate / 1000)
end
end
function wifinet.channel(self)
return self.iwinfo.channel or
tonumber(_uci_state:get("wireless", self.iwdata.device, "channel"))
end
function wifinet.signal(self)
return self.iwinfo.signal or 0
end
function wifinet.noise(self)
return self.iwinfo.noise or 0
end
function wifinet.country(self)
return self.iwinfo.country or "00"
end
function wifinet.txpower(self)
local pwr = (self.iwinfo.txpower or 0)
return pwr + self:txpower_offset()
end
function wifinet.txpower_offset(self)
return self.iwinfo.txpower_offset or 0
end
function wifinet.signal_level(self, s, n)
if self:active_bssid() ~= "00:00:00:00:00:00" then
local signal = s or self:signal()
local noise = n or self:noise()
if signal < 0 and noise < 0 then
local snr = -1 * (noise - signal)
return math.floor(snr / 5)
else
return 0
end
else
return -1
end
end
function wifinet.signal_percent(self)
local qc = self.iwinfo.quality or 0
local qm = self.iwinfo.quality_max or 0
if qc > 0 and qm > 0 then
return math.floor((100 / qm) * qc)
else
return 0
end
end
function wifinet.shortname(self)
return "%s %q" %{
lng.translate(self:active_mode()),
self:active_ssid() or self:active_bssid()
}
end
function wifinet.get_i18n(self)
return "%s: %s %q (%s)" %{
lng.translate("Wireless Network"),
lng.translate(self:active_mode()),
self:active_ssid() or self:active_bssid(),
self:ifname()
}
end
function wifinet.adminlink(self)
return dsp.build_url("admin", "network", "wireless", self.netid)
end
function wifinet.get_network(self)
return self:get_networks()[1]
end
function wifinet.get_networks(self)
local nets = { }
local net
for net in utl.imatch(tostring(self.iwdata.network)) do
if _uci_real:get("network", net) == "interface" then
nets[#nets+1] = network(net)
end
end
table.sort(nets, function(a, b) return a.sid < b.sid end)
return nets
end
function wifinet.get_interface(self)
return interface(self:ifname())
end
-- setup base protocols
_M:register_protocol("static")
_M:register_protocol("dhcp")
_M:register_protocol("none")
-- load protocol extensions
local exts = nfs.dir(utl.libpath() .. "/model/network")
if exts then
local ext
for ext in exts do
if ext:match("%.lua$") then
require("luci.model.network." .. ext:gsub("%.lua$", ""))
end
end
end
| apache-2.0 |
emoon/docking_system | bin/win32/scripts/tundra/dagsave.lua | 25 | 10957 | module(..., package.seeall)
local depgraph = require "tundra.depgraph"
local util = require "tundra.util"
local scanner = require "tundra.scanner"
local dirwalk = require "tundra.dirwalk"
local platform = require "tundra.platform"
local native = require "tundra.native"
local njson = require "tundra.native.json"
local path = require "tundra.path"
local dag_dag_magic = 0x15890105
local function get_passes(nodes)
local result = {}
local seen_passes = {}
for _, node in ipairs(nodes) do
local p = node.pass
if not seen_passes[p] then
assert(type(p) == "table", "Passes must be tables, have " .. util.tostring(p))
assert(type(p.BuildOrder) == "number", "Pass BuildOrder must be a number")
result[#result + 1] = p
seen_passes[p] = true
end
end
table.sort(result, function (a, b) return a.BuildOrder < b.BuildOrder end)
local pass_lookup = {}
for index, pass in ipairs(result) do
pass_lookup[pass] = index - 1
end
return result, pass_lookup
end
local function setup_input_deps(nodes)
local producers = {}
local cwd = native.getcwd() .. SEP
local filter
if native.host_platform == 'windows' or native.host_platform == 'macosx' then
filter = function (str) return str:lower() end
else
filter = function (str) return str end
end
local node_deps = {}
-- Record producing node for all output files
for _, n in ipairs(nodes) do
for _, output in util.nil_ipairs(n.outputs) do
if not path.is_absolute(output) then
output = cwd .. output
end
output = filter(output)
if producers[output] then
errorf("file %s set to be written by more than one target:\n%s\n%s\n",
output, n.annotation, producers[output].annotation)
end
producers[output] = n
end
if n.deps then
node_deps[n] = util.make_lookup_table(n.deps)
end
end
-- Map input files to dependencies
for _, n in ipairs(nodes) do
for _, inputf in util.nil_ipairs(n.inputs) do
if not path.is_absolute(inputf) then
inputf = cwd .. inputf
end
inputf = filter(inputf)
local producer = producers[inputf]
local deps_lut = node_deps[n]
if producer and (not deps_lut or not deps_lut[producer]) then
n.deps[#n.deps + 1] = producer
if not deps_lut then
deps_lut = {}
node_deps[n] = deps_lut
end
deps_lut[producer] = true
end
end
end
end
local function get_scanners(nodes)
local scanners = {}
local scanner_to_index = {}
for _, node in ipairs(nodes) do
local scanner = node.scanner
if scanner and not scanner_to_index[scanner] then
scanner_to_index[scanner] = #scanners
scanners[#scanners + 1] = scanner
end
end
return scanners, scanner_to_index
end
local function save_passes(w, passes)
w:begin_array("Passes")
for _, s in ipairs(passes) do
w:write_string(s.Name)
end
w:end_array()
end
local function save_scanners(w, scanners)
w:begin_array("Scanners")
for _, s in ipairs(scanners) do
w:begin_object()
w:write_string(s.Kind, 'Kind')
w:begin_array("IncludePaths")
for _, path in util.nil_ipairs(s.Paths) do
w:write_string(path)
end
w:end_array()
-- Serialize specialized state for generic scanners
if s.Kind == 'generic' then
w:write_bool(s.RequireWhitespace, 'RequireWhitespace')
w:write_bool(s.UseSeparators, 'UseSeparators')
w:write_bool(s.BareMeansSystem, 'BareMeansSystem')
w:begin_array('Keywords')
for _, kw in util.nil_ipairs(s.Keywords) do
w:write_string(kw)
end
w:end_array()
w:begin_array('KeywordsNoFollow')
for _, kw in util.nil_ipairs(s.KeywordsNoFollow) do
w:write_string(kw)
end
w:end_array()
end
w:end_object()
end
w:end_array()
end
local function save_nodes(w, nodes, pass_to_index, scanner_to_index)
w:begin_array("Nodes")
for idx, node in ipairs(nodes) do
w:begin_object()
assert(idx - 1 == node.index)
if node.action then
w:write_string(node.action, "Action")
end
if node.preaction then
w:write_string(node.preaction, "PreAction")
end
w:write_string(node.annotation, "Annotation")
w:write_number(pass_to_index[node.pass], "PassIndex")
if #node.deps > 0 then
w:begin_array("Deps")
for _, dep in ipairs(node.deps) do
w:write_number(dep.index)
end
w:end_array()
end
local function dump_file_list(list, name)
if list and #list > 0 then
w:begin_array(name)
for _, fn in ipairs(list) do
w:write_string(fn)
end
w:end_array(name)
end
end
dump_file_list(node.inputs, "Inputs")
dump_file_list(node.outputs, "Outputs")
dump_file_list(node.aux_outputs, "AuxOutputs")
-- Save environment strings
local env_count = 0
for k, v in util.nil_pairs(node.env) do
env_count = env_count + 1
end
if env_count > 0 then
w:begin_array("Env")
for k, v in pairs(node.env) do
w:begin_object()
w:write_string(k, "Key")
w:write_string(v, "Value")
w:end_object()
end
w:end_array()
end
if node.scanner then
w:write_number(scanner_to_index[node.scanner], "ScannerIndex")
end
if node.overwrite_outputs then
w:write_bool(true, "OverwriteOutputs")
end
if node.is_precious then
w:write_bool(true, "PreciousOutputs")
end
if node.expensive then
w:write_bool(true, "Expensive")
end
w:end_object()
end
w:end_array()
end
local function save_configs(w, bindings, default_variant, default_subvariant)
local configs = {}
local variants = {}
local subvariants = {}
local config_index = {}
local variant_index = {}
local subvariant_index = {}
local default_config = nil
local host_platform = platform.host_platform()
for _, b in ipairs(bindings) do
if not configs[b.Config.Name] then
configs[b.Config.Name] = #config_index
config_index[#config_index+1] = b.Config.Name
end
if not variants[b.Variant.Name] then
variants[b.Variant.Name] = #variant_index
variant_index[#variant_index+1] = b.Variant.Name
end
if not subvariants[b.SubVariant] then
subvariants[b.SubVariant] = #subvariant_index
subvariant_index[#subvariant_index+1] = b.SubVariant
end
if b.Config.DefaultOnHost == host_platform then
default_config = b.Config
end
end
assert(#config_index > 0)
assert(#variant_index > 0)
assert(#subvariant_index > 0)
local function dump_str_array(array, name)
if array and #array > 0 then
w:begin_array(name)
for _, name in ipairs(array) do
w:write_string(name)
end
w:end_array()
end
end
w:begin_object("Setup")
dump_str_array(config_index, "Configs")
dump_str_array(variant_index, "Variants")
dump_str_array(subvariant_index, "SubVariants")
w:begin_array("BuildTuples")
for index, binding in ipairs(bindings) do
w:begin_object()
w:write_number(configs[binding.Config.Name], "ConfigIndex")
w:write_number(variants[binding.Variant.Name], "VariantIndex")
w:write_number(subvariants[binding.SubVariant], "SubVariantIndex")
local function store_node_index_array(nodes, name)
w:begin_array(name)
for _, node in util.nil_ipairs(nodes) do
w:write_number(node.index)
end
w:end_array()
end
store_node_index_array(binding.AlwaysNodes, "AlwaysNodes")
store_node_index_array(binding.DefaultNodes, "DefaultNodes")
w:begin_object("NamedNodes")
for name, node in pairs(binding.NamedNodes) do
w:write_number(node.index, name)
end
w:end_object()
w:end_object()
end
w:end_array()
-- m_DefaultBuildTuple
w:begin_object("DefaultBuildTuple")
if default_config then
w:write_number(configs[default_config.Name], "ConfigIndex")
else
w:write_number(-1, "ConfigIndex")
end
if default_variant then
w:write_number(variants[default_variant.Name], "VariantIndex")
else
w:write_number(-1, "VariantIndex")
end
if default_subvariant then
w:write_number(subvariants[default_subvariant], "SubVariantIndex")
else
w:write_number(-1, "SubVariantIndex")
end
w:end_object()
w:end_object()
end
local function save_signatures(w, accessed_lua_files)
w:begin_array("FileSignatures")
for _, fn in ipairs(accessed_lua_files) do
w:begin_object()
local stat = native.stat_file(fn)
if not stat.exists then
errorf("accessed file %s is gone: %s", fn, err)
end
w:write_string(fn, "File")
w:write_number(stat.timestamp, "Timestamp")
w:end_object()
end
w:end_array()
w:begin_array("GlobSignatures")
local globs = dirwalk.all_queries()
for _, glob in ipairs(globs) do
w:begin_object()
w:write_string(glob.Path, "Path")
w:begin_array("Files")
for _, fn in ipairs(glob.Files) do w:write_string(fn) end
w:end_array()
w:begin_array("SubDirs")
for _, fn in ipairs(glob.SubDirs) do w:write_string(fn) end
w:end_array()
w:end_object()
end
w:end_array()
end
local function check_deps(nodes)
for _, node in ipairs(nodes) do
for _ , dep in ipairs(node.deps) do
if dep.pass.BuildOrder > node.pass.BuildOrder then
errorf("%s (pass: %s) depends on %s in later pass (%s)", node.annotation, node.pass.Name, dep.annotation, dep.pass.Name)
end
end
end
end
function save_dag_data(bindings, default_variant, default_subvariant, content_digest_exts, misc_options)
-- Call builtin function to get at accessed file table
local accessed_lua_files = util.table_keys(get_accessed_files())
misc_options = misc_options or {}
local max_expensive_jobs = misc_options.MaxExpensiveJobs or -1
printf("save_dag_data: %d bindings, %d accessed files", #bindings, #accessed_lua_files)
local nodes = depgraph.get_all_nodes()
-- Set node indices
for idx, node in ipairs(nodes) do
node.index = idx - 1
end
-- Set up array of passes
local passes, pass_to_index = get_passes(nodes)
-- Hook up dependencies due to input files
setup_input_deps(nodes)
check_deps(nodes)
-- Find scanners
local scanners, scanner_to_index = get_scanners(nodes)
local w = njson.new('.tundra2.dag.json')
w:begin_object()
save_configs(w, bindings, default_variant, default_subvariant)
save_passes(w, passes)
save_scanners(w, scanners)
save_nodes(w, nodes, pass_to_index, scanner_to_index)
save_signatures(w, accessed_lua_files)
if content_digest_exts and #content_digest_exts > 0 then
w:begin_array("ContentDigestExtensions")
for _, ext in ipairs(content_digest_exts) do
w:write_string(ext)
end
w:end_array()
end
w:write_number(max_expensive_jobs, "MaxExpensiveCount")
w:end_object()
w:close()
end
| bsd-3-clause |
dkogan/notion | contrib/scripts/net_client_list.lua | 7 | 2805 | -- Authors: Etan Reisner <deryni@gmail.com>
-- License: MIT, see http://opensource.org/licenses/mit-license.php
-- Last Changed: 2007-07-22
--
--[[
Author: Etan Reisner
Email: deryni@unreliablesource.net
Summary: Maintains the _NET_CLIENT_LIST property (and the _NET_CLIENT_LIST_STACKING property incorrectly) on the root window.
Last Updated: 2007-07-22
Copyright (c) Etan Reisner 2007
This software is released under the terms of the MIT license. For more
information, see http://opensource.org/licenses/mit-license.php .
--]]
local atom_window = ioncore.x_intern_atom("WINDOW", false)
local atom_client_list = ioncore.x_intern_atom("_NET_CLIENT_LIST", false)
local atom_client_list_stacking = ioncore.x_intern_atom("_NET_CLIENT_LIST_STACKING", false)
local function add_client(cwin)
if not cwin then
return
end
local rootwin = cwin:rootwin_of()
local list = {n=0}
ioncore.clientwin_i(function (cwin)
list.n = list.n + 1
list[list.n] = cwin:xid()
return true
end)
list.n = nil
ioncore.x_change_property(rootwin:xid(), atom_client_list, atom_window,
32, "replace", list)
ioncore.x_change_property(rootwin:xid(), atom_client_list_stacking,
atom_window, 32, "replace", list)
end
local function remove_client(xid)
local rootwin = ioncore.current():rootwin_of()
local list = {n=0}
ioncore.clientwin_i(function (cwin)
list.n = list.n + 1
list[list.n] = cwin:xid()
return true
end)
list.n = nil
ioncore.x_change_property(rootwin:xid(), atom_client_list, atom_window,
32, "replace", list)
ioncore.x_change_property(rootwin:xid(), atom_client_list_stacking,
atom_window, 32, "replace", list)
end
local function net_mark_supported(atom)
if (ioncore.rootwin) then
local rootwin = ioncore.rootwin()
local atom_atom = ioncore.x_intern_atom("ATOM", false)
local atom_net_supported = ioncore.x_intern_atom("_NET_SUPPORTED", false)
ioncore.x_change_property(rootwin:xid(), atom_net_supported, atom_atom,
32, "append", {atom})
end
end
add_client(ioncore.current())
do
local hook
hook = ioncore.get_hook("clientwin_mapped_hook")
if hook then
hook:add(add_client)
end
hook = nil
hook = ioncore.get_hook("clientwin_unmapped_hook")
if hook then
hook:add(remove_client)
end
net_mark_supported(atom_client_list);
end
| lgpl-2.1 |
rpetit3/darkstar | scripts/globals/mobskills/Pyric_Blast.lua | 33 | 1323 | ---------------------------------------------
-- Pyric Blast
--
-- Description: Deals Fire damage to enemies within a fan-shaped area. Additional effect: Plague
-- Type: Breath
-- Ignores Shadows
-- Range: Unknown Cone
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if(mob:getFamily() == 316) then
local mobSkin = mob:getModelId();
if (mobSkin == 1796) then
return 0;
else
return 1;
end
end
if (mob:AnimationSub() == 0) then
return 0;
else
return 1;
end
end;
function onMobWeaponSkill(target, mob, skill)
local dmgmod = MobBreathMove(mob, target, 0.01, 0.1, ELE_FIRE, 700);
local dmg = MobFinalAdjustments(dmgmod,mob,skill,target,MOBSKILL_BREATH,MOBPARAM_FIRE,MOBPARAM_IGNORE_SHADOWS);
MobStatusEffectMove(mob, target, EFFECT_PLAGUE, 5, 3, 60);
target:delHP(dmg);
if (mob:getFamily() == 313 and bit.band(mob:getBehaviour(),BEHAVIOUR_NO_TURN) == 0) then -- re-enable no turn if all three heads are up
mob:setBehaviour(bit.bor(mob:getBehaviour(), BEHAVIOUR_NO_TURN))
end
return dmg;
end;
| gpl-3.0 |
esguk811/DarkRP | gamemode/modules/doorsystem/cl_doors.lua | 5 | 5557 | local meta = FindMetaTable("Entity")
local black = Color(0, 0, 0, 255)
local white = Color(255, 255, 255, 200)
local red = Color(128, 30, 30, 255)
function meta:drawOwnableInfo()
if LocalPlayer():InVehicle() then return end
-- Look, if you want to change the way door ownership is drawn, don't edit this file, use the hook instead!
local doorDrawing = hook.Call("HUDDrawDoorData", nil, self)
if doorDrawing == true then return end
local blocked = self:getKeysNonOwnable()
local superadmin = LocalPlayer():IsSuperAdmin()
local doorTeams = self:getKeysDoorTeams()
local doorGroup = self:getKeysDoorGroup()
local playerOwned = self:isKeysOwned() or table.GetFirstValue(self:getKeysCoOwners() or {}) ~= nil
local owned = playerOwned or doorGroup or doorTeams
local doorInfo = {}
local title = self:getKeysTitle()
if title then table.insert(doorInfo, title) end
if owned then
table.insert(doorInfo, DarkRP.getPhrase("keys_owned_by"))
end
if playerOwned then
if self:isKeysOwned() then table.insert(doorInfo, self:getDoorOwner():Nick()) end
for k,v in pairs(self:getKeysCoOwners() or {}) do
local ent = Player(k)
if not IsValid(ent) or not ent:IsPlayer() then continue end
table.insert(doorInfo, ent:Nick())
end
local allowedCoOwn = self:getKeysAllowedToOwn()
if allowedCoOwn and not fn.Null(allowedCoOwn) then
table.insert(doorInfo, DarkRP.getPhrase("keys_other_allowed"))
for k,v in pairs(allowedCoOwn) do
local ent = Player(k)
if not IsValid(ent) or not ent:IsPlayer() then continue end
table.insert(doorInfo, ent:Nick())
end
end
elseif doorGroup then
table.insert(doorInfo, doorGroup)
elseif doorTeams then
for k, v in pairs(doorTeams) do
if not v or not RPExtraTeams[k] then continue end
table.insert(doorInfo, RPExtraTeams[k].name)
end
elseif blocked and superadmin then
table.insert(doorInfo, DarkRP.getPhrase("keys_allow_ownership"))
elseif not blocked then
table.insert(doorInfo, DarkRP.getPhrase("keys_unowned"))
if superadmin then
table.insert(doorInfo, DarkRP.getPhrase("keys_disallow_ownership"))
end
end
if self:IsVehicle() then
for k,v in pairs(player.GetAll()) do
if v:GetVehicle() ~= self then continue end
table.insert(doorInfo, DarkRP.getPhrase("driver", v:Nick()))
break
end
end
local x, y = ScrW() / 2, ScrH() / 2
draw.DrawNonParsedText(table.concat(doorInfo, "\n"), "TargetID", x , y + 1 , black, 1)
draw.DrawNonParsedText(table.concat(doorInfo, "\n"), "TargetID", x, y, (blocked or owned) and white or red, 1)
end
--[[---------------------------------------------------------------------------
Door data
---------------------------------------------------------------------------]]
DarkRP.doorData = DarkRP.doorData or {}
--[[---------------------------------------------------------------------------
Interface functions
---------------------------------------------------------------------------]]
function meta:getDoorData()
local doorData = DarkRP.doorData[self:EntIndex()] or {}
self.DoorData = doorData -- Backwards compatibility
return doorData
end
--[[---------------------------------------------------------------------------
Networking
---------------------------------------------------------------------------]]
--[[---------------------------------------------------------------------------
Retrieve all the data for all doors
---------------------------------------------------------------------------]]
local function retrieveAllDoorData(len)
local count = net.ReadUInt(16)
for i = 1, count do
local ix = net.ReadUInt(16)
local varCount = net.ReadUInt(8)
DarkRP.doorData[ix] = DarkRP.doorData[ix] or {}
for vc = 1, varCount do
local name, value = DarkRP.readNetDoorVar()
DarkRP.doorData[ix][name] = value
end
end
end
net.Receive("DarkRP_AllDoorData", retrieveAllDoorData)
--[[---------------------------------------------------------------------------
Update changed variables
---------------------------------------------------------------------------]]
local function updateDoorData()
local door = net.ReadUInt(32)
DarkRP.doorData[door] = DarkRP.doorData[door] or {}
local var, value = DarkRP.readNetDoorVar()
DarkRP.doorData[door][var] = value
end
net.Receive("DarkRP_UpdateDoorData", updateDoorData)
--[[---------------------------------------------------------------------------
Set a value of a single doorvar to nil
---------------------------------------------------------------------------]]
local function removeDoorVar()
local door = net.ReadUInt(16)
local id = net.ReadUInt(8)
local name = id == 0 and net.ReadString() or DarkRP.getDoorVars()[id].name
if not DarkRP.doorData[door] then return end
DarkRP.doorData[door][name] = nil
end
net.Receive("DarkRP_RemoveDoorVar", removeDoorVar)
--[[---------------------------------------------------------------------------
Remove doordata of removed entity
---------------------------------------------------------------------------]]
local function removeDoorData()
local door = net.ReadUInt(32)
DarkRP.doorData[door] = nil
end
net.Receive("DarkRP_RemoveDoorData", removeDoorData)
| mit |
rpetit3/darkstar | scripts/zones/Ordelles_Caves/npcs/qm3.lua | 13 | 1628 | -----------------------------------
-- Area: Ordelle's Caves
-- NPC: ??? (qm3)
-- Involved in Quest: A Squire's Test II
-- @pos -139 0.1 264 193
-------------------------------------
package.loaded["scripts/zones/Ordelles_Caves/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Ordelles_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (os.time() - player:getVar("SquiresTestII") <= 60 and player:hasKeyItem(STALACTITE_DEW) == false) then
player:messageSpecial(A_SQUIRE_S_TEST_II_DIALOG_II);
player:addKeyItem(STALACTITE_DEW);
player:messageSpecial(KEYITEM_OBTAINED, STALACTITE_DEW);
player:setVar("SquiresTestII",0);
elseif (player:hasKeyItem(STALACTITE_DEW)) then
player:messageSpecial(A_SQUIRE_S_TEST_II_DIALOG_III);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
player:setVar("SquiresTestII",0);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
tinchoss/Python_Android | lua/json4lua/json/json.lua | 3 | 15375 | -----------------------------------------------------------------------------
-- JSON4Lua: JSON encoding / decoding support for the Lua language.
-- json Module.
-- Author: Craig Mason-Jones
-- Homepage: http://json.luaforge.net/
-- Version: 0.9.20
-- This module is released under the The GNU General Public License (GPL).
-- Please see LICENCE.txt for details.
--
-- USAGE:
-- This module exposes two functions:
-- encode(o)
-- Returns the table / string / boolean / number / nil / json.null value as a JSON-encoded string.
-- decode(json_string)
-- Returns a Lua object populated with the data encoded in the JSON string json_string.
--
-- REQUIREMENTS:
-- compat-5.1 if using Lua 5.0
--
-- CHANGELOG
-- 0.9.20 Introduction of local Lua functions for private functions (removed _ function prefix).
-- Fixed Lua 5.1 compatibility issues.
-- Introduced json.null to have null values in associative arrays.
-- encode() performance improvement (more than 50%) through table.concat rather than ..
-- Introduced decode ability to ignore /**/ comments in the JSON string.
-- 0.9.10 Fix to array encoding / decoding to correctly manage nil/null values in arrays.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Imports and dependencies
-----------------------------------------------------------------------------
local math = require('math')
local string = require("string")
local table = require("table")
local base = _G
-----------------------------------------------------------------------------
-- Module declaration
-----------------------------------------------------------------------------
module("json")
-- Public functions
-- Private functions
local decode_scanArray
local decode_scanComment
local decode_scanConstant
local decode_scanNumber
local decode_scanObject
local decode_scanString
local decode_scanWhitespace
local encodeString
local isArray
local isEncodable
-----------------------------------------------------------------------------
-- PUBLIC FUNCTIONS
-----------------------------------------------------------------------------
--- Encodes an arbitrary Lua object / variable.
-- @param v The Lua object / variable to be JSON encoded.
-- @return String containing the JSON encoding in internal Lua string format (i.e. not unicode)
function encode (v)
-- Handle nil values
if v==nil then
return "null"
end
local vtype = base.type(v)
-- Handle strings
if vtype=='string' then
return '"' .. encodeString(v) .. '"' -- Need to handle encoding in string
end
-- Handle booleans
if vtype=='number' or vtype=='boolean' then
return base.tostring(v)
end
-- Handle tables
if vtype=='table' then
local rval = {}
-- Consider arrays separately
local bArray, maxCount = isArray(v)
if bArray then
for i = 1,maxCount do
table.insert(rval, encode(v[i]))
end
else -- An object, not an array
for i,j in base.pairs(v) do
if isEncodable(i) and isEncodable(j) then
table.insert(rval, '"' .. encodeString(i) .. '":' .. encode(j))
end
end
end
if bArray then
return '[' .. table.concat(rval,',') ..']'
else
return '{' .. table.concat(rval,',') .. '}'
end
end
-- Handle null values
if vtype=='function' and v==null then
return 'null'
end
base.assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. base.tostring(v))
end
--- Decodes a JSON string and returns the decoded value as a Lua data structure / value.
-- @param s The string to scan.
-- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1.
-- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil,
-- and the position of the first character after
-- the scanned JSON object.
function decode(s, startPos)
startPos = startPos and startPos or 1
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']')
local curChar = string.sub(s,startPos,startPos)
-- Object
if curChar=='{' then
return decode_scanObject(s,startPos)
end
-- Array
if curChar=='[' then
return decode_scanArray(s,startPos)
end
-- Number
if string.find("+-0123456789.eE", curChar, 1, true) then
return decode_scanNumber(s,startPos)
end
-- String
if curChar==[["]] or curChar==[[']] then
return decode_scanString(s,startPos)
end
if string.sub(s,startPos,startPos+1)=='/*' then
return decode(s, decode_scanComment(s,startPos))
end
-- Otherwise, it must be a constant
return decode_scanConstant(s,startPos)
end
--- The null function allows one to specify a null value in an associative array (which is otherwise
-- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null }
function null()
return null -- so json.null() will also return null ;-)
end
-----------------------------------------------------------------------------
-- Internal, PRIVATE functions.
-- Following a Python-like convention, I have prefixed all these 'PRIVATE'
-- functions with an underscore.
-----------------------------------------------------------------------------
--- Scans an array from JSON into a Lua object
-- startPos begins at the start of the array.
-- Returns the array and the next starting position
-- @param s The string being scanned.
-- @param startPos The starting position for the scan.
-- @return table, int The scanned array as a table, and the position of the next character to scan.
function decode_scanArray(s,startPos)
local array = {} -- The return value
local stringLen = string.len(s)
base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s )
startPos = startPos + 1
-- Infinite loop for array elements
repeat
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.')
local curChar = string.sub(s,startPos,startPos)
if (curChar==']') then
return array, startPos+1
end
if (curChar==',') then
startPos = decode_scanWhitespace(s,startPos+1)
end
base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.')
object, startPos = decode(s,startPos)
table.insert(array,object)
until false
end
--- Scans a comment and discards the comment.
-- Returns the position of the next character following the comment.
-- @param string s The JSON string to scan.
-- @param int startPos The starting position of the comment
function decode_scanComment(s, startPos)
base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos)
local endPos = string.find(s,'*/',startPos+2)
base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos)
return endPos+2
end
--- Scans for given constants: true, false or null
-- Returns the appropriate Lua type, and the position of the next character to read.
-- @param s The string being scanned.
-- @param startPos The position in the string at which to start scanning.
-- @return object, int The object (true, false or nil) and the position at which the next character should be
-- scanned.
function decode_scanConstant(s, startPos)
local consts = { ["true"] = true, ["false"] = false, ["null"] = nil }
local constNames = {"true","false","null"}
for i,k in base.pairs(constNames) do
--print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k)
if string.sub(s,startPos, startPos + string.len(k) -1 )==k then
return consts[k], startPos + string.len(k)
end
end
base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos)
end
--- Scans a number from the JSON encoded string.
-- (in fact, also is able to scan numeric +- eqns, which is not
-- in the JSON spec.)
-- Returns the number, and the position of the next character
-- after the number.
-- @param s The string being scanned.
-- @param startPos The position at which to start scanning.
-- @return number, int The extracted number and the position of the next character to scan.
function decode_scanNumber(s,startPos)
local endPos = startPos+1
local stringLen = string.len(s)
local acceptableChars = "+-0123456789.eE"
while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true)
and endPos<=stringLen
) do
endPos = endPos + 1
end
local stringValue = 'return ' .. string.sub(s,startPos, endPos-1)
local stringEval = base.loadstring(stringValue)
base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos)
return stringEval(), endPos
end
--- Scans a JSON object into a Lua object.
-- startPos begins at the start of the object.
-- Returns the object and the next starting position.
-- @param s The string being scanned.
-- @param startPos The starting position of the scan.
-- @return table, int The scanned object as a table and the position of the next character to scan.
function decode_scanObject(s,startPos)
local object = {}
local stringLen = string.len(s)
local key, value
base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s)
startPos = startPos + 1
repeat
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.')
local curChar = string.sub(s,startPos,startPos)
if (curChar=='}') then
return object,startPos+1
end
if (curChar==',') then
startPos = decode_scanWhitespace(s,startPos+1)
end
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.')
-- Scan the key
key, startPos = decode(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos)
startPos = decode_scanWhitespace(s,startPos+1)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
value, startPos = decode(s,startPos)
object[key]=value
until false -- infinite loop while key-value pairs are found
end
--- Scans a JSON string from the opening inverted comma or single quote to the
-- end of the string.
-- Returns the string extracted as a Lua string,
-- and the position of the next non-string character
-- (after the closing inverted comma or single quote).
-- @param s The string being scanned.
-- @param startPos The starting position of the scan.
-- @return string, int The extracted string as a Lua string, and the next character to parse.
function decode_scanString(s,startPos)
base.assert(startPos, 'decode_scanString(..) called without start position')
local startChar = string.sub(s,startPos,startPos)
base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string')
local escaped = false
local endPos = startPos + 1
local bEnded = false
local stringLen = string.len(s)
repeat
local curChar = string.sub(s,endPos,endPos)
if not escaped then
if curChar==[[\]] then
escaped = true
else
bEnded = curChar==startChar
end
else
-- If we're escaped, we accept the current character come what may
escaped = false
end
endPos = endPos + 1
base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos)
until bEnded
local stringValue = 'return ' .. string.sub(s, startPos, endPos-1)
local stringEval = base.loadstring(stringValue)
base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos)
return stringEval(), endPos
end
--- Scans a JSON string skipping all whitespace from the current start position.
-- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached.
-- @param s The string being scanned
-- @param startPos The starting position where we should begin removing whitespace.
-- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string
-- was reached.
function decode_scanWhitespace(s,startPos)
local whitespace=" \n\r\t"
local stringLen = string.len(s)
while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do
startPos = startPos + 1
end
return startPos
end
--- Encodes a string to be JSON-compatible.
-- This just involves back-quoting inverted commas, back-quotes and newlines, I think ;-)
-- @param s The string to return as a JSON encoded (i.e. backquoted string)
-- @return The string appropriately escaped.
function encodeString(s)
s = string.gsub(s,'\\','\\\\')
s = string.gsub(s,'"','\\"')
s = string.gsub(s,"'","\\'")
s = string.gsub(s,'\n','\\n')
s = string.gsub(s,'\t','\\t')
return s
end
-- Determines whether the given Lua type is an array or a table / dictionary.
-- We consider any table an array if it has indexes 1..n for its n items, and no
-- other data in the table.
-- I think this method is currently a little 'flaky', but can't think of a good way around it yet...
-- @param t The table to evaluate as an array
-- @return boolean, number True if the table can be represented as an array, false otherwise. If true,
-- the second returned value is the maximum
-- number of indexed elements in the array.
function isArray(t)
-- Next we count all the elements, ensuring that any non-indexed elements are not-encodable
-- (with the possible exception of 'n')
local maxIndex = 0
for k,v in base.pairs(t) do
if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair
if (not isEncodable(v)) then return false end -- All array elements must be encodable
maxIndex = math.max(maxIndex,k)
else
if (k=='n') then
if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements
else -- Else of (k=='n')
if isEncodable(v) then return false end
end -- End of (k~='n')
end -- End of k,v not an indexed pair
end -- End of loop across all pairs
return true, maxIndex
end
--- Determines whether the given Lua object / table / variable can be JSON encoded. The only
-- types that are JSON encodable are: string, boolean, number, nil, table and json.null.
-- In this implementation, all other types are ignored.
-- @param o The object to examine.
-- @return boolean True if the object should be JSON encoded, false if it should be ignored.
function isEncodable(o)
local t = base.type(o)
return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null)
end
| apache-2.0 |
rpetit3/darkstar | scripts/globals/items/plate_of_fin_sushi_+1.lua | 18 | 1476 | -----------------------------------------
-- ID: 5666
-- Item: plate_of_fin_sushi_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Intelligence 5
-- Accuracy % 17
-- Ranged Accuracy % 17
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5666);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_INT, 5);
target:addMod(MOD_FOOD_ACCP, 17);
target:addMod(MOD_FOOD_ACC_CAP, 999);
target:addMod(MOD_FOOD_RACCP, 17);
target:addMod(MOD_FOOD_RACC_CAP, 999);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_INT, 5);
target:delMod(MOD_FOOD_ACCP, 17);
target:delMod(MOD_FOOD_ACC_CAP, 999);
target:delMod(MOD_FOOD_RACCP, 17);
target:delMod(MOD_FOOD_RACC_CAP, 999);
end;
| gpl-3.0 |
lexa/awesome | lib/gears/color.lua | 5 | 10347 | ---------------------------------------------------------------------------
-- @author Uli Schlachter
-- @copyright 2010 Uli Schlachter
-- @release @AWESOME_VERSION@
-- @module gears.color
---------------------------------------------------------------------------
local setmetatable = setmetatable
local string = string
local table = table
local unpack = unpack or table.unpack -- v5.1: unpack, v5.2: table.unpack
local tonumber = tonumber
local ipairs = ipairs
local pairs = pairs
local type = type
local cairo = require("lgi").cairo
local surface = require("gears.surface")
local color = { mt = {} }
local pattern_cache = setmetatable({}, { __mode = 'v' })
--- Parse a HTML-color.
-- This function can parse colors like `#rrggbb` and `#rrggbbaa`.
-- Thanks to #lua for this. :)
--
-- @param col The color to parse
-- @return 4 values which each are in the range [0, 1].
-- @usage -- This will return 0, 1, 0, 1
-- gears.color.parse_color("#00ff00ff")
function color.parse_color(col)
local rgb = {}
for pair in string.gmatch(col, "[^#].") do
local i = tonumber(pair, 16)
if i then
table.insert(rgb, i / 255)
end
end
while #rgb < 4 do
table.insert(rgb, 1)
end
return unpack(rgb)
end
--- Find all numbers in a string
--
-- @tparam string s The string to parse
-- @return Each number found as a separate value
local function parse_numbers(s)
local res = {}
for k in string.gmatch(s, "-?[0-9]+[.]?[0-9]*") do
table.insert(res, tonumber(k))
end
return unpack(res)
end
--- Create a solid pattern
--
-- @param col The color for the pattern
-- @return A cairo pattern object
function color.create_solid_pattern(col)
local col = col
if col == nil then
col = "#000000"
elseif type(col) == "table" then
col = col.color
end
return cairo.Pattern.create_rgba(color.parse_color(col))
end
--- Create an image pattern from a png file
--
-- @param file The filename of the file
-- @return a cairo pattern object
function color.create_png_pattern(file)
local file = file
if type(file) == "table" then
file = file.file
end
local image = surface.load(file)
local pattern = cairo.Pattern.create_for_surface(image)
pattern:set_extend(cairo.Extend.REPEAT)
return pattern
end
--- Add stops to the given pattern.
-- @param p The cairo pattern to add stops to
-- @param iterator An iterator that returns strings. Each of those strings
-- should be in the form place,color where place is in [0, 1].
local function add_iterator_stops(p, iterator)
for k in iterator do
local sub = string.gmatch(k, "[^,]+")
local point, clr = sub(), sub()
p:add_color_stop_rgba(point, color.parse_color(clr))
end
end
--- Add a list of stops to a given pattern
local function add_stops_table(pat, arg)
for _, stop in ipairs(arg) do
pat:add_color_stop_rgba(stop[1], color.parse_color(stop[2]))
end
end
--- Create a pattern from a string
local function string_pattern(creator, arg)
local iterator = string.gmatch(arg, "[^:]+")
-- Create a table where each entry is a number from the original string
local args = { parse_numbers(iterator()) }
local to = { parse_numbers(iterator()) }
-- Now merge those two tables
for k, v in pairs(to) do
table.insert(args, v)
end
-- And call our creator function with the values
local p = creator(unpack(args))
add_iterator_stops(p, iterator)
return p
end
--- Create a linear pattern object.
-- The pattern is created from a string. This string should have the following
-- form: `"x0, y0:x1, y1:<stops>"`
-- Alternatively, the pattern can be specified as a table:
-- { type = "linear", from = { x0, y0 }, to = { x1, y1 },
-- stops = { <stops> } }
-- `x0,y0` and `x1,y1` are the start and stop point of the pattern.
-- For the explanation of `<stops>`, see `color.create_pattern`.
-- @tparam string|table arg The argument describing the pattern.
-- @return a cairo pattern object
function color.create_linear_pattern(arg)
local pat
if type(arg) == "string" then
return string_pattern(cairo.Pattern.create_linear, arg)
elseif type(arg) ~= "table" then
error("Wrong argument type: " .. type(arg))
end
pat = cairo.Pattern.create_linear(arg.from[1], arg.from[2], arg.to[1], arg.to[2])
add_stops_table(pat, arg.stops)
return pat
end
--- Create a radial pattern object.
-- The pattern is created from a string. This string should have the following
-- form: `"x0, y0, r0:x1, y1, r1:<stops>"`
-- Alternatively, the pattern can be specified as a table:
-- { type = "radial", from = { x0, y0, r0 }, to = { x1, y1, r1 },
-- stops = { <stops> } }
-- `x0,y0` and `x1,y1` are the start and stop point of the pattern.
-- `r0` and `r1` are the radii of the start / stop circle.
-- For the explanation of `<stops>`, see `color.create_pattern`.
-- @tparam string|table arg The argument describing the pattern
-- @return a cairo pattern object
function color.create_radial_pattern(arg)
local pat
if type(arg) == "string" then
return string_pattern(cairo.Pattern.create_radial, arg)
elseif type(arg) ~= "table" then
error("Wrong argument type: " .. type(arg))
end
pat = cairo.Pattern.create_radial(arg.from[1], arg.from[2], arg.from[3],
arg.to[1], arg.to[2], arg.to[3])
add_stops_table(pat, arg.stops)
return pat
end
--- Mapping of all supported color types. New entries can be added.
color.types = {
solid = color.create_solid_pattern,
png = color.create_png_pattern,
linear = color.create_linear_pattern,
radial = color.create_radial_pattern
}
--- Create a pattern from a given string.
-- For full documentation of this function, please refer to
-- `color.create_pattern`. The difference between `color.create_pattern`
-- and this function is that this function does not insert the generated
-- objects into the pattern cache. Thus, you are allowed to modify the
-- returned object.
-- @see create_pattern
-- @param col The string describing the pattern.
-- @return a cairo pattern object
function color.create_pattern_uncached(col)
-- If it already is a cairo pattern, just leave it as that
if cairo.Pattern:is_type_of(col) then
return col
end
local col = col or "#000000"
if type(col) == "string" then
local t = string.match(col, "[^:]+")
if color.types[t] then
local pos = string.len(t)
local arg = string.sub(col, pos + 2)
return color.types[t](arg)
end
elseif type(col) == "table" then
local t = col.type
if color.types[t] then
return color.types[t](col)
end
end
return color.create_solid_pattern(col)
end
--- Create a pattern from a given string.
-- This function can create solid, linear, radial and png patterns. In general,
-- patterns are specified as strings formatted as"type:arguments". "arguments"
-- is specific to the pattern used. For example, one can use
-- "radial:50,50,10:55,55,30:0,#ff0000:0.5,#00ff00:1,#0000ff"
-- Alternatively, patterns can be specified via tables. In this case, the
-- table's 'type' member specifies the type. For example:
-- { type = "radial", from = { 50, 50, 10 }, to = { 55, 55, 30 },
-- stops = { { 0, "#ff0000" }, { 0.5, "#00ff00" }, { 1, "#0000ff" } } }
-- Any argument that cannot be understood is passed to @{create_solid_pattern}.
--
-- Please note that you MUST NOT modify the returned pattern, for example by
-- calling :set_matrix() on it, because this function uses a cache and your
-- changes could thus have unintended side effects. Use @{create_pattern_uncached}
-- if you need to modify the returned pattern.
-- @see create_pattern_uncached, create_solid_pattern, create_png_pattern,
-- create_linear_pattern, create_radial_pattern
-- @param col The string describing the pattern.
-- @return a cairo pattern object
function color.create_pattern(col)
-- If it already is a cairo pattern, just leave it as that
if cairo.Pattern:is_type_of(col) then
return col
end
local col = col or "#000000"
local result = pattern_cache[col]
if not result then
result = color.create_pattern_uncached(col)
pattern_cache[col] = result
end
return result
end
--- Check if a pattern is opaque.
-- A pattern is transparent if the background on which it gets drawn (with
-- operator OVER) doesn't influence the visual result.
-- @param col An argument that `create_pattern` accepts.
-- @return The pattern if it is surely opaque, else nil
function color.create_opaque_pattern(col)
local pattern = color.create_pattern(col)
local type = pattern:get_type()
local extend = pattern:get_extend()
if type == "SOLID" then
local status, r, g, b, a = pattern:get_rgba()
if a ~= 1 then
return
end
return pattern
elseif type == "SURFACE" then
local status, surface = pattern:get_surface()
if status ~= "SUCCESS" or surface.content ~= "COLOR" then
-- The surface has an alpha channel which *might* be non-opaque
return
end
-- Only the "NONE" extend mode is forbidden, everything else doesn't
-- introduce transparent parts
if pattern:get_extend() == "NONE" then
return
end
return pattern
elseif type == "LINEAR" then
local status, stops = pattern:get_color_stop_count()
-- No color stops or extend NONE -> pattern *might* contain transparency
if stops == 0 or pattern:get_extend() == "NONE" then
return
end
-- Now check if any of the color stops contain transparency
for i = 0, stops - 1 do
local status, offset, r, g, b, a = pattern:get_color_stop_rgba(i)
if a ~= 1 then
return
end
end
return pattern
end
-- Unknown type, e.g. mesh or raster source or unsupported type (radial
-- gradients can do weird self-intersections)
end
function color.mt:__call(...)
return color.create_pattern(...)
end
return setmetatable(color, color.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
atkinson137/lootmasterplus | Libs/AceGUI-3.0/widgets/AceGUIWidget-Label.lua | 46 | 4441 | --[[-----------------------------------------------------------------------------
Label Widget
Displays text and optionally an icon.
-------------------------------------------------------------------------------]]
local Type, Version = "Label", 23
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local max, select, pairs = math.max, select, pairs
-- WoW APIs
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: GameFontHighlightSmall
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function UpdateImageAnchor(self)
if self.resizing then return end
local frame = self.frame
local width = frame.width or frame:GetWidth() or 0
local image = self.image
local label = self.label
local height
label:ClearAllPoints()
image:ClearAllPoints()
if self.imageshown then
local imagewidth = image:GetWidth()
if (width - imagewidth) < 200 or (label:GetText() or "") == "" then
-- image goes on top centered when less than 200 width for the text, or if there is no text
image:SetPoint("TOP")
label:SetPoint("TOP", image, "BOTTOM")
label:SetPoint("LEFT")
label:SetWidth(width)
height = image:GetHeight() + label:GetHeight()
else
-- image on the left
image:SetPoint("TOPLEFT")
if image:GetHeight() > label:GetHeight() then
label:SetPoint("LEFT", image, "RIGHT", 4, 0)
else
label:SetPoint("TOPLEFT", image, "TOPRIGHT", 4, 0)
end
label:SetWidth(width - imagewidth - 4)
height = max(image:GetHeight(), label:GetHeight())
end
else
-- no image shown
label:SetPoint("TOPLEFT")
label:SetWidth(width)
height = label:GetHeight()
end
self.resizing = true
frame:SetHeight(height)
frame.height = height
self.resizing = nil
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
-- set the flag to stop constant size updates
self.resizing = true
-- height is set dynamically by the text and image size
self:SetWidth(200)
self:SetText()
self:SetImage(nil)
self:SetImageSize(16, 16)
self:SetColor()
self:SetFontObject()
-- reset the flag
self.resizing = nil
-- run the update explicitly
UpdateImageAnchor(self)
end,
-- ["OnRelease"] = nil,
["OnWidthSet"] = function(self, width)
UpdateImageAnchor(self)
end,
["SetText"] = function(self, text)
self.label:SetText(text)
UpdateImageAnchor(self)
end,
["SetColor"] = function(self, r, g, b)
if not (r and g and b) then
r, g, b = 1, 1, 1
end
self.label:SetVertexColor(r, g, b)
end,
["SetImage"] = function(self, path, ...)
local image = self.image
image:SetTexture(path)
if image:GetTexture() then
self.imageshown = true
local n = select("#", ...)
if n == 4 or n == 8 then
image:SetTexCoord(...)
else
image:SetTexCoord(0, 1, 0, 1)
end
else
self.imageshown = nil
end
UpdateImageAnchor(self)
end,
["SetFont"] = function(self, font, height, flags)
self.label:SetFont(font, height, flags)
end,
["SetFontObject"] = function(self, font)
self:SetFont((font or GameFontHighlightSmall):GetFont())
end,
["SetImageSize"] = function(self, width, height)
self.image:SetWidth(width)
self.image:SetHeight(height)
UpdateImageAnchor(self)
end,
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local frame = CreateFrame("Frame", nil, UIParent)
frame:Hide()
local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlightSmall")
label:SetJustifyH("LEFT")
label:SetJustifyV("TOP")
local image = frame:CreateTexture(nil, "BACKGROUND")
-- create widget
local widget = {
label = label,
image = image,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| mit |
dwmw2/luci | build/luadoc/luadoc/util.lua | 46 | 5858 | -------------------------------------------------------------------------------
-- General utilities.
-- @release $Id: util.lua,v 1.16 2008/02/17 06:42:51 jasonsantos Exp $
-------------------------------------------------------------------------------
local posix = require "nixio.fs"
local type, table, string, io, assert, tostring, setmetatable, pcall = type, table, string, io, assert, tostring, setmetatable, pcall
-------------------------------------------------------------------------------
-- Module with several utilities that could not fit in a specific module
module "luadoc.util"
-------------------------------------------------------------------------------
-- Removes spaces from the begining and end of a given string
-- @param s string to be trimmed
-- @return trimmed string
function trim (s)
return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end
-------------------------------------------------------------------------------
-- Removes spaces from the begining and end of a given string, considering the
-- string is inside a lua comment.
-- @param s string to be trimmed
-- @return trimmed string
-- @see trim
-- @see string.gsub
function trim_comment (s)
s = string.gsub(s, "^%s*%-%-+%[%[(.*)$", "%1")
s = string.gsub(s, "^%s*%-%-+(.*)$", "%1")
return s
end
-------------------------------------------------------------------------------
-- Checks if a given line is empty
-- @param line string with a line
-- @return true if line is empty, false otherwise
function line_empty (line)
return (string.len(trim(line)) == 0)
end
-------------------------------------------------------------------------------
-- Appends two string, but if the first one is nil, use to second one
-- @param str1 first string, can be nil
-- @param str2 second string
-- @return str1 .. " " .. str2, or str2 if str1 is nil
function concat (str1, str2)
if str1 == nil or string.len(str1) == 0 then
return str2
else
return str1 .. " " .. str2
end
end
-------------------------------------------------------------------------------
-- Split text into a list consisting of the strings in text,
-- separated by strings matching delim (which may be a pattern).
-- @param delim if delim is "" then action is the same as %s+ except that
-- field 1 may be preceeded by leading whitespace
-- @usage split(",%s*", "Anna, Bob, Charlie,Dolores")
-- @usage split(""," x y") gives {"x","y"}
-- @usage split("%s+"," x y") gives {"", "x","y"}
-- @return array with strings
-- @see table.concat
function split(delim, text)
local list = {}
if string.len(text) > 0 then
delim = delim or ""
local pos = 1
-- if delim matches empty string then it would give an endless loop
if string.find("", delim, 1) and delim ~= "" then
error("delim matches empty string!")
end
local first, last
while 1 do
if delim ~= "" then
first, last = string.find(text, delim, pos)
else
first, last = string.find(text, "%s+", pos)
if first == 1 then
pos = last+1
first, last = string.find(text, "%s+", pos)
end
end
if first then -- found?
table.insert(list, string.sub(text, pos, first-1))
pos = last+1
else
table.insert(list, string.sub(text, pos))
break
end
end
end
return list
end
-------------------------------------------------------------------------------
-- Comments a paragraph.
-- @param text text to comment with "--", may contain several lines
-- @return commented text
function comment (text)
text = string.gsub(text, "\n", "\n-- ")
return "-- " .. text
end
-------------------------------------------------------------------------------
-- Wrap a string into a paragraph.
-- @param s string to wrap
-- @param w width to wrap to [80]
-- @param i1 indent of first line [0]
-- @param i2 indent of subsequent lines [0]
-- @return wrapped paragraph
function wrap(s, w, i1, i2)
w = w or 80
i1 = i1 or 0
i2 = i2 or 0
assert(i1 < w and i2 < w, "the indents must be less than the line width")
s = string.rep(" ", i1) .. s
local lstart, len = 1, string.len(s)
while len - lstart > w do
local i = lstart + w
while i > lstart and string.sub(s, i, i) ~= " " do i = i - 1 end
local j = i
while j > lstart and string.sub(s, j, j) == " " do j = j - 1 end
s = string.sub(s, 1, j) .. "\n" .. string.rep(" ", i2) ..
string.sub(s, i + 1, -1)
local change = i2 + 1 - (i - j)
lstart = j + change
len = len + change
end
return s
end
-------------------------------------------------------------------------------
-- Opens a file, creating the directories if necessary
-- @param filename full path of the file to open (or create)
-- @param mode mode of opening
-- @return file handle
function posix.open (filename, mode)
local f = io.open(filename, mode)
if f == nil then
filename = string.gsub(filename, "\\", "/")
local dir = ""
for d in string.gfind(filename, ".-/") do
dir = dir .. d
posix.mkdir(dir)
end
f = io.open(filename, mode)
end
return f
end
----------------------------------------------------------------------------------
-- Creates a Logger with LuaLogging, if present. Otherwise, creates a mock logger.
-- @param options a table with options for the logging mechanism
-- @return logger object that will implement log methods
function loadlogengine(options)
local logenabled = pcall(function()
require "logging"
require "logging.console"
end)
local logging = logenabled and logging
if logenabled then
if options.filelog then
logger = logging.file("luadoc.log") -- use this to get a file log
else
logger = logging.console("[%level] %message\n")
end
if options.verbose then
logger:setLevel(logging.INFO)
else
logger:setLevel(logging.WARN)
end
else
noop = {__index=function(...)
return function(...)
-- noop
end
end}
logger = {}
setmetatable(logger, noop)
end
return logger
end
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.