Ir para conteúdo
Entre para seguir isso  
pejuge2

7 Novas Funções Simples

Recommended Posts

pejuge2    1
pejuge2

8 Novas Funções Simples

 

Edit: Sim, eram 7 funções, mas criei uma nova e não achei necessidade de criar outro tópico :).

 

Olá a todos, vim postar 8 funções simples para Lua feitas por PeJuGe (eu mesmo =D), mas que podem ajudar bastante na avaliação de tabelas e variáveis. Caso já existam favor postar que eu removo. Elas são ótimas para estudo ^^

É importante ressaltar que as funções table.multiple e table.location não localizam números ou strings de valores compostos, ou seja, caso haja huma tabela assim: {yes = 2, 3, 5, ["no"] = 6}, não encontrará os valores yes, 2, "no" e 6, pois não são simples, sendo então ignorados. Isto por causar erros.

 

Função 1: math.multiple(value, param)

[spoiler=Função 1: math.multiple]

function math.multiple(value, param)
--> Verification of value and param and return TRUE or FALSE
  if type(value) == "number" and type(param) == "number" then
     if value % param == 0 then    
        return TRUE
     else return FALSE
     end
  else return nil
  end
end

Esta função apenas retorna TRUE caso value seja multiplo de param ou FALSE caso contrário.

 

Função 2: table.multiple(table, param)

[spoiler=Função 2: table.multiple]

function table.multiple(table, param) 
--> Definition of local value(s)
local result = 0
--> Verification of table and param and return result
  if type(param) == "number" and type(table) == "table" then
     for a = 1, #table do
        if math.multiple(table[a], param) == TRUE then
           result = result + 1
        end
     end
  else return nil
  end
  return result
--> End function
end

Esta função é apenas uma aplicação da anterior, ela retorna a quantidade de multiplos de param de table.

 

Função 3: toletter(number, base)

[spoiler=Função3: toletter]

function toletter(number, base)
--> The default values of alfabet                                                                                                                                 
local default = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
--> Verification of base value
  if base == nil or base == "" then
     base = 1
  end
--> Formula to get letter
local letter = math.floor(number - base + 1)
--> Check and return the letter
  if letter >= 1 and letter <= 26 then
     for k, v in ipairs(default) do
        if k == letter then   
           return k
        end
     end
  else return nil
  end
--> End function   
end

Esta função faz o oposto da função tonumber(), ele transforma números em letras, onde number é o número desejado base é o valor de A, caso C tenha valor 3, então a base é 1, pois A é a base.

 

Função 4: table.min(table, param1, param2)

[spoiler=Função 4: table.min]

function table.min(table, param1, param2)
--> Verification of local values
local min = nil
--> Check and return the minimum value
  if type(table) ~= "table" then
     return nil
  end
  for k, v in pairs(table) do
     if param2 ~= nil and type(k) == "number" and min == nil or param2 ~= nil and type(k) == "number" and k < min then
        if min < 0 and param1 ~= nil or min >= 0 then
           min = k
        end
     end
     if type(v) == "number" and min == nil or type(v) == "number" and v < min then
        if min < 0 and param1 ~= nil or min >= 0 then
           min = v
        end
     end
  end
  return min or nil
--> End function
end

Esta função retorna o valor mínimo da tabela table, onde caso param1 seja diferente de nil ele aceita números negativos e caso param2 seja diferente de nil ele aceita a localização do número.

 

Função 5: table.max(table, param1, param2)

[spoiler=Função 5: table.max]

function table.max(table, param1, param2)
--> Definition of the local values
local max = nil
--> Check and return the maximum value
  for k, v in pairs(table) do
     if param2 ~= nil and type(k) == "number" and max == nil or param2 ~= nil and type(k) == "number" and k > max then
        if max < 0 and param1 ~= nil or max >= 0 then
           max = k
        end
     end
     if type(v) == "number" and max == nil or type(v) == "number" and v > max then
        if max < 0 and param1 ~= nil or max >= 0 then
           max = v
        end
     end
  end
  return max
--> End function
end

Esta função retorna o valor máximo da tabela table, onde caso param1 seja diferente de nil ele aceita números negativos e caso param2 seja diferente de nil ele aceita a localização do número. Sendo assim, esta função é diferente da função table.maxn.

 

