Initial commit
authorMyhailo Danylenko <isbear@ukrpost.net>
Sun, 22 Feb 2009 23:14:24 +0200
changeset 0 65cbecad22b4
child 1 7d87d323c889
Initial commit
.gitignore
CMakeLists.txt
COPYING
README
TODO
config.h.in
main.c
util.c
util.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/.gitignore	Sun Feb 22 23:14:24 2009 +0200
@@ -0,0 +1,25 @@
+# ignore generated by libtool files (no more necessary)
+*.a
+*.o
+*.lo
+*.la
+*.so
+*.lai
+*.so.*
+# ignore backup files
+*~
+# ignore docs: they are not important and apiref is generated on the fly
+*.html
+# ignore generated makefile
+Makefile
+# ignore cmake files
+*.cmake
+CMake*
+CPack*
+# ignore generated header
+config.h
+# ignore resulting bundles
+*.deb
+*.tar.bz2
+# ignore build dir
+build
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/CMakeLists.txt	Sun Feb 22 23:14:24 2009 +0200
@@ -0,0 +1,68 @@
+
+cmake_minimum_required(VERSION 2.6)
+project(mcabber-lua C)
+
+## User options
+option(DEBUG "Enable debugging output" ON)
+option(MCABBER_INCLUDE_DIR "Path to mcabber include files" "/home/isbear/src/mcabber/hglm/mcabber/src")
+
+## Define targets
+add_library(mcabber-lua MODULE main.c util.c)
+get_target_property(mcabber-lua_SOURCES mcabber-lua SOURCES)
+
+## Packaging information
+#set(CPACK_PACKAGE_NAME mcabber-lua)
+set(CPACK_PACKAGE_VERSION_MAJOR 0)
+set(CPACK_PACKAGE_VERSION_MINOR 0)
+set(CPACK_PACKAGE_VERSION_PATCH 0)
+set(CPACK_PACKAGE_VENDOR "IsBear")
+set(CPACK_PACKAGE_CONTACT "Myhailo Danylenko <isbear@ukrpost.net>")
+set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Mcabber lua module")
+set(CPACK_PACKAGE_DESCRIPTION_FILE ${mcabber-lua_SOURCE_DIR}/README)
+set(CPACK_RESOURCE_FILE_LICENSE ${mcabber-lua_SOURCE_DIR}/COPYING)
+set(CPACK_RESOURCE_FILE_README ${mcabber-lua_SOURCE_DIR}/README)
+set(CPACK_RESOURCE_FILE_WELCOME ${mcabber-lua_SOURCE_DIR}/README)
+set(CPACK_DEBIAN_PACKAGE_SECTION libs)
+set(CPACK_SOURCE_GENERATOR TBZ2)
+set(CPACK_GENERATOR DEB)
+# FIXME: Detect architecture. How? Though, it anyway produces nonconformant deb names...
+set(CPACK_SYSTEM_NAME i386)
+# XXX: Set package name directly to get rid of -Sources?
+set(CPACK_SOURCE_IGNORE_FILES "/\\\\..*;\\\\.swp;~$;/build/;\\\\.tar\\\\.;\\\\.deb;\\\\.so")
+include(CPack)
+
+## Gather information about system
+find_package(Lua51 REQUIRED)
+#execute_process(COMMAND lua -e "print ( package.path )" OUTPUT_VARIABLE LUA_PATH OUTPUT_STRIP_TRAILING_WHITESPACE)
+#execute_process(COMMAND lua -e "print ( package.cpath )" OUTPUT_VARIABLE LUA_CPATH OUTPUT_STRIP_TRAILING_WHITESPACE)
+find_package(PkgConfig REQUIRED)
+pkg_check_modules(GLIB REQUIRED glib-2.0)
+pkg_check_modules(GMODULE REQUIRED gmodule-2.0)
+#find_package(Perl)
+
+## Set up compiler
+configure_file(config.h.in config.h)
+include_directories(SYSTEM ${LUA_INCLUDE_DIR} ${GLIB_INCLUDE_DIRS} ${GMODULE_INCLUDE_DIRS})
+target_link_libraries(mcabber-lua ${LUA_LIBRARIES} ${GLIB_LIBRARIES} ${GMODULE_LIBRARIES})
+include_directories(${mcabber-lua_SOURCE_DIR} ${mcabber-lua_BINARY_DIR} ${MCABBER_INCLUDE_DIR})
+
+## Extra targets
+#if(PERL_FOUND)
+#	add_custom_command(OUTPUT ${lua-lm_BINARY_DIR}/loudmouth.html COMMAND ${PERL_EXECUTABLE} ${lua-lm_SOURCE_DIR}/docgen.pl ${lua-lm_SOURCES} > ${lua-lm_BINARY_DIR}/loudmouth.html DEPENDS ${lua-lm_SOURCE_DIR}/docgen.pl ${lua-lm_SOURCES} WORKING_DIRECTORY ${lua-lm_SOURCE_DIR})
+#	add_custom_target(doc ALL DEPENDS ${lua-lm_BINARY_DIR}/loudmouth.html)
+#endif()
+#add_custom_target(test COMMAND env "LUA_PATH=${lua-lm_SOURCE_DIR}/?.lua;${LUA_PATH}" "LUA_CPATH=${lua-lm_SOURCE_DIR}/?.so;${lua-lm_BINARY_DIR}/?.so;${LUA_CPATH}" lua ${lua-lm_SOURCE_DIR}/test.lua DEPENDS loudmouth VERBATIM)
+#add_custom_target(test1 COMMAND env "LUA_PATH=${lua-lm_SOURCE_DIR}/?.lua;${LUA_PATH}" "LUA_CPATH=${lua-lm_SOURCE_DIR}/?.so;${lua-lm_BINARY_DIR}/?.so;${LUA_CPATH}" lua ${lua-lm_BINARY_DIR}/test.lua DEPENDS loudmouth VERBATIM)
+
+## Set up installer
+install(TARGETS mcabber-lua DESTINATION lib/mcabber)
+#install(FILES lm.lua DESTINATION share/lua/5.1)
+#install(FILES test.lua DESTINATION share/doc/${CPACK_PACKAGE_NAME}/examples)
+#if(PERL_FOUND)
+#	install(FILES ${lua-lm_BINARY_DIR}/loudmouth.html DESTINATION share/doc/${CPACK_PACKAGE_NAME})
+#endif()
+install(FILES README DESTINATION share/doc/${CPACK_PACKAGE_NAME})
+install(FILES TODO DESTINATION share/doc/${CPACK_PACKAGE_NAME})
+install(FILES COPYING DESTINATION share/doc/${CPACK_PACKAGE_NAME})
+
+## The End ## vim: se ts=4: ##
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/COPYING	Sun Feb 22 23:14:24 2009 +0200
@@ -0,0 +1,339 @@
+		    GNU GENERAL PUBLIC LICENSE
+		       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+		    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+			    NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+
+	    How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    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.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/README	Sun Feb 22 23:14:24 2009 +0200
@@ -0,0 +1,24 @@
+
+This is a lua 5.1 module for mcabber.
+
+To install it, you need lua and glib headers and libraries and
+cmake. Then do
+$ cd build
+$ cmake ..
+$ make
+# make install
+
+Debian users can instead of make install do
+$ make package
+# dpkg -i mcabber-lua-*.deb
+
+Also you can be interested in running
+$ make edit_cache
+before doing make to configure some project settings.
+
+This code underlies terms of GNU GPL v2 or later.
+
+I will be happy to get feedback, patches, suggestions, etc.
+
+  -- Myhailo Danylenko <isbear@ukrpost.net>
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TODO	Sun Feb 22 23:14:24 2009 +0200
@@ -0,0 +1,8 @@
+
+improve global print to work on other types. or improve types :)
+finish roster list information
+implement dopath() thing instead of main.config_file()
+settings list?
+non-setting settings?
+...
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/config.h.in	Sun Feb 22 23:14:24 2009 +0200
@@ -0,0 +1,27 @@
+
+#ifndef LLM_CONFIG_H
+#define LLM_CONFIG_H
+
+// define this to enable debugging output
+#cmakedefine DEBUG
+
+#ifdef DEBUG
+#  include <stdio.h>
+
+#  ifndef LLM_LOG_PREFIX
+#    define LLM_LOG_PREFIX ( NULL )
+#  endif
+
+#  define D(FORMAT...) { g_log (LLM_LOG_PREFIX, G_LOG_LEVEL_DEBUG, FORMAT); }
+#  define I(FORMAT...) { g_log (LLM_LOG_PREFIX, G_LOG_LEVEL_INFO, FORMAT); }
+#  define W(FORMAT...) { g_log (LLM_LOG_PREFIX, G_LOG_LEVEL_WARNING, FORMAT); }
+#  define E(FORMAT...) { g_log (LLM_LOG_PREFIX, G_LOG_LEVEL_ERROR, FORMAT); }
+#else
+#  define D(FORMAT...) { /* FORMAT */ }
+#  define I(FORMAT...) { /* FORMAT */ }
+#  define W(FORMAT...) { /* FORMAT */ }
+#  define E(FORMAT...) { /* FORMAT */ }
+#endif
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.c	Sun Feb 22 23:14:24 2009 +0200
@@ -0,0 +1,605 @@
+
+#include <glib.h>
+#include <gmodule.h>
+#include <lua.h>
+#include <lauxlib.h>
+#include <lualib.h>
+#include <stdio.h>       // popen, pclose, fileno
+
+#include "logprint.h"    // scr_LogPrint
+#include "screen.h"      // scr_Beep, scr_WriteIncomingMessage
+#include "hbuf.h"        // HBB_PREFIX_INFO
+#include "commands.h"    // process_command
+#include "xmpp.h"        // xmpp_getstatus, xmpp_getstatusmsg, lconnection
+#include "roster.h"      // imstatus2char, foreach_buddy, buddy_*, current_buddy, BUDDATA, ROSTER_TYPE_*
+#include "utils.h"       // from_utf8
+#include "lua_util.h"    // mcabber_config_file, string2enum
+#include "hooks.h"
+#include "settings.h"
+
+
+lua_State *lua = NULL;    // global lua state object
+
+char *mcabber_config_filename (const char *file)
+{
+  char *home = getenv("HOME");
+  if (!home)
+    return NULL;
+  return g_strconcat (home, "/.mcabber/", file ? file : "", NULL);
+}
+
+/// print
+/// Prints it's arguments to log with default priority.
+/// A: message, message...
+static int lua_global_print (lua_State *L)
+{
+  const char *message;
+  lua_concat (L, lua_gettop (L));
+  message = lua_tostring (L, -1);
+  scr_LogPrint (LPRINT_LOGNORM, message);
+  lua_pop (L, 1);
+  return 0;
+}
+
+/// dopath
+/// Loads lua file from default location.
+/// A: string (filename, without ".lua")
+static int lua_global_dopath (lua_State *L)
+{
+ // const char *name = luaL_checkstring (L, 1);
+  // FIXME
+  return 0;
+}
+
+/// main.config_file
+/// Adds mcabber default config location path to config file name.
+/// Note: not sure, that this function will stay alive long.
+/// A: string (filename)
+/// R: string (full path)
+static int lua_main_config_file (lua_State *L)
+{
+  char *home = mcabber_config_filename (lua_isstring (L, 1) ?
+                                        lua_tostring (L, 1) : NULL);
+  lua_pop (L, 1);
+  if (!home) {
+    lua_pushstring (L, "Cannot find home dir!");
+    lua_error (L);
+  }
+  lua_pushstring (L, home);
+  g_free (home); // XXX
+  return 1;
+}
+
+/// log print type
+/// V: normal, log, debug, notutf8, lognorm
+static const string2enum_t lua_lprint[] = {
+  { "normal",  LPRINT_NORMAL  },
+  { "log",     LPRINT_LOG     },
+  { "debug",   LPRINT_DEBUG   },
+  { "notutf0", LPRINT_NOTUTF8 },
+  { NULL,      0              },
+};
+
+static const string2enum_t lua_roster_type[] = {
+  { "user",    ROSTER_TYPE_USER    },
+  { "group",   ROSTER_TYPE_GROUP   },
+  { "agent",   ROSTER_TYPE_AGENT   },
+  { "room",    ROSTER_TYPE_ROOM    },
+  { "special", ROSTER_TYPE_SPECIAL },
+  { NULL,      0                   },
+};
+
+/// main.log
+/// Prints message to log.
+/// A: log print type, message, message...
+static int lua_main_log (lua_State *L)
+{
+  const char *message;
+  int type = luaL_checkenum_multi (L, 1, lua_lprint);
+  lua_concat (L, lua_gettop (L) - 1);
+  message = lua_tostring (L, -1);
+  scr_LogPrint (type, message);
+  return 0;
+}
+
+/// main.option
+/// Sets or gets value of mcabber option.
+/// You can specify nil as a value to delete option.
+/// XXX: Should we do types here?
+/// A: string (option name), string (value, optional)
+/// R: string (value, optional)
+static int lua_main_option (lua_State *L)
+{
+  const char *name = luaL_checkstring (L, 1);
+  if (lua_gettop (L) > 1) { // Set
+    if (lua_type (L, 2) == LUA_TNIL)
+      settings_del (SETTINGS_TYPE_OPTION, name);
+    else {
+      const char *value = luaL_checkstring (L, 2);
+      settings_set (SETTINGS_TYPE_OPTION, name, value);
+    }
+    return 0;
+  } else {
+    const char *value = settings_get (SETTINGS_TYPE_OPTION, name);
+    if (value)
+      lua_pushstring (L, value);
+    else
+      lua_pushnil (L);
+    return 1;
+  }
+}
+
+/// main.connection
+/// Returns lightuserdata of mcabber's loudmouth connection.
+/// This can be very useful with lua-loudmouth, and not much otherwise.
+/// R: lightuserdata
+static int lua_main_connection (lua_State *L)
+{
+  lua_pushlightuserdata (L, lconnection);
+  return 1;
+}
+
+// Well, for now
+// I cannot get how
+// To use caps.
+
+/// main.add_feature
+/// A: string (xmlns)
+static int lua_main_add_feature (lua_State *L)
+{
+//  xmpp_add_feature (luaL_checkstring (L, 1));
+  return 0;
+}
+
+/// main.del_feature
+/// A: stirng (xmlns)
+static int lua_main_del_feature (lua_State *L)
+{
+//  xmpp_del_feature (luaL_checkstring (L, 1));
+  return 0;
+}
+
+typedef struct {
+  int reference;
+  lua_State *L;
+} lua_command_callback_t;
+
+/// command function
+/// A: argument string
+void lua_main_command_handler (char *args, lua_command_callback_t *cb)
+{
+  lua_rawgeti (cb->L, LUA_REGISTRYINDEX, cb->reference);
+  lua_pushstring (cb->L, args);
+  if (lua_pcall (cb->L, 1, 0, 0)) {
+    scr_LogPrint (LPRINT_LOGNORM, "lua: Command execution error: %s",
+                  lua_tostring (cb->L, -1));
+    lua_pop (cb->L, 1);
+  }
+}
+
+/// main.add_command
+/// A: string (command name), command function
+static int lua_main_add_command (lua_State *L)
+{
+  const char *name = luaL_checkstring (L, 1);
+  lua_command_callback_t *cb;
+  luaL_argcheck (L, lua_isfunction (L, 2), 2, "function expected");
+  cb = luaL_malloc (L, sizeof (lua_command_callback_t));
+  cb->reference = luaL_ref (L, LUA_REGISTRYINDEX);
+  cb->L = L;
+  cmd_add (name, "", 0, 0, (void (*) (char *p)) lua_main_command_handler, cb);
+  return 0;
+}
+
+/// main.print_info
+/// Prints a system message to buddy's window.
+/// A: string (jid), string (message)
+static int lua_main_print_info (lua_State *L)
+{
+  char *to = jidtodisp (luaL_checkstring (L, 1));
+  const char *message = luaL_checkstring (L, 2);
+  scr_WriteIncomingMessage (to, message, 0, HBB_PREFIX_INFO, 0);
+  g_free (to);
+  return 0;
+}
+
+/// main.beep
+/// Beeps with system speaker.
+static int lua_main_beep (lua_State *L)
+{
+  scr_Beep ();
+  return 0;
+}
+
+/// main.run
+/// Runs specified mcabber command.
+/// A: string
+static int lua_main_run (lua_State *L)
+{
+  const char *command = luaL_checkstring (L, 1);
+  process_command (command, TRUE);
+  return 0;
+}
+
+/// main.status
+/// Returns your current status.
+/// R: char (status letter), string (status message)
+static int lua_main_status (lua_State *L)
+{
+  char *sm = from_utf8 (xmpp_getstatusmsg ());
+  lua_pushlstring (L, &imstatus2char[xmpp_getstatus ()], 1);
+  lua_pushstring  (L, sm);
+  g_free (sm);
+  return 2;
+}
+
+// expects table on top!
+static void lua_rosterlist_callback (gpointer buddy, lua_State *L)
+{
+  lua_pushnumber (L, lua_objlen (L, -1) + 1);
+  lua_pushstring (L, buddy_getjid (buddy));
+  lua_settable (L, -3);
+}
+
+/// main.roster
+/// Returns array of jids of buddies in roster.
+/// R: table
+static int lua_main_roster (lua_State *L)
+{
+  lua_newtable (L);
+  foreach_buddy (ROSTER_TYPE_USER|ROSTER_TYPE_AGENT|ROSTER_TYPE_ROOM, (void (*) (gpointer buddy, void *data))lua_rosterlist_callback, L);
+  return 1;
+}
+
+/// main.current_buddy
+/// Returns jid of current selected buddy.
+/// R: string
+static int lua_main_current_buddy (lua_State *L)
+{
+  lua_pushstring (L, buddy_getjid (BUDDATA (current_buddy)));
+  return 1;
+}
+
+typedef struct {
+  lua_State *L;
+  gpointer buddy;
+} lua_state_and_buddy_t; // :)
+
+// expects table on top!
+static void lua_buddy_resources_callback (gpointer resource, lua_state_and_buddy_t *d)
+{
+  lua_pushstring  (d->L, resource);
+  lua_createtable (d->L, 0, 3);
+  lua_pushstring  (d->L, "priority");
+  lua_pushnumber  (d->L, buddy_getresourceprio (d->buddy, resource));
+  lua_settable    (d->L, -3);
+  lua_pushstring  (d->L, "status");
+  lua_pushlstring (d->L, &imstatus2char[buddy_getstatus (d->buddy, resource)], 1);
+  lua_settable    (d->L, -3);
+  lua_pushstring  (d->L, "message");
+  lua_pushstring  (d->L, buddy_getstatusmsg (d->buddy, resource));
+  lua_settable    (d->L, -3);
+  lua_settable    (d->L, -3);
+}
+
+/// main.buddy_info
+/// Returns a hash table with information on specified buddy.
+/// Table contains fields type, name, onserver and resources.
+/// Resources is also a hash table, that contains tables with information,
+/// specific for each resource. In each resource table there are fields
+/// priority, status and message.
+/// A: string (jid)
+/// R: table
+static int lua_main_buddy_info (lua_State *L)
+{
+  char *jid = jidtodisp (luaL_checkstring (L, 1));
+  GSList *buddy = roster_find (jid, jidsearch,
+                          ROSTER_TYPE_USER|ROSTER_TYPE_AGENT|ROSTER_TYPE_ROOM);
+  lua_state_and_buddy_t snb;
+  g_free (jid);
+
+  if (!buddy) {
+    lua_pushnil (L);
+    return 1;
+  }
+  
+  lua_createtable (L, 0, 3);
+  lua_pushstring  (L, "type");
+  lua_pushstring  (L, enum2string (buddy_gettype (BUDDATA (buddy)),
+                                   lua_roster_type));
+  lua_settable    (L, -3);
+  lua_pushstring  (L, "name");
+  lua_pushstring  (L, buddy_getname (BUDDATA (buddy)));
+  lua_settable    (L, -3);
+  lua_pushstring  (L, "onserver");
+  lua_pushboolean (L, buddy_getonserverflag (BUDDATA (buddy)));
+  lua_settable    (L, -3);
+  lua_pushstring  (L, "resources");
+  lua_createtable (L, 0, 0);
+  snb.L     = L;
+  snb.buddy = BUDDATA (buddy);
+  g_slist_foreach (buddy_getresources (BUDDATA (buddy)),
+                   (GFunc)lua_buddy_resources_callback, &snb);
+  lua_settable    (L, -3);
+  
+  return 1;
+}
+
+// TIMER
+
+#define LUA_TIMER_PRIORITY ( G_PRIORITY_HIGH_IDLE )
+
+typedef struct {
+  int reference;
+  lua_State *L;
+} lua_timer_callback_t;
+
+static void lua_timer_callback_destroy (lua_timer_callback_t *cb)
+{
+  luaL_unref (cb->L, LUA_REGISTRYINDEX, cb->reference);
+  luaL_free (cb->L, cb);
+}
+
+/// timer function
+/// Function, that will be called periodically until it returns false.
+/// R: boolean
+static gboolean lua_timer_callback (lua_timer_callback_t *cb)
+{
+  int ret;
+  lua_rawgeti (cb->L, LUA_REGISTRYINDEX, cb->reference);
+  if (lua_pcall (cb->L, 0, 1, 0)) {
+    scr_LogPrint (LPRINT_LOGNORM, "lua: Timer callback execution error: %s",
+                  lua_tostring (cb->L, -1));
+    lua_pop (cb->L, 1);
+    return FALSE;
+  }
+  ret = lua_toboolean (cb->L, -1);
+  lua_pop (cb->L, 1);
+  return ret;
+}
+
+/// main.timer
+/// Creates new timer function, that will be called periodically.
+/// A: integer (interval, seconds), timer function
+static int lua_main_timer (lua_State *L)
+{
+  int interval = luaL_checkint (L, 1);
+  lua_timer_callback_t *cb;
+  luaL_argcheck (L, lua_isfunction (L, 2), 2, "function expected");
+
+  cb = luaL_malloc (L, sizeof (lua_timer_callback_t));
+  cb->reference = luaL_ref (L, LUA_REGISTRYINDEX);
+  cb->L         = L;
+
+  g_timeout_add_seconds_full (LUA_TIMER_PRIORITY, interval,
+                              (GSourceFunc)lua_timer_callback, cb,
+                              (GDestroyNotify)lua_timer_callback_destroy);
+  return 0;
+}
+
+// BACKGROUND PIPE READING
+
+#define LUA_BGREAD_BUFFER ( 4096 )
+
+typedef struct {
+  lua_State *L;
+  FILE      *fd;
+  int        reference;
+} lua_bgread_callback_t;
+
+static gchar lua_bgread_buffer[LUA_BGREAD_BUFFER];
+
+static void lua_bgread_callback_destroy (lua_bgread_callback_t *cb)
+{
+  luaL_unref (cb->L, LUA_REGISTRYINDEX, cb->reference);
+  pclose (cb->fd);
+  luaL_free (cb->L, cb);
+}
+
+/// background reading function
+/// Function, that processes output from pipe in asynchroneous way.
+/// A: string (data) or nil (eof)
+/// R: boolean (false if reading should be terminated)
+static gboolean
+lua_bgread_callback (GIOChannel *source, GIOCondition condition,
+                     lua_bgread_callback_t *cb)
+{
+  int ret = TRUE;
+
+  if (condition | G_IO_IN) { // data
+    while (TRUE) {
+      gsize read = 0;
+      g_io_channel_read_chars(source, lua_bgread_buffer, LUA_BGREAD_BUFFER,
+                              &read, NULL);
+      if (!read) // exausted
+        break;
+
+      lua_rawgeti (cb->L, LUA_REGISTRYINDEX, cb->reference);
+      lua_pushlstring (cb->L, lua_bgread_buffer, read);
+      if (lua_pcall (cb->L, 1, 1, 0)) {
+        scr_LogPrint (LPRINT_LOGNORM,
+                      "lua: Bgread callback execution error: %s",
+                      lua_tostring (cb->L, -1));
+        lua_pop (cb->L, 1);
+        return FALSE;
+      }
+      ret = lua_toboolean (cb->L, -1);
+      lua_pop (cb->L, 1);
+      if (!ret) // enough
+        return FALSE;
+    }
+  }
+
+  if (condition & ~G_IO_IN) { // err or hup
+    lua_rawgeti (cb->L, LUA_REGISTRYINDEX, cb->reference);
+    lua_pushnil (cb->L);
+    if (lua_pcall (cb->L, 1, 1, 0)) {
+      scr_LogPrint (LPRINT_LOGNORM, "lua: Bgread callback execution error: %s",
+                    lua_tostring (cb->L, -1));
+      lua_pop (cb->L, 1);
+      return FALSE;
+    }
+    ret = lua_toboolean (cb->L, -1);
+    lua_pop (cb->L, 1);
+  }
+
+  return ret;
+}
+
+/// main.bgread
+/// Runs specified command and passes it's output to given function.
+/// A: string (command), background reading function
+static int lua_main_bgread (lua_State *L)
+{
+  const char *command = luaL_checkstring (L, 1);
+  lua_bgread_callback_t *cb;
+  FILE *fd;
+  GIOChannel *channel;
+  const char *charset = NULL;
+  luaL_argcheck (L, lua_isfunction (L, 2), 2, "function expected");
+
+  fd = popen (command, "r");
+  if (!fd) {
+    lua_pushstring (L, "Error opening pipe");
+    lua_error (L);
+  }
+
+  channel = g_io_channel_unix_new (fileno (fd));
+// We, most likely, need this,
+// But we cannot use this,
+// It will block.
+//if (!g_get_charset (&charset))
+  g_io_channel_set_encoding (channel, charset, NULL);
+  g_io_channel_set_buffered (channel, FALSE);
+  g_io_channel_set_flags (channel, G_IO_FLAG_NONBLOCK, NULL);
+  g_io_channel_set_close_on_unref (channel, TRUE);
+
+  cb = luaL_malloc (L, sizeof (lua_bgread_callback_t));
+  cb->reference = luaL_ref (L, LUA_REGISTRYINDEX);
+  cb->L         = L;
+  cb->fd        = fd;
+
+  g_io_add_watch_full (channel, G_PRIORITY_HIGH_IDLE,
+                       G_IO_IN|G_IO_HUP|G_IO_ERR,
+                       (GIOFunc)lua_bgread_callback, cb,
+                       (GDestroyNotify)lua_bgread_callback_destroy);
+  return 0;
+}
+
+// MAIN INITIALIZATION CODE
+
+static void *lua_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
+  if (nsize == 0) {
+    g_free (ptr);
+    return NULL;
+  } else
+    return g_realloc (ptr, nsize);
+}
+
+static void lua_hook (hk_arg_t *args, lua_State *L)
+{
+  hk_arg_t *arg = args;
+  lua_getglobal (lua, "hook_handler");
+  if (!lua_isfunction (lua, -1)) {
+    lua_pop (lua, 1);
+    return;
+  }
+  lua_newtable (L);
+  while (arg->name != NULL) {
+    lua_pushstring (L, arg->name);
+    lua_pushstring (L, arg->value);
+    lua_settable (L, -3);
+    arg++;
+  }
+  if (lua_pcall (lua, 1, 0, 0)) {
+    scr_LogPrint (LPRINT_NORMAL, "lua: Error in hook_handler: %s",
+                  lua_tostring (lua, -1));
+    lua_pop (lua, 1);
+  }
+}
+
+static const luaL_Reg lua_reg_main[] = {
+  { "config_file",   lua_main_config_file   },
+  { "connection",    lua_main_connection    },
+  { "log",           lua_main_log           },
+  { "option",        lua_main_option        },
+  { "add_feature",   lua_main_add_feature   },
+  { "del_feature",   lua_main_del_feature   },
+  { "add_command",   lua_main_add_command   },
+  { "print_info",    lua_main_print_info    },
+  { "beep",          lua_main_beep          },
+  { "run",           lua_main_run           },
+  { "status",        lua_main_status        },
+  { "roster",        lua_main_roster        },
+  { "current_buddy", lua_main_current_buddy },
+  { "buddy_info",    lua_main_buddy_info    },
+  { "timer",         lua_main_timer         },
+  { "bgread",        lua_main_bgread        },
+  { NULL,            NULL                   }, // end
+};
+
+const gchar *g_module_check_init (GModule *module)
+{
+  char *initfile;
+
+  lua = lua_newstate(lua_alloc, NULL);
+  if (!lua) {
+    scr_LogPrint(LPRINT_LOGNORM, "lua: Initialization error");
+    return;
+  }
+
+  luaL_openlibs(lua);
+
+  luaL_register(lua, "main", lua_reg_main);
+  lua_pop (lua, 1);
+// lua_register(lua, "dopath", lua_global_dopath);
+  lua_register(lua, "print", lua_global_print);
+  
+  initfile = mcabber_config_filename ("mcabberrc.lua");
+  if (!initfile)
+    scr_LogPrint(LPRINT_LOGNORM, "lua: Cannot determine config file name");
+  else {
+    int err = luaL_loadfile(lua, initfile);
+    if (err)
+      scr_LogPrint(LPRINT_LOGNORM, "lua: Unable to compile rc file (%d)", err);
+    else if (lua_pcall(lua, 0, LUA_MULTRET, 0)) {
+      scr_LogPrint(LPRINT_LOGNORM, "lua: Runtime error in rc file: %s",
+          lua_tostring(lua, -1));
+      lua_pop (lua, 1);
+    } else
+      scr_LogPrint(LPRINT_LOGNORM, "Loaded mcabberrc.lua");
+    g_free(initfile); // XXX
+  }
+
+  hk_add_handler ((hk_handler_t) lua_hook, lua);
+
+  lua_getglobal (lua, "hook_start");
+  if (!lua_isfunction (lua, -1))
+    lua_pop (lua, 1);
+  else if (lua_pcall (lua, 0, 0, 0)) {
+    scr_LogPrint (LPRINT_NORMAL, "lua: Error in hook_start: %s",
+                  lua_tostring (lua, -1));
+    lua_pop (lua, 1);
+  }
+}
+
+void g_module_unload (GModule *module)
+{
+  if (lua) {
+    lua_getglobal (lua, "hook_quit");
+    if (!lua_isfunction (lua, -1))
+      lua_pop (lua, 1);
+    else if (lua_pcall (lua, 0, 0, 0)) {
+      scr_LogPrint (LPRINT_NORMAL, "lua: Error in hook_quit: %s",
+                    lua_tostring (lua, -1));
+      lua_pop (lua, 1);
+    }
+  
+    hk_del_handler ((hk_handler_t) lua_hook, lua);
+
+    lua_close (lua);
+    lua = NULL;
+  }
+}
+
+/* vim: set expandtab cindent cinoptions=>2\:2(0:  For Vim users... */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/util.c	Sun Feb 22 23:14:24 2009 +0200
@@ -0,0 +1,132 @@
+
+#include <glib.h>	// g_ascii_strcasecmp
+#include <lua.h>
+#include <lauxlib.h>
+
+#include "util.h"
+
+enum_value_t string2enum (const char *string, const string2enum_t *set)
+{
+	while (set->string) {
+		if (!g_ascii_strcasecmp (string, set->string))
+			return set->value;
+		++set;
+	}
+	return set->value;
+}
+
+const char *enum2string (enum_value_t value, const string2enum_t *set)
+{
+	while (set->string) {
+		if (value == set->value)
+			return set->string;
+		++set;
+	}
+	return NULL;
+}
+
+/// argument enum field
+/// String that will be converted to number or just plain number, that will be passed as is.
+/// Note, that if enum name is not recognized no error will be raised and default vale will be used.
+enum_value_t luaL_checkenum (lua_State *L, int index, const string2enum_t *set)
+{
+	if (lua_type (L, index) == LUA_TNUMBER)
+		return lua_tointeger (L, index);
+	else
+		return string2enum (luaL_checkstring (L, index), set);
+}
+
+/// return enum field
+/// String. If no string found, plain number will be returned.
+void luaL_pushenum (lua_State *L, enum_value_t value, const string2enum_t *set)
+{
+	const char *string = enum2string (value, set);
+	if (string != NULL)
+		lua_pushstring (L, string);
+	else
+		lua_pushinteger (L, value);
+}
+
+/// argument flags field
+/// Can be just plain number, then it is passed as is.
+/// Can be a string, then it is recognized as a single enabled flag.
+/// Or can be a table of the following format:
+/// * integer keys should have string values, that will be used as enabled flag names or numerical values, that will be just ORed;
+/// * string keys should be flag names, that will be enabled, if corresponding value contains true value.
+enum_value_t luaL_checkenum_multi (lua_State *L, int index, const string2enum_t *set)
+{
+	int type = lua_type (L, index);
+	if (type == LUA_TNUMBER)
+		return lua_tointeger (L, index);
+	else if (type == LUA_TSTRING)
+		return string2enum (lua_tostring (L, index), set);
+	else if (type == LUA_TTABLE) {
+		enum_value_t retval = 0;
+		lua_pushnil (L);
+		while (lua_next (L, index) != 0) {
+			type = lua_type (L, -2);
+			if (type == LUA_TNUMBER) {
+				type = lua_type (L, -1);
+				if (type == LUA_TNUMBER)
+					retval |= lua_tointeger (L, -1);
+				else if (type == LUA_TSTRING)
+					retval |= string2enum (lua_tostring (L, -1), set);
+				else
+					luaL_argerror (L, index, "wrong value type of flag");
+			} else if (type == LUA_TSTRING) {
+				if (lua_toboolean (L, -1))
+					retval |= string2enum (lua_tostring (L, -2), set);
+			} else
+				luaL_argerror (L, index, "wrong key type of flags table");
+			lua_pop (L, 1);
+		}
+	} else
+		luaL_argerror (L, index, "integer, string, or table of ones expected");
+	return 0; // never happens
+}
+
+/// returned flags field
+/// Is always a table with present flag names as keys with true values.
+/// Not present flags are not present in table either.
+/// Not recognized values, if present, will be stored as a number in a first sequential table member (table[1]).
+void luaL_pushenum_multi (lua_State *L, enum_value_t value, const string2enum_t *set)
+{
+	enum_value_t matched = 0;
+	lua_newtable (L);
+	while (set->string) {
+		if (value & set->value) {
+			matched |= set->value & value;
+			lua_pushstring (L, set->string);
+			lua_pushboolean (L, 1);
+			lua_settable (L, -3);
+		}
+		++set;
+	}
+	if (value ^ matched) {
+		lua_pushinteger (L, 1);
+		lua_pushinteger (L, value ^ matched);
+		lua_settable (L, -3);
+	}
+}
+
+void *luaL_malloc (lua_State *L, size_t size)
+{
+	void      *ud;
+	lua_Alloc  allocf = lua_getallocf (L, &ud);
+	return (*allocf) (ud, NULL, 0, size);
+}
+
+void *luaL_realloc (lua_State *L, void *ptr, size_t osize, size_t nsize)
+{
+	void      *ud;
+	lua_Alloc  allocf = lua_getallocf (L, &ud);
+	return (*allocf) (ud, ptr, osize, nsize);
+}
+
+void  luaL_free (lua_State *L, void *ptr)
+{
+	void      *ud;
+	lua_Alloc  allocf = lua_getallocf (L, &ud);
+	(*allocf) (ud, ptr, 1, 0);
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/util.h	Sun Feb 22 23:14:24 2009 +0200
@@ -0,0 +1,45 @@
+
+#ifndef MISC_LUA_UTIL_H
+#define MISC_LUA_UTIL_H
+
+#include <lua.h>
+
+// You can set this if anther type is required
+#ifndef enum_value_t
+#define enum_value_t int
+#endif
+
+#define lua_pushconststring(L, STRING) { lua_pushlstring (L, STRING, sizeof(STRING)); }
+
+// Array of string2eunm_t's must be ended with pair { NULL, fallback_value }
+typedef struct {
+	const char   *string;
+	enum_value_t  value;
+} string2enum_t;
+
+// If not found, fallback_value is returned
+enum_value_t  string2enum (const char *string, const string2enum_t *set);
+// If not found, NULL is returned
+const char   *enum2string (enum_value_t value, const string2enum_t *set);
+
+// returns result of string2enum on specified stack index, can handle plain numbers (no s2e called in this case)
+enum_value_t luaL_checkenum (lua_State *L, int index, const string2enum_t *set);
+// pushes onto a stack result of enum2string on a given value, if not recognized, pushes value as number
+void         luaL_pushenum (lua_State *L, enum_value_t value, const string2enum_t *set);
+
+// as luaL_checknum, but additionally handles tables as a multiple flags set.
+// table can contain both array and hash key-value pairs
+// hash entries are ORed with string2enum(key) if value resolves to lua true value
+// array entries are always ORed with string2enum(value)
+// eg { flag1, flag2, 16, flag3 = true, flag4 = { }, flag5 = nil } will set all flags except flag5 (and 16 too will be ORed)
+enum_value_t luaL_checkenum_multi (lua_State *L, int index, const string2enum_t *set);
+// pushes to stack table with all matched values from a set in a hash format
+// eg { flag1 = true, flag2 = true, flag6 = true, 16 } - that's it, if some bits will not match, they will be passed as a first array element.
+void         luaL_pushenum_multi (lua_State *L, enum_value_t value, const string2enum_t *set);
+
+void *luaL_malloc (lua_State *L, size_t size);
+void *luaL_realloc (lua_State *L, void *ptr, size_t osize, size_t nsize);
+void  luaL_free (lua_State *L, void *ptr);
+
+#endif
+