Parabéns otimo tutorial, sempre quiz saber como usar xml's .
- Fórum
- OTServ
- Tutoriais
- Tutoriais de Scripting
- Lib luaXml - lua for xml - functions
PO
tfs 0.3
Lib luaXml - lua for xml - functions
Por Poccnn, 16 de jul. de 2016 em Tutoriais de Scripting
libxml
luaxml
lualibxml
luaforxml
2
1.7k


info
Grupo: Herói
Registrado: 07/03/16
Posts: 1.4k
Reputação: +385
Gênero: Masculino
Vim aqui explicar sobre a livraria luaxml, suas funções e implementações.
Primeiro: Adicionar em seu servidor a livraria luaXml.lua e LuaXML_lib.dll
esse é o script da luaXml.lua que voce vai ter que por esse arquivo com esse codigo na mesma pasta do seu executavel.
require("LuaXML_lib")
local base = _G
local xml = xml
module("xml")
-- symbolic name for tag index, this allows accessing the tag by var[xml.TAG]
TAG = 0
-- sets or returns tag of a LuaXML object
function tag(var,tag)
if base.type(var)~="table" then return end
if base.type(tag)=="nil" then
return var[TAG]
end
var[TAG] = tag
end
-- creates a new LuaXML object either by setting the metatable of an existing Lua table or by setting its tag
function new(arg)
if base.type(arg)=="table" then
base.setmetatable(arg,{__index=xml, __tostring=xml.str})
return arg
end
local var={}
base.setmetatable(var,{__index=xml, __tostring=xml.str})
if base.type(arg)=="string" then var[TAG]=arg end
return var
end
-- appends a new subordinate LuaXML object to an existing one, optionally sets tag
function append(var,tag)
if base.type(var)~="table" then return end
local newVar = new(tag)
var[#var+1] = newVar
return newVar
end
-- converts any Lua var into an XML string
function str(var,indent,tagValue)
if base.type(var)=="nil" then return end
local indent = indent or 0
local indentStr=""
for i = 1,indent do indentStr=indentStr.." " end
local tableStr=""
if base.type(var)=="table" then
local tag = var[0] or tagValue or base.type(var)
local s = indentStr.."<"..tag
for k,v in base.pairs(var) do -- attributes
if base.type(k)=="string" then
if base.type(v)=="table" and k~="_M" then -- otherwise recursiveness imminent
tableStr = tableStr..str(v,indent+1,k)
else
s = s.." "..k.."=\""..encode(base.tostring(v)).."\""
end
end
end
if #var==0 and #tableStr==0 then
s = s.." />\n"
elseif #var==1 and base.type(var[1])~="table" and #tableStr==0 then -- single element
s = s..">"..encode(base.tostring(var[1])).."</"..tag..">\n"
else
s = s..">\n"
for k,v in base.ipairs(var) do -- elements
if base.type(v)=="string" then
s = s..indentStr.." "..encode(v).." \n"
else
s = s..str(v,indent+1)
end
end
s=s..tableStr..indentStr.."</"..tag..">\n"
end
return s
else
local tag = base.type(var)
return indentStr.."<"..tag.."> "..encode(base.tostring(var)).." </"..tag..">\n"
end
end
-- saves a Lua var as xml file
function save(var,filename)
if not var then return end
if not filename or #filename==0 then return end
local file = base.io.open(filename,"w")
file:write("<?xml version=\"1.0\"?>\n<!-- file \"",filename, "\", generated by LuaXML -->\n\n")
file:write(str(var))
base.io.close(file)
end
-- recursively parses a Lua table for a substatement fitting to the provided tag and attribute
function find(var, tag, attributeKey,attributeValue)
-- check input:
if base.type(var)~="table" then return end
if base.type(tag)=="string" and #tag==0 then tag=nil end
if base.type(attributeKey)~="string" or #attributeKey==0 then attributeKey=nil end
if base.type(attributeValue)=="string" and #attributeValue==0 then attributeValue=nil end
-- compare this table:
if tag~=nil then
if var[0]==tag and ( attributeValue == nil or var[attributeKey]==attributeValue ) then
base.setmetatable(var,{__index=xml, __tostring=xml.str})
return var
end
else
if attributeValue == nil or var[attributeKey]==attributeValue then
base.setmetatable(var,{__index=xml, __tostring=xml.str})
return var
end
end
-- recursively parse subtags:
for k,v in base.ipairs(var) do
if base.type(v)=="table" then
local ret = find(v, tag, attributeKey,attributeValue)
if ret ~= nil then return ret end
end
end
end
Não vou postar a dll para não virem dizer que tem virus. voce que tem o sistema lua implementado em seu pc, pode pegar a dll de dentro do diretorio:
copie essa dll e coloque ela na mesma pasta do executavel.
implementado essa nova livraria em seu servidor. agora irei explicar um pouco sobre as funções e implementações dessa livraria.
conhecendo as funções dessa livraria disponibilizada por lua:
existem outras funções, mas não irei tratar delas.
vamos a um uso pratico dessas funções da livraria usando como base o arquivo vocations.xml.
apenas para uso didatico, deixo aqui uma parte do codigo do arquivo vocations.xml que irei usar no codigo de exemplo.
<vocation id="0" name="None" description="none" needpremium="0" gaincap="5" gainhp="5" gainmana="5" gainhpticks="6" gainhpamount="1" gainmanaticks="6" gainmanaamount="1" manamultiplier="4.0" attackspeed="2000" soulmax="100" gainsoulticks="86800" fromvoc="0" attackable="yes">
<formula meleeDamage="1.0" distDamage="1.0" wandDamage="1.0" magDamage="1.0" magHealingDamage="1.0" defense="1.0" magDefense="1.0" armor="1.0"/>
<skill fist="1.5" club="2.0" sword="2.0" axe="2.0" distance="2.0" shielding="1.5" fishing="1.1" experience="1.0"/>
</vocation>
<vocation id="1" name="Sorcerer" description="a Sorcerer" needpremium="0" gaincap="10" gainhp="5" gainmana="30" gainhpticks="1" gainhpamount="0.8" gainmanaticks="1" gainmanaamount="6.7" manamultiplier="1.1" attackspeed="2000" soulmax="100" gainsoulticks="600" fromvoc="1">
<formula meleeDamage="1.0" distDamage="1.0" wandDamage="1.0" magDamage="1.1" magHealingDamage="1.0" defense="1.0" magDefense="1.2" armor="1.0"/>
<skill fist="1.5" club="2.0" sword="2.0" axe="2.0" distance="2.0" shielding="1.5" fishing="1.1" experience="1.0"/>
</vocation>
...
vamos agora ao codigo que irei usar como uso implementavel das funções da livraria luaxml.
Explicando o codigo postado acima.
-- Carrega o arquivo xml
local xfile_load = xml.load("vocations.xml")
-- Pega o bloco requerido segundo os parametros fornecidos.
-- pode ser qualquer parâmetro que esteja inserido na tag ('vocation' << cabeçalho da tag - 'id','4' << retornar a tag do knight, 'name','Druid' ...).
-- sempre use parâmetros em string mesmo que seja numeros, tem que ser fornecidos em string.
local xfile_find = xfile_load:find("vocation",'name','Sorcerer')
-- Verificação se houve resultado retornado.
if not xfile_find then return end
-- Criação de novos dados em xml
-- 'Sorcerer' seria a tag do cabeçalho do bloco criado >> <sorcerer> ... </sorcerer>
local new_xfile = xml.new('sorcerer')
-- Esse daqui são dois exemplos de tags que existem dentro da tag principal.
-- Cada tag é chamada por um index sucessivo e ascendente.
local formula = xfile_find[1]:find('formula')
local skills = xfile_find[2]:find('skill')
-- Modifica o nome da tag do cabeçalho; nesse caso: 'Sorcerer'(declarado em xml.new) torna-se 'Bruxo'.
new_xfile:tag('Bruxo')
-- index [1], Adiciona valores entre tags >> saida gerado por essa função >> <id>1</id>
new_xfile:append('id')[1] = xfile_find.id
-- index [0], adiciona valores na tag >> saida gerada por essa função >> <autor nome = "Marcryzius" data = "16/julho/2016" />
new_xfile:append('id')[0] = 'autor nome = "Marcryzius" data = "16/julho/2016"'
-- Mais um exemplo de adição de valores na tag >> saida gerada por essa função >> <gainCapDefAndAxe cap = "10" def = "1.0" axe = "2.0" />
new_xfile:append('gaincap')[0] = 'gainCapDefAndAxe cap = "'..xfile_find.gaincap..'" def = "'..formula.defense..'" axe = "'..skills.axe..'"'
-- Adiciona novas variaveis dentro da propria cadeia de caracteres retornanda pela função find
xfile_find['newid'] = '0'
-- Modifica valores associados as variaveis
xfile_find['id'] = 'newid'
xfile_find.newid = '2'
-- Cria uma nova tag com valores entre as tags >> <newid>2</newid>
new_xfile:append('newid')[1] = xfile_find.newid
-- Idem >> <id>newid</id>
new_xfile:append('id')[1] = xfile_find.id or 'nil'
-- Salva essa string de caracteres em um arquivo formatado como xml.
new_xfile:save('dadosXml.xml') -- insira o caminho onde vai ser salvo o arquivo.
Esse é o codigo dentro do arquivo (dadosXml.xml) gerado por esse programa:
Espero que tenham entendido. Qualquer duvida, deixe nos comentarios e tentarei ajuda-lo.
Editado Julho 16 por Poccnn