Função 6: table.location(table, value)

[spoiler=Função 5: table.location]

function table.location(table, value)
--> Verification of value
  if type(table) ~= "table" then
     return nil
  end
--> Get and return the location of the value
  for k, v in ipairs(table) do
     if value == v then
        return k
     end
  end      
  return nil
--> End function
end

Esta função retorna a localização de value na tabelatable.

 

Função 7: math.approx(value)

[spoiler=Função 7: math.approx]

function math.approx(value)
--> Verify and return the value objectify
  if type(value) == "number" then
     if math.floor(value + 0.5) > math.floor(value) then
        return math.ceil(value)
     else return math.floor(value)
     end
  else return nil
  end
--> End function
end

Esta função arredonda value para cima caso seu valor decimal seja maior ou igual a 0.5 ou para baixo caso contrário.

 

Função 8: string.toup(value, param1, param2)

[spoiler=Função 8: string.toup]

function string.toup(value, param1, param2)
--> Definition of local values
local right = string.sub(value, 2)
local up = string.upper(string.sub(value, 0, 1))
--> Check the param value
  if param1 ~= nil then
     if type(param1) ~= "number" then
        param1 = 1
     end
     if type(param2) ~= "number" then
        param2 = 1
     end
  end      
  right = string.sub(value, param2 + 1)
  up = string.upper(string.sub(value, param1, param2)) 
--> Return the string with upped letter(s)
  return string.sub(value, 0, param1 - 1) .. up .. right
--> End function   
end

Essa função meio atrazilda :ras: pega os dígitos de param1 ao param2 de value e os torna letras maiúsculas, caso não seja letra não irá desconsiderar. Caso deseje tornar a primeira letra maiúscula precisa-se apenas informar value, caso deseje-se uma letra apenas não há necessidade de informar param2.

 

Instalação:

[spoiler=Instalação]Para instalar, é simples, basta criar um arquivo com o nome 8 Novas Funções Simples e colar o script completo que está abaixo na pasta lib(...\lib) e colar isto: dofile(getDataDir() .. "lib/8 Novas Funções Simples.lua") em data.lua(...\lib\data.lua).

[spoiler=Script Completo]

--[[ PeJuGe(2010) . 8 New Simple Functions
DONT REMOVE THE CREDITS
EXCLUSIVE FOR www.otserv.com.br
TUTORIAL IN PORTUGUESE: http://forums.otserv.com.br/f179/7-novas-funcoes-simples-130036/
    + math.multiple(value, param)
      * Check if the value is multiple of param
    + table.multiple(table, param)
      * Check how many pair or odd or not numbers have on the table
    + toletter(number, base)
      * Get a letter by a number                                                       
    + table.min(table, param1, param2)
      * Get the table minimum number value
    + table.max(table, param1, param2)             
      * Get the table maximum number value
    + table.location(table, value)
      * Get the location of the value
    + math.approx(value)
      * Get the nearest number
    + string.toup(value, param1, param2) 
      * Get up selected letter(s)
]]--     

function math.multiple(value, param)
--> Verification of value and param and return TRUE or FALSE
  if type(value) == "number" and type(param) == "number" then
     if value % param == 0 then    
        return TRUE
     else return FALSE
     end
  else return nil
  end
--> End function
end

function table.multiple(table, param) 
--> Definition of local value(s)
local result = 0
--> Verification of table and param and return result
  if type(param) == "number" and type(table) == "table" then
     for a = 1, #table do
        if math.multiple(table[a], param) == TRUE then
           result = result + 1
        end
     end
  else return nil
  end
  return result
--> End function
end

function toletter(number, base)
--> The default values of alfabet                                                                                                                                 
local default = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
--> Verification of base value
  if base == nil or base == "" then
     base = 1
  end
--> Formula to get letter
local letter = math.floor(number - base + 1)
--> Check and return the letter
  if letter >= 1 and letter <= 26 then
     for k, v in ipairs(default) do
        if k == letter then   
           return k
        end
     end
  else return nil
  end
--> End function   
end

