Permalink
Browse files

Import to git

  • Loading branch information...
0 parents commit 359f3e6734cfccdff8d6f9f3421b2619bb57a1e1 @drahosp drahosp committed Oct 1, 2010
Showing with 1,071 additions and 0 deletions.
  1. +22 −0 CMakeLists.txt
  2. +429 −0 LuaXML_lib.c
  3. BIN LuaXML_lib.dll
  4. +9 −0 LuaXML_lib_cpp.c
  5. BIN LuaXml.cdr
  6. +119 −0 LuaXml.lua
  7. BIN LuaXml.png
  8. +50 −0 Makefile
  9. +130 −0 dist.cmake
  10. +14 −0 dist.info
  11. BIN lua.exe
  12. BIN lua51.dll
  13. +147 −0 readme.txt
  14. +16 −0 test.lua
  15. +135 −0 test.xml
22 CMakeLists.txt
@@ -0,0 +1,22 @@
+# Copyright (C) 2007-2009 LuaDist.
+# Submitted by David Manura
+# Redistribution and use of this file is allowed according to the terms of the MIT license.
+# For details see the COPYRIGHT file distributed with LuaDist.
+# Please note that the package source code is licensed under its own license.
+
+PROJECT(luaxml C)
+CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
+INCLUDE(dist.cmake)
+
+IF (MSVC)
+ ADD_DEFINITIONS(-TP) # treat as C++ for C99-ish features
+ SET(WORKAROUND _cpp)
+ENDIF (MSVC)
+
+ADD_LUA_MODULE(luaXML_lib LuaXML_lib${WORKAROUND}.c)
+
+# Install all files and documentation
+INSTALL (TARGETS luaXML_lib DESTINATION ${INSTALL_CMOD})
+INSTALL (FILES LuaXml.lua DESTINATION ${INSTALL_LMOD}/)
+INSTALL (FILES test.lua test.xml DESTINATION ${INSTALL_EXAMPLE})
+INSTALL (FILES readme.txt LuaXml.cdr LuaXml.png DESTINATION ${INSTALL_DATA})
429 LuaXML_lib.c
@@ -0,0 +1,429 @@
+/**
+LuaXML License
+
+LuaXml is licensed under the terms of the MIT license reproduced below,
+the same as Lua itself. This means that LuaXml is free software and can be
+used for both academic and commercial purposes at absolutely no cost.
+
+Copyright (C) 2007-2009 Gerald Franz, www.viremo.de
+
+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.
+*/
+
+#if defined __WIN32__ || defined WIN32
+# include <windows.h>
+# define _EXPORT __declspec(dllexport)
+#else
+# define _EXPORT
+#endif
+
+#include <lua.h>
+#include <lauxlib.h>
+#include <lualib.h>
+
+#include <stdio.h>
+#include <string.h>
+#include <ctype.h>
+#include <stdlib.h>
+
+static const char ESC=27;
+static const char OPN=28;
+static const char CLS=29;
+
+//--- auxliary functions -------------------------------------------
+
+static const char* char2code(unsigned char ch, char buf[8]) {
+ unsigned char i=0;
+ buf[i++]='&';
+ buf[i++]='#';
+ if(ch>99) buf[i++]=ch/100+48;
+ if(ch>9) buf[i++]=(ch%100)/10+48;
+ buf[i++]=ch%10+48;
+ buf[i++]=';';
+ buf[i]=0;
+ return buf;
+}
+
+static size_t find(const char* s, const char* pattern, size_t start) {
+ const char* found =strstr(s+start, pattern);
+ return found ? found-s : strlen(s);
+}
+
+//--- internal tokenizer -------------------------------------------
+
+typedef struct Tokenizer_s {
+ /// stores string to be tokenized
+ const char* s;
+ /// stores size of string to be tokenized
+ size_t s_size;
+ /// stores current read position
+ size_t i;
+ /// stores current read context
+ int tagMode;
+ /// stores next token, if already determined
+ const char* m_next;
+ /// size of next token
+ size_t m_next_size;
+ /// pointer to current token
+ char* m_token;
+ /// size of current token
+ size_t m_token_size;
+ /// capacity of current token
+ size_t m_token_capacity;
+} Tokenizer;
+
+Tokenizer* Tokenizer_new(const char* str, size_t str_size) {
+ Tokenizer *tok = (Tokenizer*)malloc(sizeof(Tokenizer));
+ memset(tok, 0, sizeof(Tokenizer));
+ tok->s_size = str_size;
+ tok->s = str;
+ return tok;
+}
+
+void Tokenizer_delete(Tokenizer* tok) {
+ free(tok->m_token);
+ free(tok);
+}
+
+//void Tokenizer_print(Tokenizer* tok) { printf(" @%u %s\n", tok->i, !tok->m_token ? "(null)" : (tok->m_token[0]==ESC)?"(esc)" : (tok->m_token[0]==OPN)?"(open)": (tok->m_token[0]==CLS)?"(close)" : tok->m_token); fflush(stdout); }
+
+static const char* Tokenizer_set(Tokenizer* tok, const char* s, size_t size) {
+ if(!size||!s) return 0;
+ free(tok->m_token);
+ tok->m_token = (char*)malloc(size+1);
+ strncpy(tok->m_token,s, size);
+ tok->m_token[size] = 0;
+ tok->m_token_size = tok->m_token_capacity = size;
+ //Tokenizer_print(tok);
+ return tok->m_token;
+}
+
+static void Tokenizer_append(Tokenizer* tok, char ch) {
+ if(tok->m_token_size+1>=tok->m_token_capacity) {
+ tok->m_token_capacity = (tok->m_token_capacity==0) ? 16 : tok->m_token_capacity*2;
+ tok->m_token = (char*)realloc(tok->m_token, tok->m_token_capacity);
+ }
+ tok->m_token[tok->m_token_size]=ch;
+ tok->m_token[++tok->m_token_size]=0;
+}
+
+const char* Tokenizer_next(Tokenizer* tok) {
+ const char* ESC_str = "\033";
+ const char* OPEN_str = "\034";
+ const char* CLOSE_str = "\035";
+
+
+ if(tok->m_token) {
+ free(tok->m_token);
+ tok->m_token = 0;
+ tok->m_token_size=tok->m_token_capacity = 0;
+ }
+
+ int quotMode=0;
+ int tokenComplete = 0;
+ while(tok->m_next_size || (tok->i < tok->s_size)) {
+
+ if(tok->m_next_size) {
+ Tokenizer_set(tok, tok->m_next, tok->m_next_size);
+ tok->m_next=0;
+ tok->m_next_size=0;
+ return tok->m_token;
+ }
+
+ switch(tok->s[tok->i]) {
+ case '"':
+ case '\'':
+ if(tok->tagMode) {
+ if(!quotMode) quotMode=tok->s[tok->i];
+ else if(quotMode==tok->s[tok->i]) quotMode=0;
+ }
+ Tokenizer_append(tok, tok->s[tok->i]);
+ break;
+ case '<':
+ if(!quotMode&&(tok->i+4<tok->s_size)&&(strncmp(tok->s+tok->i,"<!--",4)==0)) // strip comments
+ tok->i=find(tok->s, "-->", tok->i+4)+2;
+ else if(!quotMode&&(tok->i+9<tok->s_size)&&(strncmp(tok->s+tok->i,"<![CDATA[",9)==0)) { // interpet CDATA
+ size_t b=tok->i+9;
+ tok->i=find(tok->s, "]]>",b)+3;
+ if(!tok->m_token_size) return Tokenizer_set(tok, tok->s+b, tok->i-b-3);
+ tokenComplete = 1;
+ tok->m_next = tok->s+b;
+ tok->m_next_size = tok->i-b-3;
+ --tok->i;
+ }
+ else if(!quotMode&&(tok->i+1<tok->s_size)&&((tok->s[tok->i+1]=='?')||(tok->s[tok->i+1]=='!'))) // strip meta information
+ tok->i=find(tok->s, ">", tok->i+2);
+ else if(!quotMode&&!tok->tagMode) {
+ if((tok->i+1<tok->s_size)&&(tok->s[tok->i+1]=='/')) {
+ tok->m_next=ESC_str;
+ tok->m_next_size = 1;
+ tok->i=find(tok->s, ">", tok->i+2);
+ }
+ else {
+ tok->m_next = OPEN_str;
+ tok->m_next_size = 1;
+ tok->tagMode=1;
+ }
+ tokenComplete = 1;
+ }
+ else Tokenizer_append(tok, tok->s[tok->i]);
+ break;
+ case '/':
+ if(tok->tagMode&&!quotMode) {
+ tokenComplete = 1;
+ if((tok->i+1 < tok->s_size) && (tok->s[tok->i+1]=='>')) {
+ tok->tagMode=0;
+ tok->m_next=ESC_str;
+ tok->m_next_size = 1;
+ ++tok->i;
+ }
+ else Tokenizer_append(tok, tok->s[tok->i]);
+ }
+ else Tokenizer_append(tok, tok->s[tok->i]);
+ break;
+ case '>':
+ if(!quotMode&&tok->tagMode) {
+ tok->tagMode=0;
+ tokenComplete = 1;
+ tok->m_next = CLOSE_str;
+ tok->m_next_size = 1;
+ }
+ else Tokenizer_append(tok, tok->s[tok->i]);
+ break;
+ case ' ':
+ case '\r':
+ case '\n':
+ case '\t':
+ if(tok->tagMode&&!quotMode) {
+ if(tok->m_token_size) tokenComplete=1;
+ }
+ else if(tok->m_token_size) Tokenizer_append(tok, tok->s[tok->i]);
+ break;
+ default: Tokenizer_append(tok, tok->s[tok->i]);
+ }
+ ++tok->i;
+ if((tok->i>=tok->s_size)||(tokenComplete&&tok->m_token_size)) {
+ tokenComplete=0;
+ while(tok->m_token_size&&isspace(tok->m_token[tok->m_token_size-1])) // trim whitespace
+ tok->m_token[--tok->m_token_size]=0;
+ if(tok->m_token_size) break;
+ }
+ }
+ //Tokenizer_print(tok);
+ return tok->m_token;
+}
+
+//--- local variables ----------------------------------------------
+
+/// stores number of special character codes
+static size_t sv_code_size=0;
+/// stores currently allocated capacity for special character codes
+static size_t sv_code_capacity=16;
+/// stores code table for special characters
+static char** sv_code=0;
+
+//--- public methods -----------------------------------------------
+
+static void Xml_pushDecode(lua_State* L, const char* s, size_t s_size) {
+ size_t start=0, pos;
+ if(!s_size) s_size=strlen(s);
+ luaL_Buffer b;
+ luaL_buffinit(L, &b);
+ const char* found = strstr(s, "&#");
+ if(!found) pos = s_size;
+ else pos = found-s;
+ while(found&&(pos+5<s_size)&&(*(found+5)==';')&&isdigit(*(found+2))&&isdigit(*(found+3))&&isdigit(*(found+4)) ) {
+ if(pos>start) luaL_addlstring(&b,s+start, pos-start);
+ luaL_addchar(&b, 100*(s[pos+2]-48)+10*(s[pos+3]-48)+(s[pos+4]-48));
+ start=pos+6;
+ found = strstr(found+6, "&#");
+ if(!found) pos = s_size;
+ else pos = found-s;
+ }
+ if(pos>start) luaL_addlstring(&b,s+start, pos-start);
+ luaL_pushresult(&b);
+ size_t i;
+ for(i=sv_code_size-1; i<sv_code_size; i-=2) {
+ luaL_gsub(L, lua_tostring(L,-1), sv_code[i], sv_code[i-1]);
+ lua_remove(L,-2);
+ }
+}
+
+int Xml_eval(lua_State *L) {
+ char* str = 0;
+ size_t str_size=0;
+ if(lua_isuserdata(L,1)) str = (char*)lua_touserdata(L,1);
+ else {
+ const char * sTmp = luaL_checklstring(L,1,&str_size);
+ str = (char*)malloc(str_size+1);
+ memcpy(str, sTmp, str_size);
+ str[str_size]=0;
+ }
+ Tokenizer* tok = Tokenizer_new(str, str_size ? str_size : strlen(str));
+ lua_settop(L,0);
+ const char* token=0;
+ int firstStatement = 1;
+ while((token=Tokenizer_next(tok))!=0) if(token[0]==OPN) { // new tag found
+ if(lua_gettop(L)) {
+ int newIndex=lua_objlen(L,-1)+1;
+ lua_pushnumber(L,newIndex);
+ lua_newtable(L);
+ lua_settable(L, -3);
+ lua_pushnumber(L,newIndex);
+ lua_gettable(L,-2);
+ }
+ else {
+ if (firstStatement) {
+ lua_newtable(L);
+ firstStatement = 0;
+ }
+ else return lua_gettop(L);
+ }
+ // set metatable:
+ lua_newtable(L);
+ lua_pushliteral(L, "__index");
+ lua_getglobal(L, "xml");
+ lua_settable(L, -3);
+
+ lua_pushliteral(L, "__tostring"); // set __tostring metamethod
+ lua_getglobal(L, "xml");
+ lua_pushliteral(L,"str");
+ lua_gettable(L, -2);
+ lua_remove(L, -2);
+ lua_settable(L, -3);
+ lua_setmetatable(L, -2);
+
+ // parse tag and content:
+ lua_pushnumber(L,0); // use index 0 for storing the tag
+ lua_pushstring(L, Tokenizer_next(tok));
+ lua_settable(L, -3);
+
+ while(((token = Tokenizer_next(tok))!=0)&&(token[0]!=CLS)&&(token[0]!=ESC)) { // parse tag header
+ size_t sepPos=find(token, "=", 0);
+ if(token[sepPos]) { // regular attribute
+ const char* aVal =token+sepPos+2;
+ lua_pushlstring(L, token, sepPos);
+ Xml_pushDecode(L, aVal, strlen(aVal)-1);
+ lua_settable(L, -3);
+ }
+ }
+ if(!token||(token[0]==ESC)) {
+ if(lua_gettop(L)>1) lua_settop(L,-2); // this tag has no content, only attributes
+ else break;
+ }
+ }
+ else if(token[0]==ESC) { // previous tag is over
+ if(lua_gettop(L)>1) lua_settop(L,-2); // pop current table
+ else break;
+ }
+ else { // read elements
+ lua_pushnumber(L,lua_objlen(L,-1)+1);
+ Xml_pushDecode(L, token, 0);
+ lua_settable(L, -3);
+ }
+ Tokenizer_delete(tok);
+ free(str);
+ return lua_gettop(L);
+}
+
+int Xml_load (lua_State *L) {
+ const char * filename = luaL_checkstring(L,1);
+ FILE * file=fopen(filename,"r");
+ if(!file) return luaL_error(L,"LuaXml ERROR: \"%s\" file error or file not found!",filename);
+
+ fseek (file , 0 , SEEK_END);
+ size_t sz = ftell (file);
+ rewind (file);
+ char* buffer = (char*)malloc(sz+1);
+ fread (buffer,1,sz,file);
+ fclose(file);
+ buffer[sz]=0;
+ lua_pushlightuserdata(L,buffer);
+ lua_replace(L,1);
+ return Xml_eval(L);
+};
+
+int Xml_registerCode(lua_State *L) {
+ const char * decoded = luaL_checkstring(L,1);
+ const char * encoded = luaL_checkstring(L,2);
+
+ size_t i;
+ for(i=0; i<sv_code_size; i+=2)
+ if(strcmp(sv_code[i],decoded)==0)
+ return luaL_error(L,"LuaXml ERROR: code already exists.");
+ if(sv_code_size+2>sv_code_capacity) {
+ sv_code_capacity*=2;
+ sv_code = (char**)realloc(sv_code, sv_code_capacity*sizeof(char*));
+ }
+ sv_code[sv_code_size]=(char*)malloc(strlen(decoded)+1);
+ strcpy(sv_code[sv_code_size++], decoded);
+ sv_code[sv_code_size]=(char*)malloc(strlen(encoded)+1);
+ strcpy(sv_code[sv_code_size++],encoded);
+ return 0;
+}
+
+int Xml_encode(lua_State *L) {
+ if(lua_gettop(L)!=1) return 0;
+ luaL_checkstring(L,-1);
+ size_t i;
+ for(i=0; i<sv_code_size; i+=2) {
+ luaL_gsub(L, lua_tostring(L,-1), sv_code[i], sv_code[i+1]);
+ lua_remove(L,-2);
+ }
+ char buf[8];
+ const char* s=lua_tostring(L,1);
+ size_t start, pos;
+ luaL_Buffer b;
+ luaL_buffinit(L, &b);
+ for(start=pos=0; s[pos]!=0; ++pos) if(s[pos]<0) {
+ if(pos>start) luaL_addlstring(&b,s+start, pos-start);
+ luaL_addstring(&b,char2code((unsigned char)(s[pos]),buf));
+ start=pos+1;
+ }
+ if(pos>start) luaL_addlstring(&b,s+start, pos-start);
+ luaL_pushresult(&b);
+ lua_remove(L,-2);
+ return 1;
+}
+
+int _EXPORT luaopen_LuaXML_lib (lua_State* L) {
+ static const struct luaL_Reg funcs[] = {
+ {"load", Xml_load},
+ {"eval", Xml_eval},
+ {"encode", Xml_encode},
+ {"registerCode", Xml_registerCode},
+ {NULL, NULL}
+ };
+ luaL_register(L, "xml", funcs);
+ // register default codes:
+ if(!sv_code) {
+ sv_code=(char**)malloc(sv_code_capacity*sizeof(char*));
+ sv_code[sv_code_size++]="&";
+ sv_code[sv_code_size++]="&amp;";
+ sv_code[sv_code_size++]="<";
+ sv_code[sv_code_size++]="&lt;";
+ sv_code[sv_code_size++]=">";
+ sv_code[sv_code_size++]="&gt;";
+ sv_code[sv_code_size++]="\"";
+ sv_code[sv_code_size++]="&quot;";
+ sv_code[sv_code_size++]="'";
+ sv_code[sv_code_size++]="&apos;";
+ }
+ return 1;
+}
BIN LuaXML_lib.dll
Binary file not shown.
9 LuaXML_lib_cpp.c
@@ -0,0 +1,9 @@
+/* workaround - since MSVC doesn't support C99, compile as C++
+ with C linkage */
+extern "C" {
+#include "LuaXML_lib.c"
+}
+
+
+
+
BIN LuaXml.cdr
Binary file not shown.
119 LuaXml.lua
@@ -0,0 +1,119 @@
+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
BIN LuaXml.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
50 Makefile
@@ -0,0 +1,50 @@
+# 2009-03-16 by gf
+
+# generic compiler and linker settings:
+CC = gcc
+INCDIR = -I../lua/src
+LIB =
+LIBDIR = -L. -L../lua/src
+CFLAGS = -Os -Wall -c #-g
+
+# generic platform specific rules:
+ARCH = $(shell uname -s)
+ifeq ($(ARCH),Linux)
+ CFLAGS += -fPIC
+ LFLAGS = -fPIC -shared
+ LIBS = $(LIBDIR) $(LIB) -llua -ldl
+ EXESUFFIX =
+ SHLIBSUFFIX = .so
+
+else
+ ifeq ($(ARCH),Darwin) # MacOSX
+ LFLAGS = -bundle
+ LIBS = $(LIBDIR) -L/usr/local/lib $(LIB) -llua
+ EXESUFFIX = .app
+ SHLIBSUFFIX = .so
+
+ else # windows, MinGW
+ LFLAGS = -shared
+ LIBS = $(LIBDIR) $(LIB) -llua51 -mconsole -s
+ EXESUFFIX = .exe
+ SHLIBSUFFIX = .dll
+
+ endif
+endif
+
+# project specific targets:
+all: LuaXML_lib$(SHLIBSUFFIX)
+
+# project specific link rules:
+LuaXML_lib$(SHLIBSUFFIX): LuaXML_lib.o
+ $(CC) -o $@ $(LFLAGS) $^ $(LIBS)
+
+# project specific dependencies:
+LuaXML_lib.o: LuaXML_lib.c
+
+# generic rules and targets:
+.c.o:
+ $(CC) $(CFLAGS) $(INCDIR) -c $<
+clean:
+ rm -f *.o *~ LuaXML_lib.so LuaXML_lib.dll
+
130 dist.cmake
@@ -0,0 +1,130 @@
+# LuaDist CMake utility library.
+# Provides variables and utility functions common to LuaDist CMake builds.
+#
+# Copyright (C) 2007-2010 LuaDist.
+# by David Manura, Peter Drahos
+# Redistribution and use of this file is allowed according to the terms of the MIT license.
+# For details see the COPYRIGHT file distributed with LuaDist.
+# Please note that the package source code is licensed under its own license.
+
+# Few convinence settings
+SET (CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS true)
+SET (CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_MODULE_PATH})
+
+# Where to install module parts:
+set(INSTALL_BIN bin CACHE PATH "Where to install binaries to.")
+set(INSTALL_LIB lib CACHE PATH "Where to install libraries to.")
+set(INSTALL_INC include CACHE PATH "Where to install headers to.")
+set(INSTALL_ETC etc CACHE PATH "Where to store configuration files")
+set(INSTALL_LMOD share/lua/lmod CACHE PATH "Directory to install Lua modules.")
+set(INSTALL_CMOD share/lua/cmod CACHE PATH "Directory to install Lua binary modules.")
+set(INSTALL_DATA share/${PROJECT_NAME} CACHE PATH "Directory the package can store documentation, tests or other data in.")
+set(INSTALL_DOC ${INSTALL_DATA}/doc CACHE PATH "Recommended directory to install documentation into.")
+set(INSTALL_EXAMPLE ${INSTALL_DATA}/example CACHE PATH "Recommended directory to install examples into.")
+set(INSTALL_TEST ${INSTALL_DATA}/test CACHE PATH "Recommended directory to install tests into.")
+set(INSTALL_FOO ${INSTALL_DATA}/etc CACHE PATH "Where to install additional files")
+
+
+# In MSVC, prevent warnings that can occur when using standard libraries.
+if(MSVC)
+ add_definitions(-D_CRT_SECURE_NO_WARNINGS)
+endif(MSVC)
+
+# Adds Lua shared library module target `_target`.
+# Additional sources to build the module are listed after `_target`.
+macro(add_lua_module _target)
+ find_package(Lua51 REQUIRED)
+ include_directories(${LUA_INCLUDE_DIR}) #2DO: somehow apply only to _target?
+
+ add_library(${_target} MODULE ${ARGN})
+ set_target_properties(${_target} PROPERTIES PREFIX "")
+ target_link_libraries(${_target} ${LUA_LIBRARY})
+
+ IF(WIN32)
+ set_target_properties(${_target} PROPERTIES LINK_FLAGS "-Wl,--enable-auto-import")
+ ENDIF()
+
+endmacro(add_lua_module)
+
+# Runs Lua script `_testfile` under CTest tester.
+# Optional argument `_testcurrentdir` is current working directory to run test under
+# (defaults to ${CMAKE_CURRENT_BINARY_DIR}).
+# Both paths, if relative, are relative to ${CMAKE_CURRENT_SOURCE_DIR}.
+# Under LuaDist, set test=true in config.lua to enable testing.
+macro(add_lua_test _testfile)
+ include(CTest)
+ if(BUILD_TESTING)
+ find_program(LUA NAMES lua lua.bat)
+ get_filename_component(TESTFILEABS ${_testfile} ABSOLUTE)
+ get_filename_component(TESTFILENAME ${_testfile} NAME)
+ get_filename_component(TESTFILEBASE ${_testfile} NAME_WE)
+
+ # Write wrapper script.
+ set(TESTWRAPPER ${CMAKE_CURRENT_BINARY_DIR}/${TESTFILENAME})
+ set(TESTWRAPPERSOURCE
+"package.path = '${CMAKE_CURRENT_BINARY_DIR}/?.lua\;${CMAKE_CURRENT_SOURCE_DIR}/?.lua\;' .. package.path
+package.cpath = '${CMAKE_CURRENT_BINARY_DIR}/?.so\;${CMAKE_CURRENT_BINARY_DIR}/?.dll\;' .. package.cpath
+return dofile '${TESTFILEABS}'
+" )
+ if(${ARGC} GREATER 1)
+ set(_testcurrentdir ${ARGV1})
+ get_filename_component(TESTCURRENTDIRABS ${_testcurrentdir} ABSOLUTE)
+ set(TESTWRAPPERSOURCE
+"require 'lfs'
+lfs.chdir('${TESTCURRENTDIRABS}')
+${TESTWRAPPERSOURCE}")
+ endif()
+ FILE(WRITE ${TESTWRAPPER} ${TESTWRAPPERSOURCE})
+
+ add_test(${TESTFILEBASE} ${LUA} ${TESTWRAPPER})
+ endif(BUILD_TESTING)
+
+ # see also http://gdcm.svn.sourceforge.net/viewvc/gdcm/Sandbox/CMakeModules/UsePythonTest.cmake
+endmacro(add_lua_test)
+
+# Converts Lua source file `_source` to binary string embedded in C source
+# file `_target`. Optionally compiles Lua source to byte code (not available
+# under LuaJIT2, which doesn't have a bytecode loader). Additionally, Lua
+# versions of bin2c [1] and luac [2] may be passed respectively as additional
+# arguments.
+#
+# [1] http://lua-users.org/wiki/BinToCee
+# [2] http://lua-users.org/wiki/LuaCompilerInLua
+function(add_lua_bin2c _target _source)
+ find_program(LUA NAMES lua lua.bat)
+ execute_process(COMMAND ${LUA} -e "string.dump(function()end)" RESULT_VARIABLE _LUA_DUMP_RESULT ERROR_QUIET)
+ if (NOT ${_LUA_DUMP_RESULT})
+ SET(HAVE_LUA_DUMP true)
+ endif()
+ message("-- string.dump=${HAVE_LUA_DUMP}")
+
+ if (ARGV2)
+ get_filename_component(BIN2C ${ARGV2} ABSOLUTE)
+ set(BIN2C ${LUA} ${BIN2C})
+ else()
+ find_program(BIN2C NAMES bin2c bin2c.bat)
+ endif()
+ if (HAVE_LUA_DUMP)
+ if (ARGV3)
+ get_filename_component(LUAC ${ARGV3} ABSOLUTE)
+ set(LUAC ${LUA} ${LUAC})
+ else()
+ find_program(LUAC NAMES luac luac.bat)
+ endif()
+ endif (HAVE_LUA_DUMP)
+ message("-- bin2c=${BIN2C}")
+ message("-- luac=${LUAC}")
+
+ get_filename_component(SOURCEABS ${_source} ABSOLUTE)
+ if (HAVE_LUA_DUMP)
+ get_filename_component(SOURCEBASE ${_source} NAME_WE)
+ add_custom_command(
+ OUTPUT ${_target} DEPENDS ${_source}
+ COMMAND ${LUAC} -o ${CMAKE_CURRENT_BINARY_DIR}/${SOURCEBASE}.lo ${SOURCEABS}
+ COMMAND ${BIN2C} ${CMAKE_CURRENT_BINARY_DIR}/${SOURCEBASE}.lo ">${_target}" )
+ else()
+ add_custom_command(
+ OUTPUT ${_target} DEPENDS ${SOURCEABS}
+ COMMAND ${BIN2C} ${_source} ">${_target}" )
+ endif()
+endfunction(add_lua_bin2c)
14 dist.info
@@ -0,0 +1,14 @@
+--- This file is part of LuaDist project
+
+name = "luaxml"
+version = "1.7.3"
+
+desc = "A minimal set of XML processing function in Lua, with simple mapping between XML and Lua tables"
+author = "Gerald Franz"
+license = "MIT/X11"
+url = "http://www.viremo.de/LuaXML/"
+maintainer = "Peter Drahoš"
+
+depends = {
+ "lua ~> 5.1"
+}
BIN lua.exe
Binary file not shown.
BIN lua51.dll
Binary file not shown.
147 readme.txt
@@ -0,0 +1,147 @@
+LuaXML
+
+- a module that maps between Lua and XML without much ado
+version 1.7.2, 2009-09-06 by Gerald Franz, www.viremo.de
+
+LuaXML provides a minimal set of functions for the processing of XML data in Lua. It offers a
+very simple and natural mapping between the XML data format and Lua tables, which
+allows one to parse XML data just using Lua's normal table access and iteration
+methods: Substatements and text content is represented as array data having
+numerical keys, attributes and tags use string keys. This representation makes
+sure that the structure of XML data is exactly preserved in a read/write cycle.
+Since version 1.7, LuaXML consists of a well-optimized portable ISO-standard C file
+and a small Lua file. It is published under the same liberal licensing conditions as Lua
+itself (see below). It has been successfully compiled and used under Linux, various
+flavours of MS Windows, and MacOS X.
+
+
+
+Example
+
+-- import the LuaXML module
+require("LuaXML")
+-- load XML data from file "test.xml" into local table xfile
+local xfile = xml.load("test.xml")
+-- search for substatement having the tag "scene"
+local xscene = xfile:find("scene")
+-- if this substatement is found...
+if xscene ~= nil then
+ -- ...print it to screen
+ print(xscene)
+ -- print attribute id and first substatement
+ print( xscene.id, xscene[1] )
+ -- set attribute id
+ xscene["id"] = "newId"
+end
+
+-- create a new XML object and set its tag to "root"
+local x = xml.new("root")
+-- append a new subordinate XML object, set its tag to "child", and its content to 123
+x:append("child")[1] = 123
+print(x)
+
+
+
+Documentation
+
+LuaXML consists of the following functions:
+
+require("LuaXML")
+imports the LuaXML module.
+LuaXML consists of a lua file (LuaXML.lua) and normally a shared library (.dll/.so), although a static linking is possible as well. Both parts are imported by this call provided that they are found in Lua's package search path.
+
+function xml.new(arg)
+creates a new LuaXML object.
+ * param arg (optional), (1) a table to be converted to be converted to a LuaXML object, or (2) the tag of the new LuaXML object
+ Note that it is not mandatory to use this function in order to treat a Lua table as LuaXML object. Setting the metatable just allows the usage of a more object-oriented syntax (e.g., xmlvar:str() instead of xml.str(xmlvar) ). XML objects created by xml.load() or xml.eval() automatically offer the object-oriented syntax.
+ * Returns new LuaXML object
+
+function xml.append(var,tag)
+appends a new subordinate LuaXML object to an existing one, optionally sets tag.
+ * param var the parent LuaXML object
+ * param tag (optional) the tag of the appended LuaXML object
+ * Returns appended LuaXML object or nil in case of error
+
+function xml.load(filename)
+loads XML data from a file and returns it as table
+
+ * param filename the name and path of the file to be loaded
+ * Returns a Lua table containing the xml data in case of success or nil.
+
+function xml.save(var,filename)
+saves a Lua var as XML file.
+
+ * param var, the variable to be saved, normally a table
+ * param filename the filename to be used. An existing file of the same name gets overwritten.
+
+function xml.eval(xmlstring)
+converts an XML string to a Lua table
+
+ * param xmlstring the string to be converted
+ * Returns a Lua table containing the xml data in case of success or nil.
+
+function xml.tag(var, tag)
+sets or returns tag of a LuaXML object. This method is just "syntactic sugar" (using a typical Lua term)
+that allows the writing of clearer code. LuaXML stores the tag value of an XML statement at table
+index 0, hence it can be simply accessed or altered by var[0] or var[xml.TAG] (the latter is just a
+symbolic name for the value 0). However, writing var:tag() for access or var:tag("newTag") for altering
+may be more self explanatory.
+
+ * param var, the variable whose tag should be accessed, a LuaXML object
+ * param tag (optional) the new tag to be set.
+ * Returns the current tag as string
+
+function xml.str(var, indent, tag)
+converts any Lua var to an xml string.
+
+ * param var, the variable to be converted, normally a table
+ * param indent (optional) the current level of indentation for pretty output. Mainly for internal use.
+ * param tag (optional) the tag to be used for a table without tag. Mainly for internal use.
+ * Returns an XML string in case of success or nil.
+
+function xml.find(var, tag, attributeKey,attributeValue)
+recursively parses a Lua table for a substatement fitting to the provided tag and attribute
+
+ * param var, the table to be searched in.
+ * param tag (optional) the xml tag to be found.
+ * param attributeKey (optional) the exact attribute to be found.
+ * param attributeValue (optional) the attribute value to be found.
+ * Returns the first (sub-)table which matches the search condition or nil.
+
+function xml.registerCode(decoded,encoded)
+registers a custom code for the conversion between non-standard characters and XML character entities
+
+ * param decoded the character (sequence) to be used within Lua.
+ * param encoded the character entity to be used in XML.
+ * By default, only the most basic entities are known to LuaXML (� & < > ').
+ ANSI codes above 127 are directly converted to the XML character codes
+ of the same number. If more character codes are needed, they can be
+ registered using this function.
+
+
+
+LuaXML License
+
+LuaXML is licensed under the terms of the MIT license reproduced below,
+the same as Lua itself. This means that LuaXML is free software and can be
+used for both academic and commercial purposes at absolutely no cost.
+
+Copyright (C) 2007-2009 by Gerald Franz, www.viremo.de
+
+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.
16 test.lua
@@ -0,0 +1,16 @@
+require('LuaXml')
+
+-- load XML data from file "test.xml" into local table xfile
+local xfile = xml.load("test.xml")
+-- search for substatement having the tag "scene"
+local xscene = xfile:find("scene")
+-- if this substatement is found…
+if xscene ~= nil then
+ -- …print it to screen
+ print(xscene)
+ -- print tag, attribute id and first substatement
+ print( xscene:tag(), xscene.id, xscene[1] )
+end
+
+xfile:save"t.xml"
+print("---\nREADY.")
135 test.xml
@@ -0,0 +1,135 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<XperiML version="2.0">
+ <!-- application info -->
+ <applicationInfo>
+ <string id="author"> S&#228;lly.Doe@t&#252;bingen.de </string>
+ <string id="version"> 0.5.0 </string>
+ <string id="date"> 2004-11-23 - 2006-08-18 </string>
+ <string id="shortDescr"> a demonstration application for LuaXML scripting </string>
+ <string id="usage"> [ -i(ini.xml) ] </string>
+ </applicationInfo>
+
+<!-- initialization of the window -->
+ <deviceWindow id="0" name="window" deviceContainer="input">
+ <string id="winTitle"> my window </string>
+ <float id="mouseRelative"> 0 </float>
+ <float id="mouseNeutral"> 0.0 </float>
+ <bool id="mouseVisible"> 0 </bool>
+ <bool id="fullScreen"> 0 </bool>
+ <int id="zBufferBits"> 24 </int>
+ <int id="stencilBufferBits"> 0 </int>
+
+ <int id="winSizeX"> 800 </int>
+ <int id="winSizeY"> 600 </int>
+ <floatArray id="bgColor"> 0.5 0.6 0.7 </floatArray>
+
+ <!-- 2d visualization / overlay initialization -->
+ <overlay>
+ <floatArray id="bgNormalColor"> 1.0 1.0 1.0 0.2 </floatArray>
+ <floatArray id="fgNormalColor"> 1.0 0.0 1.0 0.7 </floatArray>
+ <floatArray id="bgSelectColor"> 0.0 0.5 1.0 0.7 </floatArray>
+ <floatArray id="fgSelectColor"> 1.0 1.0 1.0 1.0 </floatArray>
+ <!-- overlay plane minimum and maximum coordinates -->
+ <float id="minX"> -1.0 </float>
+ <float id="minY"> -1.0 </float>
+ <float id="maxX"> 1.0 </float>
+ <float id="maxY"> 1.0 </float>
+ </overlay>
+
+ <!-- X Y Z H P R (output axes) -->
+ <axesInputMapping> 0 1 2 3 4 5 </axesInputMapping>
+ <axesInputScale> 1 1 1 1 1 1 </axesInputScale>
+ <axesInputShift> 0 0 0 0 0 0 </axesInputShift>
+ </deviceWindow>
+
+
+ <deviceGraphics id="0">
+ <!-- 3d visualization initialization -->
+ <float id="nearClipping"> 0.1 </float>
+ <float id="farClipping"> 2000 </float>
+ <float id="frustumLeft"> -1.0 </float>
+ <float id="frustumRight"> 1.0 </float>
+ <float id="frustumBottom">-.75 </float>
+ <float id="frustumTop"> .75 </float>
+ <bool id="backFaceCulling"> 1 </bool>
+ <!-- camera initialization -->
+ <camera object="observer" pos="0 -3 1.6 0 0 0"/>
+ </deviceGraphics>
+
+ <!-- audio device initialization -->
+ <deviceAudio id="0" class="deviceAudioAL"> <!-- specific global settings for OpenAL -->
+ <int id="distanceModel"> 1 </int> <!-- valid arguments are NONE=0, INVERSE_DISTANCE=1 (default), INVERSE_DISTANCE_CLAMPED=2, see OpenAL ref. man. p.21 -->
+ <float id="dopplerVelocity"> 330.0 </float> <!-- corresponds to sonic speed for doppler effect calculations -->
+ <float id="dopplerFactor"> 1.0 </float> <!-- additional scaling factor for doppler effect calculations -->
+ </deviceAudio>
+
+ <!-- internal script definitions -->
+ <scripts>
+ <script name="main" mime="application/x-lua">
+ <![CDATA[
+ -- initialization
+ if nFrames==nil then
+ nFrames=0;
+ tLastFrames=ve.now();
+ end
+
+ -- termination
+ if obj.getFlag(INPUT,27) then
+ ve.exit();
+ end
+
+ -- update info line:
+ if ve.now()>=tLastFrames+1.0 then
+ tLastFrames=ve.now()
+ ovl.text(1,-1,ALIGN_RIGHT,ALIGN_BOTTOM,nFrames," fps");
+ nFrames=0;
+ end
+
+ nFrames=nFrames+1;
+ ]]>
+ </script>
+ </scripts>
+
+ <!-- resource definition -->
+ <resources>
+ <resource mime="model/vrml" id="1" name="virtualab" url="resources/virtualab.wrl"/>
+ <resource mime="model/vrml" id="2" name="surface" url="resources/virtualab_surface.wrl"/>
+ <resource mime="model/vrml" id="3" name="cube" url="resources/box.wrl"/>
+ <resource mime="model/vrml" id="5" name="ball" url="resources/ball01.wrl"/>
+ <resource mime="image/png" id="6" name="veRner" url="resources/veRner_small.png" sizeX="6" sizeY="3"/>
+ <resource mime="image/png" id="7" name="explo" url="resources/explo.png" sizeX="3" sizeY="3" timeSpan="1.0" loop="true" tileX="4" tileY="4" usePitch="true"/>
+
+ <resource mime="font/txf" id="10" name="default" url="default.txf" size="24"/>
+ <resource mime="audio/wav" id="11" loop="true" url="resources/ding.wav"/>
+ <resource mime="audio/wav" id="12" pitch="1.0" loop="true" attenuationDist="3.0" url="resources/riff01.wav"/>
+ <resource mime="audio/wav" id="13" pitch="1.0" loop="true" url="resources/river.wav"/>
+
+ <container id="20" name="box" shape="3" sound="12"/>
+ <container id="21" name="ufo" shape="5" sound="13"/>
+
+ </resources>
+
+ <!-- scene and simulation initialization -->
+ <scene id="0" script="main">
+ <object id="0" name="observer" script="camera.lua" input="window"/>
+ <object id="1" shape="1" surface="2" pos="0 0 0"/>
+ <object id="3" shape="20" sound="20" pos="-5 5 0 225 0 0"/>
+ <object id="5" shape="21" sound="21" pos="2 2 2" speed="0 2 0 30 0 0"/>
+ <object id="6" shape="6" pos="0 7 5"/>
+ <object id="7" shape="7" pos="-4.5 4.5 1.7"/>
+ <object id="11" sound="11" pos="10 -10 0"/>
+
+ <light id="0" enabled="1" position="-.5 -.75 1.0 0.0" ambient="0.3 0.3 0.3 1.0" diffuse="0.7 0.7 0.7 1.0" specular="1.0 1.0 1.0 1.0"/>
+ </scene>
+
+ <cdata_test>
+ <chars><![CDATA[x<works>]]></chars>
+ <tagged><![CDATA[<works>]]></tagged>
+ <open><![CDATA[<]]></open>
+ <close><![CDATA[>]]></close>
+ <empty><![CDATA[]]></empty>
+ </cdata_test>
+
+</XperiML>
+
+

0 comments on commit 359f3e6

Please sign in to comment.