Ir para conteúdo
Entre para seguir isso  
Magus

Global Storage melhorado

Recommended Posts

Magus    2
Magus
Nome: Global Storage melhorado

Autor: Magus

Versão: 8.0+

Testado em: TFS Crying Damsos

Com este script, você pode:

 

  • Salvar dados para serem utilizados mais tarde em outros scripts, independente se é talk/movement/creature/etc;
  • Salvar tabelas e valores boleanos com a função bônus gstorage.serialize();
  • Converter os dados, caso sejam tabelas ou boleanos, com gstorage.unserialize();
  • Optar por ser um global storage que salva após o desligamento do pc ou não.

Funções:

 

  • gstorage.add(id, valor)
  • gstorage.get(id)
  • gstorage.serialize(var)
  • gstorage.unserialize(var)

 

[spoiler=Alguns exemplos]

--Talkaction
local str = 'Mensagem gerada num talkaction.'
gstorage.add(1, str)

--Creature Script
print(gstorage.get(1)) -- Mensagem gerada num talkaction.

 

-- Movement
local corrida = {['1st'] = 'Magus', ['2nd'] = 'Skyen Hasus', ['3rd'] = 'Mock']}
gstorage.add(2, gstorage.serialize(corrida))

-- NPC
local t = gstorage.unserialize(gstorage.get(2))
doNPCsay(cid, "O primeiro lugar foi: "..t['1st'])

 

 

Instalação:

Crie um arquivo chamado gstorage.lua na pasta data/lib e adicione:

gstorage = {
   _VERSION = "1.0",

   __construct = function(dbsave)
       if(luasql == nil) then
           assert(package.loadlib("sqlite3.dll", "luaopen_luasql_sqlite3")) ()
       end

       genv = assert(luasql.sqlite3())
       gcon = assert(genv:connect(dbsave and 'store.s3db' or ':memory:'))

       assert(gcon:execute[[
         CREATE TABLE IF NOT EXISTS stores(
           id int(11),
           value varchar(999)
         )
       ]])
   end,

   add = function(id, value)
       local cur = gcon:execute(string.format([[
         SELECT id FROM stores
         WHERE id = %d]], id)
       )

       local exists = cur:fetch()

       cur:close()

       if (exists) then
           return gcon:execute(string.format([[
             UPDATE stores SET value = '%s'
             WHERE id = %d]], value, id)
           )
       else
           return gcon:execute(string.format([[
             INSERT INTO stores (id,value)
             VALUES (%d,'%s')]], id, value)
           )
       end
   end,

   get = function(id)
       local cur = assert(gcon:execute(string.format([[
         SELECT value FROM stores
         WHERE id = %d]], id)
       ))

       local ret = cur:fetch()

       cur:close()

       return ret
   end,

   serialize = function(o)
       local function subtable(t)
           local arr = string.char(123)
           for i, v in pairs(t) do
               arr = arr .. string.format('[%s] = ', type(i) == 'number' and i or '"'..i..'"')
               if (type(v) == 'table') then
                   arr = arr .. subtable(v) .. string.char(44)
               elseif (type(v) == 'function' or type(v) == 'thread' or type(v) == 'userdata') then
                   error('You cannot encode function, thread or userdata.')
               else
                   arr = arr .. string.format('%s,', type(v) == 'number' and v or '"'..v..'"')
               end
           end
           return arr:sub(1,arr:len()-1)..string.char(125)
       end

       if(type(o) == 'boolean') then
           return o and 'b:true' or 'b:false'

       elseif(type(o) == 'table') then
           return subtable(o)

       elseif (type(o) == 'function' or type(o) == 'thread' or type(o) == 'userdata') then
           error('You cannot encode function, thread or userdata.')

       else
           return o
       end
   end,

   unserialize = function(o)
       if (type(o) ~= 'string') then
           return o

       elseif(o == 'b:true') then
           return true

       elseif(o == 'b:false') then
           return false

       elseif(o:find('{.+}')) then
           return assert(loadstring(string.format("local t = %s return t", o))) () -- Obrigado pela dica Skyen Hasus!

       else
           return o
       end
   end,
}

gstorage.__construct() -- Se não quiser perder os stores depois de reiniciar o pc, coloque true na função [..__construct(true)]

 

Adicione em data.lua, no final:

dofile(getDataDir() .. "lib/gstorage.lua")

Adicionado :)

Compartilhar este post


Link para o post
Mock    32
Mock

assert(package.loadlib("sqlite3.dll", "luaopen_luasql_sqlite3")) ()

q?? ._.

nao seria mais facil:

require 'luasqlite3'?

Não faltou algums requerimentos?

Ela pra se usar em ots de hoje da p usar ela usando a otal ^^

 

mais em fim magus ta otimo ;D

Compartilhar este post


Link para o post
Magus    2
Magus

Com o require seria necessário um diretório "LuaSQL" para a DLL, do jeito que está ele já utiliza a dll que vem com o ot. E o que tá faltando?

 

Inclue lá no OTAL x)

 

PS: Vale lembrar que se der qualquer /reload no servidor e você estiver usando banco de dados na memória, os valores guardados (se tiver algum) serão resetados.

Compartilhar este post


Link para o post
Mock    32
Mock

@magus a otal ja tem luasqliute3 e luamysql

mais em fim o require ele nao abre a pasta luasql ele ve em todos os diretorios pre configurados.

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.

×