function table.min(table, param1, param2)
--> Definition of local values
local min = nil
--> Check and return the minimum value
  if type(table) ~= "table" then
     return nil
  end
  for k, v in pairs(table) do
     if param2 ~= nil and type(k) == "number" and min == nil or param2 ~= nil and type(k) == "number" and k < min then
        if min < 0 and param1 ~= nil or min >= 0 then
           min = k
        end
     end
     if type(v) == "number" and min == nil or type(v) == "number" and v < min then
        if min < 0 and param1 ~= nil or min >= 0 then
           min = v
        end
     end
  end
  return min or nil
--> End function
end

function table.max(table, param1, param2)
--> Definition of the local values
local max = nil
--> Check and return the maximum value
  for k, v in pairs(table) do
     if param2 ~= nil and type(k) == "number" and max == nil or param2 ~= nil and type(k) == "number" and k > max then
        if max < 0 and param1 ~= nil or max >= 0 then
           max = k
        end
     end
     if type(v) == "number" and max == nil or type(v) == "number" and v > max then
        if max < 0 and param1 ~= nil or max >= 0 then
           max = v
        end
     end
  end
  return max
--> End function
end

function table.location(table, value)
--> Verification of table
  if type(table) ~= "table" then
     return nil
  end
--> Get and return the location of the value
  for k, v in ipairs(table) do
     if value == v then
        return k
     end
  end      
  return nil
--> End function
end

function math.approx(value)
--> Verify and return the value objectify
  if type(value) == "number" then
     if math.floor(value + 0.5) > math.floor(value) then
        return math.ceil(value)
     else return math.floor(value)
     end
  else return nil
  end
--> End function
end  

function string.toup(value, param1, param2)
--> Definition of local values
local right = string.sub(value, 2)
local up = string.upper(string.sub(value, 0, 1))
local param1 = param1 or 1
local param2 = param2 or param1
--> Check the param value
  if param1 ~= nil then
     if type(param1) ~= "number" then
        param1 = 1
     end
     if type(param2) ~= "number" then
        param2 = 1
     end
  end      
  right = string.sub(value, param2 + 1)
  up = string.upper(string.sub(value, param1, param2)) 
--> Return the string with upped letter(s)
  return string.sub(value, 0, param1 - 1) .. up .. right
--> End function   
end

 

Bem, é isto, caso já exista alguma dessas funções ou haja algum erro, favor postar.

Editado por pejuge2
Inserção da função 8

Compartilhar este post


Link para o post
Gpwjhlkdcf    21
Gpwjhlkdcf

Tem funções legais ai, podia só dar uma melhoradinha nelas. Movido.

Compartilhar este post


Link para o post
pejuge2    1
pejuge2

Quais melhoras você tem a sugerir por exemplo? =D Se alguém tiver sugestão eu aceito ehehe

 

EDIT: FUNÇÃO string.toup ADICIONADA

Editado por pejuge2

Compartilhar este post


Link para o post
Mock    32
Mock

Tao otimas cara, pretendo usar umas na otal ok?

tem umas ai que ja existem mais com otro nome

Compartilhar este post


Link para o post
ushoriuma    0
ushoriuma

eu só de ganso na OTAL veno o mock e nord arrumarem!xD

aprabens gostei das funcoes!

Compartilhar este post


Link para o post
pejuge2    1
pejuge2

Ok mock, qualquer coisa pode me contactar! ^^. Vai por os créditos né?

Compartilhar este post


Link para o post
LokiOuT    0
LokiOuT

Gostei, mas algumas delas nao adiantou muita coisa!

 

mas vlw

Compartilhar este post


Link para o post
Socket    0
Socket

Ótimas funções, só que a maioria já existe :(

A toletter, já existe so que 95 é "a" e 122 é "z", não lembro as maiusculas.

E a função é string.char(str)

Mas mesmo assim tá ótimo ^^

Compartilhar este post


Link para o post
pejuge2    1
pejuge2

Ok, como eu disse, eu nunca vi essas funções, caso existam desconheço.

 

Obrigado por informar.

Compartilhar este post


Link para o post
Pandá s2    0
Pandá s2

Vlw bem legal mesmo!!!

 

deu para entender bastante

Compartilhar este post


Link para o post
Visitante
Este tópico está impedido de receber novos posts.
Entre para seguir isso  
  • Quem Está Navegando   0 membros estão online

    Nenhum usuário registrado visualizando esta página.

×