From ad0de345d85d0622e1831e4880e7d89582b3c905 Mon Sep 17 00:00:00 2001 From: ShadowNinja Date: Mon, 29 Apr 2013 18:07:44 -0400 Subject: [PATCH] Rewrite --- .gitignore | 10 +- .gitmodules | 3 + CMakeLists.txt | 24 +- README.txt | 129 +- doc/API.txt | 141 - doc/CHANGES.txt | 37 - doc/LICENSE-LuaIRC.txt | 7 - doc/LICENSE.txt | 15 - doc/TODO.txt | 20 - doc/lua/contents.html | 405 -- doc/lua/logo.gif | Bin 4232 -> 0 bytes doc/lua/lua.1 | 163 - doc/lua/lua.css | 15 - doc/lua/lua.html | 172 - doc/lua/luac.1 | 136 - doc/lua/luac.html | 145 - doc/lua/manual.html | 6247 ----------------- doc/lua/readme.html | 32 - doc/luairc/LICENSE | 7 - doc/luairc/README | 31 - doc/luairc/TODO | 20 - doc/luairc/index.html | 156 - doc/luairc/luadoc.css | 286 - doc/luairc/modules/callbacks.html | 858 --- doc/luairc/modules/irc.channel.html | 945 --- doc/luairc/modules/irc.constants.html | 117 - doc/luairc/modules/irc.ctcp.html | 117 - doc/luairc/modules/irc.dcc.html | 164 - doc/luairc/modules/irc.debug.html | 196 - doc/luairc/modules/irc.html | 683 -- doc/luairc/modules/irc.message.html | 117 - doc/luairc/modules/irc.misc.html | 117 - doc/luasocket/LICENSE | 20 - doc/luasocket/NEW | 54 - doc/luasocket/README | 6 - doc/luasocket/dns.html | 132 - doc/luasocket/ftp.html | 289 - doc/luasocket/home.html | 256 - doc/luasocket/http.html | 325 - doc/luasocket/installation.html | 161 - doc/luasocket/introduction.html | 333 - doc/luasocket/ltn12.html | 430 -- doc/luasocket/luasocket.png | Bin 11732 -> 0 bytes doc/luasocket/mime.html | 476 -- doc/luasocket/reference.css | 54 - doc/luasocket/reference.html | 239 - doc/luasocket/smtp.html | 417 -- doc/luasocket/socket.html | 398 -- doc/luasocket/tcp.html | 532 -- doc/luasocket/udp.html | 416 -- doc/luasocket/url.html | 329 - etc/install.sh | 11 - etc/luasocket-samples/README | 50 - etc/luasocket-samples/cddb.lua | 46 - etc/luasocket-samples/daytimeclnt.lua | 23 - etc/luasocket-samples/echoclnt.lua | 24 - etc/luasocket-samples/echosrvr.lua | 29 - etc/luasocket-samples/listener.lua | 26 - etc/luasocket-samples/lpr.lua | 51 - etc/luasocket-samples/talker.lua | 21 - etc/luasocket-samples/tinyirc.lua | 90 - etc/luasocket/README | 89 - etc/luasocket/b64.lua | 20 - etc/luasocket/check-links.lua | 112 - etc/luasocket/check-memory.lua | 17 - etc/luasocket/dict.lua | 152 - etc/luasocket/dispatch.lua | 301 - etc/luasocket/eol.lua | 14 - etc/luasocket/forward.lua | 65 - etc/luasocket/get.lua | 140 - etc/luasocket/lp.lua | 324 - etc/luasocket/qp.lua | 24 - etc/luasocket/tftp.lua | 155 - etc/publish.sh | 12 - etc/quickinst.sh | 7 - etc/tests/luairc/luabot.lua | 109 - etc/tests/luairc/test.lua | 228 - etc/tests/luasocket/README | 12 - etc/tests/luasocket/testclnt.lua | 655 -- etc/tests/luasocket/testsrvr.lua | 15 - etc/tests/luasocket/testsupport.lua | 37 - etc/zipmod.sh | 45 - quick_install.sh | 8 + src/API.txt | 87 + src/LICENSE.txt | 22 + src/LuaIRC | 1 + src/botcmds.lua | 161 +- src/callback.lua | 255 +- src/chatcmds.lua | 214 +- src/config.lua | 101 +- src/friends.lua | 22 - src/hooks.lua | 211 + src/init.lua | 221 +- src/luairc/irc.lua | 1023 --- src/luairc/irc/channel.lua | 475 -- src/luairc/irc/constants.lua | 191 - src/luairc/irc/ctcp.lua | 115 - src/luairc/irc/dcc.lua | 196 - src/luairc/irc/debug.lua | 92 - src/luairc/irc/message.lua | 69 - src/luairc/irc/misc.lua | 303 - .../luasocket/LICENSE.txt | 0 src/messages.lua | 40 + src/player_part.lua | 82 + src/util.lua | 20 + 105 files changed, 946 insertions(+), 22249 deletions(-) create mode 100644 .gitmodules delete mode 100644 doc/API.txt delete mode 100644 doc/CHANGES.txt delete mode 100644 doc/LICENSE-LuaIRC.txt delete mode 100644 doc/LICENSE.txt delete mode 100644 doc/TODO.txt delete mode 100644 doc/lua/contents.html delete mode 100644 doc/lua/logo.gif delete mode 100644 doc/lua/lua.1 delete mode 100644 doc/lua/lua.css delete mode 100644 doc/lua/lua.html delete mode 100644 doc/lua/luac.1 delete mode 100644 doc/lua/luac.html delete mode 100644 doc/lua/manual.html delete mode 100644 doc/lua/readme.html delete mode 100644 doc/luairc/LICENSE delete mode 100644 doc/luairc/README delete mode 100644 doc/luairc/TODO delete mode 100644 doc/luairc/index.html delete mode 100644 doc/luairc/luadoc.css delete mode 100644 doc/luairc/modules/callbacks.html delete mode 100644 doc/luairc/modules/irc.channel.html delete mode 100644 doc/luairc/modules/irc.constants.html delete mode 100644 doc/luairc/modules/irc.ctcp.html delete mode 100644 doc/luairc/modules/irc.dcc.html delete mode 100644 doc/luairc/modules/irc.debug.html delete mode 100644 doc/luairc/modules/irc.html delete mode 100644 doc/luairc/modules/irc.message.html delete mode 100644 doc/luairc/modules/irc.misc.html delete mode 100644 doc/luasocket/LICENSE delete mode 100644 doc/luasocket/NEW delete mode 100644 doc/luasocket/README delete mode 100644 doc/luasocket/dns.html delete mode 100644 doc/luasocket/ftp.html delete mode 100644 doc/luasocket/home.html delete mode 100644 doc/luasocket/http.html delete mode 100644 doc/luasocket/installation.html delete mode 100644 doc/luasocket/introduction.html delete mode 100644 doc/luasocket/ltn12.html delete mode 100644 doc/luasocket/luasocket.png delete mode 100644 doc/luasocket/mime.html delete mode 100644 doc/luasocket/reference.css delete mode 100644 doc/luasocket/reference.html delete mode 100644 doc/luasocket/smtp.html delete mode 100644 doc/luasocket/socket.html delete mode 100644 doc/luasocket/tcp.html delete mode 100644 doc/luasocket/udp.html delete mode 100644 doc/luasocket/url.html delete mode 100755 etc/install.sh delete mode 100644 etc/luasocket-samples/README delete mode 100644 etc/luasocket-samples/cddb.lua delete mode 100644 etc/luasocket-samples/daytimeclnt.lua delete mode 100644 etc/luasocket-samples/echoclnt.lua delete mode 100644 etc/luasocket-samples/echosrvr.lua delete mode 100644 etc/luasocket-samples/listener.lua delete mode 100644 etc/luasocket-samples/lpr.lua delete mode 100644 etc/luasocket-samples/talker.lua delete mode 100644 etc/luasocket-samples/tinyirc.lua delete mode 100644 etc/luasocket/README delete mode 100644 etc/luasocket/b64.lua delete mode 100644 etc/luasocket/check-links.lua delete mode 100644 etc/luasocket/check-memory.lua delete mode 100644 etc/luasocket/dict.lua delete mode 100644 etc/luasocket/dispatch.lua delete mode 100644 etc/luasocket/eol.lua delete mode 100644 etc/luasocket/forward.lua delete mode 100644 etc/luasocket/get.lua delete mode 100644 etc/luasocket/lp.lua delete mode 100644 etc/luasocket/qp.lua delete mode 100644 etc/luasocket/tftp.lua delete mode 100755 etc/publish.sh delete mode 100755 etc/quickinst.sh delete mode 100755 etc/tests/luairc/luabot.lua delete mode 100755 etc/tests/luairc/test.lua delete mode 100644 etc/tests/luasocket/README delete mode 100644 etc/tests/luasocket/testclnt.lua delete mode 100644 etc/tests/luasocket/testsrvr.lua delete mode 100644 etc/tests/luasocket/testsupport.lua delete mode 100755 etc/zipmod.sh create mode 100755 quick_install.sh create mode 100644 src/API.txt create mode 100644 src/LICENSE.txt create mode 160000 src/LuaIRC delete mode 100644 src/friends.lua create mode 100644 src/hooks.lua delete mode 100644 src/luairc/irc.lua delete mode 100644 src/luairc/irc/channel.lua delete mode 100644 src/luairc/irc/constants.lua delete mode 100644 src/luairc/irc/ctcp.lua delete mode 100644 src/luairc/irc/dcc.lua delete mode 100644 src/luairc/irc/debug.lua delete mode 100644 src/luairc/irc/message.lua delete mode 100644 src/luairc/irc/misc.lua rename doc/LICENSE-luasocket.txt => src/luasocket/LICENSE.txt (100%) create mode 100644 src/messages.lua create mode 100644 src/player_part.lua create mode 100644 src/util.lua diff --git a/.gitignore b/.gitignore index 469e5c3..694e583 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,3 @@ -Build* -dists -irc-* +Build irc -*.zip -*.tar.gz -*.tar.bz2 -*.marks -screenshot_*.png + diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..82cbe83 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "src/LuaIRC"] + path = src/LuaIRC + url = https://github.com/ShadowNinja/LuaIRC.git diff --git a/CMakeLists.txt b/CMakeLists.txt index 925bd25..1af3af7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,11 +1,11 @@ -# :mode=cmake:noTabs=true:tabSize=4: +# :mode=cmake: cmake_minimum_required(VERSION 2.8) project(MINETEST_IRC C) -set(MINETEST_IRC_VERSION 0.1.0) +set(MINETEST_IRC_VERSION 0.2.0) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") @@ -105,14 +105,12 @@ else() set(lib "${CMAKE_CURRENT_BINARY_DIR}/libluasocket.so") endif() -add_custom_target(pack_mod +add_custom_target(pack_mod ALL WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} # LuaIRC COMMAND ${CMAKE_COMMAND} -E make_directory ${dir} - COMMAND ${CMAKE_COMMAND} -E copy src/luairc/irc.lua ${dir} - COMMAND ${CMAKE_COMMAND} -E copy_directory src/luairc/irc ${dir}/irc - COMMAND ${CMAKE_COMMAND} -E copy doc/LICENSE-LuaIRC.txt ${dir} + COMMAND ${CMAKE_COMMAND} -E copy_directory src/LuaIRC ${dir}/irc # luasocket COMMAND ${CMAKE_COMMAND} -E make_directory ${dir} @@ -124,20 +122,22 @@ add_custom_target(pack_mod COMMAND ${CMAKE_COMMAND} -E copy src/luasocket/socket.lua ${dir} COMMAND ${CMAKE_COMMAND} -E copy src/luasocket/tp.lua ${dir} COMMAND ${CMAKE_COMMAND} -E copy src/luasocket/url.lua ${dir} - COMMAND ${CMAKE_COMMAND} -E copy doc/LICENSE-luasocket.txt ${dir} + COMMAND ${CMAKE_COMMAND} -E copy src/luasocket/LICENSE.txt ${dir} COMMAND ${CMAKE_COMMAND} -E copy ${lib} ${dir} # IRC mod COMMAND ${CMAKE_COMMAND} -E make_directory ${dir} COMMAND ${CMAKE_COMMAND} -E copy src/init.lua ${dir} + COMMAND ${CMAKE_COMMAND} -E copy src/hooks.lua ${dir} + COMMAND ${CMAKE_COMMAND} -E copy src/messages.lua ${dir} COMMAND ${CMAKE_COMMAND} -E copy src/config.lua ${dir} COMMAND ${CMAKE_COMMAND} -E copy src/callback.lua ${dir} - COMMAND ${CMAKE_COMMAND} -E copy src/friends.lua ${dir} COMMAND ${CMAKE_COMMAND} -E copy src/chatcmds.lua ${dir} COMMAND ${CMAKE_COMMAND} -E copy src/botcmds.lua ${dir} + COMMAND ${CMAKE_COMMAND} -E copy src/player_part.lua ${dir} + COMMAND ${CMAKE_COMMAND} -E copy src/util.lua ${dir} COMMAND ${CMAKE_COMMAND} -E copy README.txt ${dir} - COMMAND ${CMAKE_COMMAND} -E copy doc/API.txt ${dir} - COMMAND ${CMAKE_COMMAND} -E copy doc/LICENSE.txt ${dir} - COMMAND ${CMAKE_COMMAND} -E copy doc/CHANGES.txt ${dir} - COMMAND ${CMAKE_COMMAND} -E copy doc/TODO.txt ${dir} + COMMAND ${CMAKE_COMMAND} -E copy src/API.txt ${dir} + COMMAND ${CMAKE_COMMAND} -E copy src/LICENSE.txt ${dir} ) + diff --git a/README.txt b/README.txt index 4013c83..5949051 100644 --- a/README.txt +++ b/README.txt @@ -17,75 +17,78 @@ Make sure you have CMake (http://cmake.org/), and of course, a C compiler, For Windows, try MinGW32 (http://mingw.org/). For Unix-based systems, you should not have any problems with the C compiler since there's one (almost) always available. Puppy Linux users of course - need a separate `devx.sfs' (from the same place where you got the Puppy - ISO), since vanilla Puppy does not come with `gcc'. See your Puppy docs for + need a separate 'devx.sfs' (from the same place where you got the Puppy + ISO), since vanilla Puppy does not come with 'gcc'. See your Puppy docs for more info about how to install additional SFS files. Quick one line build for linux. -git clone https://github.com/kaeza/minetest-irc.git && cd minetest-irc && mkdir build && cd build && cmake .. && make && make pack_mod && cp -R irc -Please change the "cp -R irc" to fit your install of minetest. +git clone https://github.com/kaeza/minetest-irc.git && cd minetest-irc && git submodule update --init && ./quick_install.sh +Please change to fit your install of minetest. -To compile and "pack" the mod: +To compile and pack the mod: - Open a command prompt/terminal and CD to the minetest-irc directory. - - Create a directory named "Build", and CD into it: + - (optional) Create a directory named "Build", and CD into it: mkdir Build cd Build - Run CMake to generate the build system (see your CMake docs for more - information about command line options, in particular the `-G' option). - cmake .. + information about command line options, in particular the '-G' option). + cmake . (cmake .. if you made a seperate build directory) - Use the build tool for the generated build system to compile the native library. For example, if using Microsoft Visual Studio, open the generated workspace and build from there. If using make, just run "make" from within the Build directory. - - Again use the build tool to invoke the `pack_mod' target. For example, - if using `make', run "make pack_mod" from within the build directory. - This will create an `irc' directory inside the build directory. - This `irc' directory will be ready to be deployed to your Minetest mods - directory. + - After building you will have a folder named 'irc' in your build folder. + Move that to your mod folder. INSTALLING ---------- -Just put the created `irc' directory in any of the directories where +Just put the created 'irc' directory in any of the directories where Minetest looks for mods. For more information, see: http://wiki.minetest.com/wiki/Installing_mods SETTINGS -------- -All settings are changed in the `config.lua' file. If any of these settings - are either nil or false, the default value is used. +All settings are changed in 'minetest.conf'. If any of these settings + are either not set or false, the default value is used. - mt_irc.server (string, default "irc.freenode.net") + irc.server (string, default "irc.freenode.net") This is the IRC server the mod connects to. - mt_irc.channel (string, default "##mt-irc-mod") + irc.channel (string, default "##mt-irc-mod") The IRC channel to join. - mt_irc.dtime (number, default 0.2) - This is the time in seconds between updates in the connection. - In order not to block the game, the mod must periodically "poll" - the connection to both send messages to, and receive messages - from the channel. A high value means slower connection to IRC, - but possibly better response from the game. A low value means - the mod "polls" the connection more often, but can make the - game hang. It allows fractional values. + irc.interval (number, default 2.0) + This prevents the server from flooding. It should be at + least 2.0 but can be higher. After four messages this much + time must pass between folowing messages. - mt_irc.timeout (number, default 60.0) + irc.timeout (number, default 60.0) Underlying socket timeout in seconds. This is the time before the system drops an idle connection. - mt_irc.server_nick (string, default "minetest-"..) + irc.nick (string, default "minetest-"..) Nickname used as "proxy" for the in-game chat. - "" is the server IP address packed as a 32 bit integer. - (Currently, it's just a random 32 bit number). + "" is a random 32 bit number. - mt_irc.password (string, default "") + irc.password (string, default "") Password to use when connecting to the server. - mt_irc.message_format_out (string, default "<$(name)> $(message)") + irc.NSPass (string, default nil) + NickServ password. Don't use this if you use SASL authentication. + + irc.SASLPass (string, default nil) + SASL password, same as nickserv password. + You should use this instead of NickServ authentication + if the server supports it. + + irc.SASLUser (string, default irc.nick) + The SASL username. This should normaly be set to your main NickServ account name. + + irc.format_out (string, default "<$(name)> $(message)") This specifies how to send the messages from in-game to IRC. The strings can contain "macros" (or variable substitutions), which are specified as "$(macro_name)". @@ -102,7 +105,7 @@ All settings are changed in the `config.lua' file. If any of these settings ...will yield... "mtuser: Hello! $(xyz)" - mt_irc.message_format_in (string, + irc.format_in (string, default "<$(name)@IRC> $(message)") This specifies how the messages gotten from the IRC channel are displayed in-game. @@ -115,19 +118,19 @@ All settings are changed in the `config.lua' file. If any of these settings $(port) The IRC server port. $(channel) The IRC channel. In the default configuration, this will yield: - Hello! + Hello! - mt_irc.debug (boolean, default false) + irc.debug (boolean, default false) Whether to output debug information. - mt_irc.auto_connect (boolean, default false) - If true, the bot is connected by default. If false, a player with - `irc_admin' privilege has to use the /irc_connect command to + irc.disable_auto_connect (boolean, default false) + If false, the bot is connected by default. If true, a player with + the 'irc_admin' privilege has to use the /irc_connect command to connect to the server. - mt_irc.auto_join (boolean, default false) - If true, players join the channel automatically upon entering the - game. If false, each user must manually use the /join command to + irc.disable_auto_join (boolean, default false) + If false, players join the channel automatically upon entering the + game. If true, each user must manually use the /join command to join the channel. In any case, the players may use the /part command to opt-out of being in the channel. @@ -140,8 +143,8 @@ Once the game is connected to the IRC channel, chatting using the 'T' or This mod also adds a few chat commands: - /msg - Sends a private message to the IRC user whose nickname is `nick'. + /irc_msg + Sends a private message to a IRC user. /join Join the IRC channel. @@ -153,21 +156,21 @@ This mod also adds a few chat commands: Connect the bot manually to the IRC network. /irc_disconnect - Disconnect the bot manually to the IRC network (this does not + Disconnect the bot manually from the IRC network (this does not shutdown the game). /irc_reconnect - A combination of /irc_disconnect and /irc_connect. + Equivilant to /irc_disconnect followed by /irc_connect. You can also send private messages from IRC to in-game players, though it's a bit tricky. To do it, you must send a private message to the bot (set with - the `mt_irc.server_nick' option above), in the following format: - >playername message -For example, if there's a player named `mtuser', you can send him/her - a private message with: - /msg server_nick >mtuser Hello! + the 'irc.nick' option above), in the following format: + @playername message +For example, if there's a player named 'mtuser', you can send him/her + a private message from IRC with: + /msg server_nick @mtuser Hello! To avoid possible misunderstandings (since all in-game players use the same IRC user to converse with you), the "proxy" user will reject any @@ -175,8 +178,8 @@ To avoid possible misunderstandings (since all in-game players use the nice reminder as a private message. The bot also supports some basic commands, which are invoked by sending - a private message to it. Use `!help' to get a list of commands, and - `!help ' to get help about a specific command. + a private message to it. Use '!help' to get a list of commands, and + '!help ' to get help about a specific command. THANKS @@ -184,10 +187,11 @@ THANKS I'd like to thank the users who supported this mod both on the Minetest Forums and on the #minetest channel. In no particular order: - Shaun/kizeren, RAPHAEL, DARGON, Calinou, Exio, vortexlabs/mrtux, - marveidemanis, marktraceur, jmf/john_minetest, sdzen/Muadtralk, - VanessaE, PilzAdam, sfan5, celeron55, KikaRz, OldCoder, RealBadAngel, - and all the people who commented in the forum topic. Thanks to you all! + 0gb.us, ShadowNinja, Shaun/kizeren, RAPHAEL, DARGON, Calinou, Exio, + vortexlabs/mrtux, marveidemanis, marktraceur, jmf/john_minetest, + sdzen/Muadtralk, VanessaE, PilzAdam, sfan5, celeron55, KikaRz, + OldCoder, RealBadAngel, and all the people who commented in the + forum topic. Thanks to you all! LICENSE @@ -202,15 +206,12 @@ LICENSE as the name is changed. DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - 0. You just DO WHAT THE FUCK YOU WANT TO. + 0. You just DO WHAT THE FUCK YOU WANT TO. -The files `http.lua', `ltn12.lua', `mime.lua', `smtp.lua', `socket.lua', - and `url.lua' are part of the luasocket project - (http://luasocket.luaforge.org/). See `LICENSE-luasocket.txt' for +The files 'http.lua', 'ltn12.lua', 'mime.lua', 'smtp.lua', 'socket.lua', + and 'url.lua' are part of the luasocket project + (http://luasocket.luaforge.org/). See 'src/luasocket/LICENSE.txt' for licensing information. -The `irc.lua' file and the entire contents of the `irc' directory are part - of the LuaIRC project (http://luairc.luaforge.org/). See - `LICENSE-LuaIRC.txt' for licensing information. diff --git a/doc/API.txt b/doc/API.txt deleted file mode 100644 index 70051c6..0000000 --- a/doc/API.txt +++ /dev/null @@ -1,141 +0,0 @@ - -IRC Mod API ------------ -This file documents the API exported by the IRC mod. - - -BASICS ------- -In order to allow your mod to interface with this mod, you must add `irc' - (without the quotes) to your mod's `depends.txt' file. - - -REFERENCE ---------- - -mt_irc.say ( [name ,] message ) - Sends to either the channel (if is nil or not specified), - or to the given user (if is specified). - Example: - mt_irc.say("Hello, Channel!") - mt_irc.say("john1234", "How are you?") - -mt_irc.register_bot_command ( name, cmddef ) - Registers a new bot command named . - When an user sends a private message to the bot starting with `!name', the - command's function is called. - Here's the command definition (): - cmddef = { - params = " ...", -- A short help text for !help - description = "My command", -- What does the command? (one-liner) - func = function ( from, param ) - -- This function gets called when the command is invoked. - -- is the name of the user that invoked the command. - -- is the rest of the input (after removing !command) - end, - }; - Example: - mt_irc.register_bot_command("hello", { - params = nil, -- No params - description = "Greet user", - func = function ( from, param ) - mt_irc.say(from, "Hello!") - end, - }); - -mt_irc.connected_players [ name ] - This table holds the players who are currently on the channel (may be less - than the players in the game). It is modified by the /part and /join chat - commands. - Example: - if (mt_irc.connected_players["joe"]) then - -- Joe is talking on IRC - end - -mt_irc.register_callback ( name, func ) - Registers a function to be called when an event happens. is the name - of the event, and is the function to be called. See CALLBACKS below - for more information - Example: - mt_irc.register_callback("channel_msg", function ( from, msg ) - if (from == "joe") then - mt_irc.say("joe", "You are not allowed to do that!") - return true - end - end) - -This mod also supplies some utility functions: - -string.expandvars ( string, vars ) - Expands all occurrences of the pattern "$(varname)" with the value of - `varname' in the table. Variable names not found on the table - are left verbatim in the string. - Example: - local tpl = "$(foo) $(bar) $(baz)" - local s = tpl:expandvars({ foo=1, bar="Hello" }) - -- `s' now contains "1 Hello $(baz)" - -In addition, all the configuration options decribed in `README.txt' are - available to other mods, though they should be considered "read only". Do - not modify these settings at runtime or you will most likely crash the - server! - - -CALLBACKS ---------- -The `mt_irc.register_callback' function can register functions to be called - when some events happen. These are the events supported: - -msg_out ( from, message ) - Called right before the bot sends a message to the channel. - is the name of the user sending the message. is the - unmodified message sent by the user. - Return values: - "string" New message to be sent. - false Filter out the message (do not send anything). - nil Use original message - other Use a string repr of the value as message. - Example: - mt_irc.register_callback("msg_out", function ( from, msg ) - if (from == "joe") then - mt_irc.say("joe", "You are not allowed to do that!") - return false - end - end) - -msg_in ( from, to, message ) - Called right before the bot sends a private message to an user. - is the name of the user sending the message. is the recipient - of the message. is the unmodified message sent by the user. - Return values: - "string" New message to be sent. - false Filter out the message (do not send anything). - nil Use original message - other Use a string repr of the value as message. - Example: - mt_irc.register_callback("msg_in", function ( from, to, msg ) - if (to == "admin") then - mt_irc.say(from, "You are not allowed to do that!") - return true - end - end) - -nick_change ( old_nick, new_nick ) - Called when an user in IRC changes nickname. - and are self-explanatory. - Return value: - none - Example: - mt_irc.register_callback("nick_change", function ( old_nick, new_nick ) - mt_irc.say(from, "Hello "..new_nick.."! You were "..old_nick.."?") - end) - -part ( nick, part_msg ) - Called when an user leaves the IRC channel. - is the user leaving; is the "parting message". - Return value: - none - Example: - mt_irc.register_callback("part", function ( nick, part_msg ) - mt_irc.say(from, nick.." has left the building!") - end) diff --git a/doc/CHANGES.txt b/doc/CHANGES.txt deleted file mode 100644 index 57c8c78..0000000 --- a/doc/CHANGES.txt +++ /dev/null @@ -1,37 +0,0 @@ - -Version 0.1.2: - - Fixed the Quit: Excess Flood bug. - - Removed the `packmod' scripts in favor of a dedicated CMake target. - - Fixed packaging of mod under MinGW32. - - Export some basic API so other mods may use the connection to send - messages, etc. - - Added /irc_disconnect and /irc_reconnect chat commands. - - Added some basic documentation about the API exported by this mod. - More coming soon. - - Added automatic reconnection in case the bot is kicked from the - channel. - - Fixed delay while the bot waits for the Message Of The Day (or topic) - - Fixed bug where players were able to send messages to the channel - even if they had no `shout' priv. - -Version 0.1.1: - - Moved all user configuration to `config.lua'. - - Added formatted messages for sent and received messages and options - to change them. - - Added options to change port, password. - - Added support for sending/receiving private messages. - - Removed need for separate packmod.{sh|bat} scripts. Now everything - is (almost) nicely handled by CMake. - - Now all sources (including Lua itself) are added to a single - luasocket lib. This will hopefully fix some cases where the linker - b0rk3d with undefined references under Linux. - - Added option to enable/disable connecting when starting the game, and - the /irc_connect chat command to connect manually to the server (as - suggested by OldCoder). The /irc_connect chat command requires the - `irc_admin' privilege. - - Added option to enable/disable joining the channel when a player joins, - and the /join and /part chat commands to join and part the channel - manually if desired (as suggested by OldCoder). - -Version 0.1.0: - - At least it's working :) diff --git a/doc/LICENSE-LuaIRC.txt b/doc/LICENSE-LuaIRC.txt deleted file mode 100644 index fe30b8a..0000000 --- a/doc/LICENSE-LuaIRC.txt +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (c) 2007 Jesse Luehrs - -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. diff --git a/doc/LICENSE.txt b/doc/LICENSE.txt deleted file mode 100644 index 6ef5b70..0000000 --- a/doc/LICENSE.txt +++ /dev/null @@ -1,15 +0,0 @@ - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - Version 2, December 2004 - - Copyright (C) 2004 Sam Hocevar - - Everyone is permitted to copy and distribute verbatim or modified - copies of this license document, and changing it is allowed as long - as the name is changed. - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. You just DO WHAT THE FUCK YOU WANT TO. - diff --git a/doc/TODO.txt b/doc/TODO.txt deleted file mode 100644 index 1634d8f..0000000 --- a/doc/TODO.txt +++ /dev/null @@ -1,20 +0,0 @@ - -TODO List ---------- - - - Check for availability of nickname on join, and select a different one - until one is available. - - Implement more callbacks for `mt_irc.register_callback'. - -Not TODO List -------------- -* These things either WON'T BE SUPPORTED, or have VERY LOW priority. - - - Support for sending CTCP queries (LuaIRC seems to handle incoming - queries internally by default). - -Known Bugs ----------- - - - Apparently, some users have to install `luasocket' separately, since - the provided one won't compile/work (reported by leo_rockway). diff --git a/doc/lua/contents.html b/doc/lua/contents.html deleted file mode 100644 index 564377c..0000000 --- a/doc/lua/contents.html +++ /dev/null @@ -1,405 +0,0 @@ - - -Lua 5.1 reference manual - contents - - - - - -
-

-Lua -Lua 5.1 Reference Manual -

- - -Copyright -© 2006 Lua.org, PUC-Rio. All rights reserved. - -
- -

Contents

- - -

Quick index

- - - - - - -
-

Functions

-_G
-_VERSION
-assert
-collectgarbage
-coroutine.create
-coroutine.resume
-coroutine.running
-coroutine.status
-coroutine.wrap
-coroutine.yield
-debug.debug
-debug.getfenv
-debug.gethook
-debug.getinfo
-debug.getlocal
-debug.getmetatable
-debug.getregistry
-debug.getupvalue
-debug.setfenv
-debug.sethook
-debug.setlocal
-debug.setmetatable
-debug.setupvalue
-debug.traceback
-dofile
-error
-file:close
-file:flush
-file:lines
-file:read
-file:seek
-file:setvbuf
-file:write
-getfenv
-getmetatable
-io.close
-io.flush
-io.input
-io.lines
-io.open
-io.output
-io.popen
-io.read
-io.tmpfile
-io.type
-io.write
-ipairs
-load
-loadfile
-loadstring
-math.abs
-math.acos
-math.asin
-math.atan2
-math.atan
-math.ceil
-math.cosh
-math.cos
-math.deg
-math.exp
-math.floor
-math.fmod
-math.frexp
-math.ldexp
-math.log10
-math.log
-math.max
-math.min
-math.modf
-math.pow
-math.rad
-math.random
-math.randomseed
-math.sinh
-math.sin
-math.sqrt
-math.tanh
-math.tan
-module
-next
-os.clock
-os.date
-os.difftime
-os.execute
-os.exit
-os.getenv
-os.remove
-os.rename
-os.setlocale
-os.time
-os.tmpname
-package.cpath
-package.loaded
-package.loadlib
-package.path
-package.preload
-package.seeall
-pairs
-pcall
-print
-rawequal
-rawget
-rawset
-require
-select
-setfenv
-setmetatable
-string.byte
-string.char
-string.dump
-string.find
-string.format
-string.gmatch
-string.gsub
-string.len
-string.lower
-string.match
-string.rep
-string.reverse
-string.sub
-string.upper
-table.concat
-table.insert
-table.maxn
-table.remove
-table.sort
-tonumber
-tostring
-type
-unpack
-xpcall
- -
-

API

-lua_Alloc
-lua_CFunction
-lua_Debug
-lua_Hook
-lua_Integer
-lua_Number
-lua_Reader
-lua_State
-lua_Writer
-lua_atpanic
-lua_call
-lua_checkstack
-lua_close
-lua_concat
-lua_cpcall
-lua_createtable
-lua_dump
-lua_equal
-lua_error
-lua_gc
-lua_getallocf
-lua_getfenv
-lua_getfield
-lua_getglobal
-lua_gethook
-lua_gethookcount
-lua_gethookmask
-lua_getinfo
-lua_getlocal
-lua_getmetatable
-lua_getstack
-lua_gettable
-lua_gettop
-lua_getupvalue
-lua_insert
-lua_isboolean
-lua_iscfunction
-lua_isfunction
-lua_islightuserdata
-lua_isnil
-lua_isnumber
-lua_isstring
-lua_istable
-lua_isthread
-lua_isuserdata
-lua_lessthan
-lua_load
-lua_newstate
-lua_newtable
-lua_newthread
-lua_newuserdata
-lua_next
-lua_objlen
-lua_pcall
-lua_pop
-lua_pushboolean
-lua_pushcclosure
-lua_pushcfunction
-lua_pushfstring
-lua_pushinteger
-lua_pushlightuserdata
-lua_pushlstring
-lua_pushnil
-lua_pushnumber
-lua_pushstring
-lua_pushthread
-lua_pushvalue
-lua_pushvfstring
-lua_rawequal
-lua_rawget
-lua_rawgeti
-lua_rawset
-lua_rawseti
-lua_register
-lua_remove
-lua_replace
-lua_resume
-lua_setallocf
-lua_setfenv
-lua_setfield
-lua_setglobal
-lua_sethook
-lua_setlocal
-lua_setmetatable
-lua_settable
-lua_settop
-lua_setupvalue
-lua_status
-lua_toboolean
-lua_tocfunction
-lua_tointeger
-lua_tolstring
-lua_tonumber
-lua_topointer
-lua_tostring
-lua_tothread
-lua_touserdata
-lua_type
-lua_typename
-lua_xmove
-lua_yield
- -
-

Auxiliary library

-luaL_Buffer
-luaL_Reg
-luaL_addchar
-luaL_addlstring
-luaL_addsize
-luaL_addstring
-luaL_addvalue
-luaL_argcheck
-luaL_argerror
-luaL_buffinit
-luaL_callmeta
-luaL_checkany
-luaL_checkint
-luaL_checkinteger
-luaL_checklong
-luaL_checklstring
-luaL_checknumber
-luaL_checkoption
-luaL_checkstack
-luaL_checkstring
-luaL_checktype
-luaL_checkudata
-luaL_error
-luaL_getmetafield
-luaL_getmetatable
-luaL_gsub
-luaL_loadbuffer
-luaL_loadfile
-luaL_loadstring
-luaL_newmetatable
-luaL_newstate
-luaL_openlibs
-luaL_optint
-luaL_optinteger
-luaL_optlong
-luaL_optlstring
-luaL_optnumber
-luaL_optstring
-luaL_prepbuffer
-luaL_pushresult
-luaL_ref
-luaL_register
-luaL_typename
-luaL_typerror
-luaL_unref
-luaL_where
- -
-

- -


- -Last update: -Fri Feb 10 17:15:37 BRST 2006 - - - - diff --git a/doc/lua/logo.gif b/doc/lua/logo.gif deleted file mode 100644 index 2f5e4ac2e742fbb7675e739879211553758aea9c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4232 zcmeH``9G8i;K!fm@ywWE@XWZzZ5SF?A>^uN#>^O6HI%DVL*tw8h1>$H%uPC0$QQ=txe!o}PX)Ev+jn>*nFZ-TC=<^76WcLZL(=DJm)| zEiIKwrInSHXU?3duCC_u@5try#>U2`rlw1mF15F}U%!66tE;QKyIUmcDJ<+QF77*W zFJd#&)VAl)kJ6K zi<>tmZ{3>g>+2gB7#JQNe(>OdLh;A=`1q42PbMZNCMPF*dXxhLZw3aYhlZwyhu@Bj z%#4n{d-Q1b$&i4QMce4L#8^!oMdw{PDnm4D66&3*dxX=-YIX6DQL_g`jbzkd4k zZDCoLf=%jL&vIeE zO=XcZ9fxt`f}-DQ^%H*PHMUs(JN%UWkI|Y8h9#6~I$Cw@{RqzO4&P-x;jHCPJ6Ks2 zoU%foi)nXd_sdkiuJa@@5J4RrreKfWSnz5>eMa5yTP=)16uu)TIdx~Fhho))6jZl) z($*i>QrIX4u}u3>m{WSn_ehkUGQ& zs})aUlTH1Cj1g3ZE3=MPXsSniEwJ{e6C3N#HjD=B4`8rWIsz!a7ecYpec?WuH+y?Wsm18^$cS4WmHhH3_=r zh*ILlm*X1dB^E5($KVl&zT524%l}vpHg%;Y+LezV_&TAJCmH`idhuj-n$4FZ)UE|jXLayXa-&O3Q z?Iyo!x*$5hD_HfFnDfGYj-RD|eIb7I?%>Y_kf%}Nbd`BXb4l1(Pc+}zoUR|9%_!7f zum2T;wbx&pohtI+&@~wm3nH9xLbOYkg*`phY~TK5iC#3tZNXo9s`cahx+8j2)rh5C zQgZh6D7Ekgib|hpdhxYf{r!PTJc z!vsYG@{hA}l5kL)g)0N_)(nC<*L0qdUi*3fD5<0sn58>zklX@6Tyv3*X^}m=Cqc40 zQ6GfjG@kd1mFIm`qaubWunm_?P>WUZ`9|f_z%gGHi{n|uu(N8!L=aw5(qAcDj$-QK zu;D#j6e42OXTQD>)i zlvM$LX`$n9EEjxM$_QDF&a z7cme_rat}aXmiN&7`6Q98}dh4Z@8L_uAb#nK&GQiZOOUnA9kAEVb-csuN1AWL=sXt z{z9GCN%%l0N9QvJM;tl1nf?rrhT{*sE%4WqR?{0~aIrfCcCPxf4eh_*jjQ=`$p53Y z@_|Rsx2i}|3dNFetMQQ5y8agTK-E0D&7;@3-LUxfvZ7 z7~!p@&mFe^oca2^F|CBt+4Ly?^ViUVSAhAH>JH1GN{^TQb3QnM*x0ZiZgDyNI@_c3 z@{}(WH4*e3T~}n_^0}da4ElIxAf9B!IaL7z9X0Icvj@cIkE*~W--17&WN`Ea5)Gn> z#gpfRb#44;jVTOS{FuaZgd(-ZD848=fQzgST2MxR>wSLc1P=2HDvByz$B$IsNCC6L zCM?nK*OHj6JA9gz4|b<~2%RqelN^1Y)jIqnRs!mDKV^BQTfo@hOtz7*Ug}Ee^cbsj zNNlumRgAmt`1$b5MO;&X#5-EP<}AaY;52ihIpem&MTea$?3!DrwbYa?V`NjEfWF3z zUq5JY8Ch;L{kx&J<1K&Fe_Vn;8gk{%c;n?nA2(%(f%DCRHko3uT~VI7RE^JWEqaCq z)i|%nfj(*4|V*XhY3W%M# z*yn6SN4eUOHFxAD7B&9E_PO`G5bqgs^@J{9bk>&;PlUAiqo`j3rjQDgD!}mqLUtb` zCB}ZD@m@s#pf7bV4jreOC*JVfHZ|hyHkX!rauVdd_I9FL45d{gWH!DNYu;i(|8wVx z!)eLY6YXxZ2{Coae0xuTnxo1ACb5wtED?VJAz&@114$Ao6uG9YSy*!K;m5_mj=0^j zw%?b%AOs}ql@$TGC-!^^*_#RT5+y_kTzQG9?LPPZNAtt6cJ%d2$q(I)ws21*?xF%p zN+NeGnWRQ<5w70Rc(bl|S0Xr&5@WrmdurS|IgPB|EyuZO#=tf!35)G!HJ`E1jh^lH zTBu~rL#DhQO*XAWtBt}JHH$lc>3%r0yD|maW_(W=B_J+y164F>O4dO|@&@N3Z3p=B zmVl{|^Z&#atHY|9n&la)SBo}=3AFIF=_~LDJk6MTlA73CXtX+4bnn+c!}N}IPa5pp zwyqbqIkN|I3j_3vD6$zlu{Ps(N-J|*qzEt<$5Soh;s^AuKv_ z-Tz+O1_~6*9CJh4r}`}mbUtjbf#fX58RIIkP6&@*y9kI|5fK*_eZ%jv3U$5*x<>D_ za2M(TV8?XY+9xy>0En#Te<6X4$0&dbyd(go$~eq4u(u)EA2msyF<5ssLZ zDP|I}=~Bi_q)whWv=Ri~L1TYaNrR;5cMB@s78HF1{w&r(6GJ;_2@bD?#1p&P4n_?n0#9Vx~$qjMX=Lk?*!@aKo8m&$iPO7S{g3sFUwr`*<53(68xx7?z`2xf# zGSicy_zI(PJ|%qc2VxT+6bOE--a{k&aq7$<<= zFt)C<@|TPs`+eycPGoGL1Wn9|Ed&a2JyAmjnkm3DQBECX&`bt~odH9cUPq4M{#$-q?G3!)qO-it*&YHw+j-O* zYy78V*`4Q=kQ@^Yz*b6Tal4(Me7BGeS^;phWAW8+L^5A(=D)t?k!rLIwVAKtq=f7h z&^n&VX1-T$ScvN~639QLZ^d@niMaS{C-Q)8oHHBhwD*r~-1Ze#Q)GFOFptW32a-uF z;M@ux%i%a25NwIgXt*=GHX$3~aZfwovGL!}sf?j9TsVo^cn(%&a<--0mIXYqGe>c PWz_J}_#7St0k8iB@FZjZ diff --git a/doc/lua/lua.1 b/doc/lua/lua.1 deleted file mode 100644 index 24809cc..0000000 --- a/doc/lua/lua.1 +++ /dev/null @@ -1,163 +0,0 @@ -.\" $Id: lua.man,v 1.11 2006/01/06 16:03:34 lhf Exp $ -.TH LUA 1 "$Date: 2006/01/06 16:03:34 $" -.SH NAME -lua \- Lua interpreter -.SH SYNOPSIS -.B lua -[ -.I options -] -[ -.I script -[ -.I args -] -] -.SH DESCRIPTION -.B lua -is the stand-alone Lua interpreter. -It loads and executes Lua programs, -either in textual source form or -in precompiled binary form. -(Precompiled binaries are output by -.BR luac , -the Lua compiler.) -.B lua -can be used as a batch interpreter and also interactively. -.LP -The given -.I options -(see below) -are executed and then -the Lua program in file -.I script -is loaded and executed. -The given -.I args -are available to -.I script -as strings in a global table named -.BR arg . -If these arguments contain spaces or other characters special to the shell, -then they should be quoted -(but note that the quotes will be removed by the shell). -The arguments in -.B arg -start at 0, -which contains the string -.RI ' script '. -The index of the last argument is stored in -.BR arg.n . -The arguments given in the command line before -.IR script , -including the name of the interpreter, -are available in negative indices in -.BR arg . -.LP -At the very start, -before even handling the command line, -.B lua -executes the contents of the environment variable -.BR LUA_INIT , -if it is defined. -If the value of -.B LUA_INIT -is of the form -.RI '@ filename ', -then -.I filename -is executed. -Otherwise, the string is assumed to be a Lua statement and is executed. -.LP -Options start with -.B '\-' -and are described below. -You can use -.B "'\--'" -to signal the end of options. -.LP -If no arguments are given, -then -.B "\-v \-i" -is assumed when the standard input is a terminal; -otherwise, -.B "\-" -is assumed. -.LP -In interactive mode, -.B lua -prompts the user, -reads lines from the standard input, -and executes them as they are read. -If a line does not contain a complete statement, -then a secondary prompt is displayed and -lines are read until a complete statement is formed or -a syntax error is found. -So, one way to interrupt the reading of an incomplete statement is -to force a syntax error: -adding a -.B ';' -in the middle of a statement is a sure way of forcing a syntax error -(except inside multiline strings and comments; these must be closed explicitly). -If a line starts with -.BR '=' , -then -.B lua -displays the values of all the expressions in the remainder of the -line. The expressions must be separated by commas. -The primary prompt is the value of the global variable -.BR _PROMPT , -if this value is a string; -otherwise, the default prompt is used. -Similarly, the secondary prompt is the value of the global variable -.BR _PROMPT2 . -So, -to change the prompts, -set the corresponding variable to a string of your choice. -You can do that after calling the interpreter -or on the command line -(but in this case you have to be careful with quotes -if the prompt string contains a space; otherwise you may confuse the shell.) -The default prompts are "> " and ">> ". -.SH OPTIONS -.TP -.B \- -load and execute the standard input as a file, -that is, -not interactively, -even when the standard input is a terminal. -.TP -.BI \-e " stat" -execute statement -.IR stat . -You need to quote -.I stat -if it contains spaces, quotes, -or other characters special to the shell. -.TP -.B \-i -enter interactive mode after -.I script -is executed. -.TP -.BI \-l " name" -call -.BI require(' name ') -before executing -.IR script . -Typically used to load libraries. -.TP -.B \-v -show version information. -.SH "SEE ALSO" -.BR luac (1) -.br -http://www.lua.org/ -.SH DIAGNOSTICS -Error messages should be self explanatory. -.SH AUTHORS -R. Ierusalimschy, -L. H. de Figueiredo, -and -W. Celes -.\" EOF diff --git a/doc/lua/lua.css b/doc/lua/lua.css deleted file mode 100644 index 90f6231..0000000 --- a/doc/lua/lua.css +++ /dev/null @@ -1,15 +0,0 @@ -body { - color: #000000 ; - background-color: #FFFFFF ; - font-family: sans-serif ; -} - -a:link { - color: #000080 ; -} - -a:link:hover, a:visited:hover { - color: #000080 ; - background-color: #E0E0FF ; -} - diff --git a/doc/lua/lua.html b/doc/lua/lua.html deleted file mode 100644 index 1d435ab..0000000 --- a/doc/lua/lua.html +++ /dev/null @@ -1,172 +0,0 @@ - - - -LUA man page - - - - - -

NAME

-lua - Lua interpreter -

SYNOPSIS

-lua -[ -options -] -[ -script -[ -args -] -] -

DESCRIPTION

-lua -is the stand-alone Lua interpreter. -It loads and executes Lua programs, -either in textual source form or -in precompiled binary form. -(Precompiled binaries are output by -luac, -the Lua compiler.) -lua -can be used as a batch interpreter and also interactively. -

-The given -options -(see below) -are executed and then -the Lua program in file -script -is loaded and executed. -The given -args -are available to -script -as strings in a global table named -arg. -If these arguments contain spaces or other characters special to the shell, -then they should be quoted -(but note that the quotes will be removed by the shell). -The arguments in -arg -start at 0, -which contains the string -'script'. -The index of the last argument is stored in -arg.n. -The arguments given in the command line before -script, -including the name of the interpreter, -are available in negative indices in -arg. -

-At the very start, -before even handling the command line, -lua -executes the contents of the environment variable -LUA_INIT, -if it is defined. -If the value of -LUA_INIT -is of the form -'@filename', -then -filename -is executed. -Otherwise, the string is assumed to be a Lua statement and is executed. -

-Options start with -'-' -and are described below. -You can use -'--' -to signal the end of options. -

-If no arguments are given, -then -"-v -i" -is assumed when the standard input is a terminal; -otherwise, -"-" -is assumed. -

-In interactive mode, -lua -prompts the user, -reads lines from the standard input, -and executes them as they are read. -If a line does not contain a complete statement, -then a secondary prompt is displayed and -lines are read until a complete statement is formed or -a syntax error is found. -So, one way to interrupt the reading of an incomplete statement is -to force a syntax error: -adding a -';' -in the middle of a statement is a sure way of forcing a syntax error -(except inside multiline strings and comments; these must be closed explicitly). -If a line starts with -'=', -then -lua -displays the values of all the expressions in the remainder of the -line. The expressions must be separated by commas. -The primary prompt is the value of the global variable -_PROMPT, -if this value is a string; -otherwise, the default prompt is used. -Similarly, the secondary prompt is the value of the global variable -_PROMPT2. -So, -to change the prompts, -set the corresponding variable to a string of your choice. -You can do that after calling the interpreter -or on the command line -(but in this case you have to be careful with quotes -if the prompt string contains a space; otherwise you may confuse the shell.) -The default prompts are "> " and ">> ". -

OPTIONS

-

-- -load and execute the standard input as a file, -that is, -not interactively, -even when the standard input is a terminal. -

--e stat -execute statement -stat. -You need to quote -stat -if it contains spaces, quotes, -or other characters special to the shell. -

--i -enter interactive mode after -script -is executed. -

--l name -call -require('name') -before executing -script. -Typically used to load libraries. -

--v -show version information. -

SEE ALSO

-luac(1) -
-http://www.lua.org/ -

DIAGNOSTICS

-Error messages should be self explanatory. -

AUTHORS

-R. Ierusalimschy, -L. H. de Figueiredo, -and -W. Celes - - - diff --git a/doc/lua/luac.1 b/doc/lua/luac.1 deleted file mode 100644 index d814678..0000000 --- a/doc/lua/luac.1 +++ /dev/null @@ -1,136 +0,0 @@ -.\" $Id: luac.man,v 1.28 2006/01/06 16:03:34 lhf Exp $ -.TH LUAC 1 "$Date: 2006/01/06 16:03:34 $" -.SH NAME -luac \- Lua compiler -.SH SYNOPSIS -.B luac -[ -.I options -] [ -.I filenames -] -.SH DESCRIPTION -.B luac -is the Lua compiler. -It translates programs written in the Lua programming language -into binary files that can be later loaded and executed. -.LP -The main advantages of precompiling chunks are: -faster loading, -protecting source code from accidental user changes, -and -off-line syntax checking. -.LP -Pre-compiling does not imply faster execution -because in Lua chunks are always compiled into bytecodes before being executed. -.B luac -simply allows those bytecodes to be saved in a file for later execution. -.LP -Pre-compiled chunks are not necessarily smaller than the corresponding source. -The main goal in pre-compiling is faster loading. -.LP -The binary files created by -.B luac -are portable only among architectures with the same word size and byte order. -.LP -.B luac -produces a single output file containing the bytecodes -for all source files given. -By default, -the output file is named -.BR luac.out , -but you can change this with the -.B \-o -option. -.LP -In the command line, -you can mix -text files containing Lua source and -binary files containing precompiled chunks. -This is useful to combine several precompiled chunks, -even from different (but compatible) platforms, -into a single precompiled chunk. -.LP -You can use -.B "'\-'" -to indicate the standard input as a source file -and -.B "'\--'" -to signal the end of options -(that is, -all remaining arguments will be treated as files even if they start with -.BR "'\-'" ). -.LP -The internal format of the binary files produced by -.B luac -is likely to change when a new version of Lua is released. -So, -save the source files of all Lua programs that you precompile. -.LP -.SH OPTIONS -Options must be separate. -.TP -.B \-l -produce a listing of the compiled bytecode for Lua's virtual machine. -Listing bytecodes is useful to learn about Lua's virtual machine. -If no files are given, then -.B luac -loads -.B luac.out -and lists its contents. -.TP -.BI \-o " file" -output to -.IR file , -instead of the default -.BR luac.out . -(You can use -.B "'\-'" -for standard output, -but not on platforms that open standard output in text mode.) -The output file may be a source file because -all files are loaded before the output file is written. -Be careful not to overwrite precious files. -.TP -.B \-p -load files but do not generate any output file. -Used mainly for syntax checking and for testing precompiled chunks: -corrupted files will probably generate errors when loaded. -Lua always performs a thorough integrity test on precompiled chunks. -Bytecode that passes this test is completely safe, -in the sense that it will not break the interpreter. -However, -there is no guarantee that such code does anything sensible. -(None can be given, because the halting problem is unsolvable.) -If no files are given, then -.B luac -loads -.B luac.out -and tests its contents. -No messages are displayed if the file passes the integrity test. -.TP -.B \-s -strip debug information before writing the output file. -This saves some space in very large chunks, -but if errors occur when running a stripped chunk, -then the error messages may not contain the full information they usually do. -For instance, -line numbers and names of local variables are lost. -.TP -.B \-v -show version information. -.SH FILES -.TP 15 -.B luac.out -default output file -.SH "SEE ALSO" -.BR lua (1) -.br -http://www.lua.org/ -.SH DIAGNOSTICS -Error messages should be self explanatory. -.SH AUTHORS -L. H. de Figueiredo, -R. Ierusalimschy and -W. Celes -.\" EOF diff --git a/doc/lua/luac.html b/doc/lua/luac.html deleted file mode 100644 index 179ffe8..0000000 --- a/doc/lua/luac.html +++ /dev/null @@ -1,145 +0,0 @@ - - - -LUAC man page - - - - - -

NAME

-luac - Lua compiler -

SYNOPSIS

-luac -[ -options -] [ -filenames -] -

DESCRIPTION

-luac -is the Lua compiler. -It translates programs written in the Lua programming language -into binary files that can be later loaded and executed. -

-The main advantages of precompiling chunks are: -faster loading, -protecting source code from accidental user changes, -and -off-line syntax checking. -

-Precompiling does not imply faster execution -because in Lua chunks are always compiled into bytecodes before being executed. -luac -simply allows those bytecodes to be saved in a file for later execution. -

-Precompiled chunks are not necessarily smaller than the corresponding source. -The main goal in precompiling is faster loading. -

-The binary files created by -luac -are portable only among architectures with the same word size and byte order. -

-luac -produces a single output file containing the bytecodes -for all source files given. -By default, -the output file is named -luac.out, -but you can change this with the --o -option. -

-In the command line, -you can mix -text files containing Lua source and -binary files containing precompiled chunks. -This is useful because several precompiled chunks, -even from different (but compatible) platforms, -can be combined into a single precompiled chunk. -

-You can use -'-' -to indicate the standard input as a source file -and -'--' -to signal the end of options -(that is, -all remaining arguments will be treated as files even if they start with -'-'). -

-The internal format of the binary files produced by -luac -is likely to change when a new version of Lua is released. -So, -save the source files of all Lua programs that you precompile. -

-

OPTIONS

-Options must be separate. -

--l -produce a listing of the compiled bytecode for Lua's virtual machine. -Listing bytecodes is useful to learn about Lua's virtual machine. -If no files are given, then -luac -loads -luac.out -and lists its contents. -

--o file -output to -file, -instead of the default -luac.out. -(You can use -'-' -for standard output, -but not on platforms that open standard output in text mode.) -The output file may be a source file because -all files are loaded before the output file is written. -Be careful not to overwrite precious files. -

--p -load files but do not generate any output file. -Used mainly for syntax checking and for testing precompiled chunks: -corrupted files will probably generate errors when loaded. -Lua always performs a thorough integrity test on precompiled chunks. -Bytecode that passes this test is completely safe, -in the sense that it will not break the interpreter. -However, -there is no guarantee that such code does anything sensible. -(None can be given, because the halting problem is unsolvable.) -If no files are given, then -luac -loads -luac.out -and tests its contents. -No messages are displayed if the file passes the integrity test. -

--s -strip debug information before writing the output file. -This saves some space in very large chunks, -but if errors occur when running a stripped chunk, -then the error messages may not contain the full information they usually do. -For instance, -line numbers and names of local variables are lost. -

--v -show version information. -

FILES

-

-luac.out -default output file -

SEE ALSO

-lua(1) -
-http://www.lua.org/ -

DIAGNOSTICS

-Error messages should be self explanatory. -

AUTHORS

-L. H. de Figueiredo, -R. Ierusalimschy and -W. Celes - - - diff --git a/doc/lua/manual.html b/doc/lua/manual.html deleted file mode 100644 index a44d2e8..0000000 --- a/doc/lua/manual.html +++ /dev/null @@ -1,6247 +0,0 @@ - - - - -Lua 5.1 Reference Manual - - - - - -
-

-[Lua logo] -Lua 5.1 Reference Manual -

- -by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes -

- -Copyright -© 2006 Lua.org, PUC-Rio. All rights reserved. - -


- -

-

- - - -

1 - Introduction

- -

Lua is an extension programming language designed to support -general procedural programming with data description -facilities. -It also offers good support for object-oriented programming, -functional programming, and data-driven programming. -Lua is intended to be used as a powerful, light-weight -scripting language for any program that needs one. -Lua is implemented as a library, written in clean C -(that is, in the common subset of ANSI C and C++). - -

Being an extension language, Lua has no notion of a "main" program: -it only works embedded in a host client, -called the embedding program or simply the host. -This host program can invoke functions to execute a piece of Lua code, -can write and read Lua variables, -and can register C functions to be called by Lua code. -Through the use of C functions, Lua can be augmented to cope with -a wide range of different domains, -thus creating customized programming languages sharing a syntactical framework. -The Lua distribution includes a sample host program called lua, -which uses the Lua library to offer a complete, stand-alone Lua interpreter. - -

Lua is free software, -and is provided as usual with no guarantees, -as stated in its license. -The implementation described in this manual is available -at Lua's official web site, www.lua.org. - -

Like any other reference manual, -this document is dry in places. -For a discussion of the decisions behind the design of Lua, -see the technical papers available at Lua's web site. -For a detailed introduction to programming in Lua, -see Roberto's book, Programming in Lua. - -

-

2 - The Language

- -

This section describes the lexis, the syntax, and the semantics of Lua. -In other words, -this section describes -which tokens are valid, -how they can be combined, -and what their combinations mean. - -

The language constructs will be explained using the usual extended BNF notation, -in which -{a} means 0 or more a's, and -[a] means an optional a. -Non-terminals are shown in italics, -keywords are shown in bold, -and other terminal symbols are shown in typewriter font, -enclosed in single quotes. -The complete syntax of Lua can be found at the end of this manual. - -

2.1 - Lexical Conventions

- -

Names -(also called identifiers) -in Lua can be any string of letters, -digits, and underscores, -not beginning with a digit. -This coincides with the definition of names in most languages. -(The definition of letter depends on the current locale: -any character considered alphabetic by the current locale -can be used in an identifier.) -Identifiers are used to name variables and table fields. - -

The following keywords are reserved -and cannot be used as names: - -

-       and       break     do        else      elseif
-       end       false     for       function  if
-       in        local     nil       not       or
-       repeat    return    then      true      until     while
-
- -

Lua is a case-sensitive language: -and is a reserved word, but And and AND -are two different, valid names. -As a convention, names starting with an underscore followed by -uppercase letters (such as _VERSION) -are reserved for internal global variables used by Lua. - -

The following strings denote other tokens: -

-       +     -     *     /     %     ^     #
-       ==    ~=    <=    >=    <     >     =
-       (     )     {     }     [     ]
-       ;     :     ,     .     ..    ...
-
- -

Literal strings -can be delimited by matching single or double quotes, -and can contain the following C-like escape sequences: -

    -
  • \a --- bell -
  • \b --- backspace -
  • \f --- form feed -
  • \n --- newline -
  • \r --- carriage return -
  • \t --- horizontal tab -
  • \v --- vertical tab -
  • \\ --- backslash -
  • \" --- quotation mark (double quote) -
  • \' --- apostrophe (single quote) -
-Moreover, a `\newline´ -(that is, a backslash followed by a real newline) -results in a newline in the string. -A character in a string may also be specified by its numerical value -using the escape sequence `\ddd´, -where ddd is a sequence of up to three decimal digits. -(Note that if a numerical escape is to be followed by a digit, -it must be expressed using exactly three digits.) -Strings in Lua may contain any 8-bit value, including embedded zeros, -which can be specified as `\0´. - -

To put a double (single) quote, a newline, a backslash, -or an embedded zero -inside a literal string enclosed by double (single) quotes -you must use an escape sequence. -Any other character may be directly inserted into the literal. -(Some control characters may cause problems for the file system, -but Lua has no problem with them.) - -

Literal strings can also be defined using a long format -enclosed by long brackets. -We define an opening long bracket of level n as an opening -square bracket followed by n equal signs followed by another -opening square bracket. -So, an opening long bracket of level 0 is written as [[, -an opening long bracket of level 1 is written as [=[, -and so on. -A closing long bracket is defined similarly; -for instance, a closing long bracket of level 4 is written as ]====]. -A long string starts with an opening long bracket of any level and -ends at the first closing long bracket of the same level. -Literals in this bracketed form may run for several lines, -do not interpret any escape sequences, -and ignore long brackets of any other level. -They may contain anything except a closing bracket of the proper level -or embedded zeros. - -

For convenience, -when the opening long bracket is immediately followed by a newline, -the newline is not included in the string. -As an example, in a system using ASCII -(in which `a´ is coded as 97, -newline is coded as 10, and `1´ is coded as 49), -the four literals below denote the same string: -

-      (1)   'alo\n123"'
-      (2)   "alo\n123\""
-      (3)   '\97lo\10\04923"'
-      (4)   [[alo
-            123"]]
-      (5)   [==[
-            alo
-            123"]==]
-
- -

Numerical constants may be written with an optional decimal part -and an optional decimal exponent. -Lua also accepts integer hexadecimal constants, -by prefixing them with 0x. -Examples of valid numerical constants are -

-       3       3.0     3.1416  314.16e-2   0.31416E1  0xff  0x56
-
- -

Comments start with a double hyphen (--) -anywhere outside a string. -If the text immediately after -- is not an opening long bracket, -the comment is a short comment, -which runs until the end of the line. -Otherwise, it is a long comment, -which runs until the corresponding closing long bracket. -Long comments are frequently used to disable code temporarily. - -

2.2 - Values and Types

- -

Lua is a dynamically typed language. -This means that -variables do not have types; only values do. -There are no type definitions in the language. -All values carry their own type. - -

All values in Lua are first-class values. -This means that all values can be stored in variables, -passed as arguments to other functions, and returned as results. - -

There are eight basic types in Lua: -nil, boolean, number, -string, function, userdata, -thread, and table. -Nil is the type of the value nil, -whose main property is to be different from any other value; -it usually represents the absence of a useful value. -Boolean is the type of the values false and true. -Both nil and false make a condition false; -any other value makes it true. -Number represents real (double-precision floating-point) numbers. -(It is easy to build Lua interpreters that use other -internal representations for numbers, -such as single-precision float or long integers. -See file luaconf.h.) -String represents arrays of characters. - -Lua is 8-bit clean: -Strings may contain any 8-bit character, -including embedded zeros (`\0´) (see 2.1). - -

Lua can call (and manipulate) functions written in Lua and -functions written in C -(see 2.5.8). - -

The type userdata is provided to allow arbitrary C data to -be stored in Lua variables. -This type corresponds to a block of raw memory -and has no pre-defined operations in Lua, -except assignment and identity test. -However, by using metatables, -the programmer can define operations for userdata values -(see 2.8). -Userdata values cannot be created or modified in Lua, -only through the C API. -This guarantees the integrity of data owned by the host program. - -

The type thread represents independent threads of execution -and it is used to implement coroutines (see 2.11). -Do not confuse Lua threads with operating-system threads. -Lua supports coroutines on all systems, -even those that do not support threads. - -

The type table implements associative arrays, -that is, arrays that can be indexed not only with numbers, -but with any value (except nil). -Tables can be heterogeneous; -that is, they can contain values of all types (except nil). -Tables are the sole data structuring mechanism in Lua; -they may be used to represent ordinary arrays, -symbol tables, sets, records, graphs, trees, etc. -To represent records, Lua uses the field name as an index. -The language supports this representation by -providing a.name as syntactic sugar for a["name"]. -There are several convenient ways to create tables in Lua -(see 2.5.7). - -

Like indices, -the value of a table field can be of any type (except nil). -In particular, -because functions are first-class values, -table fields may contain functions. -Thus tables may also carry methods (see 2.5.9). - -

Tables, functions, threads, and (full) userdata values are objects: -variables do not actually contain these values, -only references to them. -Assignment, parameter passing, and function returns -always manipulate references to such values; -these operations do not imply any kind of copy. - -

The library function type returns a string describing the type -of a given value. - -

2.2.1 - Coercion

- -

Lua provides automatic conversion between -string and number values at run time. -Any arithmetic operation applied to a string tries to convert -this string to a number, following the usual conversion rules. -Conversely, whenever a number is used where a string is expected, -the number is converted to a string, in a reasonable format. -For complete control over how numbers are converted to strings, -use the format function from the string library -(see string.format). - -

2.3 - Variables

- -

Variables are places that store values. - -There are three kinds of variables in Lua: -global variables, local variables, and table fields. - -

A single name can denote a global variable or a local variable -(or a function's formal parameter, -which is a particular kind of local variable): -

-	var ::= Name
-
-Name denotes identifiers, as defined in (see 2.1). - -

Variables are assumed to be global unless explicitly declared local -(see 2.4.7). -Local variables are lexically scoped: -Local variables can be freely accessed by functions -defined inside their scope (see 2.6). - -

Before the first assignment to a variable, its value is nil. - -

Square brackets are used to index a table: -

-	var ::= prefixexp `[´ exp `]´
-
-The first expression (prefixexp) should result in a table value; -the second expression (exp) -identifies a specific entry in this table. -The expression denoting the table to be indexed has a restricted syntax; -see 2.5 for details. - -

The syntax var.Name is just syntactic sugar for -var["Name"] and is used to denote table fields: -

-	var ::= prefixexp `.´ Name
-
- -

The meaning of accesses to global variables -and table fields can be changed via metatables. -An access to an indexed variable t[i] is equivalent to -a call gettable_event(t,i). -(See 2.8 for a complete description of the -gettable_event function. -This function is not defined or callable in Lua. -We use it here only for explanatory purposes.) - -

All global variables live as fields in ordinary Lua tables, -called environment tables or simply -environments (see 2.9). -Each function has its own reference to an environment, -so that all global variables in this function -will refer to this environment table. -When a function is created, -it inherits the environment from the function that created it. -To get the environment table of a Lua function, -you call getfenv. -To replace it, -you call setfenv. -(You can only manipulate the environment of C functions -through the debug library; (see 5.9).) - -

An access to a global variable x -is equivalent to _env.x, -which in turn is equivalent to -

-       gettable_event(_env, "x")
-
-where _env is the environment of the running function. -(See 2.8 for a complete description of the -gettable_event function. -This function is not defined or callable in Lua. -Similarly, the _env variable is not defined in Lua. -We use them here only for explanatory purposes.) - -

2.4 - Statements

- -

Lua supports an almost conventional set of statements, -similar to those in Pascal or C. -This set includes -assignment, control structures, function calls, -table constructors, and variable declarations. - -

2.4.1 - Chunks

- -

The unit of execution of Lua is called a chunk. -A chunk is simply a sequence of statements, -which are executed sequentially. -Each statement can be optionally followed by a semicolon: -

-	chunk ::= {stat [`;´]}
-
-There are no empty statements and thus `;;´ is not legal. - -

Lua handles a chunk as the body of an anonymous function -with a variable number of arguments -(see 2.5.9). -As such, chunks can define local variables, -receive arguments, and return values. - -

A chunk may be stored in a file or in a string inside the host program. -When a chunk is executed, first it is pre-compiled into instructions for -a virtual machine, -and then the compiled code is executed -by an interpreter for the virtual machine. - -

Chunks may also be pre-compiled into binary form; -see program luac for details. -Programs in source and compiled forms are interchangeable; -Lua automatically detects the file type and acts accordingly. - - -

2.4.2 - Blocks

-A block is a list of statements; -syntactically, a block is the same as a chunk: -
-	block ::= chunk
-
- -

A block may be explicitly delimited to produce a single statement: -

-	stat ::= do block end
-
-Explicit blocks are useful -to control the scope of variable declarations. -Explicit blocks are also sometimes used to -add a return or break statement in the middle -of another block (see 2.4.4). - - -

2.4.3 - Assignment

- -

Lua allows multiple assignment. -Therefore, the syntax for assignment -defines a list of variables on the left side -and a list of expressions on the right side. -The elements in both lists are separated by commas: -

-	stat ::= varlist1 `=´ explist1
-	varlist1 ::= var {`,´ var}
-	explist1 ::= exp {`,´ exp}
-
-Expressions are discussed in 2.5. - -

Before the assignment, -the list of values is adjusted to the length of -the list of variables. -If there are more values than needed, -the excess values are thrown away. -If there are fewer values than needed, -the list is extended with as many nil's as needed. -If the list of expressions ends with a function call, -then all values returned by this call enter in the list of values, -before the adjustment -(except when the call is enclosed in parentheses; see 2.5). - -

The assignment statement first evaluates all its expressions -and only then are the assignments performed. -Thus the code -

-       i = 3
-       i, a[i] = i+1, 20
-
-sets a[3] to 20, without affecting a[4] -because the i in a[i] is evaluated (to 3) -before it is assigned 4. -Similarly, the line -
-       x, y = y, x
-
-exchanges the values of x and y. - -

The meaning of assignments to global variables -and table fields can be changed via metatables. -An assignment to an indexed variable t[i] = val is equivalent to -settable_event(t,i,val). -(See 2.8 for a complete description of the -settable_event function. -This function is not defined or callable in Lua. -We use it here only for explanatory purposes.) - -

An assignment to a global variable x = val -is equivalent to the assignment -_env.x = val, -which in turn is equivalent to -

-       settable_event(_env, "x", val)
-
-where _env is the environment of the running function. -(The _env variable is not defined in Lua. -We use it here only for explanatory purposes.) - -

2.4.4 - Control Structures

-The control structures -if, while, and repeat have the usual meaning and -familiar syntax: - - - -
-	stat ::= while exp do block end
-	stat ::= repeat block until exp
-	stat ::= if exp then block {elseif exp then block} [else block] end
-
-Lua also has a for statement, in two flavors (see 2.4.5). - -

The condition expression of a -control structure may return any value. -Both false and nil are considered false. -All values different from nil and false are considered true -(in particular, the number 0 and the empty string are also true). - -

In the repeat--until loop, -the inner block does not end at the until keyword, -but only after the condition. -So, the condition can refer to local variables -declared inside the loop block. - -

The return statement is used to return values -from a function or a chunk (which is just a function). - -Functions and chunks may return more than one value, -so the syntax for the return statement is -

-	stat ::= return [explist1]
-
- -

The break statement is used to terminate the execution of a -while, repeat, or for loop, -skipping to the next statement after the loop: - -

-	stat ::= break
-
-A break ends the innermost enclosing loop. - -

The return and break -statements can only be written as the last statement of a block. -If it is really necessary to return or break in the -middle of a block, -then an explicit inner block can be used, -as in the idioms -`do return end´ and -`do break end´, -because now return and break are the last statements in -their (inner) blocks. - -

2.4.5 - For Statement

- -

The for statement has two forms: -one numeric and one generic. - - -

The numeric for loop repeats a block of code while a -control variable runs through an arithmetic progression. -It has the following syntax: -

-	stat ::= for Name `=´ exp `,´ exp [`,´ exp] do block end
-
-The block is repeated for name starting at the value of -the first exp, until it passes the second exp by steps of the -third exp. -More precisely, a for statement like -
-       for var = e1, e2, e3 do block end
-
-is equivalent to the code: -
-       do
-         local _var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3)
-         if not (_var and _limit and _step) then error() end
-         while (_step>0 and _var<=_limit) or (_step<=0 and _var>=_limit) do
-           local var = _var
-           block
-           _var = _var + _step
-         end
-       end
-
-Note the following: -
    -
  • All three control expressions are evaluated only once, -before the loop starts. -They must all result in numbers. -
  • _var, _limit, and _step are invisible variables. -The names are here for explanatory purposes only. -
  • If the third expression (the step) is absent, -then a step of 1 is used. -
  • You can use break to exit a for loop. -
  • The loop variable var is local to the loop; -you cannot use its value after the for ends or is broken. -If you need the value of the loop variable var, -then assign it to another variable before breaking or exiting the loop. -
- -

The generic for statement works over functions, -called iterators. -On each iteration, the iterator function is called to produce a new value, -stopping when this new value is nil. -The generic for loop has the following syntax: -

-	stat ::= for namelist in explist1 do block end
-	namelist ::= Name {`,´ Name}
-
-A for statement like -
-       for var_1, ..., var_n in explist do block end
-
-is equivalent to the code: -
-       do
-         local _f, _s, _var = explist
-         while true do
-           local var_1, ... , var_n = _f(_s, _var)
-           _var = var_1
-           if _var == nil then break end
-           block
-         end
-       end
-
-Note the following: -
    -
  • explist is evaluated only once. -Its results are an iterator function, -a state, and an initial value for the first iterator variable. -
  • _f, _s, and _var are invisible variables. -The names are here for explanatory purposes only. -
  • You can use break to exit a for loop. -
  • The loop variables var_i are local to the loop; -you cannot use their values after the for ends. -If you need these values, -then assign them to other variables before breaking or exiting the loop. -
- -

2.4.6 - Function Calls as Statements

-To allow possible side-effects, -function calls can be executed as statements: -
-	stat ::= functioncall
-
-In this case, all returned values are thrown away. -Function calls are explained in 2.5.8. - -

2.4.7 - Local Declarations

-Local variables may be declared anywhere inside a block. -The declaration may include an initial assignment: -
-	stat ::= local namelist [`=´ explist1]
-
-If present, an initial assignment has the same semantics -of a multiple assignment (see 2.4.3). -Otherwise, all variables are initialized with nil. - -

A chunk is also a block (see 2.4.1), -and so local variables can be declared in a chunk outside any explicit block. -The scope of such local variables extends until the end of the chunk. - -

The visibility rules for local variables are explained in 2.6. - -

2.5 - Expressions

- -

-The basic expressions in Lua are the following: -

-	exp ::= prefixexp
-	exp ::= nil  |  false  |  true
-	exp ::= Number
-	exp ::= String
-	exp ::= function
-	exp ::= tableconstructor
-	exp ::= `...´
-	exp ::= exp binop exp
-	exp ::= unop exp
-	prefixexp ::= var  |  functioncall  |  `(´ exp `)´
-
- -

Numbers and literal strings are explained in 2.1; -variables are explained in 2.3; -function definitions are explained in 2.5.9; -function calls are explained in 2.5.8; -table constructors are explained in 2.5.7. -Vararg expressions, -denoted by three dots (`...´), can only be used inside -vararg functions; -they are explained in 2.5.9. - - -

Binary operators comprise arithmetic operators (see 2.5.1), -relational operators (see 2.5.2), and logical operators (see 2.5.3). -Unary operators comprise the unary minus (see 2.5.1), -the unary not (see 2.5.3), -and the unary length operator (see 2.5.5). - -

Both function calls and vararg expressions may result in multiple values. -If the expression is used as a statement (see 2.4.6) -(only possible for function calls), -then its return list is adjusted to zero elements, -thus discarding all returned values. -If the expression is used inside another expression -or in the middle of a list of expressions, -then its result list is adjusted to one element, -thus discarding all values except the first one. -If the expression is used as the last element of a list of expressions, -then no adjustment is made, -unless the call is enclosed in parentheses. - -

Here are some examples: -

-       f()                -- adjusted to 0 results
-       g(f(), x)          -- f() is adjusted to 1 result
-       g(x, f())          -- g gets x plus all values returned by f()
-       a,b,c = f(), x     -- f() is adjusted to 1 result (c gets nil)
-       a,b = ...          -- a gets the first vararg parameter, b gets
-                          -- the second (both a and b may get nil if there is
-                          -- no corresponding vararg parameter)
-       a,b,c = x, f()     -- f() is adjusted to 2 results
-       a,b,c = f()        -- f() is adjusted to 3 results
-       return f()         -- returns all values returned by f()
-       return ...         -- returns all received vararg parameters
-       return x,y,f()     -- returns x, y, and all values returned by f()
-       {f()}              -- creates a list with all values returned by f()
-       {...}              -- creates a list with all vararg parameters
-       {f(), nil}         -- f() is adjusted to 1 result
-
- -

An expression enclosed in parentheses always results in only one value. -Thus, -(f(x,y,z)) is always a single value, -even if f returns several values. -(The value of (f(x,y,z)) is the first value returned by f -or nil if f does not return any values.) - -

2.5.1 - Arithmetic Operators

-Lua supports the usual arithmetic operators: -the binary + (addition), -- (subtraction), * (multiplication), -/ (division), % (modulo), and ^ (exponentiation); -and unary - (negation). -If the operands are numbers, or strings that can be converted to -numbers (see 2.2.1), -then all operations have the usual meaning. -Exponentiation works for any exponent. -For instance, x^(-0.5) computes the inverse of the square root of x. -Modulus is defined as -
-       a % b == a - math.floor(a/b)*b
-
-That is, it is the remainder of a division that rounds -the quotient towards minus infinity. - -

2.5.2 - Relational Operators

-The relational operators in Lua are -
-       ==    ~=    <     >     <=    >=
-
-These operators always result in false or true. - -

Equality (==) first compares the type of its operands. -If the types are different, then the result is false. -Otherwise, the values of the operands are compared. -Numbers and strings are compared in the usual way. -Objects (tables, userdata, threads, and functions) -are compared by reference: -Two objects are considered equal only if they are the same object. -Every time you create a new object -(a table, userdata, thread, or function), -this new object is different from any previously existing object. - -

You can change the way that Lua compares tables and userdata -by using the "eq" metamethod (see 2.8). - -

The conversion rules of 2.2.1 -do not apply to equality comparisons. -Thus, "0"==0 evaluates to false, -and t[0] and t["0"] denote different -entries in a table. - - -

The operator ~= is exactly the negation of equality (==). - -

The order operators work as follows. -If both arguments are numbers, then they are compared as such. -Otherwise, if both arguments are strings, -then their values are compared according to the current locale. -Otherwise, Lua tries to call the "lt" or the "le" -metamethod (see 2.8). - -

2.5.3 - Logical Operators

-The logical operators in Lua are - -
-       and   or    not
-
-Like the control structures (see 2.4.4), -all logical operators consider both false and nil as false -and anything else as true. - - -

The negation operator not always returns false or true. -The conjunction operator and returns its first argument -if this value is false or nil; -otherwise, and returns its second argument. -The disjunction operator or returns its first argument -if this value is different from nil and false; -otherwise, or returns its second argument. -Both and and or use short-cut evaluation; -that is, -the second operand is evaluated only if necessary. -Here are some examples: -

-       10 or 20            --> 10
-       10 or error()       --> 10
-       nil or "a"          --> "a"
-       nil and 10          --> nil
-       false and error()   --> false
-       false and nil       --> false
-       false or nil        --> nil
-       10 and 20           --> 20
-
-(In this manual, -`-->´ indicates the result of the preceding expression.) - -

2.5.4 - Concatenation

-The string concatenation operator in Lua is -denoted by two dots (`..´). -If both operands are strings or numbers, then they are converted to -strings according to the rules mentioned in 2.2.1. -Otherwise, the "concat" metamethod is called (see 2.8). - -

2.5.5 - The Length Operator

- -

The length operator is denoted by the unary operator #. -The length of a string is its number of bytes -(that is, the usual meaning of string length when each -character is one byte). - -

The length of a table t is defined to be any -integer index n -such that t[n] is not nil and t[n+1] is nil; -moreover, if t[1] is nil, n may be zero. -For a regular array, with non-nil values from 1 to a given n, -its length is exactly that n, -the index of its last value. -If the array has "holes" -(that is, nil values between other non-nil values), -then #t may be any of the indices that -directly precedes a nil value -(that is, it may consider any such nil value as the end of -the array). - -

2.5.6 - Precedence

-Operator precedence in Lua follows the table below, -from lower to higher priority: -
-       or
-       and
-       <     >     <=    >=    ~=    ==
-       ..
-       +     -
-       *     /     %
-       not   #     - (unary)
-       ^
-
-As usual, -you can use parentheses to change the precedences of an expression. -The concatenation (`..´) and exponentiation (`^´) -operators are right associative. -All other binary operators are left associative. - -

2.5.7 - Table Constructors

-Table constructors are expressions that create tables. -Every time a constructor is evaluated, a new table is created. -Constructors can be used to create empty tables, -or to create a table and initialize some of its fields. -The general syntax for constructors is -
-	tableconstructor ::= `{´ [fieldlist] `}´
-	fieldlist ::= field {fieldsep field} [fieldsep]
-	field ::= `[´ exp `]´ `=´ exp  |  Name `=´ exp  |  exp
-	fieldsep ::= `,´  |  `;´
-
- -

Each field of the form [exp1] = exp2 adds to the new table an entry -with key exp1 and value exp2. -A field of the form name = exp is equivalent to -["name"] = exp. -Finally, fields of the form exp are equivalent to -[i] = exp, where i are consecutive numerical integers, -starting with 1. -Fields in the other formats do not affect this counting. -For example, -

-       a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
-
-is equivalent to -
-       do
-         local t = {}
-         t[f(1)] = g
-         t[1] = "x"         -- 1st exp
-         t[2] = "y"         -- 2nd exp
-         t.x = 1            -- t["x"] = 1
-         t[3] = f(x)        -- 3rd exp
-         t[30] = 23
-         t[4] = 45          -- 4th exp
-         a = t
-       end
-
- -

If the last field in the list has the form exp -and the expression is a function call or a vararg expression, -then all values returned by this expression enter the list consecutively -(see 2.5.8). -To avoid this, -enclose the function call (or the vararg expression) -in parentheses (see 2.5). - -

The field list may have an optional trailing separator, -as a convenience for machine-generated code. - -

2.5.8 - Function Calls

-A function call in Lua has the following syntax: -
-	functioncall ::= prefixexp args
-
-In a function call, -first prefixexp and args are evaluated. -If the value of prefixexp has type function, -then this function is called -with the given arguments. -Otherwise, the prefixexp "call" metamethod is called, -having as first parameter the value of prefixexp, -followed by the original call arguments -(see 2.8). - -

The form -

-	functioncall ::= prefixexp `:´ Name args
-
-can be used to call "methods". -A call v:name(...) -is syntactic sugar for v.name(v,...), -except that v is evaluated only once. - -

Arguments have the following syntax: -

-	args ::= `(´ [explist1] `)´
-	args ::= tableconstructor
-	args ::= String
-
-All argument expressions are evaluated before the call. -A call of the form f{...} is syntactic sugar for f({...}); -that is, the argument list is a single new table. -A call of the form f'...' -(or f"..." or f[[...]]) is syntactic sugar for f('...'); -that is, the argument list is a single literal string. - -

As an exception to the free-format syntax of Lua, -you cannot put a line break before the `(´ in a function call. -This restriction avoids some ambiguities in the language. -If you write -

-       a = f
-       (g).x(a)
-
-Lua would see that as a single statement, a = f(g).x(a). -So, if you want two statements, you must add a semi-colon between them. -If you actually want to call f, -you must remove the line break before (g). - -

A call of the form return functioncall is called -a tail call. -Lua implements proper tail calls -(or proper tail recursion): -In a tail call, -the called function reuses the stack entry of the calling function. -Therefore, there is no limit on the number of nested tail calls that -a program can execute. -However, a tail call erases any debug information about the -calling function. -Note that a tail call only happens with a particular syntax, -where the return has one single function call as argument; -this syntax makes the calling function return exactly -the returns of the called function. -So, none of the following examples are tail calls: -

-       return (f(x))        -- results adjusted to 1
-       return 2 * f(x)
-       return x, f(x)       -- additional results
-       f(x); return         -- results discarded
-       return x or f(x)     -- results adjusted to 1
-
- -

2.5.9 - Function Definitions

- -

The syntax for function definition is -

-	function ::= function funcbody
-	funcbody ::= `(´ [parlist1] `)´ block end
-
- -

The following syntactic sugar simplifies function definitions: -

-	stat ::= function funcname funcbody
-	stat ::= local function Name funcbody
-	funcname ::= Name {`.´ Name} [`:´ Name]
-
-The statement -
-       function f () ... end
-
-translates to -
-       f = function () ... end
-
-The statement -
-       function t.a.b.c.f () ... end
-
-translates to -
-       t.a.b.c.f = function () ... end
-
-The statement -
-       local function f () ... end
-
-translates to -
-       local f; f = function () ... end
-
-not this: -
-       local f = function () ... end
-
-(This only makes a difference when the body of the function -contains references to f.) - -

A function definition is an executable expression, -whose value has type function. -When Lua pre-compiles a chunk, -all its function bodies are pre-compiled too. -Then, whenever Lua executes the function definition, -the function is instantiated (or closed). -This function instance (or closure) -is the final value of the expression. -Different instances of the same function -may refer to different external local variables -and may have different environment tables. - -

Parameters act as local variables that are -initialized with the argument values: -

-	parlist1 ::= namelist [`,´ `...´]  |  `...´
-
-When a function is called, -the list of arguments is adjusted to -the length of the list of parameters, -unless the function is a variadic or vararg function, -which is -indicated by three dots (`...´) at the end of its parameter list. -A vararg function does not adjust its argument list; -instead, it collects all extra arguments and supplies them -to the function through a vararg expression, -which is also written as three dots. -The value of this expression is a list of all actual extra arguments, -similar to a function with multiple results. -If a vararg expression is used inside another expression -or in the middle of a list of expressions, -then its return list is adjusted to one element. -If the expression is used as the last element of a list of expressions, -then no adjustment is made -(unless the call is enclosed in parentheses). - -

As an example, consider the following definitions: -

-       function f(a, b) end
-       function g(a, b, ...) end
-       function r() return 1,2,3 end
-
-Then, we have the following mapping from arguments to parameters and -to the vararg expression: -
-       CALL            PARAMETERS
-
-       f(3)             a=3, b=nil
-       f(3, 4)          a=3, b=4
-       f(3, 4, 5)       a=3, b=4
-       f(r(), 10)       a=1, b=10
-       f(r())           a=1, b=2
-
-       g(3)             a=3, b=nil, ... -->  (nothing)
-       g(3, 4)          a=3, b=4,   ... -->  (nothing)
-       g(3, 4, 5, 8)    a=3, b=4,   ... -->  5  8
-       g(5, r())        a=5, b=1,   ... -->  2  3
-
- -

Results are returned using the return statement (see 2.4.4). -If control reaches the end of a function -without encountering a return statement, -then the function returns with no results. - -

The colon syntax -is used for defining methods, -that is, functions that have an implicit extra parameter self. -Thus, the statement -

-       function t.a.b.c:f (...) ... end
-
-is syntactic sugar for -
-       t.a.b.c.f = function (self, ...) ... end
-
- -

2.6 - Visibility Rules

- - -

Lua is a lexically scoped language. -The scope of variables begins at the first statement after -their declaration and lasts until the end of the innermost block that -includes the declaration. -Consider the following example: -

-       x = 10                -- global variable
-       do                    -- new block
-         local x = x         -- new `x', with value 10
-         print(x)            --> 10
-         x = x+1
-         do                  -- another block
-           local x = x+1     -- another `x'
-           print(x)          --> 12
-         end
-         print(x)            --> 11
-       end
-       print(x)              --> 10  (the global one)
-
- -

Notice that, in a declaration like local x = x, -the new x being declared is not in scope yet, -and so the second x refers to the outside variable. - -

Because of the lexical scoping rules, -local variables can be freely accessed by functions -defined inside their scope. -A local variable used by an inner function is called -an upvalue, or external local variable, -inside the inner function. - -

Notice that each execution of a local statement -defines new local variables. -Consider the following example: -

-       a = {}
-       local x = 20
-       for i=1,10 do
-         local y = 0
-         a[i] = function () y=y+1; return x+y end
-       end
-
-The loop creates ten closures -(that is, ten instances of the anonymous function). -Each of these closures uses a different y variable, -while all of them share the same x. - -

2.7 - Error Handling

- -

Because Lua is an embedded extension language, -all Lua actions start from C code in the host program -calling a function from the Lua library (see lua_pcall). -Whenever an error occurs during Lua compilation or execution, -control returns to C, -which can take appropriate measures -(such as printing an error message). - -

Lua code can explicitly generate an error by calling the -error function. -If you need to catch errors in Lua, -you can use the pcall function. - -

2.8 - Metatables

- -

Every value in Lua may have a metatable. -This metatable is an ordinary Lua table -that defines the behavior of the original value -under certain special operations. -You can change several aspects of the behavior -of operations over a value by setting specific fields in its metatable. -For instance, when a non-numeric value is the operand of an addition, -Lua checks for a function in the field "__add" in its metatable. -If it finds one, -Lua calls this function to perform the addition. - -

We call the keys in a metatable events -and the values metamethods. -In the previous example, the event is "add" -and the metamethod is the function that performs the addition. - -

You can query the metatable of any value -through the getmetatable function. - -

You can replace the metatable of tables -through the setmetatable -function. -You cannot change the metatable of other types from Lua -(except using the debug library); -you must use the C API for that. - -

Tables and userdata have individual metatables -(although multiple tables and userdata can share -a same table as their metatable); -values of all other types share one single metatable per type. -So, there is one single metatable for all numbers, -and for all strings, etc. - -

A metatable may control how an object behaves in arithmetic operations, -order comparisons, concatenation, length operation, and indexing. -A metatable can also define a function to be called when a userdata -is garbage collected. -For each of these operations Lua associates a specific key -called an event. -When Lua performs one of these operations over a value, -it checks whether this value has a metatable with the corresponding event. -If so, the value associated with that key (the metamethod) -controls how Lua will perform the operation. - -

Metatables control the operations listed next. -Each operation is identified by its corresponding name. -The key for each operation is a string with its name prefixed by -two underscores, `__´; -for instance, the key for operation "add" is the -string "__add". -The semantics of these operations is better explained by a Lua function -describing how the interpreter executes the operation. - -

The code shown here in Lua is only illustrative; -the real behavior is hard coded in the interpreter -and it is much more efficient than this simulation. -All functions used in these descriptions -(rawget, tonumber, etc.) -are described in 5.1. -In particular, to retrieve the metamethod of a given object, -we use the expression -

-       metatable(obj)[event]
-
-This should be read as -
-       rawget(getmetatable(obj) or {}, event)
-
-That is, the access to a metamethod does not invoke other metamethods, -and the access to objects with no metatables does not fail -(it simply results in nil). - -

    -
  • "add": -the + operation. - -

    The function getbinhandler below defines how Lua chooses a handler -for a binary operation. -First, Lua tries the first operand. -If its type does not define a handler for the operation, -then Lua tries the second operand. -

    - function getbinhandler (op1, op2, event)
    -   return metatable(op1)[event] or metatable(op2)[event]
    - end
    -
    -Using this function, -the behavior of the op1 + op2 is -
    - function add_event (op1, op2)
    -   local o1, o2 = tonumber(op1), tonumber(op2)
    -   if o1 and o2 then  -- both operands are numeric?
    -     return o1 + o2   -- `+' here is the primitive `add'
    -   else  -- at least one of the operands is not numeric
    -     local h = getbinhandler(op1, op2, "__add")
    -     if h then
    -       -- call the handler with both operands
    -       return h(op1, op2)
    -     else  -- no handler available: default behavior
    -       error("...")
    -     end
    -   end
    - end
    -
    - -

  • "sub": -the - operation. -Behavior similar to the "add" operation. - -

  • "mul": -the * operation. -Behavior similar to the "add" operation. - -

  • "div": -the / operation. -Behavior similar to the "add" operation. - -

  • "mod": -the % operation. -Behavior similar to the "add" operation, -with the operation -o1 - floor(o1/o2)*o2 as the primitive operation. - -

  • "pow": -the ^ (exponentiation) operation. -Behavior similar to the "add" operation, -with the function pow (from the C math library) -as the primitive operation. - -

  • "unm": -the unary - operation. -
    - function unm_event (op)
    -   local o = tonumber(op)
    -   if o then  -- operand is numeric?
    -     return -o  -- `-' here is the primitive `unm'
    -   else  -- the operand is not numeric.
    -     -- Try to get a handler from the operand
    -     local h = metatable(op).__unm
    -     if h then
    -       -- call the handler with the operand
    -       return h(op)
    -     else  -- no handler available: default behavior
    -       error("...")
    -     end
    -   end
    - end
    -
    - -

  • "concat": -the .. (concatenation) operation. -
    - function concat_event (op1, op2)
    -   if (type(op1) == "string" or type(op1) == "number") and
    -      (type(op2) == "string" or type(op2) == "number") then
    -     return op1 .. op2  -- primitive string concatenation
    -   else
    -     local h = getbinhandler(op1, op2, "__concat")
    -     if h then
    -       return h(op1, op2)
    -     else
    -       error("...")
    -     end
    -   end
    - end
    -
    - -

  • "len": -the # operation. -
    - function len_event (op)
    -   if type(op) == "string" then
    -     return strlen(op)         -- primitive string length
    -   elseif type(op) == "table" then
    -     return #op                -- primitive table length
    -   else
    -     local h = metatable(op).__len
    -     if h then
    -       -- call the handler with the operand
    -       return h(op)
    -     else  -- no handler available: default behavior
    -       error("...")
    -     end
    -   end
    - end
    -
    -See 2.5.5 for a description of the length of a table. - -

  • "eq": -the == operation. -The function getcomphandler defines how Lua chooses a metamethod -for comparison operators. -A metamethod only is selected when both objects -being compared have the same type -and the same metamethod for the selected operation. -
    - function getcomphandler (op1, op2, event)
    -   if type(op1) ~= type(op2) then return nil end
    -   local mm1 = metatable(op1)[event]
    -   local mm2 = metatable(op2)[event]
    -   if mm1 == mm2 then return mm1 else return nil end
    - end
    -
    -The "eq" event is defined as follows: -
    - function eq_event (op1, op2)
    -   if type(op1) ~= type(op2) then  -- different types?
    -     return false   -- different objects
    -   end
    -   if op1 == op2 then   -- primitive equal?
    -     return true   -- objects are equal
    -   end
    -   -- try metamethod
    -   local h = getcomphandler(op1, op2, "__eq")
    -   if h then
    -     return h(op1, op2)
    -   else
    -     return false
    -   end
    - end
    -
    -a ~= b is equivalent to not (a == b). - -

  • "lt": -the < operation. -
    - function lt_event (op1, op2)
    -   if type(op1) == "number" and type(op2) == "number" then
    -     return op1 < op2   -- numeric comparison
    -   elseif type(op1) == "string" and type(op2) == "string" then
    -     return op1 < op2   -- lexicographic comparison
    -   else
    -     local h = getcomphandler(op1, op2, "__lt")
    -     if h then
    -       return h(op1, op2)
    -     else
    -       error("...");
    -     end
    -   end
    - end
    -
    -a > b is equivalent to b < a. - -

  • "le": -the <= operation. -
    - function le_event (op1, op2)
    -   if type(op1) == "number" and type(op2) == "number" then
    -     return op1 <= op2   -- numeric comparison
    -   elseif type(op1) == "string" and type(op2) == "string" then
    -     return op1 <= op2   -- lexicographic comparison
    -   else
    -     local h = getcomphandler(op1, op2, "__le")
    -     if h then
    -       return h(op1, op2)
    -     else
    -       h = getcomphandler(op1, op2, "__lt")
    -       if h then
    -         return not h(op2, op1)
    -       else
    -         error("...");
    -       end
    -     end
    -   end
    - end
    -
    -a >= b is equivalent to b <= a. -Note that, in the absence of a "le" metamethod, -Lua tries the "lt", assuming that a <= b is -equivalent to not (b < a). - -

  • "index": -The indexing access table[key]. -
    - function gettable_event (table, key)
    -   local h
    -   if type(table) == "table" then
    -     local v = rawget(table, key)
    -     if v ~= nil then return v end
    -     h = metatable(table).__index
    -     if h == nil then return nil end
    -   else
    -     h = metatable(table).__index
    -     if h == nil then
    -       error("...");
    -     end
    -   end
    -   if type(h) == "function" then
    -     return h(table, key)      -- call the handler
    -   else return h[key]          -- or repeat operation on it
    -   end
    - end
    -
    - -

  • "newindex": -The indexing assignment table[key] = value. -
    - function settable_event (table, key, value)
    -   local h
    -   if type(table) == "table" then
    -     local v = rawget(table, key)
    -     if v ~= nil then rawset(table, key, value); return end
    -     h = metatable(table).__newindex
    -     if h == nil then rawset(table, key, value); return end
    -   else
    -     h = metatable(table).__newindex
    -     if h == nil then
    -       error("...");
    -     end
    -   end
    -   if type(h) == "function" then
    -     return h(table, key,value)    -- call the handler
    -   else h[key] = value             -- or repeat operation on it
    -   end
    - end
    -
    - -

  • "call": -called when Lua calls a value. -
    - function function_event (func, ...)
    -   if type(func) == "function" then
    -     return func(...)   -- primitive call
    -   else
    -     local h = metatable(func).__call
    -     if h then
    -       return h(func, ...)
    -     else
    -       error("...")
    -     end
    -   end
    - end
    -
    - -

- -

2.9 - Environments

- -

Besides metatables, -objects of types thread, function, and userdata -have another table associated with them, -called their environment. -Like metatables, environments are regular tables and -multiple objects can share the same environment. - -

Environments associated with userdata have no meaning for Lua. -It is only a feature for programmers to associate a table to -a userdata. - -

Environments associated with threads are called -global environments. -They are used as the default environment for threads and -non-nested functions created by the thread -(through loadfile, loadstring or load) -and can be directly accessed by C code (see 3.3). - -

Environments associated with C functions can be directly -accessed by C code (see 3.3). -They are used as the default environment for other C functions -created by the function. - -

Environments associated with Lua functions are used to resolve -all accesses to global variables within the function (see 2.3). -They are used as the default environment for other Lua functions -created by the function. - -

You can change the environment of a Lua function or the -running thread by calling setfenv. -You can get the environment of a Lua function or the running thread -by calling getfenv. -To manipulate the environment of other objects -(userdata, C functions, other threads) you must -use the C API. - -

2.10 - Garbage Collection

- -

Lua performs automatic memory management. -This means that -you have to worry neither about allocating memory for new objects -nor about freeing it when the objects are no longer needed. -Lua manages memory automatically by running -a garbage collector from time to time -to collect all dead objects -(that is, these objects that are no longer accessible from Lua). -All objects in Lua are subject to automatic management: -tables, userdata, functions, threads, and strings. - -

Lua implements an incremental mark-and-sweep collector. -It uses two numbers to control its garbage-collection cycles: -the garbage-collector pause and -the garbage-collector step multiplier. - -

The garbage-collector pause -controls how long the collector waits before starting a new cycle. -Larger values make the collector less aggressive. -Values smaller than 1 mean the collector will not wait to -start a new cycle. -A value of 2 means that the collector waits for the total memory in use -to double before starting a new cycle. - -

The step multiplier -controls the relative speed of the collector relative to -memory allocation. -Larger values make the collector more aggressive but also increases -the size of each incremental step. -Values smaller than 1 make the collector too slow and -may result in the collector never finishing a cycle. -The default, 2, means that the collector runs at "twice" -the speed of memory allocation. - -

You can change these numbers by calling lua_gc in C -or collectgarbage in Lua. -Both get as arguments percentage points -(so an argument 100 means a real value of 1). -With these functions you can also control -the collector directly (e.g., stop and restart it). - -

2.10.1 - Garbage-Collection Metamethods

- -

Using the C API, -you can set garbage-collector metamethods for userdata (see 2.8). -These metamethods are also called finalizers. -Finalizers allow you to coordinate Lua's garbage collection -with external resource management -(such as closing files, network or database connections, -or freeing your own memory). - -

Garbage userdata with a field __gc in their metatables are not -collected immediately by the garbage collector. -Instead, Lua puts them in a list. -After the collection, -Lua does the equivalent of the following function -for each userdata in that list: -

- function gc_event (udata)
-   local h = metatable(udata).__gc
-   if h then
-     h(udata)
-   end
- end
-
- -

At the end of each garbage-collection cycle, -the finalizers for userdata are called in reverse -order of their creation, -among those collected in that cycle. -That is, the first finalizer to be called is the one associated -with the userdata created last in the program. - -

2.10.2 - Weak Tables

- -

A weak table is a table whose elements are -weak references. -A weak reference is ignored by the garbage collector. -In other words, -if the only references to an object are weak references, -then the garbage collector will collect this object. - -

A weak table can have weak keys, weak values, or both. -A table with weak keys allows the collection of its keys, -but prevents the collection of its values. -A table with both weak keys and weak values allows the collection of -both keys and values. -In any case, if either the key or the value is collected, -the whole pair is removed from the table. -The weakness of a table is controlled by the value of the -__mode field of its metatable. -If the __mode field is a string containing the character `k´, -the keys in the table are weak. -If __mode contains `v´, -the values in the table are weak. - -

After you use a table as a metatable, -you should not change the value of its field __mode. -Otherwise, the weak behavior of the tables controlled by this -metatable is undefined. - -

2.11 - Coroutines

- -

Lua supports coroutines, -also called collaborative multithreading. -A coroutine in Lua represents an independent thread of execution. -Unlike threads in multithread systems, however, -a coroutine only suspends its execution by explicitly calling -a yield function. - -

You create a coroutine with a call to coroutine.create. -Its sole argument is a function -that is the main function of the coroutine. -The create function only creates a new coroutine and -returns a handle to it (an object of type thread); -it does not start the coroutine execution. - -

When you first call coroutine.resume, -passing as its first argument -the thread returned by coroutine.create, -the coroutine starts its execution, -at the first line of its main function. -Extra arguments passed to coroutine.resume are passed on -to the coroutine main function. -After the coroutine starts running, -it runs until it terminates or yields. - -

A coroutine can terminate its execution in two ways: -Normally, when its main function returns -(explicitly or implicitly, after the last instruction); -and abnormally, if there is an unprotected error. -In the first case, coroutine.resume returns true, -plus any values returned by the coroutine main function. -In case of errors, coroutine.resume returns false -plus an error message. - -

A coroutine yields by calling coroutine.yield. -When a coroutine yields, -the corresponding coroutine.resume returns immediately, -even if the yield happens inside nested function calls -(that is, not in the main function, -but in a function directly or indirectly called by the main function). -In the case of a yield, coroutine.resume also returns true, -plus any values passed to coroutine.yield. -The next time you resume the same coroutine, -it continues its execution from the point where it yielded, -with the call to coroutine.yield returning any extra -arguments passed to coroutine.resume. - -

The coroutine.wrap function creates a coroutine, -just like coroutine.create, -but instead of returning the coroutine itself, -it returns a function that, when called, resumes the coroutine. -Any arguments passed to this function -go as extra arguments to coroutine.resume. -coroutine.wrap returns all the values returned by coroutine.resume, -except the first one (the boolean error code). -Unlike coroutine.resume, -coroutine.wrap does not catch errors; -any error is propagated to the caller. - -

As an example, -consider the next code: -

-function foo (a)
-  print("foo", a)
-  return coroutine.yield(2*a)
-end
-
-co = coroutine.create(function (a,b)
-      print("co-body", a, b)
-      local r = foo(a+1)
-      print("co-body", r)
-      local r, s = coroutine.yield(a+b, a-b)
-      print("co-body", r, s)
-      return b, "end"
-end)
-       
-print("main", coroutine.resume(co, 1, 10))
-print("main", coroutine.resume(co, "r"))
-print("main", coroutine.resume(co, "x", "y"))
-print("main", coroutine.resume(co, "x", "y"))
-
-When you run it, it produces the following output: -
-co-body 1       10
-foo     2
-main    true    4
-co-body r
-main    true    11      -9
-co-body x       y
-main    true    10      end
-main    false   cannot resume dead coroutine
-
- -

-

3 - The Application Program Interface

- - -

This section describes the C API for Lua, that is, -the set of C functions available to the host program to communicate -with Lua. -All API functions and related types and constants -are declared in the header file lua.h. - -

Even when we use the term "function", -any facility in the API may be provided as a macro instead. -All such macros use each of its arguments exactly once -(except for the first argument, which is always a Lua state), -and so do not generate any hidden side-effects. - -

As in most C libraries, -the Lua API functions do not check their arguments for validity or consistency. -However, you can change this behavior by compiling Lua -with a proper definition for the macro luai_apicheck, -in file luaconf.h. - -

3.1 - The Stack

- -

Lua uses a virtual stack to pass values to and from C. -Each element in this stack represents a Lua value -(nil, number, string, etc.). - -

Whenever Lua calls C, the called function gets a new stack, -which is independent of previous stacks and of stacks of -C functions that are still active. -This stack initially contains any arguments to the C function -and it is where the C function pushes its results -to be returned to the caller (see lua_CFunction). - -

For convenience, -most query operations in the API do not follow a strict stack discipline. -Instead, they can refer to any element in the stack -by using an index: -A positive index represents an absolute stack position -(starting at 1); -a negative index represents an offset relative to the top of the stack. -More specifically, if the stack has n elements, -then index 1 represents the first element -(that is, the element that was pushed onto the stack first) -and -index n represents the last element; -index -1 also represents the last element -(that is, the element at the top) -and index -n represents the first element. -We say that an index is valid -if it lies between 1 and the stack top -(that is, if 1 <= abs(index) <= top). - - -

3.2 - Stack Size

- -

When you interact with Lua API, -you are responsible for ensuring consistency. -In particular, -you are responsible for controlling stack overflow. -You can use the function lua_checkstack -to grow the stack size. - -

Whenever Lua calls C, -it ensures that at least LUA_MINSTACK stack positions are available. -LUA_MINSTACK is defined as 20, -so that usually you do not have to worry about stack space -unless your code has loops pushing elements onto the stack. - -

Most query functions accept as indices any value inside the -available stack space, that is, indices up to the maximum stack size -you have set through lua_checkstack. -Such indices are called acceptable indices. -More formally, we define an acceptable index -as follows: -

-       (index < 0 && abs(index) <= top) || (index > 0 && index <= stackspace)
-
-Note that 0 is never an acceptable index. - -

3.3 - Pseudo-Indices

- -

Unless otherwise noted, -any function that accepts valid indices can also be called with -pseudo-indices, -which represent some Lua values that are accessible to C code -but which are not in the stack. -Pseudo-indices are used to access the thread environment, -the function environment, -the registry, -and the upvalues of a C function (see 3.4). - -

The thread environment (where global variables live) is -always at pseudo-index LUA_GLOBALSINDEX. -The environment of the running C function is always -at pseudo-index LUA_ENVIRONINDEX. - -

To access and change the value of global variables, -you can use regular table operations over an environment table. -For instance, to access the value of a global variable, do -

-       lua_getfield(L, LUA_GLOBALSINDEX, varname);
-
- -

3.4 - C Closures

- -

When a C function is created, -it is possible to associate some values with it, -thus creating a C closure; -these values are called upvalues and are -accessible to the function whenever it is called -(see lua_pushcclosure). - -

Whenever a C function is called, -its upvalues are located at specific pseudo-indices. -These pseudo-indices are produced by the macro -lua_upvalueindex. -The first value associated with a function is at position -lua_upvalueindex(1), and so on. -Any access to lua_upvalueindex(n), -where n is greater than the number of upvalues of the -current function, -produces an acceptable (but invalid) index. - -

3.5 - Registry

- -

Lua provides a registry, -a pre-defined table that can be used by any C code to -store whatever Lua value it needs to store. -This table is always located at pseudo-index -LUA_REGISTRYINDEX. -Any C library can store data into this table, -but it should take care to choose keys different from those used -by other libraries, to avoid collisions. -Typically, you should use as key a string containing your library name -or a light userdata with the address of a C object in your code. - -

The integer keys in the registry are used by the reference mechanism, -implemented by the auxiliary library, -and therefore should not be used for other purposes. - -

3.6 - Error Handling in C

- -

Internally, Lua uses the C longjmp facility to handle errors. -(You can also choose to use exceptions if you use C++; -See file luaconf.h.) -When Lua faces any error -(such as memory allocation errors, type errors, syntax errors, -and runtime errors) -it raises an error; -that is, it does a long jump. -A protected environment uses setjmp -to set a recover point; -any error jumps to the most recent active recover point. - -

Almost any function in the API may raise an error, -for instance due to a memory allocation error. -The following functions run in protected mode -(that is, they create a protected environment to run), -so they never raise an error: -lua_newstate, lua_close, lua_load, -lua_pcall, and lua_cpcall. - -

Inside a C function you can raise an error by calling lua_error. - -

3.7 - Functions and Types

- -

Here we list all functions and types from the C API in -alphabetical order. - -

-


lua_Alloc

-
-          typedef void * (*lua_Alloc) (void *ud,
-                                       void *ptr,
-                                       size_t osize,
-                                       size_t nsize);
-
-
- - -

The type of the memory allocation function used by Lua states. -The allocator function must provide a -functionality similar to realloc, -but not exactly the same. -Its arguments are -ud, an opaque pointer passed to lua_newstate; -ptr, a pointer to the block being allocated/reallocated/freed; -osize, the original size of the block; -nsize, the new size of the block. -ptr is NULL if and only if osize is zero. -When nsize is zero, the allocator must return NULL; -if osize is not zero, -it should free the block pointed to by ptr. -When nsize is not zero, the allocator returns NULL -if and only if it cannot fill the request. -When nsize is not zero and osize is zero, -the allocator should behave like malloc. -When nsize and osize are not zero, -the allocator behaves like realloc. -Lua assumes that the allocator never fails when -osize >= nsize. - -

Here is a simple implementation for the allocator function. -It is used in the auxiliary library by lua_newstate. -

-static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
-  (void)ud;     /* not used */
-  (void)osize;  /* not used */
-  if (nsize == 0) {
-    free(ptr);  /* ANSI requires that free(NULL) has no effect */
-    return NULL;
-  }
-  else
-    /* ANSI requires that realloc(NULL, size) == malloc(size) */
-    return realloc(ptr, nsize);
-}
-
- -

-


lua_atpanic

-
-          lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);
-
- - -

Sets a new panic function and returns the old one. - -

If an error happens outside any protected environment, -Lua calls a panic function -and then calls exit(EXIT_FAILURE), -thus exiting the host application. -Your panic function may avoid this exit by -never returning (e.g., doing a long jump). - -

The panic function can access the error message at the top of the stack. - -

-


lua_call

-
-          void lua_call (lua_State *L, int nargs, int nresults);
-
- - -

Calls a function. - -

To call a function you must use the following protocol: -First, the function to be called is pushed onto the stack; -then, the arguments to the function are pushed -in direct order; -that is, the first argument is pushed first. -Finally you call lua_call; -nargs is the number of arguments that you pushed onto the stack. -All arguments and the function value are popped from the stack -when the function is called. -The function results are pushed onto the stack when the function returns. -The number of results is adjusted to nresults, -unless nresults is LUA_MULTRET. -In this case, all results from the function are pushed. -Lua takes care that the returned values fit into the stack space. -The function results are pushed onto the stack in direct order -(the first result is pushed first), -so that after the call the last result is on the top of the stack. - -

Any error inside the called function is propagated upwards -(with a longjmp). - -

The following example shows how the host program may do the -equivalent to this Lua code: -

-       a = f("how", t.x, 14)
-
-Here it is in C: -
-    lua_getfield(L, LUA_GLOBALSINDEX, "f");          /* function to be called */
-    lua_pushstring(L, "how");                                 /* 1st argument */
-    lua_getfield(L, LUA_GLOBALSINDEX, "t");            /* table to be indexed */
-    lua_getfield(L, -1, "x");                 /* push result of t.x (2nd arg) */
-    lua_remove(L, -2);                           /* remove `t' from the stack */
-    lua_pushinteger(L, 14);                                   /* 3rd argument */
-    lua_call(L, 3, 1);         /* call function with 3 arguments and 1 result */
-    lua_setfield(L, LUA_GLOBALSINDEX, "a");        /* set global variable `a' */
-
-Note that the code above is "balanced": -at its end, the stack is back to its original configuration. -This is considered good programming practice. - -

-


lua_CFunction

-
-          typedef int (*lua_CFunction) (lua_State *L);
-
- - -

Type for C functions. - -

In order to communicate properly with Lua, -a C function must use the following protocol, -which defines the way parameters and results are passed: -A C function receives its arguments from Lua in its stack -in direct order (the first argument is pushed first). -So, when the function starts, -lua_gettop(L) returns the number of arguments received by the function. -The first argument (if any) is at index 1 -and its last argument is at index lua_gettop(L). -To return values to Lua, a C function just pushes them onto the stack, -in direct order (the first result is pushed first), -and returns the number of results. -Any other value in the stack below the results will be properly -discarded by Lua. -Like a Lua function, a C function called by Lua can also return -many results. - -

As an example, the following function receives a variable number -of numerical arguments and returns their average and sum: -

-       static int foo (lua_State *L) {
-         int n = lua_gettop(L);    /* number of arguments */
-         lua_Number sum = 0;
-         int i;
-         for (i = 1; i <= n; i++) {
-           if (!lua_isnumber(L, i)) {
-             lua_pushstring(L, "incorrect argument to function `average'");
-             lua_error(L);
-           }
-           sum += lua_tonumber(L, i);
-         }
-         lua_pushnumber(L, sum/n);        /* first result */
-         lua_pushnumber(L, sum);         /* second result */
-         return 2;                   /* number of results */
-       }
-
- -

-


lua_checkstack

-
-          int lua_checkstack (lua_State *L, int extra);
-
- - -

Ensures that there are at least extra free stack slots in the stack. -It returns false if it cannot grow the stack to that size. -This function never shrinks the stack; -if the stack is already larger than the new size, -it is left unchanged. - -

-


lua_close

-
-          void lua_close (lua_State *L);
-
- - -

Destroys all objects in the given Lua state -(calling the corresponding garbage-collection metamethods, if any) -and frees all dynamic memory used by this state. -On several platforms, you may not need to call this function, -because all resources are naturally released when the host program ends. -On the other hand, long-running programs, -such as a daemon or a web server, -might need to release states as soon as they are not needed, -to avoid growing too large. - -

-


lua_concat

-
-          void lua_concat (lua_State *L, int n);
-
- - -

Concatenates the n values at the top of the stack, -pops them, and leaves the result at the top. -If n is 1, the result is the single string on the stack -(that is, the function does nothing); -if n is 0, the result is the empty string. -Concatenation is done following the usual semantics of Lua -(see 2.5.4). - -

-


lua_cpcall

-
-          int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);
-
- - -

Calls the C function func in protected mode. -func starts with only one element in its stack, -a light userdata containing ud. -In case of errors, -lua_cpcall returns the same error codes as lua_pcall, -plus the error object on the top of the stack; -otherwise, it returns zero, and does not change the stack. -All values returned by func are discarded. - -

-


lua_createtable

-
-          void lua_createtable (lua_State *L, int narr, int nrec);
-
- - -

Creates a new empty table and pushes it onto the stack. -The new table has space pre-allocated -for narr array elements and nrec non-array elements. -This pre-allocation is useful when you know exactly how many elements -the table will have. -Otherwise you can use the function lua_newtable. - -

-


lua_dump

-
-          int lua_dump (lua_State *L, lua_Writer writer, void *data);
-
- - -

Dumps a function as a binary chunk. -Receives a Lua function on the top of the stack -and produces a binary chunk that, -if loaded again, -results in a function equivalent to the one dumped. -As it produces parts of the chunk, -lua_dump calls function writer (see lua_Writer) -with the given data -to write them. - -

The value returned is the error code returned by the last -call to the writer; -0 means no errors. - -

This function does not pop the Lua function from the stack. - -

-


lua_equal

-
-          int lua_equal (lua_State *L, int index1, int index2);
-
- - -

Returns 1 if the two values in acceptable indices index1 and -index2 are equal, -following the semantics of the Lua == operator -(that is, may call metamethods). -Otherwise returns 0. -Also returns 0 if any of the indices is non valid. - -

-


lua_error

-
-          int lua_error (lua_State *L);
-
- - -

Generates a Lua error. -The error message (which can actually be a Lua value of any type) -must be on the stack top. -This function does a long jump, -and therefore never returns. -(see luaL_error). - -

-


lua_gc

-
-          int lua_gc (lua_State *L, int what, int data);
-
- - -

Controls the garbage collector. - -

This function performs several tasks, -according to the value of the parameter what: -

    -
  • LUA_GCSTOP--- stops the garbage collector. -
  • LUA_GCRESTART--- restarts the garbage collector. -
  • LUA_GCCOLLECT--- performs a full garbage-collection cycle. -
  • LUA_GCCOUNT--- returns the current -amount of memory (in Kbytes) in use by Lua. -
  • LUA_GCCOUNTB--- returns the remainder of -dividing the current amount of bytes of memory in use by Lua -by 1024. -
  • LUA_GCSTEP--- performs an incremental step of -garbage collection. -The step "size" is controlled by data -(larger values mean more steps) in a non-specified way. -If you want to control the step size -you must tune experimentally the value of data. -The function returns 1 if the step finished a -garbage-collection cycle. -
  • LUA_GCSETPAUSE--- -sets data/100 as the new value -for the pause of the collector (see 2.10). -The function returns the previous value of the pause. -
  • LUA_GCSETSTEPMUL--- -sets arg/100 as the new value for the step multiplier of -the collector (see 2.10). -The function returns the previous value of the step multiplier. -
- -

-


lua_getallocf

-
-          lua_Alloc lua_getallocf (lua_State *L, void **ud);
-
- - -

Returns the memory allocator function of a given state. -If ud is not NULL, Lua stores in *ud the -opaque pointer passed to lua_newstate. - -

-


lua_getfenv

-
-          void lua_getfenv (lua_State *L, int index);
-
- - -

Pushes on the stack the environment table of -the value at the given index. - -

-


lua_getfield

-
-          void lua_getfield (lua_State *L, int index, const char *k);
-
- - -

Pushes onto the stack the value t[k], -where t is the value at the given valid index index. -As in Lua, this function may trigger a metamethod -for the "index" event (see 2.8). - -

-


lua_getglobal

-
-          void lua_getglobal (lua_State *L, const char *name);
-
- - -

Pushes onto the stack the value of the global name. -It is defined as a macro: -

-#define lua_getglobal(L,s)  lua_getfield(L, LUA_GLOBALSINDEX, s)
-
- -

-


lua_getmetatable

-
-          int lua_getmetatable (lua_State *L, int index);
-
- - -

Pushes onto the stack the metatable of the value at the given -acceptable index. -If the index is not valid, -or if the value does not have a metatable, -the function returns 0 and pushes nothing on the stack. - -

-


lua_gettable

-
-          void lua_gettable (lua_State *L, int index);
-
- - -

Pushes onto the stack the value t[k], -where t is the value at the given valid index index -and k is the value at the top of the stack. - -

This function pops the key from the stack -(putting the resulting value in its place). -As in Lua, this function may trigger a metamethod -for the "index" event (see 2.8). - -

-


lua_gettop

-
-          int lua_gettop (lua_State *L);
-
- - -

Returns the index of the top element in the stack. -Because indices start at 1, -this result is equal to the number of elements in the stack -(and so 0 means an empty stack). - -

-


lua_insert

-
-          void lua_insert (lua_State *L, int index);
-
- - -

Moves the top element into the given valid index, -shifting up the elements above this index to open space. -Cannot be called with a pseudo-index, -because a pseudo-index is not an actual stack position. - -

-


lua_Integer

-
-          typedef ptrdiff_t lua_Integer;
-
- - -

The type used by the Lua API to represent integral values. - -

By default it is a ptrdiff_t, -which is usually the largest integral type the machine handles -"comfortably". - -

-


lua_isboolean

-
-          int lua_isboolean (lua_State *L, int index);
-
- - -

Returns 1 if the value at the given acceptable index has type boolean, -and 0 otherwise. - -

-


lua_iscfunction

-
-          int lua_iscfunction (lua_State *L, int index);
-
- - -

Returns 1 if the value at the given acceptable index is a C function, -and 0 otherwise. - -

-


lua_isfunction

-
-          int lua_isfunction (lua_State *L, int index);
-
- - -

Returns 1 if the value at the given acceptable index is a function -(either C or Lua), and 0 otherwise. - -

-


lua_islightuserdata

-
-          int lua_islightuserdata (lua_State *L, int index);
-
- - -

Returns 1 if the value at the given acceptable index is a light userdata, -and 0 otherwise. - -

-


lua_isnil

-
-          int lua_isnil (lua_State *L, int index);
-
- - -

Returns 1 if the value at the given acceptable index is nil, -and 0 otherwise. - -

-


lua_isnumber

-
-          int lua_isnumber (lua_State *L, int index);
-
- - -

Returns 1 if the value at the given acceptable index is a number -or a string convertible to a number, -and 0 otherwise. - -

-


lua_isstring

-
-          int lua_isstring (lua_State *L, int index);
-
- - -

Returns 1 if the value at the given acceptable index is a string -or a number (which is always convertible to a string), -and 0 otherwise. - -

-


lua_istable

-
-          int lua_istable (lua_State *L, int index);
-
- - -

Returns 1 if the value at the given acceptable index is a table, -and 0 otherwise. - -

-


lua_isthread

-
-          int lua_isthread (lua_State *L, int index);
-
- - -

Returns 1 if the value at the given acceptable index is a thread, -and 0 otherwise. - -

-


lua_isuserdata

-
-          int lua_isuserdata (lua_State *L, int index);
-
- - -

Returns 1 if the value at the given acceptable index is a userdata -(either full or light), and 0 otherwise. - -

-


lua_lessthan

-
-          int lua_lessthan (lua_State *L, int index1, int index2);
-
- - -

Returns 1 if the value at acceptable index index1 is smaller -than the value at acceptable index index2, -following the semantics of the Lua < operator -(that is, may call metamethods). -Otherwise returns 0. -Also returns 0 if any of the indices is non valid. - -

-


lua_load

-
-          int lua_load (lua_State *L, lua_Reader reader, void *data,
-                                      const char *chunkname);
-
-
- - -

Loads a Lua chunk. -If there are no errors, -lua_load pushes the compiled chunk as a Lua -function on top of the stack. -Otherwise, it pushes an error message. -The return values of lua_load are: -

    -
  • 0 --- no errors; -
  • LUA_ERRSYNTAX --- -syntax error during pre-compilation. -
  • LUA_ERRMEM --- -memory allocation error. -
- -

lua_load automatically detects whether the chunk is text or binary, -and loads it accordingly (see program luac). - -

lua_load uses a user-supplied reader function to read the chunk -(see lua_Reader). -The data argument is an opaque value passed to the reader function. - -

The chunkname argument gives a name to the chunk, -which is used for error messages and in debug information (see 3.8). - -

-


lua_newstate

-
-          lua_State *lua_newstate (lua_Alloc f, void *ud);
-
- - -

Creates a new, independent state. -Returns NULL if cannot create the state -(due to lack of memory). -The argument f is the allocator function; -Lua does all memory allocation for this state through this function. -The second argument, ud, is an opaque pointer that Lua -simply passes to the allocator in every call. - -

-


lua_newtable

-
-          void lua_newtable (lua_State *L);
-
- - -

Creates a new empty table and pushes it onto the stack. -Equivalent to lua_createtable(L, 0, 0). - -

-


lua_newthread

-
-          lua_State *lua_newthread (lua_State *L);
-
- - -

Creates a new thread, pushes it on the stack, -and returns a pointer to a lua_State that represents this new thread. -The new state returned by this function shares with the original state -all global objects (such as tables), -but has an independent execution stack. - -

There is no explicit function to close or to destroy a thread. -Threads are subject to garbage collection, -like any Lua object. - -

-


lua_newuserdata

-
-          void *lua_newuserdata (lua_State *L, size_t size);
-
- - -

This function allocates a new block of memory with the given size, -pushes on the stack a new full userdata with the block address, -and returns this address. - -

Userdata represents C values in Lua. -A full userdata represents a block of memory. -It is an object (like a table): -You must create it, it can have its own metatable, -and you can detect when it is being collected. -A full userdata is only equal to itself (under raw equality). - -

When Lua collects a full userdata with a gc metamethod, -Lua calls the metamethod and marks the userdata as finalized. -When this userdata is collected again then -Lua frees its corresponding memory. - -

-


lua_next

-
-          int lua_next (lua_State *L, int index);
-
- - -

Pops a key from the stack, -and pushes a key-value pair from the table at the given index -(the "next" pair after the given key). -If there are no more elements in the table, -then lua_next returns 0 (and pushes nothing). - -

A typical traversal looks like this: -

-       /* table is in the stack at index `t' */
-       lua_pushnil(L);  /* first key */
-       while (lua_next(L, t) != 0) {
-         /* `key' is at index -2 and `value' at index -1 */
-         printf("%s - %s\n",
-           lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1)));
-         lua_pop(L, 1);  /* removes `value'; keeps `key' for next iteration */
-       }
-
- -

While traversing a table, -do not call lua_tolstring directly on a key, -unless you know that the key is actually a string. -Recall that lua_tolstring changes -the value at the given index; -this confuses the next call to lua_next. - -

-


lua_Number

-
-          typedef double lua_Number;
-
- - -

The type of numbers in Lua. -By default, it is double, but that can be changed in luaconf.h. - -

Through the configuration file you can change -Lua to operate with another type for numbers (e.g., float or long). - -

-


lua_objlen

-
-          size_t lua_objlen (lua_State *L, int index);
-
- - -

Returns the "length" of the value at the given acceptable index: -for strings, this is the string length; -for tables, this is the result of the length operator (`#´); -for userdata, this is the size of the block of memory allocated -for the userdata; -for other values, it is 0. - -

-


lua_pcall

-
-          lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);
-
- - -

Calls a function in protected mode. - -

Both nargs and nresults have the same meaning as -in lua_call. -If there are no errors during the call, -lua_pcall behaves exactly like lua_call. -However, if there is any error, -lua_pcall catches it, -pushes a single value on the stack (the error message), -and returns an error code. -Like lua_call, -lua_pcall always removes the function -and its arguments from the stack. - -

If errfunc is 0, -then the error message returned on the stack -is exactly the original error message. -Otherwise, errfunc is the stack index of an -error handler function. -(In the current implementation, this index cannot be a pseudo-index.) -In case of runtime errors, -this function will be called with the error message -and its return value will be the message returned on the stack by lua_pcall. - -

Typically, the error handler function is used to add more debug -information to the error message, such as a stack traceback. -Such information cannot be gathered after the return of lua_pcall, -since by then the stack has unwound. - -

The lua_pcall function returns 0 in case of success -or one of the following error codes -(defined in lua.h): -

    -
  • LUA_ERRRUN --- a runtime error. -
  • LUA_ERRMEM --- memory allocation error. -For such errors, Lua does not call the error handler function. -
  • LUA_ERRERR --- -error while running the error handler function. -
- -

-


lua_pop

-
-          void lua_pop (lua_State *L, int n);
-
- - -

Pops n elements from the stack. - -

-


lua_pushboolean

-
-          void lua_pushboolean (lua_State *L, int b);
-
- - -

Pushes a boolean value with value b onto the stack. - -

-


lua_pushcclosure

-
-          void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
-
- - -

Pushes a new C closure onto the stack. - -

When a C function is created, -it is possible to associate some values with it, -thus creating a C closure (see 3.4); -these values are then accessible to the function whenever it is called. -To associate values with a C function, -first these values should be pushed onto the stack -(when there are multiple values, the first value is pushed first). -Then lua_pushcclosure -is called to create and push the C function onto the stack, -with the argument n telling how many values should be -associated with the function. -lua_pushcclosure also pops these values from the stack. - -

-


lua_pushcfunction

-
-          void lua_pushcfunction (lua_State *L, lua_CFunction f);
-
- - -

Pushes a C function onto the stack. -This function receives a pointer to a C function -and pushes on the stack a Lua value of type function that, -when called, invokes the corresponding C function. - -

Any function to be registered in Lua must -follow the correct protocol to receive its parameters -and return its results (see lua_CFunction). - -

The call lua_pushcfunction(L, f) is equivalent to -lua_pushcclosure(L, f, 0). - -

-


lua_pushfstring

-
-          const char *lua_pushfstring (lua_State *L, const char *fmt, ...);
-
- - -

Pushes onto the stack a formatted string -and returns a pointer to this string. -It is similar to the C function sprintf, -but has some important differences: -

    -
  • You do not have to allocate space for the result: -The result is a Lua string and Lua takes care of memory allocation -(and deallocation, through garbage collection). -
  • The conversion specifiers are quite restricted. -There are no flags, widths, or precisions. -The conversion specifiers can only be -`%%´ (inserts a `%´ in the string), -`%s´ (inserts a zero-terminated string, with no size restrictions), -`%f´ (inserts a lua_Number), -`%p´ (inserts a pointer as a hexadecimal numeral), -`%d´ (inserts an int), and -`%c´ (inserts an int as a character). -
- -

-


lua_pushinteger

-
-          void lua_pushinteger (lua_State *L, lua_Integer n);
-
- - -

Pushes a number with value n onto the stack. - -

-


lua_pushlightuserdata

-
-          void lua_pushlightuserdata (lua_State *L, void *p);
-
- - -

Pushes a light userdata onto the stack. - -

Userdata represents C values in Lua. -A light userdata represents a pointer. -It is a value (like a number): -You do not create it, it has no metatables, -it is not collected (as it was never created). -A light userdata is equal to "any" -light userdata with the same C address. - -

-


lua_pushlstring

-
-          void lua_pushlstring (lua_State *L, const char *s, size_t len);
-
- - -

Pushes the string pointed to by s with size len -onto the stack. -Lua makes (or reuses) an internal copy of the given string, -so the memory at s can be freed or reused immediately after -the function returns. -The string can contain embedded zeros. - -

-


lua_pushnil

-
-          void lua_pushnil (lua_State *L);
-
- - -

Pushes a nil value onto the stack. - -

-


lua_pushnumber

-
-          void lua_pushnumber (lua_State *L, lua_Number n);
-
- - -

Pushes a number with value n onto the stack. - -

-


lua_pushstring

-
-          void lua_pushstring (lua_State *L, const char *s);
-
- - -

Pushes the zero-terminated string pointed to by s -onto the stack. -Lua makes (or reuses) an internal copy of the given string, -so the memory at s can be freed or reused immediately after -the function returns. -The string cannot contain embedded zeros; -it is assumed to end at the first zero. - -

-


lua_pushthread

-
-          void lua_pushthread (lua_State *L);
-
- - -

Pushes the thread represented by L onto the stack. - -

-


lua_pushvalue

-
-          void lua_pushvalue (lua_State *L, int index);
-
- - -

Pushes a copy of the element at the given valid index -onto the stack. - -

-


lua_pushvfstring

-
-          const char *lua_pushvfstring (lua_State *L, const char *fmt, va_list argp);
-
- - -

Equivalent to lua_pushfstring, except that it receives a va_list -instead of a variable number of arguments. - -

-


lua_rawequal

-
-          int lua_rawequal (lua_State *L, int index1, int index2);
-
- - -

Returns 1 if the two values in acceptable indices index1 and -index2 are primitively equal -(that is, without calling metamethods). -Otherwise returns 0. -Also returns 0 if any of the indices are non valid. - -

-


lua_rawget

-
-          void lua_rawget (lua_State *L, int index);
-
- - -

Similar to lua_gettable, but does a raw access -(i.e., without metamethods). - -

-


lua_rawgeti

-
-          void lua_rawgeti (lua_State *L, int index, int n);
-
- - -

Pushes onto the stack the value t[n], -where t is the value at the given valid index index. -The access is raw; -that is, it does not invoke metamethods. - -

-


lua_rawset

-
-          void lua_rawset (lua_State *L, int index);
-
- - -

Similar to lua_settable, but does a raw assignment -(i.e., without metamethods). - -

-


lua_rawseti

-
-          void lua_rawseti (lua_State *L, int index, int n);
-
- - -

Does the equivalent of t[n] = v, -where t is the value at the given valid index index -and v is the value at the top of the stack, - -

This function pops the value from the stack. -The assignment is raw; -that is, it does not invoke metamethods. - -

-


lua_Reader

-
-          typedef const char * (*lua_Reader)
-                               (lua_State *L, void *data, size_t *size);
-
-
- - -

The reader function used by lua_load. -Every time it needs another piece of the chunk, -lua_load calls the reader, -passing along its data parameter. -The reader must return a pointer to a block of memory -with a new piece of the chunk -and set size to the block size. -The block must exist until the reader function is called again. -To signal the end of the chunk, the reader must return NULL. -The reader function may return pieces of any size greater than zero. - -

-


lua_register

-
-          void lua_register (lua_State *L, const char *name, lua_CFunction f);
-
- - -

Sets the C function f as the new value of global name. -It is defined as a macro: -

-#define lua_register(L,n,f)  (lua_pushcfunction(L, f), lua_setglobal(L, n))
-
- -

-


lua_remove

-
-          void lua_remove (lua_State *L, int index);
-
- - -

Removes the element at the given valid index, -shifting down the elements above this index to fill the gap. -Cannot be called with a pseudo-index, -because a pseudo-index is not an actual stack position. - -

-


lua_replace

-
-          void lua_replace (lua_State *L, int index);
-
- - -

Moves the top element into the given position (and pops it), -without shifting any element -(therefore replacing the value at the given position). - -

-


lua_resume

-
-          int lua_resume (lua_State *L, int narg);
-
- - -

Starts and resumes a coroutine in a given thread. - -

To start a coroutine, you first create a new thread -(see lua_newthread); -then you push on its stack the main function plus any eventual arguments; -then you call lua_resume, -with narg being the number of arguments. -This call returns when the coroutine suspends or finishes its execution. -When it returns, the stack contains all values passed to lua_yield, -or all values returned by the body function. -lua_resume returns -LUA_YIELD if the coroutine yields, -0 if the coroutine finishes its execution -without errors, -or an error code in case of errors (see lua_pcall). -In case of errors, -the stack is not unwound, -so you can use the debug API over it. -The error message is on the top of the stack. -To restart a coroutine, you put on its stack only the values to -be passed as results from yield, -and then call lua_resume. - -

-


lua_setallocf

-
-          void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);
-
- - -

Changes the allocator function of a given state to f -with user data ud. - -

-


lua_setfenv

-
-          int lua_setfenv (lua_State *L, int index);
-
- - -

Pops a table from the stack and sets it as -the new environment for the value at the given index. -If the value at the given index is -neither a function nor a thread nor a userdata, -lua_setfenv returns 0. -Otherwise it returns 1. - -

-


lua_setfield

-
-          void lua_setfield (lua_State *L, int index, const char *k);
-
- - -

Does the equivalent to t[k] = v, -where t is the value at the given valid index index -and v is the value at the top of the stack, - -

This function pops the value from the stack. -As in Lua, this function may trigger a metamethod -for the "newindex" event (see 2.8). - -

-


lua_setglobal

-
-          void lua_setglobal (lua_State *L, const char *name);
-
- - -

Pops a value from the stack and -sets it as the new value of global name. -It is defined as a macro: -

-#define lua_setglobal(L,s)   lua_setfield(L, LUA_GLOBALSINDEX, s)
-
- -

-


lua_setmetatable

-
-          int lua_setmetatable (lua_State *L, int index);
-
- - -

Pops a table from the stack and -sets it as the new metatable for the value at the given -acceptable index. - -

-


lua_settable

-
-          void lua_settable (lua_State *L, int index);
-
- - -

Does the equivalent to t[k] = v, -where t is the value at the given valid index index, -v is the value at the top of the stack, -and k is the value just below the top. - -

This function pops both the key and the value from the stack. -As in Lua, this function may trigger a metamethod -for the "newindex" event (see 2.8). - -

-


lua_settop

-
-          void lua_settop (lua_State *L, int index);
-
- - -

Accepts any acceptable index, or 0, -and sets the stack top to this index. -If the new top is larger than the old one, -then the new elements are filled with nil. -If index is 0, then all stack elements are removed. - -

-


lua_State

-
-          typedef struct lua_State lua_State;
-
- - -

Opaque structure that keeps the whole state of a Lua interpreter. -The Lua library is fully reentrant: -it has no global variables. -All information about a state is kept in this structure. - -

A pointer to this state must be passed as the first argument to -every function in the library, except to lua_newstate, -which creates a Lua state from scratch. - -

-


lua_status

-
-          int lua_status (lua_State *L);
-
- - -

Returns the status of the thread L. - -

The status can be 0 for a normal thread, -an error code if the thread finished its execution with an error, -or LUA_YIELD if the thread is suspended. - -

-


lua_toboolean

-
-          int lua_toboolean (lua_State *L, int index);
-
- - -

Converts the Lua value at the given acceptable index to a C boolean -value (0 or 1). -Like all tests in Lua, -lua_toboolean returns 1 for any Lua value -different from false and nil; -otherwise it returns 0. -It also returns 0 when called with a non-valid index. -(If you want to accept only actual boolean values, -use lua_isboolean to test the value's type.) - -

-


lua_tocfunction

-
-          lua_CFunction lua_tocfunction (lua_State *L, int index);
-
- - -

Converts a value at the given acceptable index to a C function. -That value must be a C function; -otherwise, returns NULL. - -

-


lua_tointeger

-
-          lua_Integer lua_tointeger (lua_State *L, int idx);
-
- - -

Converts the Lua value at the given acceptable index -to the signed integral type lua_Integer. -The Lua value must be a number or a string convertible to a number -(see 2.2.1); -otherwise, lua_tointeger returns 0. - -

If the number is not an integer, -it is truncated in some non-specified way. - -

-


lua_tolstring

-
-          const char *lua_tolstring (lua_State *L, int index, size_t *len);
-
- - -

Converts the Lua value at the given acceptable index to a string -(const char*). -If len is not NULL, -it also sets *len with the string length. -The Lua value must be a string or a number; -otherwise, the function returns NULL. -If the value is a number, -then lua_tolstring also -changes the actual value in the stack to a string. -(This change confuses lua_next -when lua_tolstring is applied to keys during a table traversal.) - -

lua_tolstring returns a fully aligned pointer -to a string inside the Lua state. -This string always has a zero (`\0´) -after its last character (as in C), -but may contain other zeros in its body. -Because Lua has garbage collection, -there is no guarantee that the pointer returned by lua_tolstring -will be valid after the corresponding value is removed from the stack. - -

-


lua_tonumber

-
-          lua_Number lua_tonumber (lua_State *L, int index);
-
- - -

Converts the Lua value at the given acceptable index -to a number (see lua_Number). -The Lua value must be a number or a string convertible to a number -(see 2.2.1); -otherwise, lua_tonumber returns 0. - -

-


lua_topointer

-
-          const void *lua_topointer (lua_State *L, int index);
-
- - -

Converts the value at the given acceptable index to a generic -C pointer (void*). -The value may be a userdata, a table, a thread, or a function; -otherwise, lua_topointer returns NULL. -Lua ensures that different objects return different pointers. -There is no direct way to convert the pointer back to its original value. - -

Typically this function is used only for debug information. - -

-


lua_tostring

-
-          const char *lua_tostring (lua_State *L, int index);
-
- - -

Equivalent to lua_tolstring with len equal to NULL. - -

-


lua_tothread

-
-          lua_State *lua_tothread (lua_State *L, int index);
-
- - -

Converts the value at the given acceptable index to a Lua thread -(represented as lua_State*). -This value must be a thread; -otherwise, the function returns NULL. - -

-


lua_touserdata

-
-          void *lua_touserdata (lua_State *L, int index);
-
- - -

If the value at the given acceptable index is a full userdata, -returns its block address. -If the value is a light userdata, -returns its pointer. -Otherwise, returns NULL. - -

-


lua_type

-
-          int lua_type (lua_State *L, int index);
-
- - -

Returns the type of the value in the given acceptable index, -or LUA_TNONE for a non-valid index -(that is, an index to an "empty" stack position). -The types returned by lua_type are coded by the following constants -defined in lua.h: -LUA_TNIL, -LUA_TNUMBER, -LUA_TBOOLEAN, -LUA_TSTRING, -LUA_TTABLE, -LUA_TFUNCTION, -LUA_TUSERDATA, -LUA_TTHREAD, -and -LUA_TLIGHTUSERDATA. - -

-


lua_typename

-
-          const char *lua_typename  (lua_State *L, int tp);
-
- - -

Returns the name of the type encoded by the value tp, -which must be one the values returned by lua_type. - -

-


lua_Writer

-
-          typedef int (*lua_Writer)
-                          (lua_State *L, const void* p, size_t sz, void* ud);
-
-
- - -

The writer function used by lua_dump. -Every time it produces another piece of chunk, -lua_dump calls the writer, -passing along the buffer to be written (p), -its size (sz), -and the data parameter supplied to lua_dump. - -

The writer returns an error code: -0 means no errors; -any other value means an error and stops lua_dump from -calling the writer again. - -

-


lua_xmove

-
-          void lua_xmove (lua_State *from, lua_State *to, int n);
-
- - -

Exchange values between different threads of the same global state. - -

This function pops n values from the stack from, -and pushes them onto the stack to. - -

-


lua_yield

-
-          int lua_yield  (lua_State *L, int nresults);
-
- - -

Yields a coroutine. - -

This function should only be called as the -return expression of a C function, as follows: -

-       return lua_yield (L, nresults);
-
-When a C function calls lua_yield in that way, -the running coroutine suspends its execution, -and the call to lua_resume that started this coroutine returns. -The parameter nresults is the number of values from the stack -that are passed as results to lua_resume. - -

-

3.8 - The Debug Interface

- -

Lua has no built-in debugging facilities. -Instead, it offers a special interface -by means of functions and hooks. -This interface allows the construction of different -kinds of debuggers, profilers, and other tools -that need "inside information" from the interpreter. - -

-


lua_Debug

-
-          typedef struct lua_Debug {
-            int event;
-            const char *name;           /* (n) */
-            const char *namewhat;       /* (n) */
-            const char *what;           /* (S) */
-            const char *source;         /* (S) */
-            int currentline;            /* (l) */
-            int nups;                   /* (u) number of upvalues */
-            int linedefined;            /* (S) */
-            int lastlinedefined;        /* (S) */
-            char short_src[LUA_IDSIZE]; /* (S) */
-            /* private part */
-            ...
-          } lua_Debug;
-
-
- - -

A structure used to carry different pieces of -information about an active function. -lua_getstack fills only the private part -of this structure, for later use. -To fill the other fields of lua_Debug with useful information, -call lua_getinfo. - -

The fields of lua_Debug have the following meaning: -

    -
  • source --- -If the function was defined in a string, -then source is that string. -If the function was defined in a file, -then source starts with a `@´ followed by the file name. - -

  • short_src --- -a "printable" version of source, to be used in error messages. - -

  • linedefined --- -the line number where the definition of the function starts. - -

  • lastlinedefined --- -the line number where the definition of the function ends. - -

  • what --- -the string "Lua" if the function is a Lua function, -"C" if it is a C function, -"main" if it is the main part of a chunk, -and "tail" if it was a function that did a tail call. -In the latter case, -Lua has no other information about the function. - -

  • currentline --- -the current line where the given function is executing. -When no line information is available, -currentline is set to -1. - -

  • name --- -a reasonable name for the given function. -Because functions in Lua are first-class values, -they do not have a fixed name: -Some functions may be the value of multiple global variables, -while others may be stored only in a table field. -The lua_getinfo function checks how the function was -called to find a suitable name. -If it cannot find a name, -then name is set to NULL. - -

  • namewhat --- -explains the name field. -The value of namewhat can be -"global", "local", "method", -"field", "upvalue", or "" (the empty string), -according to how the function was called. -(Lua uses the empty string when no other option seems to apply.) - -

  • nups --- -the number of upvalues of the function. - -

- -

-


lua_gethook

-
-          lua_Hook lua_gethook (lua_State *L);
-
- - -

Returns the current hook function. - -

-


lua_gethookcount

-
-          int lua_gethookcount (lua_State *L);
-
- - -

Returns the current hook count. - -

-


lua_gethookmask

-
-          int lua_gethookmask (lua_State *L);
-
- - -

Returns the current hook mask. - -

-


lua_getinfo

-
-          int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
-
- - -

Fills the fields of lua_Debug with useful information. - -

This function returns 0 on error -(for instance, an invalid option in what). -Each character in the string what -selects some fields of the structure ar to be filled, -as indicated by the letter in parentheses in the definition of lua_Debug: -`S´ fills in the fields source, linedefined, -lastlinedefined, -and what; -`l´ fills in the field currentline, etc. -Moreover, `f´ pushes onto the stack the function that is -running at the given level. - -

To get information about a function that is not active -(that is, not in the stack), -you push it onto the stack -and start the what string with the character `>´. -For instance, to know in which line a function f was defined, -you can write the following code: -

-       lua_Debug ar;
-       lua_getfield(L, LUA_GLOBALSINDEX, "f");  /* get global `f' */
-       lua_getinfo(L, ">S", &ar);
-       printf("%d\n", ar.linedefined);
-
- -

-


lua_getlocal

-
-          const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
-
- - -

Gets information about a local variable of a given activation record. -The parameter ar must be a valid activation record that was -filled by a previous call to lua_getstack or -given as argument to a hook (see lua_Hook). -The index n selects which local variable to inspect -(1 is the first parameter or active local variable, and so on, -until the last active local variable). -lua_getlocal pushes the variable's value onto the stack -and returns its name. - -

Variable names starting with `(´ (open parentheses) -represent internal variables -(loop control variables, temporaries, and C function locals). - -

Returns NULL (and pushes nothing) -when the index is greater than -the number of active local variables. - -

-


lua_getstack

-
-          int lua_getstack (lua_State *L, int level, lua_Debug *ar);
-
- - -

Get information about the interpreter runtime stack. - -

This function fills parts of a lua_Debug structure with -an identification of the activation record -of the function executing at a given level. -Level 0 is the current running function, -whereas level n+1 is the function that has called level n. -When there are no errors, lua_getstack returns 1; -when called with a level greater than the stack depth, -it returns 0. - -

-


lua_getupvalue

-
-          const char *lua_getupvalue (lua_State *L, int funcindex, int n);
-
- - -

Gets information about a closure's upvalue. -(For Lua functions, -upvalues are the external local variables that the function uses, -and that are consequently included in its closure.) -lua_getupvalue gets the index n of an upvalue, -pushes the upvalue's value onto the stack, -and returns its name. -funcindex points to the closure in the stack. -(Upvalues have no particular order, -as they are active through the whole function. -So, they are numbered in an arbitrary order.) - -

Returns NULL (and pushes nothing) -when the index is greater than the number of upvalues. -For C functions, this function uses the empty string "" -as a name for all upvalues. - -

-


lua_Hook

-
-          typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
-
- - -

Type for debugging hook functions. - -

Whenever a hook is called, its ar argument has its field -event set to the specific event that triggered the hook. -Lua identifies these events with the following constants: -LUA_HOOKCALL, LUA_HOOKRET, -LUA_HOOKTAILRET, LUA_HOOKLINE, -and LUA_HOOKCOUNT. -Moreover, for line events, the field currentline is also set. -To get the value of any other field in ar, -the hook must call lua_getinfo. -For return events, event may be LUA_HOOKRET, -the normal value, or LUA_HOOKTAILRET. -In the latter case, Lua is simulating a return from -a function that did a tail call; -in this case, it is useless to call lua_getinfo. - -

While Lua is running a hook, it disables other calls to hooks. -Therefore, if a hook calls back Lua to execute a function or a chunk, -this execution occurs without any calls to hooks. - -

-


lua_sethook

-
-          int lua_sethook (lua_State *L, lua_Hook func, int mask, int count);
-
- - -

Sets the debugging hook function. - -

func is the hook function. -mask specifies on which events the hook will be called: -It is formed by a bitwise or of the constants -LUA_MASKCALL, -LUA_MASKRET, -LUA_MASKLINE, -and LUA_MASKCOUNT. -The count argument is only meaningful when the mask -includes LUA_MASKCOUNT. -For each event, the hook is called as explained below: -

    -
  • The call hook is called when the interpreter calls a function. -The hook is called just after Lua enters the new function, -before the function gets its arguments. -
  • The return hook is called when the interpreter returns from a function. -The hook is called just before Lua leaves the function. -You have no access to the values to be returned by the function. -
  • The line hook is called when the interpreter is about to -start the execution of a new line of code, -or when it jumps back in the code (even to the same line). -(This event only happens while Lua is executing a Lua function.) -
  • The count hook is called after the interpreter executes every -count instructions. -(This event only happens while Lua is executing a Lua function.) -
- -

A hook is disabled by setting mask to zero. - -

-


lua_setlocal

-
-          const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);
-
- - -

Sets the value of a local variable of a given activation record. -Parameters ar and n are as in lua_getlocal -(see lua_getlocal). -lua_setlocal assigns the value at the top of the stack -to the variable and returns its name. -It also pops the value from the stack. - -

Returns NULL (and pops nothing) -when the index is greater than -the number of active local variables. - -

-


lua_setupvalue

-
-          const char *lua_setupvalue (lua_State *L, int funcindex, int n);
-
- - -

Sets the value of a closure's upvalue. -Parameters funcindex and n are as in lua_getupvalue -(see lua_getupvalue). -It assigns the value at the top of the stack -to the upvalue and returns its name. -It also pops the value from the stack. - -

Returns NULL (and pops nothing) -when the index is greater than the number of upvalues. - -

-

4 - The Auxiliary Library

- -

-The auxiliary library provides several convenient functions -to interface C with Lua. -While the basic API provides the primitive functions for all -interactions between C and Lua, -the auxiliary library provides higher-level functions for some -common tasks. - -

All functions from the auxiliary library -are defined in header file lauxlib.h and -have a prefix luaL_. - -

All functions in the auxiliary library are built on -top of the basic API, -and so they provide nothing that cannot be done with this API. - -

Several functions in the auxiliary library are used to -check C function arguments. -Their names are always luaL_check* or luaL_opt*. -All of these functions raise an error if the check is not satisfied. -Because the error message is formatted for arguments -(e.g., "bad argument #1"), -you should not use these functions for other stack values. - -

4.1 - Functions and Types

- -

Here we list all functions and types from the auxiliary library -in alphabetical order. - -

-


luaL_addchar

-
-          void luaL_addchar (luaL_Buffer B, char c);
-
- - -

Adds the character c to the buffer B -(see luaL_Buffer). - -

-


luaL_addlstring

-
-          void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);
-
- - -

Adds the string pointed to by s with length l to -the buffer B -(see luaL_Buffer). -The string may contain embedded zeros. - -

-


luaL_addsize

-
-          void luaL_addsize (luaL_Buffer B, size_t n);
-
- - -

Adds a string of length n previously copied to the -buffer area (see luaL_prepbuffer) to the buffer B -(see luaL_Buffer). - -

-


luaL_addstring

-
-          void luaL_addstring (luaL_Buffer *B, const char *s);
-
- - -

Adds the zero-terminated string pointed to by s -to the buffer B -(see luaL_Buffer). -The string may not contain embedded zeros. - -

-


luaL_addvalue

-
-          void luaL_addvalue (luaL_Buffer *B);
-
- - -

Adds the value at the top of the stack -to the buffer B -(see luaL_Buffer). -Pops the value. - -

This is the only function on string buffers that can (and must) -be called with an extra element on the stack, -which is the value to be added to the buffer. - -

-


luaL_argcheck

-
-          void luaL_argcheck (lua_State *L, int cond, int numarg,
-                              const char *extramsg);
-
- - -

Checks whether cond is true. -If not, raises an error with message -"bad argument #<numarg> to <func> (<extramsg>)", -where func is retrieved from the call stack. - -

-


luaL_argerror

-
-          int luaL_argerror (lua_State *L, int numarg, const char *extramsg);
-
- - -

Raises an error with message -"bad argument #<numarg> to <func> (<extramsg>)", -where func is retrieved from the call stack. - -

This function never returns, -but it is an idiom to use it as return luaL_argerror ... -in C functions. - -

-


luaL_Buffer

-
-          typedef struct luaL_Buffer luaL_Buffer;
-
- - -

Type for a string buffer. - -

A string buffer allows C code to build Lua strings piecemeal. -Its pattern of use is as follows: -

    -
  • First you declare a variable b of type luaL_Buffer. -
  • Then you initialize it with a call luaL_buffinit(L, &b). -
  • Then you add string pieces to the buffer calling any of -the luaL_add* functions. -
  • You finish by calling luaL_pushresult(&b). -This call leaves the final string on the top of the stack. -
- -

During its normal operation, -a string buffer uses a variable number of stack slots. -So, while using a buffer, you cannot assume that you know where -the top of the stack is. -You can use the stack between successive calls to buffer operations -as long as that use is balanced; -that is, -when you call a buffer operation, -the stack is at the same level -it was immediately after the previous buffer operation. -(The only exception to this rule is luaL_addvalue.) -After calling luaL_pushresult the stack is back to its -level when the buffer was initialized, -plus the final string on its top. - -

-


luaL_buffinit

-
-          void luaL_buffinit (lua_State *L, luaL_Buffer *B);
-
- - -

Initializes a buffer B. -This function does not allocate any space; -the buffer must be declared as a variable -(see luaL_Buffer). - -

-


luaL_callmeta

-
-          int luaL_callmeta (lua_State *L, int obj, const char *e);
-
- - -

Calls a metamethod. - -

If the object at index obj has a metatable and this -metatable has a field e, -this function calls this field and passes the object as its only argument. -In this case this function returns 1 and pushes on the -stack the value returned by the call. -If there is no metatable or no metamethod, -this function returns 0 (without pushing any value on the stack). - -

-


luaL_checkany

-
-          void luaL_checkany (lua_State *L, int narg);
-
- - -

Checks whether the function has an argument -of any type (including nil) at position narg. - -

-


luaL_checkint

-
-          int luaL_checkint (lua_State *L, int narg);
-
- - -

Checks whether the function argument narg is a number -and returns this number cast to an int. - -

-


luaL_checkinteger

-
-          lua_Integer luaL_checkinteger (lua_State *L, int narg);
-
- - -

Checks whether the function argument narg is a number -and returns this number cast to a lua_Integer. - -

-


luaL_checklong

-
-          long luaL_checklong (lua_State *L, int narg);
-
- - -

Checks whether the function argument narg is a number -and returns this number cast to a long. - -

-


luaL_checklstring

-
-          const char *luaL_checklstring (lua_State *L, int narg, size_t *l);
-
- - -

Checks whether the function argument narg is a string -and returns this string; -if l is not NULL fills *l -with the string's length. - -

-


luaL_checknumber

-
-          lua_Number luaL_checknumber (lua_State *L, int narg);
-
- - -

Checks whether the function argument narg is a number -and returns this number. - -

-


luaL_checkoption

-
-          int luaL_checkoption (lua_State *L, int narg, const char *def,
-                                const char *const lst[]);
-
- - -

Checks whether the function argument narg is a string and -searches for this string in the array lst -(which must be NULL-terminated). -If def is not NULL, -uses def as a default value when -the function has no argument narg or if this argument is nil. - -

Returns the index in the array where the string was found. -Raises an error if the argument is not a string or -if the string cannot be found. - -

This is a useful function for mapping strings to C enums. -The usual convention in Lua libraries is to use strings instead of numbers -to select options. - -

-


luaL_checkstack

-
-          void luaL_checkstack (lua_State *L, int sz, const char *msg);
-
- - -

Grows the stack size to top + sz elements, -raising an error if the stack cannot grow to that size. -msg is an additional text to go into the error message. - -

-


luaL_checkstring

-
-          const char *luaL_checkstring (lua_State *L, int narg);
-
- - -

Checks whether the function argument narg is a string -and returns this string. - -

-


luaL_checktype

-
-          void luaL_checktype (lua_State *L, int narg, int t);
-
- - -

Checks whether the function argument narg has type t. - -

-


luaL_checkudata

-
-          void *luaL_checkudata (lua_State *L, int narg, const char *tname);
-
- - -

Checks whether the function argument narg is a userdata -of the type tname (see luaL_newmetatable). - -

-


luaL_error

-
-          int luaL_error (lua_State *L, const char *fmt, ...);
-
- - -

Raises an error. -The error message format is given by fmt -plus any extra arguments, -following the same rules of lua_pushfstring. -It also adds at the beginning of the message the file name and -the line number where the error occurred, -if this information is available. - -

This function never returns, -but it is an idiom to use it as return luaL_error ... -in C functions. - -

-


luaL_getmetafield

-
-          int luaL_getmetafield (lua_State *L, int obj, const char *e);
-
- - -

Pushes on the stack the field e from the metatable -of the object at index obj. -If the object does not have a metatable, -or if the metatable does not have this field, -returns 0 and pushes nothing. - -

-


luaL_getmetatable

-
-          void luaL_getmetatable (lua_State *L, const char *tname);
-
- - -

Pushes on the stack the metatable associated with name tname -in the registry (see luaL_newmetatable). - -

-


luaL_gsub

-
-          const char *luaL_gsub (lua_State *L, const char *s,
-                                 const char *p, const char *r);
-
- - -

Creates a copy of string s by replacing -any occurrence of the string p -with the string r. -Pushes the resulting string on the stack and returns it. - -

-


luaL_loadbuffer

-
-          int luaL_loadbuffer (lua_State *L, const char *buff,
-                               size_t sz, const char *name);
-
- - -

Loads a buffer as a Lua chunk. -This function uses lua_load to load the chunk in the -buffer pointed to by buff with size sz. - -

This function returns the same results as lua_load. -name is the chunk name, -used for debug information and error messages. - -

-


luaL_loadfile

-
-          int luaL_loadfile (lua_State *L, const char *filename);
-
- - -

Loads a file as a Lua chunk. -This function uses lua_load to load the chunk in the file -named filename. -If filename is NULL, -then it loads from the standard input. -The first line in the file is ignored if it starts with a #. - -

This function returns the same results as lua_load, -but it has an extra error code LUA_ERRFILE -if it cannot open/read the file. - -

-


luaL_loadstring

-
-          int luaL_loadstring (lua_State *L, const char *s);
-
- - -

Loads a string as a Lua chunk. -This function uses lua_load to load the chunk in -the zero-terminated string s. - -

This function returns the same results as lua_load. - -

-


luaL_newmetatable

-
-          int luaL_newmetatable (lua_State *L, const char *tname);
-
- - -

If the registry already has the key tname, -returns 0. -Otherwise, -creates a new table to be used as a metatable for userdata, -adds it to the registry with key tname, -and returns 1. - -

In both cases pushes on the stack the final value associated -with tname in the registry. - -

-


luaL_newstate

-
-          lua_State *luaL_newstate (void);
-
- - -

Creates a new Lua state, calling lua_newstate with an -allocation function based on the standard C realloc function -and setting a panic function (see lua_atpanic) that prints -an error message to the standard error output in case of fatal -errors. - -

Returns the new state, -or NULL if there is a memory allocation error. - -

-


luaL_openlibs

-
-          void luaL_openlibs (lua_State *L);
-
- - -

Opens all standard Lua libraries into the given state. - -

-


luaL_optint

-
-          int luaL_optint (lua_State *L, int narg, int d);
-
- - -

If the function argument narg is a number, -returns this number cast to an int. -If this argument is absent or is nil, -returns d. -Otherwise, raises an error. - -

-


luaL_optinteger

-
-          lua_Integer luaL_optinteger (lua_State *L, int narg, lua_Integer d);
-
- - -

If the function argument narg is a number, -returns this number cast to a lua_Integer. -If this argument is absent or is nil, -returns d. -Otherwise, raises an error. - -

-


luaL_optlong

-
-          long luaL_optlong (lua_State *L, int narg, long d);
-
- - -

If the function argument narg is a number, -returns this number cast to a long. -If this argument is absent or is nil, -returns d. -Otherwise, raises an error. - -

-


luaL_optlstring

-
-          const char *luaL_optlstring (lua_State *L, int narg,
-                                       const char *d, size_t *l);
-
- - -

If the function argument narg is a string, -returns this string. -If this argument is absent or is nil, -returns d. -Otherwise, raises an error. - -

If l is not NULL, -fills the position *l with the results's length. - -

-


luaL_optnumber

-
-          lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d);
-
- - -

If the function argument narg is a number, -returns this number. -If this argument is absent or is nil, -returns d. -Otherwise, raises an error. - -

-


luaL_optstring

-
-          const char *luaL_optstring (lua_State *L, int narg, const char *d);
-
- - -

If the function argument narg is a string, -returns this string. -If this argument is absent or is nil, -returns d. -Otherwise, raises an error. - -

-


luaL_prepbuffer

-
-          char *luaL_prepbuffer (luaL_Buffer *B);
-
- - -

Returns an address to a space of size LUAL_BUFFERSIZE -where you can copy a string to be added to buffer B -(see luaL_Buffer). -After copying the string into this space you must call -luaL_addsize with the size of the string to actually add -it to the buffer. - -

-


luaL_pushresult

-
-          void luaL_pushresult (luaL_Buffer *B);
-
- - -

Finishes the use of buffer B leaving the final string on -the top of the stack. - -

-


luaL_ref

-
-          int luaL_ref (lua_State *L, int t);
-
- - -

Creates and returns a reference, -in the table at index t, -for the object at the top of the stack (and pops the object). - -

A reference is a unique integer key. -As long as you do not manually add integer keys into table t, -luaL_ref ensures the uniqueness of the key it returns. -You can retrieve an object referred by reference r -by calling lua_rawgeti(L, t, r). -Function luaL_unref frees a reference and its associated object. - -

If the object at the top of the stack is nil, -luaL_ref returns the constant LUA_REFNIL. -The constant LUA_NOREF is guaranteed to be different -from any reference returned by luaL_ref. - -

-


luaL_Reg

-
-          typedef struct luaL_Reg {
-            const char *name;
-            lua_CFunction func;
-          } luaL_Reg;
-
-
- - -

Type for arrays of functions to be registered by -luaL_register. -name is the function name and func is a pointer to -the function. -Any array of luaL_Reg must end with an sentinel entry -in which both name and func are NULL. - -

-


luaL_register

-
-          void luaL_register (lua_State *L, const char *libname,
-                              const luaL_Reg *l);
-
- - -

Opens a library. - -

When called with libname equal to NULL, -simply registers all functions in the list l -(see luaL_Reg) into the table on the top of the stack. - -

When called with a non-null libname, -creates a new table t, -sets it as the value of the global variable libname, -sets it as the value of package.loaded[libname], -and registers on it all functions in the list l. -If there is a table in package.loaded[libname] or in -variable libname, -reuses this table instead of creating a new one. - -

In any case the function leaves the table -on the top of the stack. - -

-


luaL_typename

-
-          const char *luaL_typename (lua_State *L, int idx);
-
- - -

Returns the name of the type of the value at index idx. - -

-


luaL_typerror

-
-          int luaL_typerror (lua_State *L, int narg, const char *tname);
-
- - -

Generates an error with a message like -

-<location>: bad argument <narg> to <function> (<tname> expected, got <realt>)
-
-where <location> is produced by luaL_where, -<function> is the name of the current function, -and <realt> is the type name of the actual argument. - -

-


luaL_unref

-
-          void luaL_unref (lua_State *L, int t, int ref);
-
- - -

Releases reference ref from the table at index t -(see luaL_ref). -The entry is removed from the table, -so that the referred object can be collected. -The reference ref is also freed to be used again. - -

If ref is LUA_NOREF or LUA_REFNIL, -luaL_unref does nothing. - -

-


luaL_where

-
-          void luaL_where (lua_State *L, int lvl);
-
- - -

Pushes on the stack a string identifying the current position -of the control at level lvl in the call stack. -Typically this string has the format <chunkname>:<currentline>:. -Level 0 is the running function, -level 1 is the function that called the running function, -etc. - -

This function is used to build a prefix for error messages. - -

-

5 - Standard Libraries

- -

The standard Lua libraries provide useful functions -that are implemented directly through the C API. -Some of these functions provide essential services to the language -(e.g., type and getmetatable); -others provide access to "outside" services (e.g., I/O); -and others could be implemented in Lua itself, -but are quite useful or have critical performance requirements that -deserve an implementation in C (e.g., sort). - -

All libraries are implemented through the official C API -and are provided as separate C modules. -Currently, Lua has the following standard libraries: -

    -
  • basic library; -
  • package library; -
  • string manipulation; -
  • table manipulation; -
  • mathematical functions (sin, log, etc.); -
  • input and output; -
  • operating system facilities; -
  • debug facilities. -
-Except for the basic and package libraries, -each library provides all its functions as fields of a global table -or as methods of its objects. - -

To have access to these libraries, -the C host program must call -luaL_openlibs, -which open all standard libraries. -Alternatively, -it can open them individually by calling -luaopen_base (for the basic library), -luaopen_package (for the package library), -luaopen_string (for the string library), -luaopen_table (for the table library), -luaopen_math (for the mathematical library), -luaopen_io (for the I/O and the Operating System libraries), -and luaopen_debug (for the debug library). -These functions are declared in lualib.h -and should not be called directly: -you must call them like any other Lua C function, -e.g., by using lua_call. - -

5.1 - Basic Functions

- -

The basic library provides some core functions to Lua. -If you do not include this library in your application, -you should check carefully whether you need to provide -implementations for some of its facilities. - -


assert (v [, message])

-Issues an error when -the value of its argument v is false (i.e., nil or false); -otherwise, returns all its arguments. -message is an error message; -when absent, it defaults to "assertion failed!" - -


collectgarbage (opt [, arg])

- -

This function is a generic interface to the garbage collector. -It performs different functions according to its first argument, opt: -

    -
  • "stop" --- stops the garbage collector. -
  • "restart" --- restarts the garbage collector. -
  • "collect" --- performs a full garbage-collection cycle. -
  • "count" --- returns the total memory in use by Lua (in Kbytes). -
  • "step" --- performs a garbage-collection step. -The step "size" is controlled by arg -(larger values mean more steps) in a non-specified way. -If you want to control the step size -you must tune experimentally the value of arg. -Returns true if the step finished a collection cycle. -
  • "steppause" --- -sets arg/100 as the new value for the pause of -the collector (see 2.10). -
  • "setstepmul" --- -sets arg/100 as the new value for the step multiplier of -the collector (see 2.10). -
- -


dofile (filename)

-Opens the named file and executes its contents as a Lua chunk. -When called without arguments, -dofile executes the contents of the standard input (stdin). -Returns all values returned by the chunk. -In case of errors, dofile propagates the error -to its caller (that is, dofile does not run in protected mode). - -


error (message [, level])

-Terminates the last protected function called -and returns message as the error message. -Function error never returns. - -

Usually, error adds some information about the error position -at the beginning of the message. -The level argument specifies how to get the error position. -With level 1 (the default), the error position is where the -error function was called. -Level 2 points the error to where the function -that called error was called; and so on. -Passing a level 0 avoids the addition of error position information -to the message. - -


_G

-A global variable (not a function) that -holds the global environment (that is, _G._G = _G). -Lua itself does not use this variable; -changing its value does not affect any environment, -nor vice-versa. -(Use setfenv to change environments.) - -


getfenv (f)

-Returns the current environment in use by the function. -f can be a Lua function or a number -that specifies the function at that stack level: -Level 1 is the function calling getfenv. -If the given function is not a Lua function, -or if f is 0, -getfenv returns the global environment. -The default for f is 1. - -


getmetatable (object)

- -

If object does not have a metatable, returns nil. -Otherwise, -if the object's metatable has a "__metatable" field, -returns the associated value. -Otherwise, returns the metatable of the given object. - -


ipairs (t)

- -

Returns three values: an iterator function, the table t, and 0, -so that the construction -

-       for i,v in ipairs(t) do ... end
-
-will iterate over the pairs (1,t[1]), (2,t[2]), ..., -up to the first integer key with a nil value in the table. - -

See next for the caveats of modifying the table during its traversal. - -


load (func [, chunkname])

- -

Loads a chunk using function func to get its pieces. -Each call to func must return a string that concatenates -with previous results. -A return of nil (or no value) signals the end of the chunk. - -

If there are no errors, -returns the compiled chunk as a function; -otherwise, returns nil plus the error message. -The environment of the returned function is the global environment. - -

chunkname is used as the chunk name for error messages -and debug information. - -


loadfile ([filename])

- -

Similar to load, -but gets the chunk from file filename -or from the standard input, -if no file name is given. - -


loadstring (string [, chunkname])

- -

Similar to load, -but gets the chunk from the given string. - -

To load and run a given string, use the idiom -

-      assert(loadstring(s))()
-
- -


next (table [, index])

- -

Allows a program to traverse all fields of a table. -Its first argument is a table and its second argument -is an index in this table. -next returns the next index of the table -and its associated value. -When called with nil as its second argument, -next returns an initial index -and its associated value. -When called with the last index, -or with nil in an empty table, -next returns nil. -If the second argument is absent, then it is interpreted as nil. -In particular, -you can use next(t) to check whether a table is empty. - -

Lua has no declaration of fields. -There is no difference between a -field not present in a table or a field with value nil. -Therefore, next only considers fields with non-nil values. -The order in which the indices are enumerated is not specified, -even for numeric indices. -(To traverse a table in numeric order, -use a numerical for or the ipairs function.) - -

The behavior of next is undefined if, -during the traversal, -you assign any value to a non-existent field in the table. -You may however modify existing fields. -In particular, you may clear existing fields. - -


pairs (t)

- -

Returns three values: the next function, the table t, and nil, -so that the construction -

-       for k,v in pairs(t) do ... end
-
-will iterate over all key--value pairs of table t. - -

See next for the caveats of modifying the table during its traversal. - -


pcall (f, arg1, arg2, ...)

- -

Calls function f with -the given arguments in protected mode. -This means that any error inside f is not propagated; -instead, pcall catches the error -and returns a status code. -Its first result is the status code (a boolean), -which is true if the call succeeds without errors. -In such case, pcall also returns all results from the call, -after this first result. -In case of any error, pcall returns false plus the error message. - -


print (e1, e2, ...)

-Receives any number of arguments, -and prints their values to stdout, -using the tostring function to convert them to strings. -print is not intended for formatted output, -but only as a quick way to show a value, -typically for debugging. -For formatted output, use string.format. - -


rawequal (v1, v2)

-Checks whether v1 is equal to v2, -without invoking any metamethod. -Returns a boolean. - -


rawget (table, index)

-Gets the real value of table[index], -without invoking any metamethod. -table must be a table and -index any value different from nil. - -


rawset (table, index, value)

-Sets the real value of table[index] to value, -without invoking any metamethod. -table must be a table, -index any value different from nil, -and value any Lua value. - -


select (index, ...)

- -

If index is a number, -returns all arguments after argument number index. -Otherwise, index must be the string "#", -and select returns the total number of extra arguments it received. - -


setfenv (f, table)

- -

Sets the environment to be used by the given function. -f can be a Lua function or a number -that specifies the function at that stack level: -Level 1 is the function calling setfenv. -setfenv returns the given function. - -

As a special case, when f is 0 setfenv changes -the environment of the running thread. -In this case, setfenv returns no values. - -


setmetatable (table, metatable)

- -

Sets the metatable for the given table. -(You cannot change the metatable of other types from Lua, only from C.) -If metatable is nil, -removes the metatable of the given table. -If the original metatable has a "__metatable" field, -raises an error. - -

This function returns table. - -


tonumber (e [, base])

-Tries to convert its argument to a number. -If the argument is already a number or a string convertible -to a number, then tonumber returns this number; -otherwise, it returns nil. - -

An optional argument specifies the base to interpret the numeral. -The base may be any integer between 2 and 36, inclusive. -In bases above 10, the letter `A´ (in either upper or lower case) -represents 10, `B´ represents 11, and so forth, -with `Z´ representing 35. -In base 10 (the default), the number may have a decimal part, -as well as an optional exponent part (see 2.1). -In other bases, only unsigned integers are accepted. - -


tostring (e)

-Receives an argument of any type and -converts it to a string in a reasonable format. -For complete control of how numbers are converted, -use string.format. - -

If the metatable of e has a "__tostring" field, -then tostring calls the corresponding value -with e as argument, -and uses the result of the call as its result. - -


type (v)

-Returns the type of its only argument, coded as a string. -The possible results of this function are -"nil" (a string, not the value nil), -"number", -"string", -"boolean, -"table", -"function", -"thread", -and "userdata". - -


unpack (list [, i [, j]])

-Returns the elements from the given table. -This function is equivalent to -
-  return list[i], list[i+1], ..., list[j]
-
-except that the above code can be written only for a fixed number -of elements. -By default, i is 1 and j is the length of the list, -as defined by the length operator (see 2.5.5). - -


_VERSION

-A global variable (not a function) that -holds a string containing the current interpreter version. -The current contents of this variable is "Lua 5.1". - -


xpcall (f, err)

- -

This function is similar to pcall, -except that you can set a new error handler. - -

xpcall calls function f in protected mode, -using err as the error handler. -Any error inside f is not propagated; -instead, xpcall catches the error, -calls the err function with the original error object, -and returns a status code. -Its first result is the status code (a boolean), -which is true if the call succeeds without errors. -In this case, xpcall also returns all results from the call, -after this first result. -In case of any error, -xpcall returns false plus the result from err. - -

5.2 - Coroutine Manipulation

- -

The operations related to coroutines comprise a sub-library of -the basic library and come inside the table coroutine. -See 2.11 for a general description of coroutines. - -


coroutine.create (f)

- -

Creates a new coroutine, with body f. -f must be a Lua function. -Returns this new coroutine, -an object with type "thread". - -


coroutine.resume (co [, val1, ..., valn])

- -

Starts or continues the execution of coroutine co. -The first time you resume a coroutine, -it starts running its body. -The values val1, ..., valn are passed -as the arguments to the body function. -If the coroutine has yielded, -resume restarts it; -the values val1, ..., valn are passed -as the results from the yield. - -

If the coroutine runs without any errors, -resume returns true plus any values passed to yield -(if the coroutine yields) or any values returned by the body function -(if the coroutine terminates). -If there is any error, -resume returns false plus the error message. - -


coroutine.running ()

- -

Returns the running coroutine, -or nil when called by the main thread. - -


coroutine.status (co)

- -

Returns the status of coroutine co, as a string: -"running", -if the coroutine is running (that is, it called status); -"suspended", if the coroutine is suspended in a call to yield, -or if it has not started running yet; -"normal" if the coroutine is active but not running -(that is, it has resumed another coroutine); -and "dead" if the coroutine has finished its body function, -or if it has stopped with an error. - -


coroutine.wrap (f)

- -

Creates a new coroutine, with body f. -f must be a Lua function. -Returns a function that resumes the coroutine each time it is called. -Any arguments passed to the function behave as the -extra arguments to resume. -Returns the same values returned by resume, -except the first boolean. -In case of error, propagates the error. - -


coroutine.yield ([val1, ..., valn])

- -

Suspends the execution of the calling coroutine. -The coroutine cannot be running a C function, -a metamethod, or an iterator. -Any arguments to yield are passed as extra results to resume. - -

5.3 - Modules

- -

The package library provides basic -facilities for loading and building modules in Lua. -It exports two of its functions directly in the global environment: -require and module. -Everything else is exported in a table package. - -


module (name [, ...])

- -

Creates a module. -If there is a table in package.loaded[name], -this table is the module. -Otherwise, if there is a global table t with the given name, -this table is the module. -Otherwise creates a new table t and -sets it as the value of the global name and -the value of package.loaded[name]. -This function also initializes t._NAME with the given name, -t._M with the module (t itself), -and t._PACKAGE with the package name -(the full module name minus last component; see below). -Finally, module sets t as the new environment -of the current function and the new value of package.loaded[name], -so that require returns t. - -

If name is a compound name -(that is, one with components separated by dots), -module creates (or reuses, if they already exist) -tables for each component. -For instance, if name is a.b.c, -then module stores the module table in field c of -field b of global a. - -

This function may receive optional options after -the module name, -where each option is a function to be applied over the module. - -


require (modname)

- -

Loads the given module. -The function starts by looking into the table package.loaded -to determine whether modname is already loaded. -If it is, then require returns the value stored -at package.loaded[modname]. -Otherwise, it tries to find a loader for the module. - -

To find a loader, -first require queries package.preload[modname]. -If it has a value, -this value (which should be a function) is the loader. -Otherwise require searches for a Lua loader using the -path stored in package.path. -If that also fails, it searches for a C loader using the -path stored in package.cpath. -If that also fails, -it tries an all-in-one loader (see below). - -

When loading a C library, -require first uses a dynamic link facility to link the -application with the library. -Then it tries to find a C function inside this library to -be used as the loader. -The name of this C function is the string "luaopen_" -concatenated with a copy of the module name where each dot -is replaced by an underscore. -Moreover, if the module name has a hyphen, -its prefix up to (and including) the first hyphen is removed. -For instance, if the module name is a.v1-b.c, -the function name will be luaopen_b_c. - -

If require finds neither a Lua library nor a -C library for a module, -it calls the all-in-one loader. -This loader searches the C path for a library for -the root name of the given module. -For instance, when requiring a.b.c, -it will search for a C library for a. -If found, it looks into it for an open function for -the submodule; -in our example, that would be luaopen_a_b_c. -With this facility, a package can pack several C submodules -into one single library, -with each submodule keeping its original open function. - -

Once a loader is found, -require calls the loader with a single argument, modname. -If the loader returns any value, -require assigns it to package.loaded[modname]. -If the loader returns no value and -has not assigned any value to package.loaded[modname], -then require assigns true to this entry. -In any case, require returns the -final value of package.loaded[modname]. - -

If there is any error loading or running the module, -or if it cannot find any loader for the module, -then require signals an error. - -


package.cpath

- -

The path used by require to search for a C loader. - -

Lua initializes the C path package.cpath in the same way -it initializes the Lua path package.path, -using the environment variable LUA_CPATH -(plus another default path defined in luaconf.h). - -


package.loaded

- -

A table used by require to control which -modules are already loaded. -When you require a module modname and -package.loaded[modname] is not false, -require simply returns the value stored there. - -


package.loadlib (libname, funcname)

- -

Dynamically links the host program with the C library libname. -Inside this library, looks for a function funcname -and returns this function as a C function. -(So, funcname must follow the protocol (see lua_CFunction)). - -

This is a low-level function. -It completely bypasses the package and module system. -Unlike require, -it does not perform any path searching and -does not automatically adds extensions. -libname must be the complete file name of the C library, -including if necessary a path and extension. -funcname must be the exact name exported by the C library -(which may depend on the C compiler and linker used). - -

This function is not supported by ANSI C. -As such, it is only available on some platforms -(Windows, Linux, Mac OS X, Solaris, BSD, -plus other Unix systems that support the dlfcn standard). - -


package.path

- -

The path used by require to search for a Lua loader. - -

At start-up, Lua initializes this variable with -the value of the environment variable LUA_PATH or -with a default path defined in luaconf.h, -if the environment variable is not defined. -Any ";;" in the value of the environment variable -is replaced by the default path. - -

A path is a sequence of templates separated by semicolons. -For each template, require will change each interrogation -mark in the template by filename, -which is modname with each dot replaced by a -"directory separator" (such as "/" in Unix); -then it will try to load the resulting file name. -So, for instance, if the Lua path is -

-  "./?.lua;./?.lc;/usr/local/?/init.lua"
-
-the search for a Lua loader for module foo -will try to load the files -./foo.lua, ./foo.lc, and -/usr/local/foo/init.lua, in that order. - -


package.preload

- -

A table to store loaders for specific modules -(see require). - -


package.seeall (module)

- -

Sets a metatable for module with -its __index field referring to the global environment, -so that this module inherits values -from the global environment. -To be used as an option to function module. - -

5.4 - String Manipulation

- -

This library provides generic functions for string manipulation, -such as finding and extracting substrings, and pattern matching. -When indexing a string in Lua, the first character is at position 1 -(not at 0, as in C). -Indices are allowed to be negative and are interpreted as indexing backwards, -from the end of the string. -Thus, the last character is at position -1, and so on. - -

The string library provides all its functions inside the table -string. -It also sets a metatable for strings -where the __index field points to the metatable itself. -Therefore, you can use the string functions in object-oriented style. -For instance, string.byte(s, i) -can be written as s:byte(i). - -


string.byte (s [, i [, j]])

-Returns the internal numerical codes of the characters s[i], -s[i+1], ..., s[j]. -The default value for i is 1; -the default value for j is i. - -

Note that numerical codes are not necessarily portable across platforms. - -


string.char (i1, i2, ...)

-Receives 0 or more integers. -Returns a string with length equal to the number of arguments, -in which each character has the internal numerical code equal -to its corresponding argument. - -

Note that numerical codes are not necessarily portable across platforms. - -


string.dump (function)

- -

Returns a string containing a binary representation of the given function, -so that a later loadstring on this string returns -a copy of the function. -function must be a Lua function without upvalues. - -


string.find (s, pattern [, init [, plain]])

-Looks for the first match of -pattern in the string s. -If it finds a match, then find returns the indices of s -where this occurrence starts and ends; -otherwise, it returns nil. -A third, optional numerical argument init specifies -where to start the search; -its default value is 1 and may be negative. -A value of true as a fourth, optional argument plain -turns off the pattern matching facilities, -so the function does a plain "find substring" operation, -with no characters in pattern being considered "magic". -Note that if plain is given, then init must be given as well. - -

If the pattern has captures, -then in a successful match -the captured values are also returned, -after the two indices. - -


string.format (formatstring, e1, e2, ...)

-Returns a formatted version of its variable number of arguments -following the description given in its first argument (which must be a string). -The format string follows the same rules as the printf family of -standard C functions. -The only differences are that the options/modifiers -*, l, L, n, p, -and h are not supported -and that there is an extra option, q. -The q option formats a string in a form suitable to be safely read -back by the Lua interpreter: -The string is written between double quotes, -and all double quotes, newlines, embedded zeros, -and backslashes in the string -are correctly escaped when written. -For instance, the call -
-       string.format('%q', 'a string with "quotes" and \n new line')
-
-will produce the string: -
-"a string with \"quotes\" and \
- new line"
-
- -

The options c, d, E, e, f, -g, G, i, o, u, X, and x all -expect a number as argument, -whereas q and s expect a string. - -

This function does not accept string values -containing embedded zeros. - -


string.gmatch (s, pattern)

-Returns an iterator function that, -each time it is called, -returns the next captures from pattern over string s. - -

If pattern specifies no captures, -then the whole match is produced in each call. - -

As an example, the following loop -

-  s = "hello world from Lua"
-  for w in string.gmatch(s, "%a+") do
-    print(w)
-  end
-
-will iterate over all the words from string s, -printing one per line. -The next example collects all pairs key=value from the -given string into a table: -
-  t = {}
-  s = "from=world, to=Lua"
-  for k, v in string.gmatch(s, "(%w+)=(%w+)") do
-    t[k] = v
-  end
-
- -


string.gsub (s, pattern, repl [, n])

-Returns a copy of s -in which all occurrences of the pattern have been -replaced by a replacement string specified by repl, -which may be a string, a table, or a function. -gsub also returns, as its second value, -the total number of substitutions made. - -

If repl is a string, then its value is used for replacement. -The character % works as an escape character: -Any sequence in repl of the form %n, -with n between 1 and 9, -stands for the value of the n-th captured substring (see below). -The sequence %0 stands for the whole match. -The sequence %% stands for a single %. - -

If repl is a table, then the table is queried for every match, -using the first capture as the key; -if the pattern specifies no captures, -then the whole match is used as the key. - -

If repl is a function, then this function is called every time a -match occurs, with all captured substrings passed as arguments, -in order; -if the pattern specifies no captures, -then the whole match is passed as a sole argument. - -

If the value returned by the table query or by the function call -is a string or a number, -then it is used as the replacement string; -otherwise, if it is false or nil, -then there is no replacement -(that is, the original match is kept in the string). - -

The optional last parameter n limits -the maximum number of substitutions to occur. -For instance, when n is 1 only the first occurrence of -pattern is replaced. - -

Here are some examples: -

-   x = string.gsub("hello world", "(%w+)", "%1 %1")
-   --> x="hello hello world world"
-
-   x = string.gsub("hello world", "%w+", "%0 %0", 1)
-   --> x="hello hello world"
-
-   x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
-   --> x="world hello Lua from"
-
-   x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
-   --> x="home = /home/roberto, user = roberto"
-
-   x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
-         return loadstring(s)()
-       end)
-   --> x="4+5 = 9"
-
-   local t = {name="lua", version="5.1"}
-   x = string.gsub("$name%-$version.tar.gz", "%$(%w+)", t)
-   --> x="lua-5.1.tar.gz"
-
- -


string.len (s)

-Receives a string and returns its length. -The empty string "" has length 0. -Embedded zeros are counted, -so "a\000bc\000" has length 5. - -


string.lower (s)

-Receives a string and returns a copy of this string with all -uppercase letters changed to lowercase. -All other characters are left unchanged. -The definition of what an uppercase letter is depends on the current locale. - -


string.match (s, pattern [, init])

-Looks for the first match of -pattern in the string s. -If it finds one, then match returns -the captures from the pattern; -otherwise it returns nil. -If pattern specifies no captures, -then the whole match is returned. -A third, optional numerical argument init specifies -where to start the search; -its default value is 1 and may be negative. - -


string.rep (s, n)

-Returns a string that is the concatenation of n copies of -the string s. - -


string.reverse (s)

-Returns a string that is the string s reversed. - -


string.sub (s, i [, j])

-Returns the substring of s that -starts at i and continues until j; -i and j may be negative. -If j is absent, then it is assumed to be equal to -1 -(which is the same as the string length). -In particular, -the call string.sub(s,1,j) returns a prefix of s -with length j, -and string.sub(s, -i) returns a suffix of s -with length i. - -


string.upper (s)

-Receives a string and returns a copy of this string with all -lowercase letters changed to uppercase. -All other characters are left unchanged. -The definition of what a lowercase letter is depends on the current locale. - -

Patterns

- -

-A character class is used to represent a set of characters. -The following combinations are allowed in describing a character class: -

    -
  • x (where x is not one of the magic characters -^$()%.[]*+-?) ---- represents the character x itself. -
  • . --- (a dot) represents all characters. -
  • %a --- represents all letters. -
  • %c --- represents all control characters. -
  • %d --- represents all digits. -
  • %l --- represents all lowercase letters. -
  • %p --- represents all punctuation characters. -
  • %s --- represents all space characters. -
  • %u --- represents all uppercase letters. -
  • %w --- represents all alphanumeric characters. -
  • %x --- represents all hexadecimal digits. -
  • %z --- represents the character with representation 0. -
  • %x (where x is any non-alphanumeric character) --- -represents the character x. -This is the standard way to escape the magic characters. -Any punctuation character (even the non magic) -can be preceded by a `%´ -when used to represent itself in a pattern. - -

  • [set] --- -represents the class which is the union of all -characters in set. -A range of characters may be specified by -separating the end characters of the range with a `-´. -All classes %x described above may also be used as -components in set. -All other characters in set represent themselves. -For example, [%w_] (or [_%w]) -represents all alphanumeric characters plus the underscore, -[0-7] represents the octal digits, -and [0-7%l%-] represents the octal digits plus -the lowercase letters plus the `-´ character. - -

    The interaction between ranges and classes is not defined. -Therefore, patterns like [%a-z] or [a-%%] -have no meaning. - -

  • [^set] --- -represents the complement of set, -where set is interpreted as above. -
-For all classes represented by single letters (%a, %c, etc.), -the corresponding uppercase letter represents the complement of the class. -For instance, %S represents all non-space characters. - -

The definitions of letter, space, and other character groups -depend on the current locale. -In particular, the class [a-z] may not be equivalent to %l. - -

-A pattern item may be -

    -
  • -a single character class, -which matches any single character in the class; -
  • -a single character class followed by `*´, -which matches 0 or more repetitions of characters in the class. -These repetition items will always match the longest possible sequence; -
  • -a single character class followed by `+´, -which matches 1 or more repetitions of characters in the class. -These repetition items will always match the longest possible sequence; -
  • -a single character class followed by `-´, -which also matches 0 or more repetitions of characters in the class. -Unlike `*´, -these repetition items will always match the shortest possible sequence; -
  • -a single character class followed by `?´, -which matches 0 or 1 occurrence of a character in the class; -
  • -%n, for n between 1 and 9; -such item matches a substring equal to the n-th captured string -(see below); -
  • -%bxy, where x and y are two distinct characters; -such item matches strings that start with x, end with y, -and where the x and y are balanced. -This means that, if one reads the string from left to right, -counting +1 for an x and -1 for a y, -the ending y is the first y where the count reaches 0. -For instance, the item %b() matches expressions with -balanced parentheses. -
- -

-A pattern is a sequence of pattern items. -A `^´ at the beginning of a pattern anchors the match at the -beginning of the subject string. -A `$´ at the end of a pattern anchors the match at the -end of the subject string. -At other positions, -`^´ and `$´ have no special meaning and represent themselves. - -

-A pattern may contain sub-patterns enclosed in parentheses; -they describe captures. -When a match succeeds, the substrings of the subject string -that match captures are stored (captured) for future use. -Captures are numbered according to their left parentheses. -For instance, in the pattern "(a*(.)%w(%s*))", -the part of the string matching "a*(.)%w(%s*)" is -stored as the first capture (and therefore has number 1); -the character matching "." is captured with number 2, -and the part matching "%s*" has number 3. - -

As a special case, the empty capture () captures -the current string position (a number). -For instance, if we apply the pattern "()aa()" on the -string "flaaap", there will be two captures: 3 and 5. - -

A pattern cannot contain embedded zeros. Use %z instead. - -

5.5 - Table Manipulation

-This library provides generic functions for table manipulation. -It provides all its functions inside the table table. - -

Most functions in the table library assume that the table -represents an array or a list. -For these functions, when we talk about the "length" of a table -we mean the result of the length operator. - -


table.concat (table [, sep [, i [, j]]])

-Returns table[i]..sep..table[i+1] ... sep..table[j]. -The default value for sep is the empty string, -the default for i is 1, -and the default for j is the length of the table. -If i is greater than j, returns the empty string. - -


table.insert (table, [pos,] value)

- -

Inserts element value at position pos in table, -shifting up other elements to open space, if necessary. -The default value for pos is n+1, -where n is the length of the table (see 2.5.5), -so that a call table.insert(t,x) inserts x at the end -of table t. - -


table.maxn (table)

- -

Returns the largest positive numerical index of the given table, -or zero if the table has no positive numerical indices. -(To do its job this function does a linear traversal of -the whole table.) - -


table.remove (table [, pos])

- -

Removes from table the element at position pos, -shifting down other elements to close the space, if necessary. -Returns the value of the removed element. -The default value for pos is n, -where n is the length of the table, -so that a call table.remove(t) removes the last element -of table t. - -


table.sort (table [, comp])

-Sorts table elements in a given order, in-place, -from table[1] to table[n], -where n is the length of the table. -If comp is given, -then it must be a function that receives two table elements, -and returns true -when the first is less than the second -(so that not comp(a[i+1],a[i]) will be true after the sort). -If comp is not given, -then the standard Lua operator < is used instead. - -

The sort algorithm is not stable; -that is, elements considered equal by the given order -may have their relative positions changed by the sort. - -

5.6 - Mathematical Functions

- -

This library is an interface to the standard C math library. -It provides all its functions inside the table math. -The library provides the following functions: - - - - - - - - -

-       math.abs     math.acos    math.asin    math.atan    math.atan2
-       math.ceil    math.cos     math.cosh    math.deg     math.exp
-       math.floor   math.fmod    math.frexp   math.ldexp   math.log
-       math.log10   math.max     math.min     math.modf    math.pow
-       math.rad     math.random  math.randomseed           math.sin
-       math.sinh    math.sqrt    math.tan     math.tanh
-
-plus a variable math.pi and -a variable math.huge, -with the value HUGE_VAL. -Most of these functions -are only interfaces to the corresponding functions in the C library. -All trigonometric functions work in radians. -The functions math.deg and math.rad convert -between radians and degrees. - -

The function math.max returns the maximum -value of its numeric arguments. -Similarly, math.min computes the minimum. -Both can be used with 1, 2, or more arguments. - -

The function math.modf corresponds to the modf C function. -It returns two values: -The integral part and the fractional part of its argument. -The function math.frexp also returns 2 values: -The normalized fraction and the exponent of its argument. - -

The functions math.random and math.randomseed -are interfaces to the simple random generator functions -rand and srand that are provided by ANSI C. -(No guarantees can be given for their statistical properties.) -When called without arguments, -math.random returns a pseudo-random real number -in the range [0,1). -When called with a number n, -math.random returns -a pseudo-random integer in the range [1,n]. -When called with two arguments, -l and u, -math.random returns a pseudo-random -integer in the range [l,u]. -The math.randomseed function sets a "seed" -for the pseudo-random generator: -Equal seeds produce equal sequences of numbers. - -

5.7 - Input and Output Facilities

- -

The I/O library provides two different styles for file manipulation. -The first one uses implicit file descriptors; -that is, there are operations to set a default input file and a -default output file, -and all input/output operations are over these default files. -The second style uses explicit file descriptors. - -

When using implicit file descriptors, -all operations are supplied by table io. -When using explicit file descriptors, -the operation io.open returns a file descriptor -and then all operations are supplied as methods of the file descriptor. - -

The table io also provides -three predefined file descriptors with their usual meanings from C: -io.stdin, io.stdout, and io.stderr. - -

Unless otherwise stated, -all I/O functions return nil on failure -(plus an error message as a second result) -and some value different from nil on success. - -


io.close ([file])

- -

Equivalent to file:close(). -Without a file, closes the default output file. - -


io.flush ()

- -

Equivalent to file:flush over the default output file. - -


io.input ([file])

- -

When called with a file name, it opens the named file (in text mode), -and sets its handle as the default input file. -When called with a file handle, -it simply sets this file handle as the default input file. -When called without parameters, -it returns the current default input file. - -

In case of errors this function raises the error, -instead of returning an error code. - -


io.lines ([filename])

- -

Opens the given file name in read mode -and returns an iterator function that, -each time it is called, -returns a new line from the file. -Therefore, the construction -

-       for line in io.lines(filename) do ... end
-
-will iterate over all lines of the file. -When the iterator function detects the end of file, -it returns nil (to finish the loop) and automatically closes the file. - -

The call io.lines() (without a file name) is equivalent -to io.input():lines(); -that is, it iterates over the lines of the default input file. -In this case it does not close the file when the loop ends. - -


io.open (filename [, mode])

- -

This function opens a file, -in the mode specified in the string mode. -It returns a new file handle, -or, in case of errors, nil plus an error message. - -

The mode string can be any of the following: -

    -
  • "r" --- read mode (the default); -
  • "w" --- write mode; -
  • "a" --- append mode; -
  • "r+" --- update mode, all previous data is preserved; -
  • "w+" --- update mode, all previous data is erased; -
  • "a+" --- append update mode, previous data is preserved, - writing is only allowed at the end of file. -
-The mode string may also have a `b´ at the end, -which is needed in some systems to open the file in binary mode. -This string is exactly what is used in the -standard C function fopen. - -


io.output ([file])

- -

Similar to io.input, but operates over the default output file. - -


io.popen ([prog [, mode]])

- -

Starts program prog in a separated process and returns -a file handle that you can use to read data from this program -(if mode is "r", the default) -or to write data to this program -(if mode is "w"). - -

This function is system dependent and is not available -on all platforms. - -


io.read (format1, ...)

- -

Equivalent to io.input():read. - -


io.tmpfile ()

- -

Returns a handle for a temporary file. -This file is opened in update mode -and it is automatically removed when the program ends. - -


io.type (obj)

- -

Checks whether obj is a valid file handle. -Returns the string "file" if obj is an open file handle, -"closed file" if obj is a closed file handle, -or nil if obj is not a file handle. - -


io.write (value1, ...)

- -

Equivalent to io.output():write. - -


file:close ()

- -

Closes file. -Note that files are automatically closed when -their handles are garbage collected, -but that takes an unpredictable amount of time to happen. - -


file:flush ()

- -

Saves any written data to file. - -


file:lines ()

- -

Returns an iterator function that, -each time it is called, -returns a new line from the file. -Therefore, the construction -

-       for line in file:lines() do ... end
-
-will iterate over all lines of the file. -(Unlike io.lines, this function does not close the file -when the loop ends.) - -


file:read (format1, ...)

- -

Reads the file file, -according to the given formats, which specify what to read. -For each format, -the function returns a string (or a number) with the characters read, -or nil if it cannot read data with the specified format. -When called without formats, -it uses a default format that reads the entire next line -(see below). - -

The available formats are -

    -
  • "*n" reads a number; -this is the only format that returns a number instead of a string. -
  • "*a" reads the whole file, starting at the current position. -On end of file, it returns the empty string. -
  • "*l" reads the next line (skipping the end of line), -returning nil on end of file. -This is the default format. -
  • number reads a string with up to this number of characters, -returning nil on end of file. -If number is zero, -it reads nothing and returns an empty string, -or nil on end of file. -
- -


file:seek ([whence] [, offset])

- -

Sets and gets the file position, -measured from the beginning of the file, -to the position given by offset plus a base -specified by the string whence, as follows: -

    -
  • "set" --- base is position 0 (beginning of the file); -
  • "cur" --- base is current position; -
  • "end" --- base is end of file; -
-In case of success, function seek returns the final file position, -measured in bytes from the beginning of the file. -If this function fails, it returns nil, -plus a string describing the error. - -

The default value for whence is "cur", -and for offset is 0. -Therefore, the call file:seek() returns the current -file position, without changing it; -the call file:seek("set") sets the position to the -beginning of the file (and returns 0); -and the call file:seek("end") sets the position to the -end of the file, and returns its size. - -


file:setvbuf (mode [, size])

- -

Sets the buffering mode for an output file. -There are three available modes: -

    -
  • "no" --- -no buffering; the result of any output operation appears immediately. -
  • "full" --- -full buffering; output operation is performed only -when the buffer is full (or when you explicitly flush the file (see 5.7)). -
  • "line" --- -line buffering; output is buffered until a newline is output -or there is any input from some special files -(such as a terminal device). -
-For the last two cases, sizes -specifies the size of the buffer, in bytes. -The default is an appropriate size. - -


file:write (value1, ...)

- -

Writes the value of each of its arguments to -the file. -The arguments must be strings or numbers. -To write other values, -use tostring or string.format before write. - -

5.8 - Operating System Facilities

- -

This library is implemented through table os. - -


os.clock ()

- -

Returns an approximation of the amount in seconds of CPU time -used by the program. - -


os.date ([format [, time]])

- -

Returns a string or a table containing date and time, -formatted according to the given string format. - -

If the time argument is present, -this is the time to be formatted -(see the os.time function for a description of this value). -Otherwise, date formats the current time. - -

If format starts with `!´, -then the date is formatted in Coordinated Universal Time. -After this optional character, -if format is *t, -then date returns a table with the following fields: -year (four digits), month (1--12), day (1--31), -hour (0--23), min (0--59), sec (0--61), -wday (weekday, Sunday is 1), -yday (day of the year), -and isdst (daylight saving flag, a boolean). - -

If format is not *t, -then date returns the date as a string, -formatted according to the same rules as the C function strftime. - -

When called without arguments, -date returns a reasonable date and time representation that depends on -the host system and on the current locale -(that is, os.date() is equivalent to os.date("%c")). - -


os.difftime (t2, t1)

- -

Returns the number of seconds from time t1 to time t2. -In POSIX, Windows, and some other systems, -this value is exactly t2-t1. - -


os.execute ([command])

- -

This function is equivalent to the C function system. -It passes command to be executed by an operating system shell. -It returns a status code, which is system-dependent. -If command is absent, then it returns nonzero if a shell is available -and zero otherwise. - -


os.exit ([code])

- -

Calls the C function exit, -with an optional code, -to terminate the host program. -The default value for code is the success code. - -


os.getenv (varname)

- -

Returns the value of the process environment variable varname, -or nil if the variable is not defined. - -


os.remove (filename)

- -

Deletes the file or directory with the given name. -Directories must be empty to be removed. -If this function fails, it returns nil, -plus a string describing the error. - -


os.rename (oldname, newname)

- -

Renames file or directory named oldname to newname. -If this function fails, it returns nil, -plus a string describing the error. - -


os.setlocale (locale [, category])

- -

Sets the current locale of the program. -locale is a string specifying a locale; -category is an optional string describing which category to change: -"all", "collate", "ctype", -"monetary", "numeric", or "time"; -the default category is "all". -The function returns the name of the new locale, -or nil if the request cannot be honored. - -


os.time ([table])

- -

Returns the current time when called without arguments, -or a time representing the date and time specified by the given table. -This table must have fields year, month, and day, -and may have fields hour, min, sec, and isdst -(for a description of these fields, see the os.date function). - -

The returned value is a number, whose meaning depends on your system. -In POSIX, Windows, and some other systems, this number counts the number -of seconds since some given start time (the "epoch"). -In other systems, the meaning is not specified, -and the number returned by time can be used only as an argument to -date and difftime. - -


os.tmpname ()

- -

Returns a string with a file name that can -be used for a temporary file. -The file must be explicitly opened before its use -and explicitly removed when no longer needed. - -

5.9 - The Debug Library

- -

This library provides -the functionality of the debug interface to Lua programs. -You should exert care when using this library. -The functions provided here should be used exclusively for debugging -and similar tasks, such as profiling. -Please resist the temptation to use them as a -usual programming tool: -They can be very slow. -Moreover, several of its functions -violate some assumptions about Lua code -(e.g., that variables local to a function -cannot be accessed from outside or -that userdata metatables cannot be changed by Lua code) -and therefore can compromise otherwise secure code. - -

All functions in this library are provided -inside the debug table. - -


debug.debug ()

- -

Enters an interactive mode with the user, -running each string that the user enters. -Using simple commands and other debug facilities, -the user can inspect global and local variables, -change their values, evaluate expressions, and so on. -A line containing only the word cont finishes this function, -so that the caller continues its execution. - -

Note that commands for debug.debug are not lexically nested -within any function, and so have no direct access to local variables. - -


debug.getfenv (o)

-Returns the environment of object o. - -


debug.gethook ()

- -

Returns the current hook settings, as three values: -the current hook function, the current hook mask, -and the current hook count -(as set by the debug.sethook function). - -


debug.getinfo (function [, what])

- -

Returns a table with information about a function. -You can give the function directly, -or you can give a number as the value of function, -which means the function running at level function of the call stack: -Level 0 is the current function (getinfo itself); -level 1 is the function that called getinfo; -and so on. -If function is a number larger than the number of active functions, -then getinfo returns nil. - -

The returned table contains all the fields returned by lua_getinfo, -with the string what describing which fields to fill in. -The default for what is to get all information available. -If present, -the option `f´ -adds a field named func with the function itself. - -

For instance, the expression debug.getinfo(1,"n").name returns -a name of the current function, if a reasonable name can be found, -and debug.getinfo(print) returns a table with all available information -about the print function. - -


debug.getlocal (level, local)

- -

This function returns the name and the value of the local variable -with index local of the function at level level of the stack. -(The first parameter or local variable has index 1, and so on, -until the last active local variable.) -The function returns nil if there is no local -variable with the given index, -and raises an error when called with a level out of range. -(You can call debug.getinfo to check whether the level is valid.) - -

Variable names starting with `(´ (open parentheses) -represent internal variables -(loop control variables, temporaries, and C function locals). - -


debug.getmetatable (object)

- -

Returns the metatable of the given object -or nil if it does not have a metatable. - -


debug.getregistry ()

- -

Returns the registry table (see 3.5). - -


debug.getupvalue (func, up)

- -

This function returns the name and the value of the upvalue -with index up of the function func. -The function returns nil if there is no upvalue with the given index. - -


debug.setfenv (object, table)

- -

Sets the environment of the given object to the given table. - -


debug.sethook (hook, mask [, count])

- -

Sets the given function as a hook. -The string mask and the number count describe -when the hook will be called. -The string mask may have the following characters, -with the given meaning: -

    -
  • "c" --- The hook is called every time Lua calls a function; -
  • "r" --- The hook is called every time Lua returns from a function; -
  • "l" --- The hook is called every time Lua enters a new line of code. -
-With a count different from zero, -the hook is called after every count instructions. - -

When called without arguments, -debug.sethook turns off the hook. - -

When the hook is called, its first parameter is a string -describing the event that has triggered its call: -"call", "return" (or "tail return"), -"line", and "count". -For line events, -the hook also gets the new line number as its second parameter. -Inside a hook, -you can call getinfo with level 2 to get more information about -the running function -(level 0 is the getinfo function, -and level 1 is the hook function), -unless the event is "tail return". -In this case, Lua is only simulating the return, -and a call to getinfo will return invalid data. - -


debug.setlocal (level, local, value)

- -

This function assigns the value value to the local variable -with index local of the function at level level of the stack. -The function returns nil if there is no local -variable with the given index, -and raises an error when called with a level out of range. -(You can call getinfo to check whether the level is valid.) -Otherwise, it returns the name of the local variable. - -


debug.setmetatable (object, table)

- -

Sets the metatable for the given object to the given table -(which can be nil). - -


debug.setupvalue (func, up, value)

- -

This function assigns the value value to the upvalue -with index up of the function func. -The function returns nil if there is no upvalue -with the given index. -Otherwise, it returns the name of the upvalue. - -


debug.traceback ([message])

- -

Returns a string with a traceback of the call stack. -An optional message string is appended -at the beginning of the traceback. -This function is typically used with xpcall to produce -better error messages. - -

-

6 - Lua Stand-alone

- -

Although Lua has been designed as an extension language, -to be embedded in a host C program, -it is also frequently used as a stand-alone language. -An interpreter for Lua as a stand-alone language, -called simply lua, -is provided with the standard distribution. -The stand-alone interpreter includes -all standard libraries, including the debug library. -Its usage is: -

-      lua [options] [script [args]]
-
-The options are: -
    -
  • -e stat executes string stat; -
  • -l mod "requires" mod; -
  • -i enters interactive mode after running script; -
  • -v prints version information; -
  • -- stops handling options; -
  • - executes stdin as a file and stops handling options. -
-After handling its options, lua runs the given script, -passing to it the given args as string arguments. -When called without arguments, -lua behaves as lua -v -i -when the standard input (stdin) is a terminal, -and as lua - otherwise. - -

Before running any argument, -the interpreter checks for an environment variable LUA_INIT. -If its format is @filename, -then lua executes the file. -Otherwise, lua executes the string itself. - -

All options are handled in order, except -i. -For instance, an invocation like -

-       $ lua -e'a=1' -e 'print(a)' script.lua
-
-will first set a to 1, then print the value of a (which is `1´), -and finally run the file script.lua with no arguments. -(Here $ is the shell prompt. Your prompt may be different.) - -

Before starting to run the script, -lua collects all arguments in the command line -in a global table called arg. -The script name is stored at index 0, -the first argument after the script name goes to index 1, -and so on. -Any arguments before the script name -(that is, the interpreter name plus the options) -go to negative indices. -For instance, in the call -

-       $ lua -la b.lua t1 t2
-
-the interpreter first runs the file a.lua, -then creates a table -
-       arg = { [-2] = "lua", [-1] = "-la",
-               [0] = "b.lua",
-               [1] = "t1", [2] = "t2" }
-
-and finally runs the file b.lua. -The script is called with arg[1], arg[2], ... -as arguments; -it can also access these arguments with the vararg expression `...´. - -

In interactive mode, -if you write an incomplete statement, -the interpreter waits for its completion -by issuing a different prompt. - -

If the global variable _PROMPT contains a string, -then its value is used as the prompt. -Similarly, if the global variable _PROMPT2 contains a string, -its value is used as the secondary prompt -(issued during incomplete statements). -Therefore, both prompts can be changed directly on the command line. -For instance, -

-       $ lua -e"_PROMPT='myprompt> '" -i
-
-(the outer pair of quotes is for the shell, -the inner pair is for Lua), -or in any Lua programs by assigning to _PROMPT. -Note the use of -i to enter interactive mode; otherwise, -the program would just end silently right after the assignment to _PROMPT. - -

To allow the use of Lua as a -script interpreter in Unix systems, -the stand-alone interpreter skips -the first line of a chunk if it starts with #. -Therefore, Lua scripts can be made into executable programs -by using chmod +x and the #! form, -as in -

-#!/usr/local/bin/lua
-
-(Of course, -the location of the Lua interpreter may be different in your machine. -If lua is in your PATH, -then -
-#!/usr/bin/env lua
-
-is a more portable solution.) - -


- -

Incompatibilities with the Previous Version

- - -

Here we list the incompatibilities that may be found when moving a program -from Lua 5.0 to Lua 5.1. -You can avoid most of the incompatibilities compiling Lua with -appropriate options (see file luaconf.h). -However, -all these compatibility options will be removed in the next version of Lua. - -

Incompatibilities with version 5.0

- -

Changes in the Language

-
    -
  • -The vararg system changed from the pseudo-argument arg with a -table with the extra arguments to the vararg expression. -(Option LUA_COMPAT_VARARG in luaconf.h.) - -

  • -There was a subtle change in the scope of the implicit -variables of the for statement and for the repeat statement. - -

  • -The long string/long comment syntax ([[...]]) does not allow nesting. -You can use the new syntax ([=[...]=]) in these cases. -(Option LUA_COMPAT_LSTR in luaconf.h.) - -

- -

Changes in the Libraries

-
    - -

  • -Function string.gfind was renamed string.gmatch. -(Option LUA_COMPAT_GFIND) - -

  • -When string.gsub is called with a function as its -third argument, -whenever this function returns nil or false the -replacement string is the whole match, -instead of the empty string. - -

  • -Function table.setn was deprecated. -Function table.getn corresponds -to the new length operator (#); -use the operator instead of the function. -(Option LUA_COMPAT_GETN) - -

  • -Function loadlib was renamed package.loadlib. -(Option LUA_COMPAT_LOADLIB) - -

  • -Function math.mod was renamed math.fmod. -(Option LUA_COMPAT_MOD) - -

  • -Functions table.foreach and table.foreachi are deprecated. -You can use a for loop with pairs or ipairs instead. - -

  • -There were substantial changes in function require due to -the new module system. -However, the new behavior is mostly compatible with the old, -but require gets the path from package.path instead -of from LUA_PATH. - -

  • -Function collectgarbage has different arguments. -Function gcinfo is deprecated; -use collectgarbage("count") instead. - -

- -

Changes in the API

-
    - -

  • -The luaopen_* functions (to open libraries) -cannot be called directly, -like a regular C function. -They must be called through Lua, -like a Lua function. - -

  • -Function lua_open was replaced by lua_newstate to -allow the user to set a memory allocation function. -You can use luaL_newstate from the standard library to -create a state with a standard allocation function -(based on realloc). - -

  • -Functions luaL_getn and luaL_setn -(from the auxiliary library) are deprecated. -Use lua_objlen instead of luaL_getn -and nothing instead of luaL_setn. - -

  • -Function luaL_openlib was replaced by luaL_register. - -

- -

- -

The Complete Syntax of Lua

- - -

Here is the complete syntax of Lua in extended BNF. -It does not describe operator priorities or some syntactical restrictions, -such as return and break statements -can only appear as the last statement of a block. - -

- -

-
-	chunk ::= {stat [`;´]} [laststat[`;´]]
-
-	block ::= chunk
-
-	stat ::=  varlist1 `=´ explist1  | 
-		 functioncall  | 
-		 do block end  | 
-		 while exp do block end  | 
-		 repeat block until exp  | 
-		 if exp then block {elseif exp then block} [else block] end  | 
-		 for Name `=´ exp `,´ exp [`,´ exp] do block end  | 
-		 for namelist in explist1 do block end  | 
-		 function funcname funcbody  | 
-		 local function Name funcbody  | 
-		 local namelist [`=´ explist1] 
-
-	laststat ::= return [explist1]  |  break
-
-	funcname ::= Name {`.´ Name} [`:´ Name]
-
-	varlist1 ::= var {`,´ var}
-
-	var ::=  Name  |  prefixexp `[´ exp `]´  |  prefixexp `.´ Name 
-
-	namelist ::= Name {`,´ Name}
-
-	explist1 ::= {exp `,´} exp
-
-	exp ::=  nil  |  false  |  true  |  Number  |  String  |  `...´  | 
-		 function  |  prefixexp  |  tableconstructor  |  exp binop exp  |  unop exp 
-
-	prefixexp ::= var  |  functioncall  |  `(´ exp `)´
-
-	functioncall ::=  prefixexp args  |  prefixexp `:´ Name args 
-
-	args ::=  `(´ [explist1] `)´  |  tableconstructor  |  String 
-
-	function ::= function funcbody
-
-	funcbody ::= `(´ [parlist1] `)´ block end
-
-	parlist1 ::= namelist [`,´ `...´]  |  `...´
-
-	tableconstructor ::= `{´ [fieldlist] `}´
-
-	fieldlist ::= field {fieldsep field} [fieldsep]
-
-	field ::= `[´ exp `]´ `=´ exp  |  Name `=´ exp  |  exp
-
-	fieldsep ::= `,´  |  `;´
-
-	binop ::= `+´  |  `-´  |  `*´  |  `/´  |  `^´  |  `%´  |  `..´  | 
-		 `<´  |  `<=´  |  `>´  |  `>=´  |  `==´  |  `~=´  | 
-		 and  |  or
-
-	unop ::= `-´  |  not  |  `#´
-
-
- -

- -

- - - diff --git a/doc/lua/readme.html b/doc/lua/readme.html deleted file mode 100644 index db20a69..0000000 --- a/doc/lua/readme.html +++ /dev/null @@ -1,32 +0,0 @@ - - -Lua documentation - - - - - -


-

-Lua -Documentation -

- - - -
- -Last update: -Wed Sep 7 12:57:50 BRST 2005 - - - - diff --git a/doc/luairc/LICENSE b/doc/luairc/LICENSE deleted file mode 100644 index fe30b8a..0000000 --- a/doc/luairc/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (c) 2007 Jesse Luehrs - -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. diff --git a/doc/luairc/README b/doc/luairc/README deleted file mode 100644 index 50112b9..0000000 --- a/doc/luairc/README +++ /dev/null @@ -1,31 +0,0 @@ -LuaIRC v0.3 -Jesse Luehrs (jluehrs2@uiuc.edu) - -OVERVIEW -======== -LuaIRC is a fully featured IRC framework written entirely in Lua. It provides an event driven system for connecting to IRC servers and responding to actions such as messages, joins/parts, and channel mode changes, among other things. DCC SEND is also fully implemented, both for sending and receiving files. - -INSTALL -======= -This module requires LuaSocket (http://www.cs.princeton.edu/~diego/professional/luasocket/) and Lua 5.1. To install, modify the Make.config file with paths appropriate to your system and run 'make install'. - -DOCUMENTATION -============= -Documentation of the API can be found in the doc/ directory. It was autogenerated from the source files by LuaDoc (http://luadoc.luaforge.net/). - -LuaIRC has only been tested on Freenode so far, but I plan to expand this to other servers in the future. It's quite possible that it works on other servers anyway, however, so feel free to try it out, and send in bug reports for things that break. - -CHANGES -======= -0.3 -- Major cleanup and restructuring again, documentation added, first public release -0.2 -- Major cleanup and restructuring -0.1 -- Initial implementation, enough to get it talking to the IRC server - -COPYRIGHT AND LICENSE -===================== -Copyright (C) 2007 Jesse Luehrs - -This code is distributed under the MIT license; a copy is in the LICENSE file distributed with the source. diff --git a/doc/luairc/TODO b/doc/luairc/TODO deleted file mode 100644 index 7fafb6e..0000000 --- a/doc/luairc/TODO +++ /dev/null @@ -1,20 +0,0 @@ -- Reorganize the modules a bit more... we should have a src/irc/dcc/send.lua, src/irc/ctcp/base.lua, src/irc/ctcp/dcc.lua, etc. also, most (all?) of the handlers should be moved out of irc.lua into, say, src/irc/base.lua -- Separate out the DCC module some more so that the callbacks aren't registered unless the module is loaded -- Also separate out all of the CTCP commands/callbacks into the CTCP module -- Rework the way irc.lua uses things from modules - the whole underscore but public thing... do i want to keep that? i suppose it's not horrible... look into this more -- Implement callbacks for user mode changes (need to figure out how to represent users in the callback info) -- Allow a server parameter in whois() so that the returned data can include the user's idle time -- chan:ban()/chan:unban() should take a usermask, not a nick, or be able to generate a usermask from a nick, or something like that -- Clean up misc.split -- Implement DCC CHAT -- Implement DCC XMIT/OFFER -- Implement some more of the newer CTCP commands -- Implement more information requests - - who - - whowas - - info - - stats - - links - - trace (not freenode supported) -- Implement XDCC (?) -- Handle endianness in the IP address conversion functions diff --git a/doc/luairc/index.html b/doc/luairc/index.html deleted file mode 100644 index 7636da2..0000000 --- a/doc/luairc/index.html +++ /dev/null @@ -1,156 +0,0 @@ - - - - Reference - - - - - -
- -
- -
-
-
- -
- - - -
- - - -

Modules

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
callbacksThese are the callbacks that are available to register.
ircLuaIRC - IRC framework written in Lua
irc.channelThis module implements a channel object representing a single channel we have joined.
irc.constantsThis module holds various constants used by the IRC protocol.
irc.ctcpThis module implements the various quoting and escaping requirements of the CTCP protocol.
irc.dccThis module implements the DCC protocol.
irc.debugThis module implements a few useful debug functions for use throughout the rest of the code.
irc.messageThis module contains parsing functions for IRC server messages.
irc.miscThis module contains various useful functions which didn't fit in any of the other modules.
- - - - - - -
- -
- -
-

Valid XHTML 1.0!

-
- -
- - diff --git a/doc/luairc/luadoc.css b/doc/luairc/luadoc.css deleted file mode 100644 index bc0f98a..0000000 --- a/doc/luairc/luadoc.css +++ /dev/null @@ -1,286 +0,0 @@ -body { - margin-left: 1em; - margin-right: 1em; - font-family: arial, helvetica, geneva, sans-serif; - background-color:#ffffff; margin:0px; -} - -code { - font-family: "Andale Mono", monospace; -} - -tt { - font-family: "Andale Mono", monospace; -} - -body, td, th { font-size: 11pt; } - -h1, h2, h3, h4 { margin-left: 0em; } - -textarea, pre, tt { font-size:10pt; } -body, td, th { color:#000000; } -small { font-size:0.85em; } -h1 { font-size:1.5em; } -h2 { font-size:1.25em; } -h3 { font-size:1.15em; } -h4 { font-size:1.06em; } - -a:link { font-weight:bold; color: #004080; text-decoration: none; } -a:visited { font-weight:bold; color: #006699; text-decoration: none; } -a:link:hover { text-decoration:underline; } -hr { color:#cccccc } -img { border-width: 0px; } - - -h3 { padding-top: 1em; } - -p { margin-left: 1em; } - -p.name { - font-family: "Andale Mono", monospace; - padding-top: 1em; - margin-left: 0em; -} - -blockquote { margin-left: 3em; } - -pre.example { - background-color: rgb(245, 245, 245); - border-top-width: 1px; - border-right-width: 1px; - border-bottom-width: 1px; - border-left-width: 1px; - border-top-style: solid; - border-right-style: solid; - border-bottom-style: solid; - border-left-style: solid; - border-top-color: silver; - border-right-color: silver; - border-bottom-color: silver; - border-left-color: silver; - padding: 1em; - margin-left: 1em; - margin-right: 1em; - font-family: "Andale Mono", monospace; - font-size: smaller; -} - - -hr { - margin-left: 0em; - background: #00007f; - border: 0px; - height: 1px; -} - -ul { list-style-type: disc; } - -table.index { border: 1px #00007f; } -table.index td { text-align: left; vertical-align: top; } -table.index ul { padding-top: 0em; margin-top: 0em; } - -table { - border: 1px solid black; - border-collapse: collapse; - margin-left: auto; - margin-right: auto; -} -th { - border: 1px solid black; - padding: 0.5em; -} -td { - border: 1px solid black; - padding: 0.5em; -} -div.header, div.footer { margin-left: 0em; } - -#container -{ - margin-left: 1em; - margin-right: 1em; - background-color: #f0f0f0; -} - -#product -{ - text-align: center; - border-bottom: 1px solid #cccccc; - background-color: #ffffff; -} - -#product big { - font-size: 2em; -} - -#product_logo -{ -} - -#product_name -{ -} - -#product_description -{ -} - -#main -{ - background-color: #f0f0f0; - border-left: 2px solid #cccccc; -} - -#navigation -{ - float: left; - width: 18em; - margin: 0; - vertical-align: top; - background-color: #f0f0f0; - overflow:visible; -} - -#navigation h1 { - background-color:#e7e7e7; - font-size:1.1em; - color:#000000; - text-align:left; - margin:0px; - padding:0.2em; - border-top:1px solid #dddddd; - border-bottom:1px solid #dddddd; -} - -#navigation ul -{ - font-size:1em; - list-style-type: none; - padding: 0; - margin: 1px; -} - -#navigation li -{ - text-indent: -1em; - margin: 0em 0em 0em 0.5em; - display: block; - padding: 3px 0px 0px 12px; -} - -#navigation li li a -{ - padding: 0px 3px 0px -1em; -} - -#content -{ - margin-left: 18em; - padding: 1em; - border-left: 2px solid #cccccc; - border-right: 2px solid #cccccc; - background-color: #ffffff; -} - -#about -{ - clear: both; - margin: 0; - padding: 5px; - border-top: 2px solid #cccccc; - background-color: #ffffff; -} - -@media print { - body { - font: 12pt "Times New Roman", "TimeNR", Times, serif; - } - a { font-weight:bold; color: #004080; text-decoration: underline; } - - #main { background-color: #ffffff; border-left: 0px; } - #container { margin-left: 2%; margin-right: 2%; background-color: #ffffff; } - - #content { margin-left: 0px; padding: 1em; border-left: 0px; border-right: 0px; background-color: #ffffff; } - - #navigation { display: none; - } - pre.example { - font-family: "Andale Mono", monospace; - font-size: 10pt; - page-break-inside: avoid; - } -} - -table.module_list td -{ - border-width: 1px; - padding: 3px; - border-style: solid; - border-color: #cccccc; -} -table.module_list td.name { background-color: #f0f0f0; } -table.module_list td.summary { width: 100%; } - -table.file_list -{ - border-width: 1px; - border-style: solid; - border-color: #cccccc; - border-collapse: collapse; -} -table.file_list td -{ - border-width: 1px; - padding: 3px; - border-style: solid; - border-color: #cccccc; -} -table.file_list td.name { background-color: #f0f0f0; } -table.file_list td.summary { width: 100%; } - - -table.function_list -{ - border-width: 1px; - border-style: solid; - border-color: #cccccc; - border-collapse: collapse; -} -table.function_list td -{ - border-width: 1px; - padding: 3px; - border-style: solid; - border-color: #cccccc; -} -table.function_list td.name { background-color: #f0f0f0; } -table.function_list td.summary { width: 100%; } - - -table.table_list -{ - border-width: 1px; - border-style: solid; - border-color: #cccccc; - border-collapse: collapse; -} -table.table_list td -{ - border-width: 1px; - padding: 3px; - border-style: solid; - border-color: #cccccc; -} -table.table_list td.name { background-color: #f0f0f0; } -table.table_list td.summary { width: 100%; } - -dl.function dt {border-top: 1px solid #ccc; padding-top: 1em;} -dl.function dd {padding-bottom: 1em;} -dl.function h3 {padding: 0; margin: 0; font-size: medium;} - -dl.table dt {border-top: 1px solid #ccc; padding-top: 1em;} -dl.table dd {padding-bottom: 1em;} -dl.table h3 {padding: 0; margin: 0; font-size: medium;} - -#TODO: make module_list, file_list, function_list, table_list inherit from a list - diff --git a/doc/luairc/modules/callbacks.html b/doc/luairc/modules/callbacks.html deleted file mode 100644 index f633e1d..0000000 --- a/doc/luairc/modules/callbacks.html +++ /dev/null @@ -1,858 +0,0 @@ - - - - Reference - - - - - -
- -
- -
-
-
- -
- - - -
- -

Module callbacks

- -

These are the callbacks that are available to register.

- - - -

Functions

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
channel_act (channel, from, message)This callback is triggered whenever a user performs a CTCP ACTION in a channel.
channel_msg (channel, from, message)This callback is triggered whenever a user sends a message to a channel.
channel_notice (channel, from, message)This callback is triggered whenever a user sends a notice to a channel.
connect ()This callback is triggered when the connection has completed.
ctcp_error (from, to, message)This callback is triggered when a CTCP command resulted in an error (for example, if the remote client doesn't implement that CTCP command).
dcc_send (from, to, filename, address, port, filesize)This callback is triggered when a user offers to send you a file using DCC SEND.
deop (channel, from, to)This callback is triggered whenever somebody loses ops.
devoice (channel, from, to)This callback is triggered whenever somebody loses voice.
invite (from, channel)This callback is triggered whenever an invite to a channel is received.
join (channel, from)This callback is triggered when a user joins a channel.
kick (channel, to, from)This callback is triggered when a user is kicked from a channel.
me_join (channel)This callback is triggered after a join() command completes.
nick_change (from, old_nick)This callback is triggered when a user changes their nick.
op (channel, from, to)This callback is triggered when a user is opped.
part (channel, from, message)This callback is triggered when a user leaves a channel.
private_act (from, message)This callback is triggered when a user sends a CTCP ACTION in a private message.
private_msg (from, message)This callback is triggered when a user sends a private message.
private_notice (from, message)This callback is triggered when a user sends a private notice.
quit (from, message)This callback is triggered when a user quits.
topic_change (channel)This callback is triggered when a user changes the topic in a channel.
voice (channel, from, to)This callback is triggered when a user is voiced.
- - - - - - -
-
- - - -

Functions

-
- - - -
channel_act (channel, from, message)
-
-This callback is triggered whenever a user performs a CTCP ACTION in a channel. - - -

Parameters

-
    - -
  • - channel: Channel object for where the action was performed -
  • - -
  • - from: User who performed the action -
  • - -
  • - message: The action which was performed -
  • - -
- - - - - - -
- - - - -
channel_msg (channel, from, message)
-
-This callback is triggered whenever a user sends a message to a channel. - - -

Parameters

-
    - -
  • - channel: Channel object for where the message was sent -
  • - -
  • - from: User who sent the message -
  • - -
  • - message: The message which was sent -
  • - -
- - - - - - -
- - - - -
channel_notice (channel, from, message)
-
-This callback is triggered whenever a user sends a notice to a channel. - - -

Parameters

-
    - -
  • - channel: Channel object for where the notice was sent -
  • - -
  • - from: User who sent the message -
  • - -
  • - message: The notice which was sent -
  • - -
- - - - - - -
- - - - -
connect ()
-
-This callback is triggered when the connection has completed. - - - - - - - -
- - - - -
ctcp_error (from, to, message)
-
-This callback is triggered when a CTCP command resulted in an error (for example, if the remote client doesn't implement that CTCP command). - - -

Parameters

-
    - -
  • - from: User who sent the error response -
  • - -
  • - to: Who the response was sent to (either you or a channel you are in) -
  • - -
  • - message: A description of the error -
  • - -
- - - - - - -
- - - - -
dcc_send (from, to, filename, address, port, filesize)
-
-This callback is triggered when a user offers to send you a file using DCC SEND. It allows you to determine whether or not you want to accept the file. - - -

Parameters

-
    - -
  • - from: User offering the file -
  • - -
  • - to: User who is being offered the file (likely yourself) -
  • - -
  • - filename: Name of the file being offered -
  • - -
  • - address: IP address of the user offering the file -
  • - -
  • - port: Port to connect to at that address -
  • - -
  • - filesize: Size of the file being offered -
  • - -
- - - - -

Return value:

-True to accept the file, false to reject it - - - -
- - - - -
deop (channel, from, to)
-
-This callback is triggered whenever somebody loses ops. - - -

Parameters

-
    - -
  • - channel: Channel object for where the user lost ops -
  • - -
  • - from: User who removed the ops -
  • - -
  • - to: User who lost ops -
  • - -
- - - - - - -
- - - - -
devoice (channel, from, to)
-
-This callback is triggered whenever somebody loses voice. - - -

Parameters

-
    - -
  • - channel: Channel object for where the user lost voice -
  • - -
  • - from: User who removed the voice -
  • - -
  • - to: User who lost voice -
  • - -
- - - - - - -
- - - - -
invite (from, channel)
-
-This callback is triggered whenever an invite to a channel is received. - - -

Parameters

-
    - -
  • - from: User who sent the invite -
  • - -
  • - channel: Channel name that the invite was to -
  • - -
- - - - - - -
- - - - -
join (channel, from)
-
-This callback is triggered when a user joins a channel. - - -

Parameters

-
    - -
  • - channel: Channel object for where there was a join -
  • - -
  • - from: User who joined -
  • - -
- - - - - - -
- - - - -
kick (channel, to, from)
-
-This callback is triggered when a user is kicked from a channel. - - -

Parameters

-
    - -
  • - channel: Channel object for where there was a kick -
  • - -
  • - to: User who was kicked -
  • - -
  • - from: User who did the kicking -
  • - -
- - - - - - -
- - - - -
me_join (channel)
-
-This callback is triggered after a join() command completes. - - -

Parameters

-
    - -
  • - channel: Channel object for the joined channel -
  • - -
- - - - - - -
- - - - -
nick_change (from, old_nick)
-
-This callback is triggered when a user changes their nick. - - -

Parameters

-
    - -
  • - from: User who changed their nick -
  • - -
  • - old_nick: The previous nick of that user -
  • - -
- - - - - - -
- - - - -
op (channel, from, to)
-
-This callback is triggered when a user is opped. - - -

Parameters

-
    - -
  • - channel: Channel object for where the user was opped -
  • - -
  • - from: User who gave the ops -
  • - -
  • - to: User who was opped -
  • - -
- - - - - - -
- - - - -
part (channel, from, message)
-
-This callback is triggered when a user leaves a channel. - - -

Parameters

-
    - -
  • - channel: Channel object for where the part occurred -
  • - -
  • - from: User who left -
  • - -
  • - message: Part message from the user -
  • - -
- - - - - - -
- - - - -
private_act (from, message)
-
-This callback is triggered when a user sends a CTCP ACTION in a private message. - - -

Parameters

-
    - -
  • - from: User who sent the action -
  • - -
  • - message: The action that was sent -
  • - -
- - - - - - -
- - - - -
private_msg (from, message)
-
-This callback is triggered when a user sends a private message. - - -

Parameters

-
    - -
  • - from: User who sent the message -
  • - -
  • - message: The message that was sent -
  • - -
- - - - - - -
- - - - -
private_notice (from, message)
-
-This callback is triggered when a user sends a private notice. - - -

Parameters

-
    - -
  • - from: User who sent the notice -
  • - -
  • - message: The notice that was sent -
  • - -
- - - - - - -
- - - - -
quit (from, message)
-
-This callback is triggered when a user quits. - - -

Parameters

-
    - -
  • - from: User who quit -
  • - -
  • - message: The user's quit message -
  • - -
- - - - - - -
- - - - -
topic_change (channel)
-
-This callback is triggered when a user changes the topic in a channel. The contents of the topic can be seen in the topic field of the channel object. - - -

Parameters

-
    - -
  • - channel: Channel object for where the topic was changed. -
  • - -
- - - - - - -
- - - - -
voice (channel, from, to)
-
-This callback is triggered when a user is voiced. - - -

Parameters

-
    - -
  • - channel: Channel object for where the user was voiced -
  • - -
  • - from: User who gave the voice -
  • - -
  • - to: User who was voiced -
  • - -
- - - - - - -
- - -
- - - - - - -
- -
- -
-

Valid XHTML 1.0!

-
- -
- - diff --git a/doc/luairc/modules/irc.channel.html b/doc/luairc/modules/irc.channel.html deleted file mode 100644 index f061a3c..0000000 --- a/doc/luairc/modules/irc.channel.html +++ /dev/null @@ -1,945 +0,0 @@ - - - - Reference - - - - - -
- -
- -
-
-
- -
- - - -
- -

Module irc.channel

- -

This module implements a channel object representing a single channel we have joined.

- - - -

Functions

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ban (self, name)Ban a user from a channel.
contains (self, nick)Test if a user is in the channel.
deop (self, name)Remove ops from a user.
devoice (self, name)Remove voice from a user.
each_member (self)Iterator over all users in the channel
each_op (self)Iterator over the ops in the channel
each_user (self)Iterator over the normal users in the channel
each_voice (self)Iterator over the voiced users in the channel
members (self)Gets an array of all the users in the channel.
new (chan)Creates a new Channel object.
op (self, name)Give a user ops on a channel.
ops (self)Gets an array of all the ops in the channel.
set_invite_only (self, set)Set whether joining the channel requires an invite.
set_key (self, key)Set a channel password.
set_limit (self, new_limit)Set a channel limit.
set_moderated (self, set)Set whether voice is required to speak.
set_no_outside_messages (self, set)If true, users must be in the channel to send messages to it.
set_private (self, set)Set the private state of a channel.
set_secret (self, set)Set the secret state of a channel.
set_topic_lock (self, set)If true, the topic can only be changed by an op.
unban (self, name)Remove a ban on a user.
users (self)Gets an array of all the normal users in the channel.
voice (self, name)Give a user voice on a channel.
voices (self)Gets an array of all the voiced users in the channel.
- - - - -

Tables

- - - - - - - -
ChannelAn object of the Channel class represents a single joined channel.
- - - -
-
- - - -

Functions

-
- - - -
ban (self, name)
-
-Ban a user from a channel. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
  • - name: User to ban -
  • - -
- - - - - - -
- - - - -
contains (self, nick)
-
-Test if a user is in the channel. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
  • - nick: Nick to search for -
  • - -
- - - - -

Return value:

-True if the nick is in the channel, false otherwise - - - -
- - - - -
deop (self, name)
-
-Remove ops from a user. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
  • - name: User to remove ops from -
  • - -
- - - - - - -
- - - - -
devoice (self, name)
-
-Remove voice from a user. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
  • - name: User to remove voice from -
  • - -
- - - - - - -
- - - - -
each_member (self)
-
-Iterator over all users in the channel - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
- - - - - - -
- - - - -
each_op (self)
-
-Iterator over the ops in the channel - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
- - - - - - -
- - - - -
each_user (self)
-
-Iterator over the normal users in the channel - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
- - - - - - -
- - - - -
each_voice (self)
-
-Iterator over the voiced users in the channel - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
- - - - - - -
- - - - -
members (self)
-
-Gets an array of all the users in the channel. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
- - - - -

Return value:

-Array of channel users - - - -
- - - - -
new (chan)
-
-Creates a new Channel object. - - -

Parameters

-
    - -
  • - chan: Name of the new channel -
  • - -
- - - - -

Return value:

-The new channel instance - - - -
- - - - -
op (self, name)
-
-Give a user ops on a channel. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
  • - name: User to op -
  • - -
- - - - - - -
- - - - -
ops (self)
-
-Gets an array of all the ops in the channel. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
- - - - -

Return value:

-Array of channel ops - - - -
- - - - -
set_invite_only (self, set)
-
-Set whether joining the channel requires an invite. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
  • - set: True to set the channel invite only, false to unset it -
  • - -
- - - - - - -
- - - - -
set_key (self, key)
-
-Set a channel password. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
  • - key: New channel password (optional; password is unset if this argument isn't passed) -
  • - -
- - - - - - -
- - - - -
set_limit (self, new_limit)
-
-Set a channel limit. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
  • - new_limit: New value for the channel limit (optional; limit is unset if this argument isn't passed) -
  • - -
- - - - - - -
- - - - -
set_moderated (self, set)
-
-Set whether voice is required to speak. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
  • - set: True to set the channel as moderated, false to unset it -
  • - -
- - - - - - -
- - - - -
set_no_outside_messages (self, set)
-
-If true, users must be in the channel to send messages to it. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
  • - set: True to require users to be in the channel to send messages to it, false to remove this restriction -
  • - -
- - - - - - -
- - - - -
set_private (self, set)
-
-Set the private state of a channel. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
  • - set: True to set the channel as private, false to unset it -
  • - -
- - - - - - -
- - - - -
set_secret (self, set)
-
-Set the secret state of a channel. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
  • - set: True to set the channel as secret, false to unset it -
  • - -
- - - - - - -
- - - - -
set_topic_lock (self, set)
-
-If true, the topic can only be changed by an op. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
  • - set: True to lock the topic, false to unlock it -
  • - -
- - - - - - -
- - - - -
unban (self, name)
-
-Remove a ban on a user. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
  • - name: User to unban -
  • - -
- - - - - - -
- - - - -
users (self)
-
-Gets an array of all the normal users in the channel. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
- - - - -

Return value:

-Array of channel normal users - - - -
- - - - -
voice (self, name)
-
-Give a user voice on a channel. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
  • - name: User to give voice to -
  • - -
- - - - - - -
- - - - -
voices (self)
-
-Gets an array of all the voiced users in the channel. - - -

Parameters

-
    - -
  • - self: Channel object -
  • - -
- - - - -

Return value:

-Array of channel voiced users - - - -
- - -
- - - - -

Tables

-
- -
Channel
-
An object of the Channel class represents a single joined channel. It has several table fields, and can be used in string contexts (returning the channel name).
- - -Fields -
    - -
  • - name: Name of the channel (read only) -
  • - -
  • - topic: Channel topic, if set (read/write, writing to this sends a topic change request to the server for this channel) -
  • - -
  • - chanmode: Channel mode (public/private/secret) (read only) -
  • - -
  • - members: Array of all members of this channel -
  • - -
- - -
- - -
- - - -
- -
- -
-

Valid XHTML 1.0!

-
- -
- - diff --git a/doc/luairc/modules/irc.constants.html b/doc/luairc/modules/irc.constants.html deleted file mode 100644 index 8a7aa74..0000000 --- a/doc/luairc/modules/irc.constants.html +++ /dev/null @@ -1,117 +0,0 @@ - - - - Reference - - - - - -
- -
- -
-
-
- -
- - - -
- -

Module irc.constants

- -

This module holds various constants used by the IRC protocol.

- - - - - - - - -
-
- - - - - - - - -
- -
- -
-

Valid XHTML 1.0!

-
- -
- - diff --git a/doc/luairc/modules/irc.ctcp.html b/doc/luairc/modules/irc.ctcp.html deleted file mode 100644 index 02e6aae..0000000 --- a/doc/luairc/modules/irc.ctcp.html +++ /dev/null @@ -1,117 +0,0 @@ - - - - Reference - - - - - -
- -
- -
-
-
- -
- - - -
- -

Module irc.ctcp

- -

This module implements the various quoting and escaping requirements of the CTCP protocol.

- - - - - - - - -
-
- - - - - - - - -
- -
- -
-

Valid XHTML 1.0!

-
- -
- - diff --git a/doc/luairc/modules/irc.dcc.html b/doc/luairc/modules/irc.dcc.html deleted file mode 100644 index 0dc0a6d..0000000 --- a/doc/luairc/modules/irc.dcc.html +++ /dev/null @@ -1,164 +0,0 @@ - - - - Reference - - - - - -
- -
- -
-
-
- -
- - - -
- -

Module irc.dcc

- -

This module implements the DCC protocol. File transfers (DCC SEND) are handled, but DCC CHAT is not, as of yet.

- - - -

Functions

- - - - - - - -
send (nick, filename, port)Offers a file to a remote user.
- - - - - - -
-
- - - -

Functions

-
- - - -
send (nick, filename, port)
-
-Offers a file to a remote user. - - -

Parameters

-
    - -
  • - nick: User to offer the file to -
  • - -
  • - filename: Filename to offer -
  • - -
  • - port: Port to accept connections on (optional, defaults to choosing an available port between FIRST_PORT and LAST_PORT above) -
  • - -
- - - - - - -
- - -
- - - - - - -
- -
- -
-

Valid XHTML 1.0!

-
- -
- - diff --git a/doc/luairc/modules/irc.debug.html b/doc/luairc/modules/irc.debug.html deleted file mode 100644 index b6377e0..0000000 --- a/doc/luairc/modules/irc.debug.html +++ /dev/null @@ -1,196 +0,0 @@ - - - - Reference - - - - - -
- -
- -
-
-
- -
- - - -
- -

Module irc.debug

- -

This module implements a few useful debug functions for use throughout the rest of the code.

- - - -

Functions

- - - - - - - - - - - - - - - - - -
disable ()Turns off debug output.
enable ()Turns on debug output.
set_output (file)Redirects output to a file rather than stdout.
- - - - - - -
-
- - - -

Functions

-
- - - -
disable ()
-
-Turns off debug output. - - - - - - - -
- - - - -
enable ()
-
-Turns on debug output. - - - - - - - -
- - - - -
set_output (file)
-
-Redirects output to a file rather than stdout. - - -

Parameters

-
    - -
  • - file: File to write debug output to -
  • - -
- - - - - - -
- - -
- - - - - - -
- -
- -
-

Valid XHTML 1.0!

-
- -
- - diff --git a/doc/luairc/modules/irc.html b/doc/luairc/modules/irc.html deleted file mode 100644 index 0556fef..0000000 --- a/doc/luairc/modules/irc.html +++ /dev/null @@ -1,683 +0,0 @@ - - - - Reference - - - - - -
- -
- -
-
-
- -
- - - -
- -

Module irc

- -

LuaIRC - IRC framework written in Lua

- -

Release: 0.3

- - - -

Functions

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
act (name, action)Perform a /me action.
channels ()Iterate over currently joined channels.
connect (args)Start a connection to the irc server.
ctcp_ping (cb, nick)Send a CTCP ping request.
ctcp_time (cb, nick)Send a localtime request.
ctcp_version (cb, nick)Send a client version request.
get_ip ()Get the local IP address for the server connection.
join (channel)Join a channel.
notice (name, message)Send a notice to a user or channel.
part (channel)Leave a channel.
quit (message)Close the connection to the irc server.
register_callback (name, fn)Register a user function to be called when a specific event occurs.
say (name, message)Send a message to a user or channel.
send (command, ...)Send a raw IRC command.
server_time (cb)Request the current time of the server you are connected to.
server_version (cb)Request the version of the IRC server you are currently connected to.
set_ip (new_ip)Set the local IP manually (to allow for NAT workarounds)
whois (cb, nick)Request WHOIS information about a given user.
- - - - - - -
-
- - - -

Functions

-
- - - -
act (name, action)
-
-Perform a /me action. - - -

Parameters

-
    - -
  • - name: User or channel to send the action to -
  • - -
  • - action: Action to send -
  • - -
- - - - - - -
- - - - -
channels ()
-
-Iterate over currently joined channels. channels() is an iterator function for use in for loops. For example,
for chan in irc.channels() do print(chan:name) end
- - - - - - - -See also: - - - irc.channel - - - - -
- - - - -
connect (args)
-
-Start a connection to the irc server. - - -

Parameters

-
    - -
  • - args: Table of named arguments containing connection parameters. Defaults are the all-caps versions of these parameters given at the top of the file, and are overridable by setting them as well, i.e.
    irc.NETWORK = irc.freenode.net
    Possible options are:
    • network: address of the irc network to connect to (default: 'localhost')
    • port: port to connect to (default: '6667')
    • pass: irc server password (default: don't send)
    • nick: nickname to connect as (default: 'luabot')
    • username: username to connect with (default: 'LuaIRC')
    • realname: realname to connect with (default: 'LuaIRC')
    • timeout: amount of time in seconds to wait before dropping an idle connection (default: '60')
    -
  • - -
- - - - - - -
- - - - -
ctcp_ping (cb, nick)
-
-Send a CTCP ping request. - - -

Parameters

-
    - -
  • - cb: Callback to call when the information is available. The single table parameter to this callback will contain the fields:
    • nick: the nick which responded to the request
    • time: the roundtrip ping time, in seconds
    -
  • - -
  • - nick: User to ping -
  • - -
- - - - - - -
- - - - -
ctcp_time (cb, nick)
-
-Send a localtime request. - - -

Parameters

-
    - -
  • - cb: Callback to call when the information is available. The single table parameter to this callback will contain the fields:
    • nick: the nick which responded to the request
    • time: the localtime reported by the remote client
    -
  • - -
  • - nick: User to request the localtime from -
  • - -
- - - - - - -
- - - - -
ctcp_version (cb, nick)
-
-Send a client version request. - - -

Parameters

-
    - -
  • - cb: Callback to call when the information is available. The single table parameter to this callback will contain the fields:
    • nick: the nick which responded to the request
    • version: the version reported by the remote client
    -
  • - -
  • - nick: User to request the client version from -
  • - -
- - - - - - -
- - - - -
get_ip ()
-
-Get the local IP address for the server connection. - - - - - -

Return value:

-A string representation of the local IP address that the IRC server connection is communicating on - - - -
- - - - -
join (channel)
-
-Join a channel. - - -

Parameters

-
    - -
  • - channel: Channel to join -
  • - -
- - - - - - -
- - - - -
notice (name, message)
-
-Send a notice to a user or channel. - - -

Parameters

-
    - -
  • - name: User or channel to send the notice to -
  • - -
  • - message: Message to send -
  • - -
- - - - - - -
- - - - -
part (channel)
-
-Leave a channel. - - -

Parameters

-
    - -
  • - channel: Channel to leave -
  • - -
- - - - - - -
- - - - -
quit (message)
-
-Close the connection to the irc server. - - -

Parameters

-
    - -
  • - message: Quit message (optional, defaults to 'Leaving') -
  • - -
- - - - - - -
- - - - -
register_callback (name, fn)
-
-Register a user function to be called when a specific event occurs. - - -

Parameters

-
    - -
  • - name: Name of the event -
  • - -
  • - fn: Function to call when the event occurs, or nil to clear the callback for this event -
  • - -
- - - - -

Return value:

-Value of the original callback for this event (or nil if no previous callback had been set) - - - -
- - - - -
say (name, message)
-
-Send a message to a user or channel. - - -

Parameters

-
    - -
  • - name: User or channel to send the message to -
  • - -
  • - message: Message to send -
  • - -
- - - - - - -
- - - - -
send (command, ...)
-
-Send a raw IRC command. - - -

Parameters

-
    - -
  • - command: String containing the raw IRC command -
  • - -
  • - ...: Arguments to the command. Each argument is either a string or an array. Strings are sent literally, arrays are CTCP quoted as a group. The last argument (if it exists) is preceded by a : (so it may contain spaces). -
  • - -
- - - - - - -
- - - - -
server_time (cb)
-
-Request the current time of the server you are connected to. - - -

Parameters

-
    - -
  • - cb: Callback to call when the information is available. The single table parameter to this callback will contain the fields:
    • server: the server which responded to the request
    • time: the time reported by the server
    -
  • - -
- - - - - - -
- - - - -
server_version (cb)
-
-Request the version of the IRC server you are currently connected to. - - -

Parameters

-
    - -
  • - cb: Callback to call when the information is available. The single table parameter to this callback will contain the fields:
    • server: the server which responded to the request
    • version: the server version
    • comments: other data provided by the server
    -
  • - -
- - - - - - -
- - - - -
set_ip (new_ip)
-
-Set the local IP manually (to allow for NAT workarounds) - - -

Parameters

-
    - -
  • - new_ip: IP address to set -
  • - -
- - - - - - -
- - - - -
whois (cb, nick)
-
-Request WHOIS information about a given user. - - -

Parameters

-
    - -
  • - cb: Callback to call when the information is available. The single table parameter to this callback may contain any or all of the fields:
    • nick: the nick that was passed to this function (this field will always be here)
    • user: the IRC username of the user
    • host: the user's hostname
    • realname: the IRC realname of the user
    • server: the IRC server the user is connected to
    • serverinfo: arbitrary information about the above server
    • awaymsg: set to the user's away message if they are away
    • is_oper: true if the user is an IRCop
    • idle_time: amount of time the user has been idle
    • channels: array containing the channels the user has joined
    -
  • - -
  • - nick: User to request WHOIS information about -
  • - -
- - - - - - -
- - -
- - - - - - -
- -
- -
-

Valid XHTML 1.0!

-
- -
- - diff --git a/doc/luairc/modules/irc.message.html b/doc/luairc/modules/irc.message.html deleted file mode 100644 index a4ed396..0000000 --- a/doc/luairc/modules/irc.message.html +++ /dev/null @@ -1,117 +0,0 @@ - - - - Reference - - - - - -
- -
- -
-
-
- -
- - - -
- -

Module irc.message

- -

This module contains parsing functions for IRC server messages.

- - - - - - - - -
-
- - - - - - - - -
- -
- -
-

Valid XHTML 1.0!

-
- -
- - diff --git a/doc/luairc/modules/irc.misc.html b/doc/luairc/modules/irc.misc.html deleted file mode 100644 index df87d89..0000000 --- a/doc/luairc/modules/irc.misc.html +++ /dev/null @@ -1,117 +0,0 @@ - - - - Reference - - - - - -
- -
- -
-
-
- -
- - - -
- -

Module irc.misc

- -

This module contains various useful functions which didn't fit in any of the other modules.

- - - - - - - - -
-
- - - - - - - - -
- -
- -
-

Valid XHTML 1.0!

-
- -
- - diff --git a/doc/luasocket/LICENSE b/doc/luasocket/LICENSE deleted file mode 100644 index 90d88e7..0000000 --- a/doc/luasocket/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -LuaSocket 2.0 license -Copyright © 2004-2005 Diego Nehab - -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. diff --git a/doc/luasocket/NEW b/doc/luasocket/NEW deleted file mode 100644 index 7c94368..0000000 --- a/doc/luasocket/NEW +++ /dev/null @@ -1,54 +0,0 @@ -What's New - -There is no big change for the 2.0 (final) release. It is -basically a bug fix release. The main improvement is in the -non-blocking support. - - * New: sample module dispatch.lua implements a coroutine - based dispatcher; - * New: sample check-links.lua works both in blocking and - non-blocking mode using coroutines (using the new - dispatcher); - * New: sample forward.lua implements a coroutine based - forward server (using the new dispatcher); - * Improved: tcp:send(data, i, j) to return (i+sent-1). This - is great for non-blocking I/O, but might break some code; - * Improved: HTTP, SMTP, and FTP functions to accept a new - field create that overrides the function used to create - socket objects; - * Improved: smtp.message now supports multipart/alternative - (for the HTML messages we all love so much); - * Fixed: smtp.send was hanging on errors returned by LTN12 - sources; - * Fixed: url.absolute() to work when base_url is in parsed - form; - * Fixed: http.request() not to redirect when the location - header is empty (naughty servers...); - * Fixed: tcp{client}:shutdown() to check for class instead - of group; - * Fixed: The manual to stop using socket.try() in place of - assert(), since it can't; - * Improved: Got rid of package.loaded.base = _G kludge; - * Fixed: Parts of the manual referred to require("http") - instead of require("socket.http"); - * Improved: Socket and MIME binaries are called 'core' each - inside their directory (ex. "socket/core.dll"). The 'l' - prefix was just a bad idea; - * Improved: Using bundles in Mac OS X, instead of dylibs; - * Fixed: luasocket.h to export luaopen_socket_core; - * Fixed: udp:setpeername() so you can "disconnect" an UDP - socket; - * Fixed: A weird bug in HTTP support that caused some - requests to fail (Florian Berger); - * Fixed: Bug in socket.select() that caused sockets with - descriptor 0 to be ignored (Renato Maia); - * Fixed: "Bug" that caused dns.toip() to crash under uLinux - (William Trenker); - * Fixed: "Bug" that caused gethostbyname to crash under VMS - (Renato Maia); - * Fixed: tcp:send("") to return 0 bytes sent (Alexander - Marinov); - * Improved: socket.DEBUG and socket.VERSION became - socket._DEBUGs and socket._VERSION for uniformity with other - libraries; - * Improved: socket.select now works on empty sets on Windows. diff --git a/doc/luasocket/README b/doc/luasocket/README deleted file mode 100644 index acb4dfe..0000000 --- a/doc/luasocket/README +++ /dev/null @@ -1,6 +0,0 @@ -This is the LuaSocket 2.0. It has been tested on WinXP, Mac OS X, -and Linux. Please use the Lua mailing list to report any bugs -(or "features") you encounter. - -Have fun, -Diego Nehab. diff --git a/doc/luasocket/dns.html b/doc/luasocket/dns.html deleted file mode 100644 index 826e4a2..0000000 --- a/doc/luasocket/dns.html +++ /dev/null @@ -1,132 +0,0 @@ - - - - - - -LuaSocket: DNS support - - - - - - - -
-
-
- - - -
-LuaSocket -
Network support for the Lua language -
-

-home · -download · -installation · -introduction · -reference -

-
-
-
- - - -

DNS

- -

-Name resolution functions return all information obtained from the -resolver in a table of the form: -

- -
-resolved = {
-  name = canonic-name,
-  alias = alias-list,
-  ip = ip-address-list
-} -
- -

-Note that the alias list can be empty. -

- - - -

-socket.dns.gethostname() -

- -

-Returns the standard host name for the machine as a string. -

- - - -

-socket.dns.tohostname(address) -

- -

-Converts from IP address to host name. -

- -

-Address can be an IP address or host name. -

- -

-The function returns a string with the canonic host name of the given -address, followed by a table with all information returned by -the resolver. In case of error, the function returns nil -followed by an error message. -

- - - -

-socket.dns.toip(address) -

- -

-Converts from host name to IP address. -

- -

-Address can be an IP address or host name. -

- -

-Returns a string with the first IP address found for address, -followed by a table with all information returned by the resolver. -In case of error, the function returns nil followed by an error -message. -

- - - - - - - diff --git a/doc/luasocket/ftp.html b/doc/luasocket/ftp.html deleted file mode 100644 index 4398a2a..0000000 --- a/doc/luasocket/ftp.html +++ /dev/null @@ -1,289 +0,0 @@ - - - - - - -LuaSocket: FTP support - - - - - - - -
-
-
- - - -
-LuaSocket -
Network support for the Lua language -
-

-home · -download · -installation · -introduction · -reference -

-
-
-
- - - -

FTP

- -

-FTP (File Transfer Protocol) is a protocol used to transfer files -between hosts. The ftp namespace offers thorough support -to FTP, under a simple interface. The implementation conforms to -RFC 959. -

- -

-High level functions are provided supporting the most common operations. -These high level functions are implemented on top of a lower level -interface. Using the low-level interface, users can easily create their -own functions to access any operation supported by the FTP -protocol. For that, check the implementation. -

- -

-To really benefit from this module, a good understanding of - -LTN012, Filters sources and sinks is necessary. -

- -

-To obtain the ftp namespace, run: -

- -
--- loads the FTP module and any libraries it requires
-local ftp = require("socket.ftp")
-
- -

-URLs MUST conform to -RFC -1738, that is, an URL is a string in the form: -

- -
- -[ftp://][<user>[:<password>]@]<host>[:<port>][/<path>][type=a|i] -
- -

-The following constants in the namespace can be set to control the default behavior of -the FTP module: -

- -
    -
  • PASSWORD: default anonymous password. -
  • PORT: default port used for the control connection; -
  • TIMEOUT: sets the timeout for all I/O operations; -
  • USER: default anonymous user; -
- - - - -

-ftp.get(url)
-ftp.get{
-  host = string,
-  sink = LTN12 sink,
-  argument or path = string,
-  [user = string,]
-  [password = string]
-  [command = string,]
-  [port = number,]
-  [type = string,]
-  [step = LTN12 pump step,]
-  [create = function]
-} -

- -

-The get function has two forms. The simple form has fixed -functionality: it downloads the contents of a URL and returns it as a -string. The generic form allows a lot more control, as explained -below. -

- -

-If the argument of the get function is a table, the function -expects at least the fields host, sink, and one of -argument or path (argument takes -precedence). Host is the server to connect to. Sink is -the simple -LTN12 -sink that will receive the downloaded data. Argument or -path give the target path to the resource in the server. The -optional arguments are the following: -

-
    -
  • user, password: User name and password used for -authentication. Defaults to "ftp:anonymous@anonymous.org"; -
  • command: The FTP command used to obtain data. Defaults to -"retr", but see example below; -
  • port: The port to used for the control connection. Defaults to 21; -
  • type: The transfer mode. Can take values "i" or -"a". Defaults to whatever is the server default; -
  • step: -LTN12 -pump step function used to pass data from the -server to the sink. Defaults to the LTN12 pump.step function; -
  • create: An optional function to be used instead of -socket.tcp when the communications socket is created. -
- -

-If successful, the simple version returns the URL contents as a -string, and the generic function returns 1. In case of error, both -functions return nil and an error message describing the -error. -

- -
--- load the ftp support
-local ftp = require("socket.ftp")
-
--- Log as user "anonymous" on server "ftp.tecgraf.puc-rio.br",
--- and get file "lua.tar.gz" from directory "pub/lua" as binary.
-f, e = ftp.get("ftp://ftp.tecgraf.puc-rio.br/pub/lua/lua.tar.gz;type=i")
-
- -
--- load needed modules
-local ftp = require("socket.ftp")
-local ltn12 = require("ltn12")
-local url = require("socket.url")
-
--- a function that returns a directory listing
-function nlst(u)
-    local t = {}
-    local p = url.parse(u)
-    p.command = "nlst"
-    p.sink = ltn12.sink.table(t)
-    local r, e = ftp.get(p)
-    return r and table.concat(t), e
-end
-
- - - -

-ftp.put(url, content)
-ftp.put{
-  host = string,
-  source = LTN12 sink,
-  argument or path = string,
-  [user = string,]
-  [password = string]
-  [command = string,]
-  [port = number,]
-  [type = string,]
-  [step = LTN12 pump step,]
-  [create = function]
-} -

- -

-The put function has two forms. The simple form has fixed -functionality: it uploads a string of content into a URL. The generic form -allows a lot more control, as explained below. -

- -

-If the argument of the put function is a table, the function -expects at least the fields host, source, and one of -argument or path (argument takes -precedence). Host is the server to connect to. Source is -the simple -LTN12 -source that will provide the contents to be uploaded. -Argument or -path give the target path to the resource in the server. The -optional arguments are the following: -

-
    -
  • user, password: User name and password used for -authentication. Defaults to "ftp:anonymous@anonymous.org"; -
  • command: The FTP command used to send data. Defaults to -"stor", but see example below; -
  • port: The port to used for the control connection. Defaults to 21; -
  • type: The transfer mode. Can take values "i" or -"a". Defaults to whatever is the server default; -
  • step: -LTN12 -pump step function used to pass data from the -server to the sink. Defaults to the LTN12 pump.step function; -
  • create: An optional function to be used instead of -socket.tcp when the communications socket is created. -
- -

-Both functions return 1 if successful, or nil and an error -message describing the reason for failure. -

- -
--- load the ftp support
-local ftp = require("socket.ftp")
-
--- Log as user "fulano" on server "ftp.example.com",
--- using password "silva", and store a file "README" with contents 
--- "wrong password, of course"
-f, e = ftp.put("ftp://fulano:silva@ftp.example.com/README", 
-    "wrong password, of course")
-
- -
--- load the ftp support
-local ftp = require("socket.ftp")
-local ltn12 = require("ltn12")
-
--- Log as user "fulano" on server "ftp.example.com",
--- using password "silva", and append to the remote file "LOG", sending the
--- contents of the local file "LOCAL-LOG"
-f, e = ftp.put{
-  host = "ftp.example.com", 
-  user = "fulano",
-  password = "silva",
-  command = "appe",
-  argument = "LOG",
-  source = ltn12.source.file(io.open("LOCAL-LOG", "r"))
-}
-
- - - - - - - - diff --git a/doc/luasocket/home.html b/doc/luasocket/home.html deleted file mode 100644 index 06369a7..0000000 --- a/doc/luasocket/home.html +++ /dev/null @@ -1,256 +0,0 @@ - - - - - - -LuaSocket: Network support for the Lua language - - - - - - - -
-
-
- - - -
-LuaSocket -
Network support for the Lua language -
-

-home · -download · -installation · -introduction · -reference -

-
-
-
- - - -

What is LuaSocket?

- -

-LuaSocket is a Lua extension library -that is composed by two parts: a C core that provides support for the TCP -and UDP transport layers, and a set of Lua modules that add support for -functionality commonly needed by applications that deal with the Internet. -

- -

-The core support has been implemented so that it is both efficient and -simple to use. It is available to any Lua application once it has been -properly initialized by the interpreter in use. The code has been tested -and runs well on several Windows and Unix platforms.

- -

-Among the support modules, the most commonly used implement the -SMTP -(sending e-mails), -HTTP -(WWW access) and -FTP -(uploading and downloading files) client -protocols. These provide a very natural and generic interface to the -functionality defined by each protocol. -In addition, you will find that the -MIME (common encodings), -URL -(anything you could possible want to do with one) and -LTN12 -(filters, sinks, sources and pumps) modules can be very handy. -

- -

-The library is available under the same - -terms and conditions as the Lua language, the MIT license. The idea is -that if you can use Lua in a project, you should also be able to use -LuaSocket. -

- -

-Copyright © 2004-2005 Diego Nehab. All rights reserved.
-Author: Diego Nehab -

- - - -

Download

- -

-LuaSocket version 2.0 (final) is now available for download! It is -compatible with Lua 5.0 and has been tested on -Windows XP, Linux, and Mac OS X. -

- -

-The library can be downloaded in source code from the -LuaSocket -project page at LuaForge. -Besides the full C and Lua source code for the library, the distribution -contains several examples, this user's manual and basic test procedures. -

- -

-Danilo Tuler is maintaining Win32 binaries for LuaSocket, which are also -available from LuaForge. These are compatible with the -LuaBinaries -available from LuaForge. -

- -

-For those that want to give LuaSocket a quick try, download the -stand-alone archive and unpack everything into -a directory, say c:\luasocket. Then set LUA_INIT to load -the compat-5.1.lua and set LUA_PATH and -LUA_CPATH to look for files in the current directory: -

- -
-c:\luasocket\> set LUA_INIT=@c:\luasocket\compat-5.1.lua
-c:\luasocket\> set LUA_CPATH=?.dll
-c:\luasocket\> set LUA_PATH=?.lua
-
- -

-From that directory, you can then run the interpreter and it should find all -files it needs. To download this manual page from the Internet, for example, -do the following: -

- -
-c:\luasocket\> lua50
-Lua 5.0.2  Copyright (C) 1994-2004 Tecgraf, PUC-Rio
-> http = require"socket.http"
-> print(http.request"http://www.cs.princeton.edu/~diego/professional/luasocket/")
---> the source to this web page gets dumped to terminal
-
- -

When you are done playing, take a look at the -installation section of the manual to find out -how to properly install the library.

- - - -

Special thanks

- -

-Throughout LuaSocket's history, many people gave suggestions that helped -improve it. For that, I thank the Lua community. -Special thanks go to -David Burgess, who has helped push the library to a new level of quality and -from whom I have learned a lot of stuff that doesn't show up in RFCs. -Special thanks also to Carlos Cassino, who played a big part in the -extensible design seen in the C core of LuaSocket 2.0. Recently, Mike Pall -has been helping a lot too! Thanks to you all! -

- - - -

What's New

- -

-There is no big change for the 2.0 (final) release. It is basically a -bug fix release. The only improvement is in the non-blocking -support. -

- -
    -
  • New: sample module dispatch.lua implements a -coroutine based dispatcher; -
  • New: sample check-links.lua works -both in blocking and non-blocking mode using coroutines -(using the new dispatcher); -
  • New: sample forward.lua implements a coroutine -based forward server (using the new dispatcher); -
  • Improved: tcp:send(data, i, j) to return (i+sent-1). This is great for non-blocking I/O, but might break some code; -
  • Improved: HTTP, SMTP, and FTP functions to accept a new field -create that overrides the function used to create socket objects; -
  • Improved: smtp.message now supports multipart/alternative -(for the HTML messages we all love so much); -
  • Fixed: smtp.send was hanging on errors returned by LTN12 sources; -
  • Fixed: url.absolute() to work when base_url is in -parsed form; -
  • Fixed: http.request() not to redirect when the location -header is empty (naughty servers...); -
  • Fixed: tcp{client}:shutdown() to check for class instead of -group; -
  • Fixed: The manual to stop using socket.try() in place of -assert(), since it can't; -
  • Improved: Got rid of package.loaded.base = _G kludge; -
  • Fixed: Parts of the manual referred to require("http") instead of -require("socket.http"); -
  • Improved: Socket and MIME binaries are called 'core' each inside their -directory (ex. "socket/core.dll"). The 'l' prefix was just a bad idea; -
  • Improved: Using bundles in Mac OS X, instead of dylibs; -
  • Fixed: luasocket.h to export luaopen_socket_core; -
  • Fixed: udp:setpeername() so you can "disconnect" an -UDP socket; -
  • Fixed: A weird bug in HTTP support that caused some requests to -fail (Florian Berger); -
  • Fixed: Bug in socket.select() that caused sockets -with descriptor 0 to be ignored (Renato Maia); -
  • Fixed: "Bug" that caused dns.toip() to crash under uLinux -(William Trenker); -
  • Fixed: "Bug" that caused gethostbyname to crash under VMS -(Renato Maia); -
  • Fixed: tcp:send("") to return 0 bytes sent (Alexander Marinov); -
  • Improved: socket.DEBUG and socket.VERSION became socket._DEBUGs and socket._VERSION for uniformity with other libraries; -
  • Improved: socket.select now works on empty sets on Windows. -
- - - -

Incompatibilities with previous versions

- -
    -
  • If you use the return value of tcp:send() and you -use the extra parameters to select only part of the string to be sent, your -code is now broken, but when you fix it, it will be much simpler; -
  • If you check socket.DEBUG or socket.VERSION, -change it to socket._DEBUG or socket._VERSION. -
- - - -

Old Versions

- -

-All previous versions of the LuaSocket library can be downloaded -here. Although these versions are no longer supported, they are -still available for those that have compatibility issues. -

- - - - - - - diff --git a/doc/luasocket/http.html b/doc/luasocket/http.html deleted file mode 100644 index a60ed25..0000000 --- a/doc/luasocket/http.html +++ /dev/null @@ -1,325 +0,0 @@ - - - - - - -LuaSocket: HTTP support - - - - - - - -
-
-
- - - -
-LuaSocket -
Network support for the Lua language -
-

-home · -download · -introduction · -introduction · -reference -

-
-
-
- - - -

HTTP

- -

-HTTP (Hyper Text Transfer Protocol) is the protocol used to exchange -information between web-browsers and servers. The http -namespace offers full support for the client side of the HTTP -protocol (i.e., -the facilities that would be used by a web-browser implementation). The -implementation conforms to the HTTP/1.1 standard, -RFC -2616. -

- -

-The module exports functions that provide HTTP functionality in different -levels of abstraction. From the simple -string oriented requests, through generic -LTN12 based, down to even lower-level if you bother to look through the source code. -

- -

-To obtain the http namespace, run: -

- -
--- loads the HTTP module and any libraries it requires
-local http = require("socket.http")
-
- -

-URLs must conform to -RFC -1738, -that is, an URL is a string in the form: -

- -
-
-[http://][<user>[:<password>]@]<host>[:<port>][/<path>] 
-
-
- -

-MIME headers are represented as a Lua table in the form: -

- -
- - -
-headers = {
-  field-1-name = field-1-value,
-  field-2-name = field-2-value,
-  field-3-name = field-3-value,
-  ...
-  field-n-name = field-n-value
-} -
-
- -

-Field names are case insensitive (as specified by the standard) and all -functions work with lowercase field names. -Field values are left unmodified. -

- -

-Note: MIME headers are independent of order. Therefore, there is no problem -in representing them in a Lua table. -

- -

-The following constants can be set to control the default behavior of -the HTTP module: -

- -
    -
  • PORT: default port used for connections; -
  • PROXY: default proxy used for connections; -
  • TIMEOUT: sets the timeout for all I/O operations; -
  • USERAGENT: default user agent reported to server. -
- - - -

-http.request(url [, body])
-http.request{
-  url = string,
-  [sink = LTN12 sink,]
-  [method = string,]
-  [headers = header-table,]
-  [source = LTN12 source],
-  [step = LTN12 pump step,]
-  [proxy = string,]
-  [redirect = boolean,]
-  [create = function]
-} -

- -

-The request function has two forms. The simple form downloads -a URL using the GET or POST method and is based -on strings. The generic form performs any HTTP method and is -LTN12 based. -

- -

-If the first argument of the request function is a string, it -should be an url. In that case, if a body -is provided as a string, the function will perform a POST method -in the url. Otherwise, it performs a GET in the -url -

- -

-If the first argument is instead a table, the most important fields are -the url and the simple -LTN12 -sink that will receive the downloaded content. -Any part of the url can be overridden by including -the appropriate field in the request table. -If authentication information is provided, the function -uses the Basic Authentication Scheme (see note) -to retrieve the document. If sink is nil, the -function discards the downloaded data. The optional parameters are the -following: -

-
    -
  • method: The HTTP request method. Defaults to "GET"; -
  • headers: Any additional HTTP headers to send with the request; -
  • source: simple -LTN12 -source to provide the request body. If there -is a body, you need to provide an appropriate "content-length" -request header field, or the function will attempt to send the body as -"chunked" (something few servers support). Defaults to the empty source; -
  • step: -LTN12 -pump step function used to move data. -Defaults to the LTN12 pump.step function. -
  • proxy: The URL of a proxy server to use. Defaults to no proxy; -
  • redirect: Set to false to prevent the -function from automatically following 301 or 302 server redirect messages; -
  • create: An optional function to be used instead of -socket.tcp when the communications socket is created. -
- -

-In case of failure, the function returns nil followed by an -error message. If successful, the simple form returns the response -body as a string, followed by the response status code, the response -headers and the response status line. The complex function returns the same -information, except the first return value is just the number 1 (the body -goes to the sink). -

- -

-Even when the server fails to provide the contents of the requested URL (URL not found, for example), -it usually returns a message body (a web page informing the -URL was not found or some other useless page). To make sure the -operation was successful, check the returned status code. For -a list of the possible values and their meanings, refer to RFC -2616. -

- -

-Here are a few examples with the simple interface: -

- -
--- load the http module
-local io = require("io")
-local http = require("socket.http")
-local ltn12 = require("ltn12")
-
--- connect to server "www.cs.princeton.edu" and retrieves this manual
--- file from "~diego/professional/luasocket/http.html" and print it to stdout
-http.request{ 
-    url = "http://www.cs.princeton.edu/~diego/professional/luasocket/http.html", 
-    sink = ltn12.sink.file(io.stdout)
-}
-
--- connect to server "www.example.com" and tries to retrieve
--- "/private/index.html". Fails because authentication is needed.
-b, c, h = http.request("http://www.example.com/private/index.html")
--- b returns some useless page telling about the denied access, 
--- h returns authentication information
--- and c returns with value 401 (Authentication Required)
-
--- tries to connect to server "wrong.host" to retrieve "/"
--- and fails because the host does not exist.
-r, e = http.request("http://wrong.host/")
--- r is nil, and e returns with value "host not found"
-
- -

-And here is an example using the generic interface: -

- -
--- load the http module
-http = require("socket.http")
-
--- Requests information about a document, without downloading it.
--- Useful, for example, if you want to display a download gauge and need
--- to know the size of the document in advance
-r, c, h = http.request {
-  method = "HEAD",
-  url = "http://www.tecgraf.puc-rio.br/~diego"
-}
--- r is 1, c is 200, and h would return the following headers:
--- h = {
---   date = "Tue, 18 Sep 2001 20:42:21 GMT",
---   server = "Apache/1.3.12 (Unix)  (Red Hat/Linux)",
---   ["last-modified"] = "Wed, 05 Sep 2001 06:11:20 GMT",
---   ["content-length"] = 15652,
---   ["connection"] = "close",
---   ["content-Type"] = "text/html"
--- }
-
- -

-Note: Some URLs are protected by their -servers from anonymous download. For those URLs, the server must receive -some sort of authentication along with the request or it will deny -download and return status "401 Authentication Required". -

- -

-The HTTP/1.1 standard defines two authentication methods: the Basic -Authentication Scheme and the Digest Authentication Scheme, both -explained in detail in -RFC 2068. -

- -

The Basic Authentication Scheme sends -<user> and -<password> unencrypted to the server and is therefore -considered unsafe. Unfortunately, by the time of this implementation, -the wide majority of servers and browsers support the Basic Scheme only. -Therefore, this is the method used by the toolkit whenever -authentication is required. -

- -
--- load required modules
-http = require("socket.http")
-mime = require("mime")
-
--- Connect to server "www.example.com" and tries to retrieve
--- "/private/index.html", using the provided name and password to
--- authenticate the request
-b, c, h = http.request("http://fulano:silva@www.example.com/private/index.html")
-
--- Alternatively, one could fill the appropriate header and authenticate
--- the request directly.
-r, c = http.request {
-  url = "http://www.example.com/private/index.html",
-  headers = { authentication = "Basic " .. (mime.b64("fulano:silva")) }
-}
-
- - - - - - - diff --git a/doc/luasocket/installation.html b/doc/luasocket/installation.html deleted file mode 100644 index fa1d96f..0000000 --- a/doc/luasocket/installation.html +++ /dev/null @@ -1,161 +0,0 @@ - - - - - - -LuaSocket: Installation - - - - - - - -
-
-
- - - -
-LuaSocket -
Network support for the Lua language -
-

-home · -download · -installation · -introduction · -reference -

-
-
-
- - - -

Installation

- -

LuaSocket 2.0 uses the new package proposal for Lua 5.1. -All Lua library developers are encouraged to update their libraries so that -all libraries can coexist peacefully and users can benefit from the -standardization and flexibility of the standard. -

- -

-The proposal was considered important enough by some of us to justify -early adoption, even before release of Lua 5.1. -Thus, a compatibility module -compat-5.1 -has been released in conjunction with Roberto Ierusalimschy and The Kepler Project team. -It implements the Lua 5.1 package proposal on top of Lua 5.0.

- -

As far as LuaSocket is concerned, this means that whoever is -deploying a non-standard distribution of LuaSocket will probably -have no problems customizing it. Here we will only describe the standard distribution. If the standard doesn't meet your -needs, we refer you to the Lua discussion list, where any question about -the package scheme will likely already have been answered. -

- -

Directory structure

- -

On Unix systems, the standard distribution uses two base -directories, one for system dependent files, and another for system -independent files. Let's call these directories <CDIR> -and <LDIR>, respectively. -For instance, in my laptop, I use '/usr/local/lib/lua/5.0' for -<CDIR> and '/usr/local/share/lua/5.0' for -<LDIR>. On Windows, sometimes only one directory is used, say -'c:\program files\lua\5.0'. Here is the standard LuaSocket -distribution directory structure:

- -
-<LDIR>/compat-5.1.lua
-<LDIR>/ltn12.lua
-<LDIR>/socket.lua
-<CDIR>/socket/core.dll
-<LDIR>/socket/http.lua
-<LDIR>/socket/tp.lua
-<LDIR>/socket/ftp.lua
-<LDIR>/socket/smtp.lua
-<LDIR>/socket/url.lua
-<LDIR>/mime.lua
-<CDIR>/mime/core.dll
-
- -

Naturally, on Unix systems, core.dll -would be replaced by core.so. -

- -

In order for the interpreter to find all LuaSocket components, three -environment variables need to be set. The first environment variable tells -the interpreter to load the compat-5.1.lua module at startup:

- -
-LUA_INIT=@<LDIR>/compat-5.1.lua
-
- -

-The other two environment variables instruct the compatibility module to -look for dynamic libraries and extension modules in the appropriate -directories and with the appropriate filename extensions. -

- -
-LUA_PATH=<LDIR>/?.lua;?.lua
-LUA_CPATH=<CDIR>/?.dll;?.dll
-
- -

Again, naturally, on Unix systems the shared library extension would be -.so instead of .dll.

- -

Using LuaSocket

- -

With the above setup, and an interpreter with shared library support, -it should be easy to use LuaSocket. Just fire the interpreter and use the -require function to gain access to whatever module you need:

- -
-Lua 5.0.2  Copyright (C) 1994-2004 Tecgraf, PUC-Rio
-> socket = require("socket")
-> print(socket._VERSION)
---> LuaSocket 2.0
-
- -

Each module loads their dependencies automatically, so you only need to -load the modules you directly depend upon:

- -
-Lua 5.0.2  Copyright (C) 1994-2004 Tecgraf, PUC-Rio
-> http = require("socket.http")
-> print(http.request("http://www.cs.princeton.edu/~diego/professional/luasocket"))
---> homepage gets dumped to terminal
-
- - - - - - - diff --git a/doc/luasocket/introduction.html b/doc/luasocket/introduction.html deleted file mode 100644 index bb55762..0000000 --- a/doc/luasocket/introduction.html +++ /dev/null @@ -1,333 +0,0 @@ - - - - - - -LuaSocket: Introduction to the core - - - - - - - -
-
-
- - - -
-LuaSocket -
Network support for the Lua language -
-

-home · -download · -installation · -introduction · -reference -

-
-
-
- - - -

Introduction

- -

-LuaSocket is a Lua extension library -that is composed by two parts: a C core that provides support for the TCP -and UDP transport layers, and a set of Lua modules that add support for -the SMTP (sending e-mails), HTTP (WWW access) and FTP (uploading and -downloading files) protocols and other functionality commonly needed by -applications that deal with the Internet. This introduction is about the C -core. -

- -

-Communication in LuaSocket is performed via I/O objects. These can -represent different network domains. Currently, support is provided for TCP -and UDP, but nothing prevents other developers from implementing SSL, Local -Domain, Pipes, File Descriptors etc. I/O objects provide a standard -interface to I/O across different domains and operating systems. -

- -

-The API design had two goals in mind. First, users -experienced with the C API to sockets should feel comfortable using LuaSocket. -Second, the simplicity and the feel of the Lua language should be -preserved. To achieve these goals, the LuaSocket API keeps the function names and semantics the C API whenever possible, but their usage in Lua has been greatly simplified. -

- - -

-One of the simplifications is the receive pattern capability. -Applications can read data from stream domains (such as TCP) -line by line, block by block, or until the connection is closed. -All I/O reads are buffered and the performance differences between -different receive patterns are negligible. -

- -

-Another advantage is the flexible timeout control -mechanism. As in C, all I/O operations are blocking by default. For -example, the send, -receive and -accept methods -of the TCP domain will block the caller application until -the operation is completed (if ever!). However, with a call to the -settimeout -method, an application can specify upper limits on -the time it can be blocked by LuaSocket (the "total" timeout), on -the time LuaSocket can internally be blocked by any OS call (the -"block" timeout) or a combination of the two. Each LuaSocket -call might perform several OS calls, so that the two timeout values are -not equivalent. -

- -

-Finally, the host name resolution is transparent, meaning that most -functions and methods accept both IP addresses and host names. In case a -host name is given, the library queries the system's resolver and -tries the main IP address returned. Note that direct use of IP addresses -is more efficient, of course. The -toip -and tohostname -functions from the DNS module are provided to convert between host names and IP addresses. -

- -

-Together, these changes make network programming in LuaSocket much simpler -than it is in C, as the following sections will show. -

- - - -

TCP

- -

-TCP (Transfer Control Protocol) is reliable stream protocol. In other -words, applications communicating through TCP can send and receive data as -an error free stream of bytes. Data is split in one end and -reassembled transparently on the other end. There are no boundaries in -the data transfers. The library allows users to read data from the -sockets in several different granularities: patterns are available for -lines, arbitrary sized blocks or "read up to connection closed", all with -good performance. -

- -

-The library distinguishes three types of TCP sockets: master, -client and server sockets. -

- -

-Master sockets are newly created TCP sockets returned by the function -socket.tcp. A master socket is -transformed into a server socket -after it is associated with a local address by a call to the -bind method followed by a call to the -listen. Conversely, a master socket -can be changed into a client socket with the method -connect, -which associates it with a remote address. -

- -

-On server sockets, applications can use the -accept method -to wait for a client connection. Once a connection is established, a -client socket object is returned representing this connection. The -other methods available for server socket objects are -getsockname, -setoption, -settimeout, and -close. -

- -

-Client sockets are used to exchange data between two applications over -the Internet. Applications can call the methods -send and -receive -to send and receive data. The other methods -available for client socket objects are -getsockname, -getpeername, -setoption, -settimeout, -shutdown, and -close. -

- -

-Example: -

-
-

-A simple echo server, using LuaSocket. The program binds to an ephemeral -port (one that is chosen by the operating system) on the local host and -awaits client connections on that port. When a connection is established, -the program reads a line from the remote end and sends it back, closing -the connection immediately. You can test it using the telnet -program. -

- -
--- load namespace
-local socket = require("socket")
--- create a TCP socket and bind it to the local host, at any port
-local server = assert(socket.bind("*", 0))
--- find out which port the OS chose for us
-local ip, port = server:getsockname()
--- print a message informing what's up
-print("Please telnet to localhost on port " .. port)
-print("After connecting, you have 10s to enter a line to be echoed")
--- loop forever waiting for clients
-while 1 do
-  -- wait for a connection from any client
-  local client = server:accept()
-  -- make sure we don't block waiting for this client's line
-  client:settimeout(10)
-  -- receive the line
-  local line, err = client:receive()
-  -- if there was no error, send it back to the client
-  if not err then client:send(line .. "\n") end
-  -- done with client, close the object
-  client:close()
-end
-
-
- - - -

UDP

- -

-UDP (User Datagram Protocol) is a non-reliable datagram protocol. In -other words, applications communicating through UDP send and receive -data as independent blocks, which are not guaranteed to reach the other -end. Even when they do reach the other end, they are not guaranteed to be -error free. Data transfers are atomic, one datagram at a time. Reading -only part of a datagram discards the rest, so that the following read -operation will act on the next datagram. The advantages are in -simplicity (no connection setup) and performance (no error checking or -error correction). -

- -

-Note that although no guarantees are made, these days -networks are so good that, under normal circumstances, few errors -happen in practice. -

- -

-An UDP socket object is created by the -socket.udp function. UDP -sockets do not need to be connected before use. The method -sendto -can be used immediately after creation to -send a datagram to IP address and port. Host names are not allowed -because performing name resolution for each packet would be forbiddingly -slow. Methods -receive and -receivefrom -can be used to retrieve datagrams, the latter returning the IP and port of -the sender as extra return values (thus being slightly less -efficient). -

- -

-When communication is performed repeatedly with a single peer, an -application should call the -setpeername method to specify a -permanent partner. Methods -sendto and -receivefrom -can no longer be used, but the method -send can be used to send data -directly to the peer, and the method -receive -will only return datagrams originating -from that peer. There is about 30% performance gain due to this practice. -

- -

-To associate an UDP socket with a local address, an application calls the -setsockname -method before sending any datagrams. Otherwise, the socket is -automatically bound to an ephemeral address before the first data -transmission and once bound the local address cannot be changed. -The other methods available for UDP sockets are -getpeername, -getsockname, -settimeout, -setoption and -close. -

- -

-Example: -

-
-

-A simple daytime client, using LuaSocket. The program connects to a remote -server and tries to retrieve the daytime, printing the answer it got or an -error message. -

- -
--- change here to the host an port you want to contact
-local host, port = "localhost", 13
--- load namespace
-local socket = require("socket")
--- convert host name to ip address
-local ip = assert(socket.dns.toip(host))
--- create a new UDP object
-local udp = assert(socket.udp())
--- contact daytime host
-assert(udp:sendto("anything", ip, port))
--- retrieve the answer and print results
-io.write(assert(udp:receive()))
-
-
- - - -

Support modules

- -

Although not covered in the introduction, LuaSocket offers -much more than TCP and UDP functionality. As the library -evolved, support for HTTP, FTP, -and SMTP were built on top of these. These modules -and many others are covered by the reference manual. -

- - - - - - - diff --git a/doc/luasocket/ltn12.html b/doc/luasocket/ltn12.html deleted file mode 100644 index 7d2842e..0000000 --- a/doc/luasocket/ltn12.html +++ /dev/null @@ -1,430 +0,0 @@ - - - - - - -LuaSocket: LTN12 module - - - - - - - -
-
-
- - - -
-LuaSocket -
Network support for the Lua language -
-

-home · -download · -installation · -introduction · -reference -

-
-
-
- - - -

LTN12

- -

The ltn12 namespace implements the ideas described in - -LTN012, Filters sources and sinks. This manual simply describes the -functions. Please refer to the LTN for a deeper explanation of the -functionality provided by this module. -

- -

-To obtain the ltn12 namespace, run: -

- -
--- loads the LTN21 module
-local ltn12 = require("ltn12")
-
- - - -

Filters

- - - -

-ltn12.filter.chain(filter1, filter2 -[, ... filterN]) -

- -

-Returns a filter that passes all data it receives through each of a -series of given filters. -

- -

-Filter1 to filterN are simple -filters. -

- -

-The function returns the chained filter. -

- -

-The nesting of filters can be arbitrary. For instance, the useless filter -below doesn't do anything but return the data that was passed to it, -unaltered. -

- -
--- load required modules
-local ltn12 = require("ltn12")
-local mime = require("mime")
-
--- create a silly identity filter
-id = ltn12.filter.chain(
-  mime.encode("quoted-printable"),
-  mime.encode("base64"),
-  mime.decode("base64"),
-  mime.decode("quoted-printable")
-)
-
- - - -

-ltn12.filter.cycle(low [, ctx, extra]) -

- -

-Returns a high-level filter that cycles though a low-level filter by -passing it each chunk and updating a context between calls. -

- -

-Low is the low-level filter to be cycled, -ctx is the initial context and extra is any extra -argument the low-level filter might take. -

- -

-The function returns the high-level filter. -

- -
--- load the ltn12 module
-local ltn12 = require("ltn12")
-
--- the base64 mime filter factory
-encodet['base64'] = function()
-    return ltn12.filter.cycle(b64, "")
-end
-
- - - -

Pumps

- - - -

-ltn12.pump.all(source, sink) -

- -

-Pumps all data from a source to a sink. -

- -

-If successful, the function returns a value that evaluates to -true. In case -of error, the function returns a false value, followed by an error message. -

- - - -

-ltn12.pump.step(source, sink) -

- -

-Pumps one chunk of data from a source to a sink. -

- -

-If successful, the function returns a value that evaluates to -true. In case -of error, the function returns a false value, followed by an error message. -

- - - -

Sinks

- - - -

-ltn12.sink.chain(filter, sink) -

- -

-Creates and returns a new sink that passes data through a filter before sending it to a given sink. -

- - - -

-ltn12.sink.error(message) -

- -

-Creates and returns a sink that aborts transmission with the error -message. -

- - - -

-ltn12.sink.file(handle, message) -

- -

-Creates a sink that sends data to a file. -

- -

-Handle is a file handle. If handle is nil, -message should give the reason for failure. -

- -

-The function returns a sink that sends all data to the given handle -and closes the file when done, or a sink that aborts the transmission with -the error message -

- -

-In the following example, notice how the prototype is designed to -fit nicely with the io.open function. -

- -
--- load the ltn12 module
-local ltn12 = require("ltn12")
-
--- copy a file
-ltn12.pump.all(
-  ltn12.source.file(io.open("original.png")),
-  ltn12.sink.file(io.open("copy.png"))
-)
-
- - - -

-ltn12.sink.null() -

- -

-Returns a sink that ignores all data it receives. -

- - - -

-ltn12.sink.simplify(sink) -

- -

-Creates and returns a simple sink given a fancy sink. -

- - - -

-ltn12.sink.table([table]) -

- -

-Creates a sink that stores all chunks in a table. The chunks can later be -efficiently concatenated into a single string. -

- -

-Table is used to hold the chunks. If -nil, the function creates its own table. -

- -

-The function returns the sink and the table used to store the chunks. -

- -
--- load needed modules
-local http = require("socket.http")
-local ltn12 = require("ltn12")
-
--- a simplified http.get function
-function http.get(u)
-  local t = {}
-  local respt = request{
-    url = u,
-    sink = ltn12.sink.table(t)
-  }
-  return table.concat(t), respt.headers, respt.code
-end
-
- - - -

Sources

- - - -

-ltn12.source.cat(source1 [, source2, ..., -sourceN]) -

- -

-Creates a new source that produces the concatenation of the data produced -by a number of sources. -

- -

-Source1 to sourceN are the original -sources. -

- -

-The function returns the new source. -

- - - -

-ltn12.source.chain(source, filter) -

- -

-Creates a new source that passes data through a filter -before returning it. -

- -

-The function returns the new source. -

- - - -

-ltn12.source.empty() -

- -

-Creates and returns an empty source. -

- - - -

-ltn12.source.error(message) -

- -

-Creates and returns a source that aborts transmission with the error -message. -

- - - -

-ltn12.source.file(handle, message) -

- -

-Creates a source that produces the contents of a file. -

- -

-Handle is a file handle. If handle is nil, -message should give the reason for failure. -

- -

-The function returns a source that reads chunks of data from -given handle and returns it to the user, -closing the file when done, or a source that aborts the transmission with -the error message -

- -

-In the following example, notice how the prototype is designed to -fit nicely with the io.open function. -

- -
--- load the ltn12 module
-local ltn12 = require("ltn12")
-
--- copy a file
-ltn12.pump.all(
-  ltn12.source.file(io.open("original.png")),
-  ltn12.sink.file(io.open("copy.png"))
-)
-
- - - -

-ltn12.source.simplify(source) -

- -

-Creates and returns a simple source given a fancy source. -

- - - -

-ltn12.source.string(string) -

- -

-Creates and returns a source that produces the contents of a -string, chunk by chunk. -

- - - - - - - diff --git a/doc/luasocket/luasocket.png b/doc/luasocket/luasocket.png deleted file mode 100644 index d24a95495b55894b96aec1b01d0b7c02cc43f168..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 11732 zcmW++1ymGm7oH`T4vD3t6_iHlmKN!jUJ*q)M0$ml4r%F-?(Rkw1f;uDI;HcU@1L`A z&hG3xbMD^v-Y0Ibx~c*JE;TLy00c^kvYOyK;=d;p4SZEGI!^%rPAw%_Y3(nw``+#@ z+H#YZC52O;q6g)Bl}USLraK2Qg7$Fz@nAnRBwR5Zr4vbf)|SIW2J?Idh4}}=@OJR~ zcy=JN4uB*Ju0|~DuW}aRuPic(GQG-Br7ezyI}@F|`~1_jk<vF(q$U3K0YJ;ImxnqIVrJD)*0_au!r(hC8CxFA^2o+Lf5kb64 z>*Yn$i0Rh3b7WNR<^N^eVjo458Ow};G)uUWX2%9(ymGEf6aj91t+u_Hs=Ug|Xw4l5 zAs3N_E+R=AzC;)twpOH9_IG_c}6sn**$rhYO2AIsRqMas}{!22RRMUY#g>}f0?5`f$9U(DgE z=VgXql9O04ZEkM*-X8aKbaasX|5!tXhlYinTGkel)y(ZDa2ZFlus?gIObmlJTMeaM zUtcT5JOOWrDqP-FC_2O&kb>S{4c#V~%$gc|;{Xsv00V$H0EF$pJK%-Ohk;LJe;PK^ z$dsvMdhrOZV*tZ=rhX?mIXNSv6c(k`r$rO9WWqwU$>w$cDeEf95Z3$eFJ*3j(Y$qdwfl`bQ^=sXA%1DG(9vj>cBLpN-5eSL4ffuDoJX7yJv7|$wwj%Q5T1wc#o zT9b&0l~f+A(q^ihH*r$Aq%_EYaq@G~-Y!@S%i8uBrHl;P=qQ#( zAMa0X`ERuU5Jm3efR#ou8vMlUfz=PkhtF& zy|AXR`-vxzeUnf66P}rg^7Av5S9tqNWH{m=cg|0n10ELnSp0gYs4PvwoBBnH;jny> z!g-=bhh>f9;3HB}-4esIf9VhN!sGxjS$Y@YjE#b2G?7WAILl-Q1mvFWMxrCsbBqq_ z-I=wmCUagV)Y>nZn3zbo9n2SK<>5BC?dsc$EQCTQa%v|C+c(EGAJ%KUFE`XW7U;1%C zZf!LMA|)-&33S04oQamc63Z5>4J5uUC?Mf#Ie3Hifwi!Ikd2Qon)eAyiEi6z&dWjR zX@Ex_X$C|PpWjz!#Hz25e+y~J&j?Y&;`?Ju$!*f&C?8IYW)>Hx*YW53;wOw@i*#a5 zefd!DZb|S?XV1bTq+2W4SR=SXe|({^#t>7TglHwv}Dd5UH}KPh#xa z0WJL>OBvE%M@AsLyc97?fy5LW;CHqvC z!pzLCh=G)5@@8wHXYypu-6i=S?r;CmOWYJ+_C_feP2fsFf-V`dyYvqW3>YQZEx~|1 zd%oLtS4)hzyunsUB5N^|?(@TZwYKW_3-@QNJCpzL5`;lQLb3SA!EVMBf|n4nw&ve% zi+dhHT{ue}NhezC{_n44e|-33aYIW{<17={46i(l*&x^RJhs?0{b53nRp2cifHiEc zg5>S*zTBY07^6Ii;l*V@=kf2bKi@<4Jf;DQb+n0EGwgu;n-b|@-?K!~3sV@4oh%gH zK}p7H@Rm>59YKt2Q36U>cl+X=>y;WQsi^ElZx>yY=2$QX%*}0t)8H+BVXmvMCj|g} zBr$@Jek>fF5ejH1L-qhLjx8Rpvt2}y=l{lvyn#Q~#PUJ8Pv(wRK7Fz-hMt){#Rm|) z76TF=HTR;JpU>L{304z1?0hpy?PX+S#KFO7H8cGX7{ZjzNPoSyyN1Ojh7^V6itQ4U+12{z zhre^r*2t?xk57xI+sD>r59YZYW2Le?h8(q9vJ_Vr!2@6q2qo8;9XV% zlsFj}8YU$t7m>c=saI`i)14;uo12R>y*~*(J-s+N>4P4>QdDE#f3$}VScGXQlSD(0 zx!Ll6@WSsNsqNX>x(4Me)1tBAzE;6^KkhaFY(bWfi9*4E0h;2Rx^wMxwYi`usmI{ zTUqs-1xKq7QyKlLzISJbEI4@Y*(M>IUSqj(Zi~Y5@yV=8Hof9e(#Ra*um+B|=^oa9Kb0+HS}f5? ziW@=DG7}RMb8^7)$Q8$;RQ^+yHDt0NoY!MDc*ysx$QRu#>?}6qkGZ57J)<5vNe&rY z95u>6v}aVi$8Ro8YT`O5oyYue)AriuZda77TeX0I@jHu5P`QJP7gRc0mUuO`)&jq* zt#xa`?T~Ex@J~KeCwgzLj+=+ap%aNy7}fJ=i83vGQuoSAa_)K~0W+E`gRM9jZ6E6^ zIzz>NmNt?*=qo&o7iHl&@0iSDE>|&_ChpV|al=XBztud=t4J#0Rlj<*c|j+pk89?3 zK+w$w12D~yKMq?xr|BPrK3yL1$eAzx^!HE%)EJ>Ap{YDOo0<`aQ5;SN zumrOy@BRw*ud0m4!lde!0;GxxnUL=iYwMmvzs?jpn_w7F2#`naToRB-*^YSH1bI|( zREZwWU!F~Ui(X&aobCZ|H~WTsCGIy8tg^H59S*BPdiLi+O}?z`j*e2x48%GCTpxIB z4Nn$Zh-mQXR>YTI2;xNN$EtIa`tedogq7Nsw&I%G0v-2vH=jOz5`}I}G_qF*DbU{) zo0doN{+%a*eVA_ew^H(!^6Aq+&Awls^=>j_`}tTg!1V9c%F~rN=_OO1gF=98HtpzJ z!pFDf+oN@V<4>nL0WWr3Q^DyyM`*_xu3mW9`2 zs*^)F9c8T^W@{+sJH895n4ei3*hCVo4(1^oS}UU@`eQy&X%RXSPcHwjHq+(Hae9BX zth->sAD7!)cPl7O=M|v2+Hts~`1rr8e_gQCbrFpR zswqMmT3Y;8gS3Yic&;V6xf{VxCD5f(+@_FDKM}lW4$W78Q`dSFglV;rVV(*|XZuKK zM_9#_Npf;pn(W7>@(xErU{p)(&R$Ngip8A!ob)(k&c3aswpM_fTdjK$OoeaGn}ctD z@R%>Rf3>)7TFRJJfGlt4x#{V=B+lAw<`!)1ythn#`DyE9V~yQXgzi9-v~gGpItN|? zj{yfAXETi0*w}cj%%^6~^2b3t41~2bl0MDLGRDp03Y@*aCkwLJX1xM;54U+%lt~vW zH^zPMrryh_#GcnALKuHFi1Ryd-(LOB;%|M5U+^I(_BH8X?{uZJ6@>9gCK-tzyY0t&oyW*RT_?i($Nm??qi~d>u9i>w5xm`JEPNZu~I`R zY{FADWn4`4lr?f6mNChD$MyLJtd4mRZ=;(!N&$%A6EyTviB8~OsN?(TjyS@Jej zeo3{R2BLjeP*}KgdAt_Q;@Z9@ z8S{&Y$7WVr-DHu4;wvQux6+6&pZ4jcE)fo?{5y_78Vw8cnj2pmr~+-OBN1) z#5np#RrCmh3DL8nu8qIQFl`eur?QGv)ZLvRlITSr3YCKT|M>5Kkwh)AyGR2So*d7f zQH!{+eIaIEO=2+*^tYSU1~PVuHnT)*fD9(wM_%O^U+6^95Fp?LxSCCl%pA}S7UuU;D%unrrP2U7$P(R1}XX=!QYwS6uLz{0>NHfa$N z5TFq2cNu9>lN2YAl8fJbgQ~0}L|44INZ>^^54>5L{W?D%N&`1pIL0`?f{j{DIe2ZYhc5?xQ-$*cPfNsv=2D7x)vpM6EAY%hvm#Tn1w z1*V&?Jo9jWEtq0tJY4UNqEMgJuJZwzpx^IK)@hCu0oPTYvN?m75j)crg?)X`q1)F@ z=SUa}xpmf-id(8`ET2**CT0!DLa6}soKzL|K?uB{w3J=2jx>YWzvFd(+B~{(Kd_E* zv~`OHOxKl>No~J4&9R5@qDc6>@2|FP=Tu*l>XJpSP}`w5#3up3kaz-XzW_H$u;1v- zdFq9q2qi}2D@u$HHZ~kwT$7WSTiG~a0K?PGtfumvr^J>t*>TS$CEZHF?p~>);~U>& zl`@@R`9$e5(pT&VY$Z@$_nBdbK}fILlCgHw^2%egFfaj$!o$NC7!Xn(=H@H4wsXzb zbP)LX^t8|40aoB}M-m%Q>Rk0dCXk!=#5C85=Q6Ebbe%$lguItVpHSM(9d)@aVhhtO zor-CDxSKxoZKH&1^oUlLLdf*Jj`>dAA-wpijvIm@AxL~z*xBW)M=zF7T3bP$Gb zyF4Gpgjic!%ZF2M!~wLxV0s%`d-M9SSr`mXLUM24Dy$Y?psH|xySdjD=*#enAq*uL zi3Qyj+5|hnLl@CMN-kQkLxQ-OWM$z_D_Y^5CpNLvUfPm zqgN8X_qbn7AghftHWY+>lrKI@BR+!YQBF=;Z{_dC#+z25DWOd!9@#wRmLKjbbaE;D zgCvYTx<%e=sQGZ3$Ss$@IS`aif4k6njofNfW1_z%0<-Mb^UQKbu2K>9S3PDD|S2d9eNHc=`$9EBJkbHp%dC z+0dau#BM415l4Q_1Y_2;chiH&5z4RHYw7iFn4`e~`e9SA-u4e^CY4P7!lrqY*wQPu zjTEgYqCF$3AH<_Na(sF=zxm){o|W3Z5|(?3y)a-~4js(2 zAd>!={OG2+YL0Bvc0b7@V28l(r>5M;m3g}tJIu`f78Wv0OlWVOh;LSARXeCQ#XZ_y zAZGDtblT_xR|6@IG4TecmP!0Z%u}`8oSbjpzPTTNGY>&fuABFD%yD1zA9)>hnc6$yPd&NM~?VNv2s{eEeuLy^R3C#kF4YJp6&>4`nnP zIREu%+xKqQ$k%rYcpBPGOis?@?Qv`GE9!c6GE{5N4I-~ptWJlLsYj-z!5 z1tCpzgn@c!E-o!ZDLl_mav{h~F5{~G58UuDp}M>D2Y%ay#-?z2C4Hs2+4Yl?T<1+{ zYwKc}?;^D07Q8ldpOKQc8_9*LO$?MzSa7~ePI>vxagU^(ZJb`2 zDmvnL?I#-AZHX?8%wnC8n8<8aRwo_CPIPqiW8YiHi{Uh`TL@SZW$?euehWT3DBd1j z`fz}Y3Jb;nstnwgrDoE^tytK56W4+O9!4x+?P+=nnc!OvEMH%7gy83=Hqu#y;cgs> zD!D;H&g-v{eAoMo=r`EpLce3i609oCw4G|)6r-c z8irPsmhBCQLk6Wa$P8)||3Kh9Pr@J5Nw{nwI{d*6%K_F`bgUm|AZ6C8_n-b829gA2 zi2|x(D5FMZLrID4=3pw3*bzdpa5>2%dZ%)$lb#p`>lH35DIp*t!X~niQn{kyU#+v3 z99e>$2Y4ZQHY?lO%>N|K^e04yN7UA@i{WLDPt*{?%;H&0zp$e%kLC3gDJ~CYMPU;? z9vB>q2n(w=ECFS8P!pyIm1C*nL-qCbWo2dkIwn~JSDXLvBH-J%xP$~yPMzh?5du`w zC19EN12|h~I#5S01v!KBJp&QzaVhf_X=qJdzmCpiUtf`>Ww_Olz}}LnD!ZuDI`2_O zwH!P8@KA~{Ohmt8*$D>Zsw9%q)2GM9b;E9M{|(s+BzIc`hlD7rsNmz{-(IdorhAR9509!2|8UM_-;hW*}k6cE~^2xVns%WrHH zVPdja?~U3VN^kpey!s7~^89dVX?Xa1bTlay6%LnA@Zk67+5@rY=bvjHE9bds_OaqD zIIAg}m{7^cBa)j4n^}_4j(Qa(6N-=w%KI@-i4q05f3IZ7|2(a0^S(%4+LH-#EY;dI zBlV*rY+^f|B@bePo*26kbi;z9*;JL?96l;mXLn2Oo4-tFhM zf+$93Ymq&f=j#*%+A$UOab=SN9FJE?4pJTCIom;vzOTRk6_kMb#fP2o0;cw-FJ5TJ z{Y&}BC1zpRlbwf@Trd73?DXz(Z^j=&+ls-)gapc|^ENit=9!Gqe`@e08qL$w8C0WV zV-2PVXOE2_18+j@H#YQ&b*bP=vY!eB6-glu_%sxSR80zaVhC?k*rnrI);O8~*Oxhv zJimYc9z^RPXHZp*=vonSKgr%P(x_obFE*ToONvq5VJ`Wej^J1eHa|i*Q)S3$7*42j zs?iUUZ)Uv*GT1o8=6&bup+K_9lE$TUG?WpRaVFT-VA~E<e%GuCfhlIdI_Jb-O=u?>sggFDV`2Yynt|Oa_=2&0+feZmVR;M@fx=HN$)-c zf>mbVYsRP4a1p7_KWoicWq$DX z3};4#QiKC_M}%KucKr5ijpW^LwX8Z@Q7yfxtf?3z@;fG;=0P+6Z?o?p!U&iD z{XrJX|Fp<7r|nqY?o-jvhMB*#cs($!Lb1EkcPrY&FDt6^0YFl+4J1(_w1k81mX;gE z230`2MFlKep7J52%)Qg2<-X~#waT!>+U#4N+|lqWxTY4i#%%EOS6jtk0Kexw^GgHZ z810kAGjpS>JTMl6T(ISq7>i1Z-b67gJf3TIAE9$&0oqL;lK%BQzwz@A&j{B4OUv^F zG&G9zeAz37sn&?ZUwBNFvMNM~rKPsqb`gOt-46>M#jC5A+uJmKebgi}pPMSJbqsYT z_=zONu-fIJq6=?QM*41Obn&8cS;-t@=M-;ZNu*n#e~u~%c!WW z#RQ(?c1=6nUVbyElDOQIq|D6?C~_RklKk^$pS#U#`Hx^*aAc&IOMa)#WU7d((i|BI zH83#dyy;VIw;=v107G<>m{MabfxE8t?tEm*RC0WFw%NQZxb4oi)G$m+$SAdgpk3Je zxI6Jl%rn~b50kTO&Kg#nC9# zb67IK1CPMOlV5aJ3;E5WqhkPCZns%khDa79F?`?oZ?@Ojgyw#S%`+Ly^R~;?P)t0E zEf*1kcr`F2VD-Dc_NbakNlW7zWS&s9ONTNXl$Mn(HM;Ibv%W??*=5(&!=RxgpHNG= zjGWZ%4sIf(K5hT_Q#Xd}L6}Io0zF?kMP_hNV({4q4)lowtN?5r3x?UBz!Gsj5 zD_}eWJf0RU%QN@=G3NDfK^hWh(_G3!Kib%M?UvN(7VCq~w=}z}B=k{fkDnU5^6Kjk zAGTuDB(^bc=r}F1*+5CMT+bvC-OQO6Kgd|EPJ(N}Jj{_031j`8PR!5v?k-kP+rax1;eNA zZYe2wW6UJggv(wf?s>D4c-o)!0eQ?CgIz1A5W#w}vypnFI_(-J-{H zF)=Y7p5b?VS65e5_yObNnZy*H!Z+=aj?(?+Uh-#^rjjb6=ofN>+A1qL4{*vq9w^OD-I;& zbxS^PF&bTz+X$_ak>uarBvaIxcQFA?`37J5Q6(-SMkIZ`4R?1JhpFP8LHVs)T-unj z3JPWVV9y942g5osF#-CDA3lC0dFKC}D^+#Uj@~Mi7#9ae*z3|kOKa?CrE7v>f&Ufg zbDGIz!h7VeZ;~$##NPznd&K?K#Uezo;AqTV_ed@_SnDJy?rp!o&TVPAs~VD+tAHzL zXpCel#pHrF_2`k7wsve>oMqh{91fQg)6FxGUtmTIySs`Q>+4UK8aILP0mJkkaZ<=H zVfomT(^Gw!()jRc$9-e%fO z3NbUh{;>b|m4q^q2bD5){v8sLHN14kCC>7z+M=6qke9LXt)}1x?9rg5 z^0w$92Pm~4q`_+D682oj7I6YhRKl)m;$VUSm5v4Q>1KH+fpisT7JsO8ae2N!99 zmRooXmVW&9T4dzINxuSE+GA^9M>`bGGg%n0oIFC!qNCxb`?k7l^aWR{7?+n3#t09^ zhK7U`=I4K~wIz=l3d!1XX#}fuX!bbQki(t;q`E~TlG8DG@8~p$#oPd7iBD)H@5e!t zg*@jQ@z(a0QA?P27%yW68z&s~>#^khy0IH8UTV)6fWv4}3EIGuHUhqvD}h;>MfLwq zHu|monl32a-s1V~_Va~sgEKFhWZm!h+(r6j$Lx#QIKVjA%;-0zzOzc-G-8xJJl#4M zSJ>&Lgb#EG8@G7;eVWekSZLUEOKkSo`YuQyc^}L*g~-P>h9x5-Bg_gBAi$USa+G0G zmcYU;D0l&W3jzUC&{9aiUy4B4vlJ-4jJ2CC@35|sxH}ztX4@QU>1Y-z6lvKVvXG~i z!2Ir)zEkOLD<6LLI%{wRL) z`}gnMZMT&f8B+0#4k<^SljyvxoQng! z#`B$`o8%4&Ocd&Xg!OY%OG}G51B28{zt2<~(~l@z=pZB(VN~HL^R9sXnX1jz?oe>X;QZc# zQ=Ifr328yj1YrZo=?6;7jPWaRaCAQ7BXB9RG` zXLd?++7yphXb(?&TKxHin3&hq$p)yZlyt4|!0?w{>GH>vQ;;B{mv0VWv*Y+ z9aP&|!8x3juE0k!WO5J$IR7LQv|xuF-qNA4q*X?@Ra|OR((Kf>y5dOeWgu>1fS=Jg z+vsNhJ58KbSeWwp^JL%`yIJQec8RH%+b^7WHWh46Pc<~8wQ}*31i2j#=70V85s~rX z4Epf`wv9re+HN?uFWc_zc+ugps zclu?E3J`}sH7m!)&CSik#3Ulp*uP&d%E-O}H5M%@YB9cF2@Gg%-Z^Y5d(Kf@R^05d ztywg&^WD=IZq|A5@f(uY3@(JY5@`=aI6EYs)y}g(Hn@Uj8pL&DD@DyJ4dY`jw%EH)dJC1{b>8XxbgO>&T<48c2Z=p(ouFJv|T)aQ+3_$jiVa%Cc#WqZGFDIy|bu(y}Eav$qvsf+nf zi@!+IH@?C*m1F^At{2O{eWnsJtc7MaX(c#+{J2eN>ZPHf@n1{~s@?}l`?pP>OS&x*dCX-rHKT=`WQqbmSfzw^bd5Dt zU--|lb1~UJ=jA=l417!~%D&IcMJhwy-O|K%qk!%>b&k;mmfAfq+C%A*_BDoMqoaI$ zd>-WuZW>IOF9Zekbag2xC?e=3B^Vi{Ej^w!?N-X{yzy&&3o&$XvqnR(D1keY1|0Ut zVguzgXA*RU2wJdGQoZ<~Zf2IzZGl5bNI`?gnMDN;$x>IA3uktHS`Y6bG>FGx1k(vT zlS^DfCqshxJ~boD*VO@HNQkE@pSiKXq_jU>0VfRXdSCUsvKds_x3)g;M$OI5O_iB0 zjgB%EL&44jPGMo>nKytD1~CPg@ljDxGK+}hnL>Iuzd8&E#)rJB&qc+Sx?vTQle$F{ zB4+J?EyFlyv69HF0%I8&8Pn7HB}j)TiaWkB@eWQ|KrN%ut$LR65}}YFZkqr>ze9U~ zU=U~QTjkl&a~dvudbd=0ME?r$ptq6>Tl2wKT6sWQ(d-$zSLUV$r>w4cb*_o - - - - - -LuaSocket: MIME module - - - - - - - -
-
-
- - - -
-LuaSocket -
Network support for the Lua language -
-

-home · -download · -installation · -introduction · -reference -

-
-
-
- - - -

MIME

- -

-The mime namespace offers filters that apply and remove common -content transfer encodings, such as Base64 and Quoted-Printable. -It also provides functions to break text into lines and change -the end-of-line convention. -MIME is described mainly in -RFC 2045, -2046, -2047, -2048, and -2049. -

- -

-All functionality provided by the MIME module -follows the ideas presented in - -LTN012, Filters sources and sinks. -

- -

-To obtain the mime namespace, run: -

- -
--- loads the MIME module and everything it requires
-local mime = require("mime")
-
- - - - -

High-level filters

- - - -

-mime.normalize([marker]) -

- -

-Converts most common end-of-line markers to a specific given marker. -

- -

-Marker is the new marker. It defaults to CRLF, the canonic -end-of-line marker defined by the MIME standard. -

- -

-The function returns a filter that performs the conversion. -

- -

-Note: There is no perfect solution to this problem. Different end-of-line -markers are an evil that will probably plague developers forever. -This function, however, will work perfectly for text created with any of -the most common end-of-line markers, i.e. the Mac OS (CR), the Unix (LF), -or the DOS (CRLF) conventions. Even if the data has mixed end-of-line -markers, the function will still work well, although it doesn't -guarantee that the number of empty lines will be correct. -

- - - -

-mime.decode("base64")
-mime.decode("quoted-printable") -

- -

-Returns a filter that decodes data from a given transfer content -encoding. -

- - - -

-mime.encode("base64")
-mime.encode("quoted-printable" [, mode]) -

- -

-Returns a filter that encodes data according to a given transfer content -encoding. -

- -

-In the Quoted-Printable case, the user can specify whether the data is -textual or binary, by passing the mode strings "text" or -"binary". Mode defaults to "text". -

- -

-Although both transfer content encodings specify a limit for the line -length, the encoding filters do not break text into lines (for -added flexibility). -Below is a filter that converts binary data to the Base64 transfer content -encoding and breaks it into lines of the correct size. -

- -
-base64 = ltn12.filter.chain(
-  mime.encode("base64"),
-  mime.wrap("base64")
-)
-
- -

-Note: Text data has to be converted to canonic form -before being encoded. -

- -
-base64 = ltn12.filter.chain(
-  mime.normalize(),
-  mime.encode("base64"),
-  mime.wrap("base64")
-)
-
- - - -

-mime.stuff()
-

- -

-Creates and returns a filter that performs stuffing of SMTP messages. -

- -

-Note: The smtp.send function -uses this filter automatically. You don't need to chain it with your -source, or apply it to your message body. -

- - - -

-mime.wrap("text" [, length])
-mime.wrap("base64")
-mime.wrap("quoted-printable") -

- -

-Returns a filter that breaks data into lines. -

- -

-The "text" line-wrap filter simply breaks text into lines by -inserting CRLF end-of-line markers at appropriate positions. -Length defaults 76. -The "base64" line-wrap filter works just like the default -"text" line-wrap filter with default length. -The function can also wrap "quoted-printable" lines, taking care -not to break lines in the middle of an escaped character. In that case, the -line length is fixed at 76. -

- -

-For example, to create an encoding filter for the Quoted-Printable transfer content encoding of text data, do the following: -

- -
-qp = ltn12.filter.chain(
-  mime.normalize(),
-  mime.encode("quoted-printable"),
-  mime.wrap("quoted-printable")
-)
-
- -

-Note: To break into lines with a different end-of-line convention, apply -a normalization filter after the line break filter. -

- - - -

Low-level filters

- - - -

-A, B = mime.b64(C [, D]) -

- -

-Low-level filter to perform Base64 encoding. -

- -

-A is the encoded version of the largest prefix of -C..D -that can be encoded unambiguously. B has the remaining bytes of -C..D, before encoding. -If D is nil, A is padded with -the encoding of the remaining bytes of C. -

- -

-Note: The simplest use of this function is to encode a string into it's -Base64 transfer content encoding. Notice the extra parenthesis around the -call to mime.b64, to discard the second return value. -

- -
-print((mime.b64("diego:password")))
---> ZGllZ286cGFzc3dvcmQ=
-
- - -

-A, n = mime.dot(m [, B]) -

- -

-Low-level filter to perform SMTP stuffing and enable transmission of -messages containing the sequence "CRLF.CRLF". -

- -

-A is the stuffed version of B. 'n' gives the -number of characters from the sequence CRLF seen in the end of B. -'m' should tell the same, but for the previous chunk. -

- -

Note: The message body is defined to begin with -an implicit CRLF. Therefore, to stuff a message correctly, the -first m should have the value 2. -

- -
-print((string.gsub(mime.dot(2, ".\r\nStuffing the message.\r\n.\r\n."), "\r\n", "\\n")))
---> ..\nStuffing the message.\n..\n..
-
- -

-Note: The smtp.send function -uses this filter automatically. You don't need to -apply it again. -

- - - -

-A, B = mime.eol(C [, D, marker]) -

- -

-Low-level filter to perform end-of-line marker translation. -For each chunk, the function needs to know if the last character of the -previous chunk could be part of an end-of-line marker or not. This is the -context the function receives besides the chunk. An updated version of -the context is returned after each new chunk. -

- -

-A is the translated version of D. C is the -ASCII value of the last character of the previous chunk, if it was a -candidate for line break, or 0 otherwise. -B is the same as C, but for the current -chunk. Marker gives the new end-of-line marker and defaults to CRLF. -

- -
--- translates the end-of-line marker to UNIX
-unix = mime.eol(0, dos, "\n") 
-
- - - -

-A, B = mime.qp(C [, D, marker]) -

- -

-Low-level filter to perform Quoted-Printable encoding. -

- -

-A is the encoded version of the largest prefix of -C..D -that can be encoded unambiguously. B has the remaining bytes of -C..D, before encoding. -If D is nil, A is padded with -the encoding of the remaining bytes of C. -Throughout encoding, occurrences of CRLF are replaced by the -marker, which itself defaults to CRLF. -

- -

-Note: The simplest use of this function is to encode a string into it's -Quoted-Printable transfer content encoding. -Notice the extra parenthesis around the call to mime.qp, to discard the second return value. -

- -
-print((mime.qp("maçã")))
---> ma=E7=E3=
-
- - - -

-A, m = mime.qpwrp(n [, B, length]) -

- -

-Low-level filter to break Quoted-Printable text into lines. -

- -

-A is a copy of B, broken into lines of at most -length bytes (defaults to 76). -'n' should tell how many bytes are left for the first -line of B and 'm' returns the number of bytes -left in the last line of A. -

- -

-Note: Besides breaking text into lines, this function makes sure the line -breaks don't fall in the middle of an escaped character combination. Also, -this function only breaks lines that are bigger than length bytes. -

- - - -

-A, B = mime.unb64(C [, D]) -

- -

-Low-level filter to perform Base64 decoding. -

- -

-A is the decoded version of the largest prefix of -C..D -that can be decoded unambiguously. B has the remaining bytes of -C..D, before decoding. -If D is nil, A is the empty string -and B returns whatever couldn't be decoded. -

- -

-Note: The simplest use of this function is to decode a string from it's -Base64 transfer content encoding. -Notice the extra parenthesis around the call to mime.unqp, to discard the second return value. -

- -
-print((mime.unb64("ZGllZ286cGFzc3dvcmQ=")))
---> diego:password
-
- - - -

-A, B = mime.unqp(C [, D]) -

- -

-Low-level filter to remove the Quoted-Printable transfer content encoding -from data. -

- -

-A is the decoded version of the largest prefix of -C..D -that can be decoded unambiguously. B has the remaining bytes of -C..D, before decoding. -If D is nil, A is augmented with -the encoding of the remaining bytes of C. -

- -

-Note: The simplest use of this function is to decode a string from it's -Quoted-Printable transfer content encoding. -Notice the extra parenthesis around the call to mime.unqp, to discard the second return value. -

- -
-print((mime.qp("ma=E7=E3=")))
---> maçã
-
- - - -

-A, m = mime.wrp(n [, B, length]) -

- -

-Low-level filter to break text into lines with CRLF marker. -Text is assumed to be in the normalize form. -

- -

-A is a copy of B, broken into lines of at most -length bytes (defaults to 76). -'n' should tell how many bytes are left for the first -line of B and 'm' returns the number of bytes -left in the last line of A. -

- -

-Note: This function only breaks lines that are bigger than -length bytes. The resulting line length does not include the CRLF -marker. -

- - - - - - - - diff --git a/doc/luasocket/reference.css b/doc/luasocket/reference.css deleted file mode 100644 index b1dd25d..0000000 --- a/doc/luasocket/reference.css +++ /dev/null @@ -1,54 +0,0 @@ -body { - margin-left: 1em; - margin-right: 1em; - font-family: "Verdana", sans-serif; -} - -tt { - font-family: "Andale Mono", monospace; -} - -h1, h2, h3, h4 { margin-left: 0em; } - - -h3 { padding-top: 1em; } - -p { margin-left: 1em; } - -p.name { - font-family: "Andale Mono", monospace; - padding-top: 1em; - margin-left: 0em; -} - -a[href] { color: #00007f; } - -blockquote { margin-left: 3em; } - -pre.example { - background: #ccc; - padding: 1em; - margin-left: 1em; - font-family: "Andale Mono", monospace; - font-size: small; -} - -hr { - margin-left: 0em; - background: #00007f; - border: 0px; - height: 1px; -} - -ul { list-style-type: disc; } - -table.index { border: 1px #00007f; } -table.index td { text-align: left; vertical-align: top; } -table.index ul { padding-top: 0em; margin-top: 0em; } - -h1:first-letter, -h2:first-letter, -h2:first-letter, -h3:first-letter { color: #00007f; } - -div.header, div.footer { margin-left: 0em; } diff --git a/doc/luasocket/reference.html b/doc/luasocket/reference.html deleted file mode 100644 index ed1702d..0000000 --- a/doc/luasocket/reference.html +++ /dev/null @@ -1,239 +0,0 @@ - - - - - - -LuaSocket: Index to reference manual - - - - - - - -
-
-
- - - -
-LuaSocket -
Network support for the Lua language -
-

-home · -download · -installation · -introduction · -reference -

-
-
-
- - - -

Reference

- -
-DNS (in socket) -
-toip, -tohostname, -gethostname. -
-
- - - -
-FTP -
-get, -put. -
-
- - - -
-HTTP -
-request. -
-
- - - -
-LTN12 -
-filter: -chain, -cycle. -
-
-pump: -all, -step. -
-
-sink: -chain, -error, -file, -null, -simplify, -table. -
-
-source: -cat, -chain, -empty, -error, -file, -simplify, -string. -
-
- - - -
-MIME -
-high-level: -normalize, -decode, -encode, -stuff, -wrap. -
-
-low-level: -b64, -dot, -eol, -qp, -wrp, -qpwrp. -unb64, -unqp, -
-
- - - -
-SMTP -
-message, -send. -
-
- - - -
-Socket -
-_DEBUG, -dns, -gettime, -newtry, -protect, -select, -sink, -skip, -sleep, -source, -tcp, -try, -udp, -_VERSION. -
-
- - - -
-TCP (in socket) -
-accept, -bind, -close, -connect, -getpeername, -getsockname, -getstats, -receive, -send, -setoption, -setstats, -settimeout, -shutdown. -
-
- - - -
-UDP (in socket) -
-close, -getpeername, -getsockname, -receive, -receivefrom, -send, -sendto, -setpeername, -setsockname, -setoption, -settimeout. -
-
- - - -
-URL -
-absolute, -build, -build_path, -escape, -parse, -parse_path, -unescape. -
-
- - - - - - - diff --git a/doc/luasocket/smtp.html b/doc/luasocket/smtp.html deleted file mode 100644 index 833aa83..0000000 --- a/doc/luasocket/smtp.html +++ /dev/null @@ -1,417 +0,0 @@ - - - - - - -LuaSocket: SMTP support - - - - - - - -
-
-
- - - -
-LuaSocket -
Network support for the Lua language -
-

-home · -download · -installation · -introduction · -reference -

-
-
-
- - - -

SMTP

- -

The smtp namespace provides functionality to send e-mail -messages. The high-level API consists of two functions: one to -define an e-mail message, and another to actually send the message. -Although almost all users will find that these functions provide more than -enough functionality, the underlying implementation allows for even more -control (if you bother to read the code). -

- -

The implementation conforms to the Simple Mail Transfer Protocol, -RFC 2821. -Another RFC of interest is RFC 2822, -which governs the Internet Message Format. -Multipart messages (those that contain attachments) are part -of the MIME standard, but described mainly -in RFC -2046 - -

In the description below, good understanding of LTN012, Filters -sources and sinks and the MIME module is -assumed. In fact, the SMTP module was the main reason for their -creation.

- -

-To obtain the smtp namespace, run: -

- -
--- loads the SMTP module and everything it requires
-local smtp = require("socket.smtp")
-
- -

-MIME headers are represented as a Lua table in the form: -

- -
- - -
-headers = {
-  field-1-name = field-1-value,
-  field-2-name = field-2-value,
-  field-3-name = field-3-value,
-  ...
-  field-n-name = field-n-value
-} -
-
- -

-Field names are case insensitive (as specified by the standard) and all -functions work with lowercase field names. -Field values are left unmodified. -

- -

-Note: MIME headers are independent of order. Therefore, there is no problem -in representing them in a Lua table. -

- -

-The following constants can be set to control the default behavior of -the SMTP module: -

- -
    -
  • DOMAIN: domain used to greet the server; -
  • PORT: default port used for the connection; -
  • SERVER: default server used for the connection; -
  • TIMEOUT: default timeout for all I/O operations; -
  • ZONE: default time zone. -
- - - -

-smtp.send{
-  from = string,
-  rcpt = string or string-table,
-  source = LTN12 source,
-  [user = string,]
-  [password = string,]
-  [server = string,]
-  [port = number,]
-  [domain = string,]
-  [step = LTN12 pump step,]
-  [create = function]
-} -

- -

-Sends a message to a recipient list. Since sending messages is not as -simple as downloading an URL from a FTP or HTTP server, this function -doesn't have a simple interface. However, see the -message source factory for -a very powerful way to define the message contents. -

- - -

-The sender is given by the e-mail address in the from field. -Rcpt is a Lua table with one entry for each recipient e-mail -address, or a string -in case there is just one recipient. -The contents of the message are given by a simple -LTN12 -source. Several arguments are optional: -

-
    -
  • user, password: User and password for -authentication. The function will attempt LOGIN and PLAIN authentication -methods if supported by the server (both are unsafe); -
  • server: Server to connect to. Defaults to "localhost"; -
  • port: Port to connect to. Defaults to 25; -
  • domain: Domain name used to greet the server; Defaults to the -local machine host name; -
  • step: -LTN12 -pump step function used to pass data from the -source to the server. Defaults to the LTN12 pump.step function; -
  • create: An optional function to be used instead of -socket.tcp when the communications socket is created. -
- -

-If successful, the function returns 1. Otherwise, the function returns -nil followed by an error message. -

- -

-Note: SMTP servers can be very picky with the format of e-mail -addresses. To be safe, use only addresses of the form -"<fulano@example.com>" in the from and -rcpt arguments to the send function. In headers, e-mail -addresses can take whatever form you like.

- -

-Big note: There is a good deal of misconception with the use of the -destination address field headers, i.e., the 'To', 'Cc', -and, more importantly, the 'Bcc' headers. Do not add a -'Bcc' header to your messages because it will probably do the -exact opposite of what you expect. -

- -

-Only recipients specified in the rcpt list will receive a copy of the -message. Each recipient of an SMTP mail message receives a copy of the -message body along with the headers, and nothing more. The headers -are part of the message and should be produced by the -LTN12 -source function. The rcpt list is not -part of the message and will not be sent to anyone. -

- -

-RFC 2822 -has two important and short sections, "3.6.3. Destination address -fields" and "5. Security considerations", explaining the proper -use of these headers. Here is a summary of what it says: -

- -
    -
  • To: contains the address(es) of the primary recipient(s) -of the message; -
  • Cc: (where the "Cc" means "Carbon Copy" in the sense of -making a copy on a typewriter using carbon paper) contains the -addresses of others who are to receive the message, though the -content of the message may not be directed at them; -
  • Bcc: (where the "Bcc" means "Blind Carbon -Copy") contains addresses of recipients of the message whose addresses are not to be revealed to other recipients of the message. -
- -

-The LuaSocket send function does not care or interpret the -headers you send, but it gives you full control over what is sent and -to whom it is sent: -

-
    -
  • If someone is to receive the message, the e-mail address has -to be in the recipient list. This is the only parameter that controls who -gets a copy of the message; -
  • If there are multiple recipients, none of them will automatically -know that someone else got that message. That is, the default behavior is -similar to the Bcc field of popular e-mail clients; -
  • It is up to you to add the To header with the list of primary -recipients so that other recipients can see it; -
  • It is also up to you to add the Cc header with the -list of additional recipients so that everyone else sees it; -
  • Adding a header Bcc is nonsense, unless it is -empty. Otherwise, everyone receiving the message will see it and that is -exactly what you don't want to happen! -
- -

-I hope this clarifies the issue. Otherwise, please refer to -RFC 2821 -and -RFC 2822. -

- -
--- load the smtp support
-local smtp = require("socket.smtp")
-
--- Connects to server "localhost" and sends a message to users
--- "fulano@example.com",  "beltrano@example.com", 
--- and "sicrano@example.com".
--- Note that "fulano" is the primary recipient, "beltrano" receives a
--- carbon copy and neither of them knows that "sicrano" received a blind
--- carbon copy of the message.
-from = "<luasocket@example.com>"
-
-rcpt = {
-  "<fulano@example.com>",
-  "<beltrano@example.com>",
-  "<sicrano@example.com>"
-}
-
-mesgt = {
-  headers = {
-    to = "Fulano da Silva <fulano@example.com>",
-    cc = '"Beltrano F. Nunes" <beltrano@example.com>',
-    subject = "My first message"
-  },
-  body = "I hope this works. If it does, I can send you another 1000 copies."
-}
-
-r, e = smtp.send{
-  from = from,
-  rcpt = rcpt, 
-  source = smtp.message(mesgt)
-}
-
- - - -

-smtp.message(mesgt) -

- -

-Returns a simple -LTN12 source that sends an SMTP message body, possibly multipart (arbitrarily deep). -

- -

-The only parameter of the function is a table describing the message. -Mesgt has the following form (notice the recursive structure): -

- -
- - -
-mesgt = {
-  headers = header-table,
-  body = LTN12 source or string or -multipart-mesgt
-}

-multipart-mesgt = {
-  [preamble = string,]
-  [1] = mesgt,
-  [2] = mesgt,
-  ...
-  [n] = mesgt,
-  [epilogue = string,]
-}
-
-
- -

-For a simple message, all that is needed is a set of headers -and the body. The message body can be given as a string -or as a simple -LTN12 -source. For multipart messages, the body is a table that -recursively defines each part as an independent message, plus an optional -preamble and epilogue. -

- -

-The function returns a simple -LTN12 -source that produces the -message contents as defined by mesgt, chunk by chunk. -Hopefully, the following -example will make things clear. When in doubt, refer to the appropriate RFC -as listed in the introduction.

- -
--- load the smtp support and its friends
-local smtp = require("socket.smtp")
-local mime = require("mime")
-local ltn12 = require("ltn12")
-
--- creates a source to send a message with two parts. The first part is 
--- plain text, the second part is a PNG image, encoded as base64.
-source = smtp.message{
-  headers = {
-     -- Remember that headers are *ignored* by smtp.send. 
-     from = "Sicrano de Oliveira <sicrano@example.com>",
-     to = "Fulano da Silva <fulano@example.com>",
-     subject = "Here is a message with attachments"
-  },
-  body = {
-    preamble = "If your client doesn't understand attachments, \r\n" ..
-               "it will still display the preamble and the epilogue.\r\n" ..
-               "Preamble will probably appear even in a MIME enabled client.",
-    -- first part: no headers means plain text, us-ascii.
-    -- The mime.eol low-level filter normalizes end-of-line markers.
-    [1] = { 
-      body = mime.eol(0, [[
-        Lines in a message body should always end with CRLF. 
-        The smtp module will *NOT* perform translation. However, the 
-        send function *DOES* perform SMTP stuffing, whereas the message
-        function does *NOT*.
-      ]])
-    },
-    -- second part: headers describe content to be a png image, 
-    -- sent under the base64 transfer content encoding.
-    -- notice that nothing happens until the message is actually sent. 
-    -- small chunks are loaded into memory right before transmission and 
-    -- translation happens on the fly.
-    [2] = { 
-      headers = {
-        ["content-type"] = 'image/png; name="image.png"',
-        ["content-disposition"] = 'attachment; filename="image.png"',
-        ["content-description"] = 'a beautiful image',
-        ["content-transfer-encoding"] = "BASE64"
-      },
-      body = ltn12.source.chain(
-        ltn12.source.file(io.open("image.png", "rb")),
-        ltn12.filter.chain(
-          mime.encode("base64"),
-          mime.wrap()
-        )
-      )
-    },
-    epilogue = "This might also show up, but after the attachments"
-  }
-}
-
--- finally send it
-r, e = smtp.send{
-    from = "<sicrano@example.com>",
-    rcpt = "<fulano@example.com>",
-    source = source,
-}
-
- - - - - - - diff --git a/doc/luasocket/socket.html b/doc/luasocket/socket.html deleted file mode 100644 index d050a42..0000000 --- a/doc/luasocket/socket.html +++ /dev/null @@ -1,398 +0,0 @@ - - - - - - -LuaSocket: The socket namespace - - - - - - - -
-
-
- - - -
-LuaSocket -
Network support for the Lua language -
-

-home · -download · -installation · -introduction · -reference -

-
-
-
- - - -

The socket namespace

- -

-The socket namespace contains the core functionality of LuaSocket. -

- -

-To obtain the socket namespace, run: -

- -
--- loads the socket module 
-local socket = require("socket")
-
- - - -

-socket.bind(address, port [, backlog]) -

- -

-This function is a shortcut that creates and returns a TCP server object -bound to a local address and port, ready to -accept client connections. Optionally, -user can also specify the backlog argument to the -listen method (defaults to 32). -

- -

-Note: The server object returned will have the option "reuseaddr" -set to true. -

- - - -

-socket.connect(address, port [, locaddr, locport]) -

- -

-This function is a shortcut that creates and returns a TCP client object -connected to a remote host at a given port. Optionally, -the user can also specify the local address and port to bind -(locaddr and locport). -

- - - -

-socket._DEBUG -

- -

-This constant is set to true if the library was compiled -with debug support. -

- - - -

-socket.newtry(finalizer) -

- -

-Creates and returns a clean -try -function that allows for cleanup before the exception -is raised. -

- -

-Finalizer is a function that will be called before -try throws the exception. It will be called -in protected mode. -

- -

-The function returns your customized try function. -

- -

-Note: This idea saved a lot of work with the -implementation of protocols in LuaSocket: -

- -
-foo = socket.protect(function()
-    -- connect somewhere
-    local c = socket.try(socket.connect("somewhere", 42))
-    -- create a try function that closes 'c' on error
-    local try = socket.newtry(function() c:close() end)
-    -- do everything reassured c will be closed 
-    try(c:send("hello there?\r\n"))
-    local answer = try(c:receive())
-    ...
-    try(c:send("good bye\r\n"))
-    c:close()
-end)
-
- - - - -

-socket.protect(func) -

- -

-Converts a function that throws exceptions into a safe function. This -function only catches exceptions thrown by the try -and newtry functions. It does not catch normal -Lua errors. -

- -

-Func is a function that calls -try (or assert, or error) -to throw exceptions. -

- -

-Returns an equivalent function that instead of throwing exceptions, -returns nil followed by an error message. -

- -

-Note: Beware that if your function performs some illegal operation that -raises an error, the protected function will catch the error and return it -as a string. This is because the try function -uses errors as the mechanism to throw exceptions. -

- - - -

-socket.select(recvt, sendt [, timeout]) -

- -

-Waits for a number of sockets to change status. -

- -

-Recvt is an array with the sockets to test for characters -available for reading. Sockets in the sendt array are watched to -see if it is OK to immediately write on them. Timeout is the -maximum amount of time (in seconds) to wait for a change in status. A -nil, negative or omitted timeout value allows the -function to block indefinitely. Recvt and sendt can also -be empty tables or nil. Non-socket values (or values with -non-numeric indices) in the arrays will be silently ignored. -

- -

The function returns a table with the sockets ready for -reading, a table with the sockets ready for writing and an error message. -The error message is "timeout" if a timeout condition was met and -nil otherwise. The returned tables are associative, to -simplify the test if a specific socket has changed status. -

- -

-Important note: a known bug in WinSock causes select to fail -on non-blocking TCP sockets. The function may return a socket as -writable even though the socket is not ready for sending. -

- -

-Another important note: calling select with a server socket in the receive parameter before a call to accept does not guarantee -accept will return immediately. -Use the settimeout -method or accept might block forever. -

- - - -

-socket.sink(mode, socket) -

- -

-Creates an -LTN12 -sink from a stream socket object. -

- -

-Mode defines the behavior of the sink. The following -options are available: -

-
    -
  • "http-chunked": sends data through socket after applying the -chunked transfer coding, closing the socket when done; -
  • "close-when-done": sends all received data through the -socket, closing the socket when done; -
  • "keep-open": sends all received data through the -socket, leaving it open when done. -
-

-Socket is the stream socket object used to send the data. -

- -

-The function returns a sink with the appropriate behavior. -

- - - -

-socket.skip(d [, ret1, ret2 ... retN]) -

- -

-Drops a number of arguments and returns the remaining. -

- -

-D is the number of arguments to drop. Ret1 to -retN are the arguments. -

- -

-The function returns retd+1 to retN. -

- -

-Note: This function is useful to avoid creation of dummy variables: -

- -
--- get the status code and separator from SMTP server reply 
-local code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)"))
-
- - - -

-socket.sleep(time) -

- -

-Freezes the program execution during a given amount of time. -

- -

-Time is the number of seconds to sleep for. -The function truncates time down to the nearest integer. -

- - - -

-socket.source(mode, socket [, length]) -

- -

-Creates an -LTN12 -source from a stream socket object. -

- -

-Mode defines the behavior of the source. The following -options are available: -

-
    -
  • "http-chunked": receives data from socket and removes the -chunked transfer coding before returning the data; -
  • "by-length": receives a fixed number of bytes from the -socket. This mode requires the extra argument length; -
  • "until-closed": receives data from a socket until the other -side closes the connection. -
-

-Socket is the stream socket object used to receive the data. -

- -

-The function returns a source with the appropriate behavior. -

- - - -

-socket.gettime() -

- -

-Returns the time in seconds, relative to the origin of the -universe. You should subtract the values returned by this function -to get meaningful values. -

- -
-t = socket.gettime()
--- do stuff
-print(socket.gettime() - t .. " seconds elapsed")
-
- - - -

-socket.try(ret1 [, ret2 ... retN]) -

- -

-Throws an exception in case of error. The exception can only be caught -by the protect function. It does not explode -into an error message. -

- -

-Ret1 to retN can be arbitrary -arguments, but are usually the return values of a function call -nested with try. -

- -

-The function returns ret1 to retN if -ret1 is not nil. Otherwise, it calls error passing ret2. -

- -
--- connects or throws an exception with the appropriate error message
-c = socket.try(socket.connect("localhost", 80))
-
- - - -

-socket._VERSION -

- -

-This constant has a string describing the current LuaSocket version. -

- - - - - - - diff --git a/doc/luasocket/tcp.html b/doc/luasocket/tcp.html deleted file mode 100644 index 39fa6b7..0000000 --- a/doc/luasocket/tcp.html +++ /dev/null @@ -1,532 +0,0 @@ - - - - - - -LuaSocket: TCP/IP support - - - - - - - -
-
-
- - - -
-LuaSocket -
Network support for the Lua language -
-

-home · -download · -installation · -introduction · -reference -

-
-
-
- - - -

TCP

- - - -

-socket.tcp() -

- -

-Creates and returns a TCP master object. A master object can -be transformed into a server object with the method -listen (after a call to bind) or into a client object with -the method connect. The only other -method supported by a master object is the -close method.

- -

-In case of success, a new master object is returned. In case of error, -nil is returned, followed by an error message. -

- - - -

-server:accept() -

- -

-Waits for a remote connection on the server -object and returns a client object representing that connection. -

- -

-If a connection is successfully initiated, a client object is returned. -If a timeout condition is met, the method returns nil -followed by the error string 'timeout'. Other errors are -reported by nil followed by a message describing the error. -

- -

-Note: calling socket.select -with a server object in -the recvt parameter before a call to accept does -not guarantee accept will return immediately. Use the settimeout method or accept -might block until another client shows up. -

- - - -

-master:bind(address, port) -

- -

-Binds a master object to address and port on the -local host. - -

-Address can be an IP address or a host name. -Port must be an integer number in the range [0..64K). -If address -is '*', the system binds to all local interfaces -using the INADDR_ANY constant. If port is 0, the system automatically -chooses an ephemeral port. -

- -

-In case of success, the method returns 1. In case of error, the -method returns nil followed by an error message. -

- -

-Note: The function socket.bind -is available and is a shortcut for the creation of server sockets. -

- - - -

-master:close()
-client:close()
-server:close() -

- -

-Closes a TCP object. The internal socket used by the object is closed -and the local address to which the object was -bound is made available to other applications. No further operations -(except for further calls to the close method) are allowed on -a closed socket. -

- -

-Note: It is important to close all used sockets once they are not -needed, since, in many systems, each socket uses a file descriptor, -which are limited system resources. Garbage-collected objects are -automatically closed before destruction, though. -

- - - -

-master:connect(address, port) -

- -

-Attempts to connect a master object to a remote host, transforming it into a -client object. -Client objects support methods -send, -receive, -getsockname, -getpeername, -settimeout, -and close. -

- -

-Address can be an IP address or a host name. -Port must be an integer number in the range [1..64K). -

- -

-In case of error, the method returns nil followed by a string -describing the error. In case of success, the method returns 1. -

- -

-Note: The function socket.connect -is available and is a shortcut for the creation of client sockets. -

- -

-Note: Starting with LuaSocket 2.0, -the settimeout -method affects the behavior of connect, causing it to return -with an error in case of a timeout. If that happens, you can still call socket.select with the socket in the -sendt table. The socket will be writable when the connection is -established. -

- - - -

-client:getpeername() -

- -

-Returns information about the remote side of a connected client object. -

- -

-Returns a string with the IP address of the peer, followed by the -port number that peer is using for the connection. -In case of error, the method returns nil. -

- -

-Note: It makes no sense to call this method on server objects. -

- - - -

-master:getsockname()
-client:getsockname()
-server:getsockname() -

- -

-Returns the local address information associated to the object. -

- -

-The method returns a string with local IP address and a number with -the port. In case of error, the method returns nil. -

- - - -

-master:getstats()
-client:getstats()
-server:getstats()
-

- -

-Returns accounting information on the socket, useful for throttling -of bandwidth. -

- -

-The method returns the number of bytes received, the number of bytes sent, -and the age of the socket object in seconds. -

- - - -

-master:listen(backlog) -

- -

-Specifies the socket is willing to receive connections, transforming the -object into a server object. Server objects support the -accept, -getsockname, -setoption, -settimeout, -and close methods. -

- -

-The parameter backlog specifies the number of client -connections that can -be queued waiting for service. If the queue is full and another client -attempts connection, the connection is refused. -

- -

-In case of success, the method returns 1. In case of error, the -method returns nil followed by an error message. -

- - - -

-client:receive([pattern [, prefix]]) -

- -

-Reads data from a client object, according to the specified read -pattern. Patterns follow the Lua file I/O format, and the difference in performance between all patterns is negligible. -

- -

-Pattern can be any of the following: -

- -
    -
  • '*a': reads from the socket until the connection is -closed. No end-of-line translation is performed; -
  • '*l': reads a line of text from the socket. The line is -terminated by a LF character (ASCII 10), optionally preceded by a -CR character (ASCII 13). The CR and LF characters are not included in -the returned line. This is the default pattern; -
  • number: causes the method to read a specified number -of bytes from the socket. -
- -

-Prefix is an optional string to be concatenated to the beginning -of any received data before return. -

- -

-If successful, the method returns the received pattern. In case of error, -the method returns nil followed by an error message which -can be the string 'closed' in case the connection was -closed before the transmission was completed or the string -'timeout' in case there was a timeout during the operation. -Also, after the error message, the function returns the partial result of -the transmission. -

- -

-Important note: This function was changed severely. It used -to support multiple patterns (but I have never seen this feature used) and -now it doesn't anymore. Partial results used to be returned in the same -way as successful results. This last feature violated the idea that all -functions should return nil on error. Thus it was changed -too. -

- - - -

-client:send(data [, i [, j]]) -

- -

-Sends data through client object. -

- -

-Data is the string to be sent. The optional arguments -i and j work exactly like the standard -string.sub Lua function to allow the selection of a -substring to be sent. -

- -

-If successful, the method returns the index of the last byte -within [i, j] that has been sent. Notice that, if -i is 1 or absent, this is effectively the total -number of bytes sent. In case of error, the method returns -nil, followed by an error message, followed -by the index of the last byte within [i, j] that -has been sent. You might want to try again from the byte -following that. The error message can be 'closed' -in case the connection was closed before the transmission -was completed or the string 'timeout' in case -there was a timeout during the operation. -

- -

-Note: Output is not buffered. For small strings, -it is always better to concatenate them in Lua -(with the '..' operator) and send the result in one call -instead of calling the method several times. -

- - - -

-client:setoption(option [, value])
-server:setoption(option [, value]) -

- -

-Sets options for the TCP object. Options are only needed by low-level or -time-critical applications. You should only modify an option if you -are sure you need it. -

- -

-Option is a string with the option name, and value -depends on the option being set: - -

    - -
  • 'keepalive': Setting this option to true enables -the periodic transmission of messages on a connected socket. Should the -connected party fail to respond to these messages, the connection is -considered broken and processes using the socket are notified; - -
  • 'linger': Controls the action taken when unsent data are -queued on a socket and a close is performed. The value is a table with a -boolean entry 'on' and a numeric entry for the time interval -'timeout' in seconds. If the 'on' field is set to -true, the system will block the process on the close attempt until -it is able to transmit the data or until 'timeout' has passed. If -'on' is false and a close is issued, the system will -process the close in a manner that allows the process to continue as -quickly as possible. I do not advise you to set this to anything other than -zero; - -
  • 'reuseaddr': Setting this option indicates that the rules -used in validating addresses supplied in a call to -bind should allow reuse of local addresses; - -
  • 'tcp-nodelay': Setting this option to true -disables the Nagle's algorithm for the connection. - -
- -

-The method returns 1 in case of success, or nil otherwise. -

- -

-Note: The descriptions above come from the man pages. -

- - - -

-master:setstats(received, sent, age)
-client:setstats(received, sent, age)
-server:setstats(received, sent, age)
-

- -

-Resets accounting information on the socket, useful for throttling -of bandwidth. -

- -

-Received is a number with the new number of bytes received. -Sent is a number with the new number of bytes sent. -Age is the new age in seconds. -

- -

-The method returns 1 in case of success and nil otherwise. -

- - - -

-master:settimeout(value [, mode])
-client:settimeout(value [, mode])
-server:settimeout(value [, mode]) -

- -

-Changes the timeout values for the object. By default, -all I/O operations are blocking. That is, any call to the methods -send, -receive, and -accept -will block indefinitely, until the operation completes. The -settimeout method defines a limit on the amount of time the -I/O methods can block. When a timeout is set and the specified amount of -time has elapsed, the affected methods give up and fail with an error code. -

- -

-The amount of time to wait is specified as the -value parameter, in seconds. There are two timeout modes and -both can be used together for fine tuning: -

- -
    -
  • 'b': block timeout. Specifies the upper limit on -the amount of time LuaSocket can be blocked by the operating system -while waiting for completion of any single I/O operation. This is the -default mode;
  • - -
  • 't': total timeout. Specifies the upper limit on -the amount of time LuaSocket can block a Lua script before returning from -a call.
  • -
- -

-The nil timeout value allows operations to block -indefinitely. Negative timeout values have the same effect. -

- -

-Note: although timeout values have millisecond precision in LuaSocket, -large blocks can cause I/O functions not to respect timeout values due -to the time the library takes to transfer blocks to and from the OS -and to and from the Lua interpreter. Also, function that accept host names -and perform automatic name resolution might be blocked by the resolver for -longer than the specified timeout value. -

- -

-Note: The old timeout method is deprecated. The name has been -changed for sake of uniformity, since all other method names already -contained verbs making their imperative nature obvious. -

- - - -

-client:shutdown(mode)
-

- -

-Shuts down part of a full-duplex connection. -

- -

-Mode tells which way of the connection should be shut down and can -take the value: -

    -
  • "both": disallow further sends and receives on the object. -This is the default mode; -
  • "send": disallow further sends on the object; -
  • "receive": disallow further receives on the object. -
- -

-This function returns 1. -

- - - - - - - diff --git a/doc/luasocket/udp.html b/doc/luasocket/udp.html deleted file mode 100644 index 60c5ba3..0000000 --- a/doc/luasocket/udp.html +++ /dev/null @@ -1,416 +0,0 @@ - - - - - - -LuaSocket: UDP support - - - - - - - -
-
-
- - - -
-LuaSocket -
Network support for the Lua language -
-

-home · -download · -installation · -introduction · -reference -

-
-
-
- - - - -

UDP

- - - -

-socket.udp() -

- -

-Creates and returns an unconnected UDP object. Unconnected objects support the -sendto, -receive, -receivefrom, -getsockname, -setoption, -settimeout, -setpeername, -setsockname, and -close. -The setpeername -is used to connect the object. -

- -

-In case of success, a new unconnected UDP object -returned. In case of error, nil is returned, followed by -an error message. -

- - - -

-connected:close()
-unconnected:close() -

- -

-Closes a UDP object. The internal socket -used by the object is closed and the local address to which the -object was bound is made available to other applications. No -further operations (except for further calls to the close -method) are allowed on a closed socket. -

- -

-Note: It is important to close all used sockets -once they are not needed, since, in many systems, each socket uses -a file descriptor, which are limited system resources. -Garbage-collected objects are automatically closed before -destruction, though. -

- - - -

-connected:getpeername() -

- -

-Retrieves information about the peer -associated with a connected UDP object. -

- -

-Returns the IP address and port number of the peer. -

- -

-Note: It makes no sense to call this method on unconnected objects. -

- - - -

-connected:getsockname()
-unconnected:getsockname() -

- -

-Returns the local address information associated to the object. -

- -

-The method returns a string with local IP -address and a number with the port. In case of error, the method -returns nil. -

- -

-Note: UDP sockets are not bound to any address -until the setsockname or the -sendto method is called for the -first time (in which case it is bound to an ephemeral port and the -wild-card address). -

- - - -

-connected:receive([size])
-unconnected:receive([size]) -

- -

-Receives a datagram from the UDP object. If -the UDP object is connected, only datagrams coming from the peer -are accepted. Otherwise, the returned datagram can come from any -host. -

- -

-The optional size parameter -specifies the maximum size of the datagram to be retrieved. If -there are more than size bytes available in the datagram, -the excess bytes are discarded. If there are less then -size bytes available in the current datagram, the -available bytes are returned. If size is omitted, the -maximum datagram size is used (which is currently limited by the -implementation to 8192 bytes). -

- -

-In case of success, the method returns the -received datagram. In case of timeout, the method returns -nil followed by the string 'timeout'. -

- - - -

-unconnected:receivefrom([size]) -

- -

-Works exactly as the receive -method, except it returns the IP -address and port as extra return values (and is therefore slightly less -efficient). -

- - - -

-connected:send(datagram) -

- -

-Sends a datagram to the UDP peer of a connected object. -

- -

-Datagram is a string with the datagram contents. -The maximum datagram size for UDP is 64K minus IP layer overhead. -However datagrams larger than the link layer packet size will be -fragmented, which may deteriorate performance and/or reliability. -

- -

-If successful, the method returns 1. In case of -error, the method returns nil followed by an error message. -

- -

-Note: In UDP, the send method never blocks -and the only way it can fail is if the underlying transport layer -refuses to send a message to the specified address (i.e. no -interface accepts the address). -

- - - -

-unconnected:sendto(datagram, ip, port) -

- -

-Sends a datagram to the specified IP address and port number. -

- -

-Datagram is a string with the -datagram contents. -The maximum datagram size for UDP is 64K minus IP layer overhead. -However datagrams larger than the link layer packet size will be -fragmented, which may deteriorate performance and/or reliability. -Ip is the IP address of the recipient. -Host names are not allowed for performance reasons. - -Port is the port number at the recipient. -

- -

-If successful, the method returns 1. In case of -error, the method returns nil followed by an error message. -

- -

-Note: In UDP, the send method never blocks -and the only way it can fail is if the underlying transport layer -refuses to send a message to the specified address (i.e. no -interface accepts the address). -

- - - -

-connected:setpeername('*')
-unconnected:setpeername(address, port) -

- -

-Changes the peer of a UDP object. This -method turns an unconnected UDP object into a connected UDP -object or vice versa. -

- -

-For connected objects, outgoing datagrams -will be sent to the specified peer, and datagrams received from -other peers will be discarded by the OS. Connected UDP objects must -use the send and -receive methods instead of -sendto and -receivefrom. -

- -

-Address can be an IP address or a -host name. Port is the port number. If address is -'*' and the object is connected, the peer association is -removed and the object becomes an unconnected object again. In that -case, the port argument is ignored. -

- -

-In case of error the method returns -nil followed by an error message. In case of success, the -method returns 1. -

- -

-Note: Since the address of the peer does not have -to be passed to and from the OS, the use of connected UDP objects -is recommended when the same peer is used for several transmissions -and can result in up to 30% performance gains. -

- - - -

-unconnected:setsockname(address, port) -

- -

-Binds the UDP object to a local address. -

- -

-Address can be an IP address or a -host name. If address is '*' the system binds to -all local interfaces using the constant INADDR_ANY. If -port is 0, the system chooses an ephemeral port. -

- -

-If successful, the method returns 1. In case of -error, the method returns nil followed by an error -message. -

- -

-Note: This method can only be called before any -datagram is sent through the UDP object, and only once. Otherwise, -the system automatically binds the object to all local interfaces -and chooses an ephemeral port as soon as the first datagram is -sent. After the local address is set, either automatically by the -system or explicitly by setsockname, it cannot be -changed. -

- - - -

-connected:setoption(option [, value])
-unconnected:setoption(option [, value]) -

- -

-Sets options for the UDP object. Options are -only needed by low-level or time-critical applications. You should -only modify an option if you are sure you need it.

-

Option is a string with the option -name, and value depends on the option being set: -

- -
    -
  • 'dontroute': Setting this option to true -indicates that outgoing messages should bypass the standard routing -facilities;
  • -
  • 'broadcast': Setting this option to true -requests permission to send broadcast datagrams on the -socket.
  • -
- -

-The method returns 1 in case of success, or -nil followed by an error message otherwise. -

- -

-Note: The descriptions above come from the man -pages. -

- - - -

-connected:settimeout(value)
-unconnected:settimeout(value) -

- -

-Changes the timeout values for the object. By default, the -receive and -receivefrom -operations are blocking. That is, any call to the methods will block -indefinitely, until data arrives. The settimeout function defines -a limit on the amount of time the functions can block. When a timeout is -set and the specified amount of time has elapsed, the affected methods -give up and fail with an error code. -

- -

-The amount of time to wait is specified as -the value parameter, in seconds. The nil timeout -value allows operations to block indefinitely. Negative -timeout values have the same effect. -

- -

-Note: In UDP, the send -and sendto methods never block (the -datagram is just passed to the OS and the call returns -immediately). Therefore, the settimeout method has no -effect on them. -

- -

-Note: The old timeout method is -deprecated. The name has been changed for sake of uniformity, since -all other method names already contained verbs making their -imperative nature obvious. -

- - - - - - - diff --git a/doc/luasocket/url.html b/doc/luasocket/url.html deleted file mode 100644 index 5785224..0000000 --- a/doc/luasocket/url.html +++ /dev/null @@ -1,329 +0,0 @@ - - - - - - -LuaSocket: URL support - - - - - - - -
-
-
- - - -
-LuaSocket -
Network support for the Lua language -
-

-home · -download · -installation · -introduction · -reference -

-
-
-
- - - -

URL

- -

-The url namespace provides functions to parse, protect, -and build URLs, as well as functions to compose absolute URLs -from base and relative URLs, according to -RFC -2396. -

- -

-To obtain the url namespace, run: -

- -
--- loads the URL module 
-local url = require("socket.url")
-
- -

-An URL is defined by the following grammar: -

- -
- -<url> ::= [<scheme>:][//<authority>][/<path>][;<params>][?<query>][#<fragment>]
-<authority> ::= [<userinfo>@]<host>[:<port>]
-<userinfo> ::= <user>[:<password>]
-<path> ::= {<segment>/}<segment>
-
-
- - - -

-url.absolute(base, relative) -

- -

-Builds an absolute URL from a base URL and a relative URL. -

- -

-Base is a string with the base URL or -a parsed URL table. Relative is a -string with the relative URL. -

- -

-The function returns a string with the absolute URL. -

- -

-Note: The rules that -govern the composition are fairly complex, and are described in detail in -RFC 2396. -The example bellow should give an idea of what the rules are. -

- -
-http://a/b/c/d;p?q
-
-+
-
-g:h      =  g:h
-g        =  http://a/b/c/g
-./g      =  http://a/b/c/g
-g/       =  http://a/b/c/g/
-/g       =  http://a/g
-//g      =  http://g
-?y       =  http://a/b/c/?y
-g?y      =  http://a/b/c/g?y
-#s       =  http://a/b/c/d;p?q#s
-g#s      =  http://a/b/c/g#s
-g?y#s    =  http://a/b/c/g?y#s
-;x       =  http://a/b/c/;x
-g;x      =  http://a/b/c/g;x
-g;x?y#s  =  http://a/b/c/g;x?y#s
-.        =  http://a/b/c/
-./       =  http://a/b/c/
-..       =  http://a/b/
-../      =  http://a/b/
-../g     =  http://a/b/g
-../..    =  http://a/
-../../   =  http://a/
-../../g  =  http://a/g
-
- - - -

-url.build(parsed_url) -

- -

-Rebuilds an URL from its parts. -

- -

-Parsed_url is a table with same components returned by -parse. -Lower level components, if specified, -take precedence over high level components of the URL grammar. -

- -

-The function returns a string with the built URL. -

- - - -

-url.build_path(segments, unsafe) -

- -

-Builds a <path> component from a list of -<segment> parts. -Before composition, any reserved characters found in a segment are escaped into -their protected form, so that the resulting path is a valid URL path -component. -

- -

-Segments is a list of strings with the <segment> -parts. If unsafe is anything but nil, reserved -characters are left untouched. -

- -

-The function returns a string with the -built <path> component. -

- - - -

-url.escape(content) -

- -

-Applies the URL escaping content coding to a string -Each byte is encoded as a percent character followed -by the two byte hexadecimal representation of its integer -value. -

- -

-Content is the string to be encoded. -

- -

-The function returns the encoded string. -

- -
--- load url module
-url = require("socket.url")
-
-code = url.escape("/#?;")
--- code = "%2f%23%3f%3b"
-
- - - -

-url.parse(url, default) -

- -

-Parses an URL given as a string into a Lua table with its components. -

- -

-Url is the URL to be parsed. If the default table is -present, it is used to store the parsed fields. Only fields present in the -URL are overwritten. Therefore, this table can be used to pass default -values for each field. -

- -

-The function returns a table with all the URL components: -

- -
-parsed_url = {
-  url = string,
-  scheme = string,
-  authority = string,
-  path = string,
-  params = string,
-  query = string,
-  fragment = string,
-  userinfo = string,
-  host = string,
-  port = string,
-  user = string,
-  password = string
-} -
- -
--- load url module
-url = require("socket.url")
-
-parsed_url = url.parse("http://www.example.com/cgilua/index.lua?a=2#there")
--- parsed_url = {
---   scheme = "http",
---   authority = "www.example.com",
---   path = "/cgilua/index.lua"
---   query = "a=2",
---   fragment = "there",
---   host = "www.puc-rio.br",
--- }
-
-parsed_url = url.parse("ftp://root:passwd@unsafe.org/pub/virus.exe;type=i")
--- parsed_url = {
---   scheme = "ftp",
---   authority = "root:passwd@unsafe.org",
---   path = "/pub/virus.exe",
---   params = "type=i",
---   userinfo = "root:passwd",
---   host = "unsafe.org",
---   user = "root",
---   password = "passwd",
--- }
-
- - - -

-url.parse_path(path) -

- -

-Breaks a <path> URL component into all its -<segment> parts. -

- -

-Path is a string with the path to be parsed. -

- -

-Since some characters are reserved in URLs, they must be escaped -whenever present in a <path> component. Therefore, before -returning a list with all the parsed segments, the function removes -escaping from all of them. -

- - - -

-url.unescape(content) -

- -

-Removes the URL escaping content coding from a string. -

- -

-Content is the string to be decoded. -

- -

-The function returns the decoded string. -

- - - - - - - diff --git a/etc/install.sh b/etc/install.sh deleted file mode 100755 index 03fe6d9..0000000 --- a/etc/install.sh +++ /dev/null @@ -1,11 +0,0 @@ -#! /bin/sh - -# ONLY FOR MAINTAINER USE!! - -destdir="$HOME/.minetest/games/testing/mods/irc"; - -echo rm -fr "\"$destdir\""; -rm -fr "$destdir"; - -echo cp -fr Build/irc "\"$destdir\""; -cp -fr Build/irc "$destdir"; diff --git a/etc/luasocket-samples/README b/etc/luasocket-samples/README deleted file mode 100644 index e63a6f5..0000000 --- a/etc/luasocket-samples/README +++ /dev/null @@ -1,50 +0,0 @@ -This directory contains some sample programs using -LuaSocket. This code is not supported. - - listener.lua -- socket to stdout - talker.lua -- stdin to socket - -listener.lua and talker.lua are about the simplest -applications you can write using LuaSocket. Run - - 'lua listener.lua' and 'lua talker.lua' - -on different terminals. Whatever you type on talk.lua will -be printed by listen.lua. - - lpr.lua -- lpr client - -This is a cool program written by David Burgess to print -files using the Line Printer Daemon protocol, widely used in -Unix machines. It uses the lp.lua implementation, in the -etc directory. Just run 'lua lpr.lua -queue=' and the file will print! - - cddb.lua -- CDDB client - -This is the first try on a simple CDDB client. Not really -useful, but one day it might become a module. - - daytimeclnt.lua -- day time client - -Just run the program to retrieve the hour and date in -readable form from any server running an UDP daytime daemon. - - echoclnt.lua -- UDP echo client - echosrvr.lua -- UDP echo server - -These are a UDP echo client/server pair. They work with -other client and servers as well. - - tinyirc.lua -- irc like broadcast server - -This is a simple server that waits simultaneously on two -server sockets for telnet connections. Everything it -receives from the telnet clients is broadcasted to every -other connected client. It tests the select function and -shows how to create a simple server whith LuaSocket. Just -run tinyirc.lua and then open as many telnet connections -as you want to ports 8080 and 8081. - -Good luck, -Diego. diff --git a/etc/luasocket-samples/cddb.lua b/etc/luasocket-samples/cddb.lua deleted file mode 100644 index 883730c..0000000 --- a/etc/luasocket-samples/cddb.lua +++ /dev/null @@ -1,46 +0,0 @@ -local socket = require("socket") -local http = require("socket.http") - -if not arg or not arg[1] or not arg[2] then - print("luasocket cddb.lua []") - os.exit(1) -end - -local server = arg[3] or "http://freedb.freedb.org/~cddb/cddb.cgi" - -function parse(body) - local lines = string.gfind(body, "(.-)\r\n") - local status = lines() - local code, message = socket.skip(2, string.find(status, "(%d%d%d) (.*)")) - if tonumber(code) ~= 210 then - return nil, code, message - end - local data = {} - for l in lines do - local c = string.sub(l, 1, 1) - if c ~= '#' and c ~= '.' then - local key, value = socket.skip(2, string.find(l, "(.-)=(.*)")) - value = string.gsub(value, "\\n", "\n") - value = string.gsub(value, "\\\\", "\\") - value = string.gsub(value, "\\t", "\t") - data[key] = value - end - end - return data, code, message -end - -local host = socket.dns.gethostname() -local query = "%s?cmd=cddb+read+%s+%s&hello=LuaSocket+%s+LuaSocket+2.0&proto=6" -local url = string.format(query, server, arg[1], arg[2], host) -local body, headers, code = http.get(url) - -if code == 200 then - local data, code, error = parse(body) - if not data then - print(error or code) - else - for i,v in pairs(data) do - io.write(i, ': ', v, '\n') - end - end -else print(error) end diff --git a/etc/luasocket-samples/daytimeclnt.lua b/etc/luasocket-samples/daytimeclnt.lua deleted file mode 100644 index 90ab39e..0000000 --- a/etc/luasocket-samples/daytimeclnt.lua +++ /dev/null @@ -1,23 +0,0 @@ ------------------------------------------------------------------------------ --- UDP sample: daytime protocol client --- LuaSocket sample files --- Author: Diego Nehab --- RCS ID: $Id: daytimeclnt.lua,v 1.11 2004/06/21 06:07:57 diego Exp $ ------------------------------------------------------------------------------ -local socket = require"socket" -host = host or "127.0.0.1" -port = port or 13 -if arg then - host = arg[1] or host - port = arg[2] or port -end -host = socket.dns.toip(host) -udp = socket.udp() -print("Using host '" ..host.. "' and port " ..port.. "...") -udp:setpeername(host, port) -udp:settimeout(3) -sent, err = udp:send("anything") -if err then print(err) os.exit() end -dgram, err = udp:receive() -if not dgram then print(err) os.exit() end -io.write(dgram) diff --git a/etc/luasocket-samples/echoclnt.lua b/etc/luasocket-samples/echoclnt.lua deleted file mode 100644 index 038be4c..0000000 --- a/etc/luasocket-samples/echoclnt.lua +++ /dev/null @@ -1,24 +0,0 @@ ------------------------------------------------------------------------------ --- UDP sample: echo protocol client --- LuaSocket sample files --- Author: Diego Nehab --- RCS ID: $Id: echoclnt.lua,v 1.10 2005/01/02 22:44:00 diego Exp $ ------------------------------------------------------------------------------ -local socket = require("socket") -host = host or "localhost" -port = port or 7 -if arg then - host = arg[1] or host - port = arg[2] or port -end -host = socket.dns.toip(host) -udp = assert(socket.udp()) -assert(udp:setpeername(host, port)) -print("Using remote host '" ..host.. "' and port " .. port .. "...") -while 1 do - line = io.read() - if not line or line == "" then os.exit() end - assert(udp:send(line)) - dgram = assert(udp:receive()) - print(dgram) -end diff --git a/etc/luasocket-samples/echosrvr.lua b/etc/luasocket-samples/echosrvr.lua deleted file mode 100644 index 2697ca4..0000000 --- a/etc/luasocket-samples/echosrvr.lua +++ /dev/null @@ -1,29 +0,0 @@ ------------------------------------------------------------------------------ --- UDP sample: echo protocol server --- LuaSocket sample files --- Author: Diego Nehab --- RCS ID: $Id: echosrvr.lua,v 1.12 2005/11/22 08:33:29 diego Exp $ ------------------------------------------------------------------------------ -local socket = require("socket") -host = host or "127.0.0.1" -port = port or 7 -if arg then - host = arg[1] or host - port = arg[2] or port -end -print("Binding to host '" ..host.. "' and port " ..port.. "...") -udp = assert(socket.udp()) -assert(udp:setsockname(host, port)) -assert(udp:settimeout(5)) -ip, port = udp:getsockname() -assert(ip, port) -print("Waiting packets on " .. ip .. ":" .. port .. "...") -while 1 do - dgram, ip, port = udp:receivefrom() - if dgram then - print("Echoing '" .. dgram .. "' to " .. ip .. ":" .. port) - udp:sendto(dgram, ip, port) - else - print(ip) - end -end diff --git a/etc/luasocket-samples/listener.lua b/etc/luasocket-samples/listener.lua deleted file mode 100644 index 9260fbb..0000000 --- a/etc/luasocket-samples/listener.lua +++ /dev/null @@ -1,26 +0,0 @@ ------------------------------------------------------------------------------ --- TCP sample: Little program to dump lines received at a given port --- LuaSocket sample files --- Author: Diego Nehab --- RCS ID: $Id: listener.lua,v 1.11 2005/01/02 22:44:00 diego Exp $ ------------------------------------------------------------------------------ -local socket = require("socket") -host = host or "*" -port = port or 8080 -if arg then - host = arg[1] or host - port = arg[2] or port -end -print("Binding to host '" ..host.. "' and port " ..port.. "...") -s = assert(socket.bind(host, port)) -i, p = s:getsockname() -assert(i, p) -print("Waiting connection from talker on " .. i .. ":" .. p .. "...") -c = assert(s:accept()) -print("Connected. Here is the stuff:") -l, e = c:receive() -while not e do - print(l) - l, e = c:receive() -end -print(e) diff --git a/etc/luasocket-samples/lpr.lua b/etc/luasocket-samples/lpr.lua deleted file mode 100644 index 2b059b1..0000000 --- a/etc/luasocket-samples/lpr.lua +++ /dev/null @@ -1,51 +0,0 @@ -local lp = require("socket.lp") - -local function usage() - print('\nUsage: lua lpr.lua [filename] [keyword=val...]\n') - print('Valid keywords are :') - print( - ' host=remote host or IP address (default "localhost")\n' .. - ' queue=remote queue or printer name (default "printer")\n' .. - ' port=remote port number (default 515)\n' .. - ' user=sending user name\n' .. - ' format=["binary" | "text" | "ps" | "pr" | "fortran"] (default "binary")\n' .. - ' banner=true|false\n' .. - ' indent=number of columns to indent\n' .. - ' mail=email of address to notify when print is complete\n' .. - ' title=title to use for "pr" format\n' .. - ' width=width for "text" or "pr" formats\n' .. - ' class=\n' .. - ' job=\n' .. - ' name=\n' .. - ' localbind=true|false\n' - ) - return nil -end - -if not arg or not arg[1] then - return usage() -end - -do - local opt = {} - local pat = "[%s%c%p]*([%w]*)=([\"]?[%w%s_!@#$%%^&*()<>:;]+[\"]\?\.?)" - for i = 2, table.getn(arg), 1 do - string.gsub(arg[i], pat, function(name, value) opt[name] = value end) - end - if not arg[2] then - return usage() - end - if arg[1] ~= "query" then - opt.file = arg[1] - r,e=lp.send(opt) - io.stdout:write(tostring(r or e),'\n') - else - r,e=lp.query(opt) - io.stdout:write(tostring(r or e), '\n') - end -end - --- trivial tests ---lua lp.lua lp.lua queue=default host=localhost ---lua lp.lua lp.lua queue=default host=localhost format=binary localbind=1 ---lua lp.lua query queue=default host=localhost diff --git a/etc/luasocket-samples/talker.lua b/etc/luasocket-samples/talker.lua deleted file mode 100644 index 607ff31..0000000 --- a/etc/luasocket-samples/talker.lua +++ /dev/null @@ -1,21 +0,0 @@ ------------------------------------------------------------------------------ --- TCP sample: Little program to send text lines to a given host/port --- LuaSocket sample files --- Author: Diego Nehab --- RCS ID: $Id: talker.lua,v 1.9 2005/01/02 22:44:00 diego Exp $ ------------------------------------------------------------------------------ -local socket = require("socket") -host = host or "localhost" -port = port or 8080 -if arg then - host = arg[1] or host - port = arg[2] or port -end -print("Attempting connection to host '" ..host.. "' and port " ..port.. "...") -c = assert(socket.connect(host, port)) -print("Connected! Please type stuff (empty line to stop):") -l = io.read() -while l and l ~= "" and not e do - assert(c:send(l .. "\n")) - l = io.read() -end diff --git a/etc/luasocket-samples/tinyirc.lua b/etc/luasocket-samples/tinyirc.lua deleted file mode 100644 index f474302..0000000 --- a/etc/luasocket-samples/tinyirc.lua +++ /dev/null @@ -1,90 +0,0 @@ ------------------------------------------------------------------------------ --- Select sample: simple text line server --- LuaSocket sample files. --- Author: Diego Nehab --- RCS ID: $Id: tinyirc.lua,v 1.14 2005/11/22 08:33:29 diego Exp $ ------------------------------------------------------------------------------ -local socket = require("socket") -host = host or "*" -port1 = port1 or 8080 -port2 = port2 or 8181 -if arg then - host = arg[1] or host - port1 = arg[2] or port1 - port2 = arg[3] or port2 -end - -server1 = assert(socket.bind(host, port1)) -server2 = assert(socket.bind(host, port2)) -server1:settimeout(1) -- make sure we don't block in accept -server2:settimeout(1) - -io.write("Servers bound\n") - --- simple set implementation --- the select function doesn't care about what is passed to it as long as --- it behaves like a table --- creates a new set data structure -function newset() - local reverse = {} - local set = {} - return setmetatable(set, {__index = { - insert = function(set, value) - if not reverse[value] then - table.insert(set, value) - reverse[value] = table.getn(set) - end - end, - remove = function(set, value) - local index = reverse[value] - if index then - reverse[value] = nil - local top = table.remove(set) - if top ~= value then - reverse[top] = index - set[index] = top - end - end - end - }}) -end - -set = newset() - -io.write("Inserting servers in set\n") -set:insert(server1) -set:insert(server2) - -while 1 do - local readable, _, error = socket.select(set, nil) - for _, input in ipairs(readable) do - -- is it a server socket? - if input == server1 or input == server2 then - io.write("Waiting for clients\n") - local new = input:accept() - if new then - new:settimeout(1) - io.write("Inserting client in set\n") - set:insert(new) - end - -- it is a client socket - else - local line, error = input:receive() - if error then - input:close() - io.write("Removing client from set\n") - set:remove(input) - else - io.write("Broadcasting line '", line, "'\n") - writable, error = socket.skip(1, socket.select(nil, set, 1)) - if not error then - for __, output in ipairs(writable) do - if output ~= input then - output:send(line .. "\n") - end - end - else io.write("No client ready to receive!!!\n") end - end - end - end -end diff --git a/etc/luasocket/README b/etc/luasocket/README deleted file mode 100644 index 5a919cd..0000000 --- a/etc/luasocket/README +++ /dev/null @@ -1,89 +0,0 @@ -This directory contains code that is more useful than the -samples. This code *is* supported. - - tftp.lua -- Trivial FTP client - -This module implements file retrieval by the TFTP protocol. -Its main use was to test the UDP code, but since someone -found it usefull, I turned it into a module that is almost -official (no uploads, yet). - - dict.lua -- Dict client - -The dict.lua module started with a cool simple client -for the DICT protocol, written by Luiz Henrique Figueiredo. -This new version has been converted into a library, similar -to the HTTP and FTP libraries, that can be used from within -any luasocket application. Take a look on the source code -and you will be able to figure out how to use it. - - lp.lua -- LPD client library - -The lp.lua module implements the client part of the Line -Printer Daemon protocol, used to print files on Unix -machines. It is courtesy of David Burgess! See the source -code and the lpr.lua in the examples directory. - - b64.lua - qp.lua - eol.lua - -These are tiny programs that perform Base64, -Quoted-Printable and end-of-line marker conversions. - - get.lua -- file retriever - -This little program is a client that uses the FTP and -HTTP code to implement a command line file graber. Just -run - - lua get.lua [] - -to download a remote file (either ftp:// or http://) to -the specified local file. The program also prints the -download throughput, elapsed time, bytes already downloaded -etc during download. - - check-memory.lua -- checks memory consumption - -This is just to see how much memory each module uses. - - dispatch.lua -- coroutine based dispatcher - -This is a first try at a coroutine based non-blocking -dispatcher for LuaSocket. Take a look at 'check-links.lua' -and at 'forward.lua' to see how to use it. - - check-links.lua -- HTML link checker program - -This little program scans a HTML file and checks for broken -links. It is similar to check-links.pl by Jamie Zawinski, -but uses all facilities of the LuaSocket library and the Lua -language. It has not been thoroughly tested, but it should -work. Just run - - lua check-links.lua [-n] {} > output - -and open the result to see a list of broken links. You can -also use the '-n' switch to run the same program in -non-blocking mode to see how much faster things can get. - - forward.lua -- coroutine based forward server - -This is a forward server that can accept several connections -and transfers simultaneously using non-blocking I/O and the -coroutine-based dispatcher. You can run, for example - - lua forward.lua 8080:proxy.com:3128 - -to redirect all local conections to port 8080 to the host -'proxy.com' at port 3128. - - unix.c and unix.h - -This is an implementation of Unix local domain sockets and -demonstrates how to extend LuaSocket with a new type of -transport. It has been tested on Linux and on Mac OS X. - -Good luck, -Diego. diff --git a/etc/luasocket/b64.lua b/etc/luasocket/b64.lua deleted file mode 100644 index f75c423..0000000 --- a/etc/luasocket/b64.lua +++ /dev/null @@ -1,20 +0,0 @@ ------------------------------------------------------------------------------ --- Little program to convert to and from Base64 --- LuaSocket sample files --- Author: Diego Nehab --- RCS ID: $Id: b64.lua,v 1.8 2004/06/16 04:28:21 diego Exp $ ------------------------------------------------------------------------------ -local ltn12 = require("ltn12") -local mime = require("mime") -local source = ltn12.source.file(io.stdin) -local sink = ltn12.sink.file(io.stdout) -local convert -if arg and arg[1] == '-d' then - convert = mime.decode("base64") -else - local base64 = mime.encode("base64") - local wrap = mime.wrap() - convert = ltn12.filter.chain(base64, wrap) -end -sink = ltn12.sink.chain(convert, sink) -ltn12.pump.all(source, sink) diff --git a/etc/luasocket/check-links.lua b/etc/luasocket/check-links.lua deleted file mode 100644 index a989f8c..0000000 --- a/etc/luasocket/check-links.lua +++ /dev/null @@ -1,112 +0,0 @@ ------------------------------------------------------------------------------ --- Little program that checks links in HTML files, using coroutines and --- non-blocking I/O via the dispatcher module. --- LuaSocket sample files --- Author: Diego Nehab --- RCS ID: $$ ------------------------------------------------------------------------------ -local url = require("socket.url") -local dispatch = require("dispatch") -local http = require("socket.http") -dispatch.TIMEOUT = 10 - --- make sure the user knows how to invoke us -arg = arg or {} -if table.getn(arg) < 1 then - print("Usage:\n luasocket check-links.lua [-n] {}") - exit() -end - --- '-n' means we are running in non-blocking mode -if arg[1] == "-n" then - -- if non-blocking I/O was requested, use real dispatcher interface - table.remove(arg, 1) - handler = dispatch.newhandler("coroutine") -else - -- if using blocking I/O, use fake dispatcher interface - handler = dispatch.newhandler("sequential") -end - -local nthreads = 0 - --- get the status of a URL using the dispatcher -function getstatus(link) - local parsed = url.parse(link, {scheme = "file"}) - if parsed.scheme == "http" then - nthreads = nthreads + 1 - handler:start(function() - local r, c, h, s = http.request{ - method = "HEAD", - url = link, - create = handler.tcp - } - if r and c == 200 then io.write('\t', link, '\n') - else io.write('\t', link, ': ', tostring(c), '\n') end - nthreads = nthreads - 1 - end) - end -end - -function readfile(path) - path = url.unescape(path) - local file, error = io.open(path, "r") - if file then - local body = file:read("*a") - file:close() - return body - else return nil, error end -end - -function load(u) - local parsed = url.parse(u, { scheme = "file" }) - local body, headers, code, error - local base = u - if parsed.scheme == "http" then - body, code, headers = http.request(u) - if code == 200 then - -- if there was a redirect, update base to reflect it - base = headers.location or base - end - if not body then - error = code - end - elseif parsed.scheme == "file" then - body, error = readfile(parsed.path) - else error = string.format("unhandled scheme '%s'", parsed.scheme) end - return base, body, error -end - -function getlinks(body, base) - -- get rid of comments - body = string.gsub(body, "%<%!%-%-.-%-%-%>", "") - local links = {} - -- extract links - body = string.gsub(body, '[Hh][Rr][Ee][Ff]%s*=%s*"([^"]*)"', function(href) - table.insert(links, url.absolute(base, href)) - end) - body = string.gsub(body, "[Hh][Rr][Ee][Ff]%s*=%s*'([^']*)'", function(href) - table.insert(links, url.absolute(base, href)) - end) - string.gsub(body, "[Hh][Rr][Ee][Ff]%s*=%s*(.-)>", function(href) - table.insert(links, url.absolute(base, href)) - end) - return links -end - -function checklinks(address) - local base, body, error = load(address) - if not body then print(error) return end - print("Checking ", base) - local links = getlinks(body, base) - for _, link in ipairs(links) do - getstatus(link) - end -end - -for _, address in ipairs(arg) do - checklinks(url.absolute("file:", address)) -end - -while nthreads > 0 do - handler:step() -end diff --git a/etc/luasocket/check-memory.lua b/etc/luasocket/check-memory.lua deleted file mode 100644 index 7bd984d..0000000 --- a/etc/luasocket/check-memory.lua +++ /dev/null @@ -1,17 +0,0 @@ -function load(s) - collectgarbage() - local a = gcinfo() - _G[s] = require(s) - collectgarbage() - local b = gcinfo() - print(s .. ":\t " .. (b-a) .. "k") -end - -load("socket.url") -load("ltn12") -load("socket") -load("mime") -load("socket.tp") -load("socket.smtp") -load("socket.http") -load("socket.ftp") diff --git a/etc/luasocket/dict.lua b/etc/luasocket/dict.lua deleted file mode 100644 index c082c24..0000000 --- a/etc/luasocket/dict.lua +++ /dev/null @@ -1,152 +0,0 @@ ------------------------------------------------------------------------------ --- Little program to download DICT word definitions --- LuaSocket sample files --- Author: Diego Nehab --- RCS ID: $Id: dict.lua,v 1.22 2005/11/22 08:33:29 diego Exp $ ------------------------------------------------------------------------------ - ------------------------------------------------------------------------------ --- Load required modules ------------------------------------------------------------------------------ -local base = _G -local string = require("string") -local table = require("table") -local socket = require("socket") -local url = require("socket.url") -local tp = require("socket.tp") -module("socket.dict") - ------------------------------------------------------------------------------ --- Globals ------------------------------------------------------------------------------ -HOST = "dict.org" -PORT = 2628 -TIMEOUT = 10 - ------------------------------------------------------------------------------ --- Low-level dict API ------------------------------------------------------------------------------ -local metat = { __index = {} } - -function open(host, port) - local tp = socket.try(tp.connect(host or HOST, port or PORT, TIMEOUT)) - return base.setmetatable({tp = tp}, metat) -end - -function metat.__index:greet() - return socket.try(self.tp:check(220)) -end - -function metat.__index:check(ok) - local code, status = socket.try(self.tp:check(ok)) - return code, - base.tonumber(socket.skip(2, string.find(status, "^%d%d%d (%d*)"))) -end - -function metat.__index:getdef() - local line = socket.try(self.tp:receive()) - local def = {} - while line ~= "." do - table.insert(def, line) - line = socket.try(self.tp:receive()) - end - return table.concat(def, "\n") -end - -function metat.__index:define(database, word) - database = database or "!" - socket.try(self.tp:command("DEFINE", database .. " " .. word)) - local code, count = self:check(150) - local defs = {} - for i = 1, count do - self:check(151) - table.insert(defs, self:getdef()) - end - self:check(250) - return defs -end - -function metat.__index:match(database, strat, word) - database = database or "!" - strat = strat or "." - socket.try(self.tp:command("MATCH", database .." ".. strat .." ".. word)) - self:check(152) - local mat = {} - local line = socket.try(self.tp:receive()) - while line ~= '.' do - database, word = socket.skip(2, string.find(line, "(%S+) (.*)")) - if not mat[database] then mat[database] = {} end - table.insert(mat[database], word) - line = socket.try(self.tp:receive()) - end - self:check(250) - return mat -end - -function metat.__index:quit() - self.tp:command("QUIT") - return self:check(221) -end - -function metat.__index:close() - return self.tp:close() -end - ------------------------------------------------------------------------------ --- High-level dict API ------------------------------------------------------------------------------ -local default = { - scheme = "dict", - host = "dict.org" -} - -local function there(f) - if f == "" then return nil - else return f end -end - -local function parse(u) - local t = socket.try(url.parse(u, default)) - socket.try(t.scheme == "dict", "invalid scheme '" .. t.scheme .. "'") - socket.try(t.path, "invalid path in url") - local cmd, arg = socket.skip(2, string.find(t.path, "^/(.)(.*)$")) - socket.try(cmd == "d" or cmd == "m", " should be 'm' or 'd'") - socket.try(arg and arg ~= "", "need at least in URL") - t.command, t.argument = cmd, arg - arg = string.gsub(arg, "^:([^:]+)", function(f) t.word = f end) - socket.try(t.word, "need at least in URL") - arg = string.gsub(arg, "^:([^:]*)", function(f) t.database = there(f) end) - if cmd == "m" then - arg = string.gsub(arg, "^:([^:]*)", function(f) t.strat = there(f) end) - end - string.gsub(arg, ":([^:]*)$", function(f) t.n = base.tonumber(f) end) - return t -end - -local function tget(gett) - local con = open(gett.host, gett.port) - con:greet() - if gett.command == "d" then - local def = con:define(gett.database, gett.word) - con:quit() - con:close() - if gett.n then return def[gett.n] - else return def end - elseif gett.command == "m" then - local mat = con:match(gett.database, gett.strat, gett.word) - con:quit() - con:close() - return mat - else return nil, "invalid command" end -end - -local function sget(u) - local gett = parse(u) - return tget(gett) -end - -get = socket.protect(function(gett) - if base.type(gett) == "string" then return sget(gett) - else return tget(gett) end -end) - diff --git a/etc/luasocket/dispatch.lua b/etc/luasocket/dispatch.lua deleted file mode 100644 index dd76d6d..0000000 --- a/etc/luasocket/dispatch.lua +++ /dev/null @@ -1,301 +0,0 @@ ------------------------------------------------------------------------------ --- A hacked dispatcher module --- LuaSocket sample files --- Author: Diego Nehab --- RCS ID: $$ ------------------------------------------------------------------------------ -local base = _G -local socket = require("socket") -local coroutine = require("coroutine") -module("dispatch") - --- if too much time goes by without any activity in one of our sockets, we --- just kill it -TIMEOUT = 60 - ------------------------------------------------------------------------------ --- We implement 3 types of dispatchers: --- sequential --- coroutine --- threaded --- The user can choose whatever one is needed ------------------------------------------------------------------------------ -local handlert = {} - --- default handler is coroutine -function newhandler(mode) - mode = mode or "coroutine" - return handlert[mode]() -end - -local function seqstart(self, func) - return func() -end - --- sequential handler simply calls the functions and doesn't wrap I/O -function handlert.sequential() - return { - tcp = socket.tcp, - start = seqstart - } -end - ------------------------------------------------------------------------------ --- Mega hack. Don't try to do this at home. ------------------------------------------------------------------------------ --- we can't yield across calls to protect, so we rewrite it with coxpcall --- make sure you don't require any module that uses socket.protect before --- loading our hack -function socket.protect(f) - return function(...) - local co = coroutine.create(f) - while true do - local results = {coroutine.resume(co, unpack(arg))} - local status = table.remove(results, 1) - if not status then - if type(results[1]) == 'table' then - return nil, results[1][1] - else error(results[1]) end - end - if coroutine.status(co) == "suspended" then - arg = {coroutine.yield(unpack(results))} - else - return unpack(results) - end - end - end -end - ------------------------------------------------------------------------------ --- Simple set data structure. O(1) everything. ------------------------------------------------------------------------------ -local function newset() - local reverse = {} - local set = {} - return setmetatable(set, {__index = { - insert = function(set, value) - if not reverse[value] then - table.insert(set, value) - reverse[value] = table.getn(set) - end - end, - remove = function(set, value) - local index = reverse[value] - if index then - reverse[value] = nil - local top = table.remove(set) - if top ~= value then - reverse[top] = index - set[index] = top - end - end - end - }}) -end - ------------------------------------------------------------------------------ --- socket.tcp() wrapper for the coroutine dispatcher ------------------------------------------------------------------------------ -local function cowrap(dispatcher, tcp, error) - if not tcp then return nil, error end - -- put it in non-blocking mode right away - tcp:settimeout(0) - -- metatable for wrap produces new methods on demand for those that we - -- don't override explicitly. - local metat = { __index = function(table, key) - table[key] = function(...) - arg[1] = tcp - return tcp[key](unpack(arg)) - end - return table[key] - end} - -- does our user want to do his own non-blocking I/O? - local zero = false - -- create a wrap object that will behave just like a real socket object - local wrap = { } - -- we ignore settimeout to preserve our 0 timeout, but record whether - -- the user wants to do his own non-blocking I/O - function wrap:settimeout(value, mode) - if value == 0 then zero = true - else zero = false end - return 1 - end - -- send in non-blocking mode and yield on timeout - function wrap:send(data, first, last) - first = (first or 1) - 1 - local result, error - while true do - -- return control to dispatcher and tell it we want to send - -- if upon return the dispatcher tells us we timed out, - -- return an error to whoever called us - if coroutine.yield(dispatcher.sending, tcp) == "timeout" then - return nil, "timeout" - end - -- try sending - result, error, first = tcp:send(data, first+1, last) - -- if we are done, or there was an unexpected error, - -- break away from loop - if error ~= "timeout" then return result, error, first end - end - end - -- receive in non-blocking mode and yield on timeout - -- or simply return partial read, if user requested timeout = 0 - function wrap:receive(pattern, partial) - local error = "timeout" - local value - while true do - -- return control to dispatcher and tell it we want to receive - -- if upon return the dispatcher tells us we timed out, - -- return an error to whoever called us - if coroutine.yield(dispatcher.receiving, tcp) == "timeout" then - return nil, "timeout" - end - -- try receiving - value, error, partial = tcp:receive(pattern, partial) - -- if we are done, or there was an unexpected error, - -- break away from loop. also, if the user requested - -- zero timeout, return all we got - if (error ~= "timeout") or zero then - return value, error, partial - end - end - end - -- connect in non-blocking mode and yield on timeout - function wrap:connect(host, port) - local result, error = tcp:connect(host, port) - if error == "timeout" then - -- return control to dispatcher. we will be writable when - -- connection succeeds. - -- if upon return the dispatcher tells us we have a - -- timeout, just abort - if coroutine.yield(dispatcher.sending, tcp) == "timeout" then - return nil, "timeout" - end - -- when we come back, check if connection was successful - result, error = tcp:connect(host, port) - if result or error == "already connected" then return 1 - else return nil, "non-blocking connect failed" end - else return result, error end - end - -- accept in non-blocking mode and yield on timeout - function wrap:accept() - while 1 do - -- return control to dispatcher. we will be readable when a - -- connection arrives. - -- if upon return the dispatcher tells us we have a - -- timeout, just abort - if coroutine.yield(dispatcher.receiving, tcp) == "timeout" then - return nil, "timeout" - end - local client, error = tcp:accept() - if error ~= "timeout" then - return cowrap(dispatcher, client, error) - end - end - end - -- remove cortn from context - function wrap:close() - dispatcher.stamp[tcp] = nil - dispatcher.sending.set:remove(tcp) - dispatcher.sending.cortn[tcp] = nil - dispatcher.receiving.set:remove(tcp) - dispatcher.receiving.cortn[tcp] = nil - return tcp:close() - end - return setmetatable(wrap, metat) -end - - ------------------------------------------------------------------------------ --- Our coroutine dispatcher ------------------------------------------------------------------------------ -local cometat = { __index = {} } - -function schedule(cortn, status, operation, tcp) - if status then - if cortn and operation then - operation.set:insert(tcp) - operation.cortn[tcp] = cortn - operation.stamp[tcp] = socket.gettime() - end - else error(operation) end -end - -function kick(operation, tcp) - operation.cortn[tcp] = nil - operation.set:remove(tcp) -end - -function wakeup(operation, tcp) - local cortn = operation.cortn[tcp] - -- if cortn is still valid, wake it up - if cortn then - kick(operation, tcp) - return cortn, coroutine.resume(cortn) - -- othrewise, just get scheduler not to do anything - else - return nil, true - end -end - -function abort(operation, tcp) - local cortn = operation.cortn[tcp] - if cortn then - kick(operation, tcp) - coroutine.resume(cortn, "timeout") - end -end - --- step through all active cortns -function cometat.__index:step() - -- check which sockets are interesting and act on them - local readable, writable = socket.select(self.receiving.set, - self.sending.set, 1) - -- for all readable connections, resume their cortns and reschedule - -- when they yield back to us - for _, tcp in ipairs(readable) do - schedule(wakeup(self.receiving, tcp)) - end - -- for all writable connections, do the same - for _, tcp in ipairs(writable) do - schedule(wakeup(self.sending, tcp)) - end - -- politely ask replacement I/O functions in idle cortns to - -- return reporting a timeout - local now = socket.gettime() - for tcp, stamp in pairs(self.stamp) do - if tcp.class == "tcp{client}" and now - stamp > TIMEOUT then - abort(self.sending, tcp) - abort(self.receiving, tcp) - end - end -end - -function cometat.__index:start(func) - local cortn = coroutine.create(func) - schedule(cortn, coroutine.resume(cortn)) -end - -function handlert.coroutine() - local stamp = {} - local dispatcher = { - stamp = stamp, - sending = { - name = "sending", - set = newset(), - cortn = {}, - stamp = stamp - }, - receiving = { - name = "receiving", - set = newset(), - cortn = {}, - stamp = stamp - }, - } - function dispatcher.tcp() - return cowrap(dispatcher, socket.tcp()) - end - return setmetatable(dispatcher, cometat) -end - diff --git a/etc/luasocket/eol.lua b/etc/luasocket/eol.lua deleted file mode 100644 index b90be79..0000000 --- a/etc/luasocket/eol.lua +++ /dev/null @@ -1,14 +0,0 @@ ------------------------------------------------------------------------------ --- Little program to adjust end of line markers. --- LuaSocket sample files --- Author: Diego Nehab --- RCS ID: $Id: eol.lua,v 1.8 2005/11/22 08:33:29 diego Exp $ ------------------------------------------------------------------------------ -local mime = require("mime") -local ltn12 = require("ltn12") -local marker = '\n' -if arg and arg[1] == '-d' then marker = '\r\n' end -local filter = mime.normalize(marker) -local source = ltn12.source.chain(ltn12.source.file(io.stdin), filter) -local sink = ltn12.sink.file(io.stdout) -ltn12.pump.all(source, sink) diff --git a/etc/luasocket/forward.lua b/etc/luasocket/forward.lua deleted file mode 100644 index 9073ac4..0000000 --- a/etc/luasocket/forward.lua +++ /dev/null @@ -1,65 +0,0 @@ --- load our favourite library -local dispatch = require("dispatch") -local handler = dispatch.newhandler() - --- make sure the user knows how to invoke us -if table.getn(arg) < 1 then - print("Usage") - print(" lua forward.lua ...") - os.exit(1) -end - --- function to move data from one socket to the other -local function move(foo, bar) - local live - while 1 do - local data, error, partial = foo:receive(2048) - live = data or error == "timeout" - data = data or partial - local result, error = bar:send(data) - if not live or not result then - foo:close() - bar:close() - break - end - end -end - --- for each tunnel, start a new server -for i, v in ipairs(arg) do - -- capture forwarding parameters - local _, _, iport, ohost, oport = string.find(v, "([^:]+):([^:]+):([^:]+)") - assert(iport, "invalid arguments") - -- create our server socket - local server = assert(handler.tcp()) - assert(server:setoption("reuseaddr", true)) - assert(server:bind("*", iport)) - assert(server:listen(32)) - -- handler for the server object loops accepting new connections - handler:start(function() - while 1 do - local client = assert(server:accept()) - assert(client:settimeout(0)) - -- for each new connection, start a new client handler - handler:start(function() - -- handler tries to connect to peer - local peer = assert(handler.tcp()) - assert(peer:settimeout(0)) - assert(peer:connect(ohost, oport)) - -- if sucessful, starts a new handler to send data from - -- client to peer - handler:start(function() - move(client, peer) - end) - -- afte starting new handler, enter in loop sending data from - -- peer to client - move(peer, client) - end) - end - end) -end - --- simply loop stepping the server -while 1 do - handler:step() -end diff --git a/etc/luasocket/get.lua b/etc/luasocket/get.lua deleted file mode 100644 index f259ea9..0000000 --- a/etc/luasocket/get.lua +++ /dev/null @@ -1,140 +0,0 @@ ------------------------------------------------------------------------------ --- Little program to download files from URLs --- LuaSocket sample files --- Author: Diego Nehab --- RCS ID: $Id: get.lua,v 1.24 2005/11/22 08:33:29 diego Exp $ ------------------------------------------------------------------------------ -local socket = require("socket") -local http = require("socket.http") -local ftp = require("socket.ftp") -local url = require("socket.url") -local ltn12 = require("ltn12") - --- formats a number of seconds into human readable form -function nicetime(s) - local l = "s" - if s > 60 then - s = s / 60 - l = "m" - if s > 60 then - s = s / 60 - l = "h" - if s > 24 then - s = s / 24 - l = "d" -- hmmm - end - end - end - if l == "s" then return string.format("%5.0f%s", s, l) - else return string.format("%5.2f%s", s, l) end -end - --- formats a number of bytes into human readable form -function nicesize(b) - local l = "B" - if b > 1024 then - b = b / 1024 - l = "KB" - if b > 1024 then - b = b / 1024 - l = "MB" - if b > 1024 then - b = b / 1024 - l = "GB" -- hmmm - end - end - end - return string.format("%7.2f%2s", b, l) -end - --- returns a string with the current state of the download -local remaining_s = "%s received, %s/s throughput, %2.0f%% done, %s remaining" -local elapsed_s = "%s received, %s/s throughput, %s elapsed " -function gauge(got, delta, size) - local rate = got / delta - if size and size >= 1 then - return string.format(remaining_s, nicesize(got), nicesize(rate), - 100*got/size, nicetime((size-got)/rate)) - else - return string.format(elapsed_s, nicesize(got), - nicesize(rate), nicetime(delta)) - end -end - --- creates a new instance of a receive_cb that saves to disk --- kind of copied from luasocket's manual callback examples -function stats(size) - local start = socket.gettime() - local got = 0 - return function(chunk) - -- elapsed time since start - local delta = socket.gettime() - start - if chunk then - -- total bytes received - got = got + string.len(chunk) - -- not enough time for estimate - if delta > 0.1 then - io.stderr:write("\r", gauge(got, delta, size)) - io.stderr:flush() - end - else - -- close up - io.stderr:write("\r", gauge(got, delta), "\n") - end - return chunk - end -end - --- determines the size of a http file -function gethttpsize(u) - local r, c, h = http.request {method = "HEAD", url = u} - if c == 200 then - return tonumber(h["content-length"]) - end -end - --- downloads a file using the http protocol -function getbyhttp(u, file) - local save = ltn12.sink.file(file or io.stdout) - -- only print feedback if output is not stdout - if file then save = ltn12.sink.chain(stats(gethttpsize(u)), save) end - local r, c, h, s = http.request {url = u, sink = save } - if c ~= 200 then io.stderr:write(s or c, "\n") end -end - --- downloads a file using the ftp protocol -function getbyftp(u, file) - local save = ltn12.sink.file(file or io.stdout) - -- only print feedback if output is not stdout - -- and we don't know how big the file is - if file then save = ltn12.sink.chain(stats(), save) end - local gett = url.parse(u) - gett.sink = save - gett.type = "i" - local ret, err = ftp.get(gett) - if err then print(err) end -end - --- determines the scheme -function getscheme(u) - -- this is an heuristic to solve a common invalid url poblem - if not string.find(u, "//") then u = "//" .. u end - local parsed = url.parse(u, {scheme = "http"}) - return parsed.scheme -end - --- gets a file either by http or ftp, saving as -function get(u, name) - local fout = name and io.open(name, "wb") - local scheme = getscheme(u) - if scheme == "ftp" then getbyftp(u, fout) - elseif scheme == "http" then getbyhttp(u, fout) - else print("unknown scheme" .. scheme) end -end - --- main program -arg = arg or {} -if table.getn(arg) < 1 then - io.write("Usage:\n lua get.lua []\n") - os.exit(1) -else get(arg[1], arg[2]) end diff --git a/etc/luasocket/lp.lua b/etc/luasocket/lp.lua deleted file mode 100644 index 3269920..0000000 --- a/etc/luasocket/lp.lua +++ /dev/null @@ -1,324 +0,0 @@ ------------------------------------------------------------------------------ --- LPD support for the Lua language --- LuaSocket toolkit. --- Author: David Burgess --- Modified by Diego Nehab, but David is in charge --- RCS ID: $Id: lp.lua,v 1.14 2005/11/21 07:04:44 diego Exp $ ------------------------------------------------------------------------------ ---[[ - if you have any questions: RFC 1179 -]] --- make sure LuaSocket is loaded -local io = require("io") -local base = _G -local os = require("os") -local math = require("math") -local string = require("string") -local socket = require("socket") -local ltn12 = require("ltn12") -module("socket.lp") - --- default port -PORT = 515 -SERVER = os.getenv("SERVER_NAME") or os.getenv("COMPUTERNAME") or "localhost" -PRINTER = os.getenv("PRINTER") or "printer" - -local function connect(localhost, option) - local host = option.host or SERVER - local port = option.port or PORT - local skt - local try = socket.newtry(function() if skt then skt:close() end end) - if option.localbind then - -- bind to a local port (if we can) - local localport = 721 - local done, err - repeat - skt = socket.try(socket.tcp()) - try(skt:settimeout(30)) - done, err = skt:bind(localhost, localport) - if not done then - localport = localport + 1 - skt:close() - skt = nil - else break end - until localport > 731 - socket.try(skt, err) - else skt = socket.try(socket.tcp()) end - try(skt:connect(host, port)) - return { skt = skt, try = try } -end - ---[[ -RFC 1179 -5.3 03 - Send queue state (short) - - +----+-------+----+------+----+ - | 03 | Queue | SP | List | LF | - +----+-------+----+------+----+ - Command code - 3 - Operand 1 - Printer queue name - Other operands - User names or job numbers - - If the user names or job numbers or both are supplied then only those - jobs for those users or with those numbers will be sent. - - The response is an ASCII stream which describes the printer queue. - The stream continues until the connection closes. Ends of lines are - indicated with ASCII LF control characters. The lines may also - contain ASCII HT control characters. - -5.4 04 - Send queue state (long) - - +----+-------+----+------+----+ - | 04 | Queue | SP | List | LF | - +----+-------+----+------+----+ - Command code - 4 - Operand 1 - Printer queue name - Other operands - User names or job numbers - - If the user names or job numbers or both are supplied then only those - jobs for those users or with those numbers will be sent. - - The response is an ASCII stream which describes the printer queue. - The stream continues until the connection closes. Ends of lines are - indicated with ASCII LF control characters. The lines may also - contain ASCII HT control characters. -]] - --- gets server acknowledement -local function recv_ack(con) - local ack = con.skt:receive(1) - con.try(string.char(0) == ack, "failed to receive server acknowledgement") -end - --- sends client acknowledement -local function send_ack(con) - local sent = con.skt:send(string.char(0)) - con.try(sent == 1, "failed to send acknowledgement") -end - --- sends queue request --- 5.2 02 - Receive a printer job --- --- +----+-------+----+ --- | 02 | Queue | LF | --- +----+-------+----+ --- Command code - 2 --- Operand - Printer queue name --- --- Receiving a job is controlled by a second level of commands. The --- daemon is given commands by sending them over the same connection. --- The commands are described in the next section (6). --- --- After this command is sent, the client must read an acknowledgement --- octet from the daemon. A positive acknowledgement is an octet of --- zero bits. A negative acknowledgement is an octet of any other --- pattern. -local function send_queue(con, queue) - queue = queue or PRINTER - local str = string.format("\2%s\10", queue) - local sent = con.skt:send(str) - con.try(sent == string.len(str), "failed to send print request") - recv_ack(con) -end - --- sends control file --- 6.2 02 - Receive control file --- --- +----+-------+----+------+----+ --- | 02 | Count | SP | Name | LF | --- +----+-------+----+------+----+ --- Command code - 2 --- Operand 1 - Number of bytes in control file --- Operand 2 - Name of control file --- --- The control file must be an ASCII stream with the ends of lines --- indicated by ASCII LF. The total number of bytes in the stream is --- sent as the first operand. The name of the control file is sent as --- the second. It should start with ASCII "cfA", followed by a three --- digit job number, followed by the host name which has constructed the --- control file. Acknowledgement processing must occur as usual after --- the command is sent. --- --- The next "Operand 1" octets over the same TCP connection are the --- intended contents of the control file. Once all of the contents have --- been delivered, an octet of zero bits is sent as an indication that --- the file being sent is complete. A second level of acknowledgement --- processing must occur at this point. - --- sends data file --- 6.3 03 - Receive data file --- --- +----+-------+----+------+----+ --- | 03 | Count | SP | Name | LF | --- +----+-------+----+------+----+ --- Command code - 3 --- Operand 1 - Number of bytes in data file --- Operand 2 - Name of data file --- --- The data file may contain any 8 bit values at all. The total number --- of bytes in the stream may be sent as the first operand, otherwise --- the field should be cleared to 0. The name of the data file should --- start with ASCII "dfA". This should be followed by a three digit job --- number. The job number should be followed by the host name which has --- constructed the data file. Interpretation of the contents of the --- data file is determined by the contents of the corresponding control --- file. If a data file length has been specified, the next "Operand 1" --- octets over the same TCP connection are the intended contents of the --- data file. In this case, once all of the contents have been --- delivered, an octet of zero bits is sent as an indication that the --- file being sent is complete. A second level of acknowledgement --- processing must occur at this point. - - -local function send_hdr(con, control) - local sent = con.skt:send(control) - con.try(sent and sent >= 1 , "failed to send header file") - recv_ack(con) -end - -local function send_control(con, control) - local sent = con.skt:send(control) - con.try(sent and sent >= 1, "failed to send control file") - send_ack(con) -end - -local function send_data(con,fh,size) - local buf - while size > 0 do - buf,message = fh:read(8192) - if buf then - st = con.try(con.skt:send(buf)) - size = size - st - else - con.try(size == 0, "file size mismatch") - end - end - recv_ack(con) -- note the double acknowledgement - send_ack(con) - recv_ack(con) - return size -end - - ---[[ -local control_dflt = { - "H"..string.sub(socket.hostname,1,31).."\10", -- host - "C"..string.sub(socket.hostname,1,31).."\10", -- class - "J"..string.sub(filename,1,99).."\10", -- jobname - "L"..string.sub(user,1,31).."\10", -- print banner page - "I"..tonumber(indent).."\10", -- indent column count ('f' only) - "M"..string.sub(mail,1,128).."\10", -- mail when printed user@host - "N"..string.sub(filename,1,131).."\10", -- name of source file - "P"..string.sub(user,1,31).."\10", -- user name - "T"..string.sub(title,1,79).."\10", -- title for banner ('p' only) - "W"..tonumber(width or 132).."\10", -- width of print f,l,p only - - "f"..file.."\10", -- formatted print (remove control chars) - "l"..file.."\10", -- print - "o"..file.."\10", -- postscript - "p"..file.."\10", -- pr format - requires T, L - "r"..file.."\10", -- fortran format - "U"..file.."\10", -- Unlink (data file only) -} -]] - --- generate a varying job number -local seq = 0 -local function newjob(connection) - seq = seq + 1 - return math.floor(socket.gettime() * 1000 + seq)%1000 -end - - -local format_codes = { - binary = 'l', - text = 'f', - ps = 'o', - pr = 'p', - fortran = 'r', - l = 'l', - r = 'r', - o = 'o', - p = 'p', - f = 'f' -} - --- lp.send{option} --- requires option.file - -send = socket.protect(function(option) - socket.try(option and base.type(option) == "table", "invalid options") - local file = option.file - socket.try(file, "invalid file name") - local fh = socket.try(io.open(file,"rb")) - local datafile_size = fh:seek("end") -- get total size - fh:seek("set") -- go back to start of file - local localhost = socket.dns.gethostname() or os.getenv("COMPUTERNAME") - or "localhost" - local con = connect(localhost, option) --- format the control file - local jobno = newjob() - local localip = socket.dns.toip(localhost) - localhost = string.sub(localhost,1,31) - local user = string.sub(option.user or os.getenv("LPRUSER") or - os.getenv("USERNAME") or os.getenv("USER") or "anonymous", 1,31) - local lpfile = string.format("dfA%3.3d%-s", jobno, localhost); - local fmt = format_codes[option.format] or 'l' - local class = string.sub(option.class or localip or localhost,1,31) - local _,_,ctlfn = string.find(file,".*[%/%\\](.*)") - ctlfn = string.sub(ctlfn or file,1,131) - local cfile = - string.format("H%-s\nC%-s\nJ%-s\nP%-s\n%.1s%-s\nU%-s\nN%-s\n", - localhost, - class, - option.job or "LuaSocket", - user, - fmt, lpfile, - lpfile, - ctlfn); -- mandatory part of ctl file - if (option.banner) then cfile = cfile .. 'L'..user..'\10' end - if (option.indent) then cfile = cfile .. 'I'..base.tonumber(option.indent)..'\10' end - if (option.mail) then cfile = cfile .. 'M'..string.sub((option.mail),1,128)..'\10' end - if (fmt == 'p' and option.title) then cfile = cfile .. 'T'..string.sub((option.title),1,79)..'\10' end - if ((fmt == 'p' or fmt == 'l' or fmt == 'f') and option.width) then - cfile = cfile .. 'W'..base.tonumber(option,width)..'\10' - end - - con.skt:settimeout(option.timeout or 65) --- send the queue header - send_queue(con, option.queue) --- send the control file header - local cfilecmd = string.format("\2%d cfA%3.3d%-s\n",string.len(cfile), jobno, localhost); - send_hdr(con,cfilecmd) - --- send the control file - send_control(con,cfile) - --- send the data file header - local dfilecmd = string.format("\3%d dfA%3.3d%-s\n",datafile_size, jobno, localhost); - send_hdr(con,dfilecmd) - --- send the data file - send_data(con,fh,datafile_size) - fh:close() - con.skt:close(); - return jobno, datafile_size -end) - --- --- lp.query({host=,queue=printer|'*', format='l'|'s', list=}) --- -query = socket.protect(function(p) - p = p or {} - local localhost = socket.dns.gethostname() or os.getenv("COMPUTERNAME") - or "localhost" - local con = connect(localhost,p) - local fmt - if string.sub(p.format or 's',1,1) == 's' then fmt = 3 else fmt = 4 end - con.try(con.skt:send(string.format("%c%s %s\n", fmt, p.queue or "*", - p.list or ""))) - local data = con.try(con.skt:receive("*a")) - con.skt:close() - return data -end) diff --git a/etc/luasocket/qp.lua b/etc/luasocket/qp.lua deleted file mode 100644 index a4c0cad..0000000 --- a/etc/luasocket/qp.lua +++ /dev/null @@ -1,24 +0,0 @@ ------------------------------------------------------------------------------ --- Little program to convert to and from Quoted-Printable --- LuaSocket sample files --- Author: Diego Nehab --- RCS ID: $Id: qp.lua,v 1.5 2004/06/17 21:46:22 diego Exp $ ------------------------------------------------------------------------------ -local ltn12 = require("ltn12") -local mime = require("mime") -local convert -arg = arg or {} -local mode = arg and arg[1] or "-et" -if mode == "-et" then - local normalize = mime.normalize() - local qp = mime.encode("quoted-printable") - local wrap = mime.wrap("quoted-printable") - convert = ltn12.filter.chain(normalize, qp, wrap) -elseif mode == "-eb" then - local qp = mime.encode("quoted-printable", "binary") - local wrap = mime.wrap("quoted-printable") - convert = ltn12.filter.chain(qp, wrap) -else convert = mime.decode("quoted-printable") end -local source = ltn12.source.chain(ltn12.source.file(io.stdin), convert) -local sink = ltn12.sink.file(io.stdout) -ltn12.pump.all(source, sink) diff --git a/etc/luasocket/tftp.lua b/etc/luasocket/tftp.lua deleted file mode 100644 index 94eaf34..0000000 --- a/etc/luasocket/tftp.lua +++ /dev/null @@ -1,155 +0,0 @@ ------------------------------------------------------------------------------ --- TFTP support for the Lua language --- LuaSocket toolkit. --- Author: Diego Nehab --- RCS ID: $Id: tftp.lua,v 1.16 2005/11/22 08:33:29 diego Exp $ ------------------------------------------------------------------------------ - ------------------------------------------------------------------------------ --- Load required files ------------------------------------------------------------------------------ -local base = _G -local table = require("table") -local math = require("math") -local string = require("string") -local socket = require("socket") -local ltn12 = require("ltn12") -local url = require("socket.url") -module("socket.tftp") - ------------------------------------------------------------------------------ --- Program constants ------------------------------------------------------------------------------ -local char = string.char -local byte = string.byte - -PORT = 69 -local OP_RRQ = 1 -local OP_WRQ = 2 -local OP_DATA = 3 -local OP_ACK = 4 -local OP_ERROR = 5 -local OP_INV = {"RRQ", "WRQ", "DATA", "ACK", "ERROR"} - ------------------------------------------------------------------------------ --- Packet creation functions ------------------------------------------------------------------------------ -local function RRQ(source, mode) - return char(0, OP_RRQ) .. source .. char(0) .. mode .. char(0) -end - -local function WRQ(source, mode) - return char(0, OP_RRQ) .. source .. char(0) .. mode .. char(0) -end - -local function ACK(block) - local low, high - low = math.mod(block, 256) - high = (block - low)/256 - return char(0, OP_ACK, high, low) -end - -local function get_OP(dgram) - local op = byte(dgram, 1)*256 + byte(dgram, 2) - return op -end - ------------------------------------------------------------------------------ --- Packet analysis functions ------------------------------------------------------------------------------ -local function split_DATA(dgram) - local block = byte(dgram, 3)*256 + byte(dgram, 4) - local data = string.sub(dgram, 5) - return block, data -end - -local function get_ERROR(dgram) - local code = byte(dgram, 3)*256 + byte(dgram, 4) - local msg - _,_, msg = string.find(dgram, "(.*)\000", 5) - return string.format("error code %d: %s", code, msg) -end - ------------------------------------------------------------------------------ --- The real work ------------------------------------------------------------------------------ -local function tget(gett) - local retries, dgram, sent, datahost, dataport, code - local last = 0 - socket.try(gett.host, "missing host") - local con = socket.try(socket.udp()) - local try = socket.newtry(function() con:close() end) - -- convert from name to ip if needed - gett.host = try(socket.dns.toip(gett.host)) - con:settimeout(1) - -- first packet gives data host/port to be used for data transfers - local path = string.gsub(gett.path or "", "^/", "") - path = url.unescape(path) - retries = 0 - repeat - sent = try(con:sendto(RRQ(path, "octet"), gett.host, gett.port)) - dgram, datahost, dataport = con:receivefrom() - retries = retries + 1 - until dgram or datahost ~= "timeout" or retries > 5 - try(dgram, datahost) - -- associate socket with data host/port - try(con:setpeername(datahost, dataport)) - -- default sink - local sink = gett.sink or ltn12.sink.null() - -- process all data packets - while 1 do - -- decode packet - code = get_OP(dgram) - try(code ~= OP_ERROR, get_ERROR(dgram)) - try(code == OP_DATA, "unhandled opcode " .. code) - -- get data packet parts - local block, data = split_DATA(dgram) - -- if not repeated, write - if block == last+1 then - try(sink(data)) - last = block - end - -- last packet brings less than 512 bytes of data - if string.len(data) < 512 then - try(con:send(ACK(block))) - try(con:close()) - try(sink(nil)) - return 1 - end - -- get the next packet - retries = 0 - repeat - sent = try(con:send(ACK(last))) - dgram, err = con:receive() - retries = retries + 1 - until dgram or err ~= "timeout" or retries > 5 - try(dgram, err) - end -end - -local default = { - port = PORT, - path ="/", - scheme = "tftp" -} - -local function parse(u) - local t = socket.try(url.parse(u, default)) - socket.try(t.scheme == "tftp", "invalid scheme '" .. t.scheme .. "'") - socket.try(t.host, "invalid host") - return t -end - -local function sget(u) - local gett = parse(u) - local t = {} - gett.sink = ltn12.sink.table(t) - tget(gett) - return table.concat(t) -end - -get = socket.protect(function(gett) - if base.type(gett) == "string" then return sget(gett) - else return tget(gett) end -end) - diff --git a/etc/publish.sh b/etc/publish.sh deleted file mode 100755 index 13f9eb0..0000000 --- a/etc/publish.sh +++ /dev/null @@ -1,12 +0,0 @@ -#! /bin/sh - -# ONLY FOR MAINTAINER USE!! - -cd "`dirname "$0"`"; -dir="`pwd`"; -cd ..; - -"$dir/zipmod.sh"; - -echo cp -f dists/* ~/Dropbox/Public/minetest/mods/; -cp -f dists/* ~/Dropbox/Public/minetest/mods/; diff --git a/etc/quickinst.sh b/etc/quickinst.sh deleted file mode 100755 index a561d82..0000000 --- a/etc/quickinst.sh +++ /dev/null @@ -1,7 +0,0 @@ -#! /bin/sh -cd Build \ - && cmake .. \ - && make \ - && make pack_mod \ - && rm -fr ~/.minetest/games/testing/mods/irc \ - && cp -fr irc ~/.minetest/games/testing/mods/ diff --git a/etc/tests/luairc/luabot.lua b/etc/tests/luairc/luabot.lua deleted file mode 100755 index d65cc51..0000000 --- a/etc/tests/luairc/luabot.lua +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env lua - -local irc = require 'irc' -irc.DEBUG = true - -local nick = "doylua" - -local envs = {} - -local function create_env() - return { - _VERSION = _VERSION, - assert = assert, - collectgarbage = collectgarbage, - error = error, - getfenv = getfenv, - getmetatable = getmetatable, - ipairs = ipairs, - loadstring = loadstring, - next = next, - pairs = pairs, - pcall = pcall, - rawequal = rawequal, - rawget = rawget, - rawset = rawset, - select = select, - setfenv = setfenv, - setmetatable = setmetatable, - tonumber = tonumber, - tostring = tostring, - type = type, - unpack = unpack, - xpcall = xpcall, - coroutine = coroutine, - math = math, - string = string, - table = table, - } -end - -local commands = { - eval = function(target, from, code) - code = code:gsub("^=", "return ") - local fn, err = loadstring(code) - if not fn then - irc.say(target, from .. ": Error loading code: " .. code .. err:match(".*(:.-)$")) - return - else - setfenv(fn, envs[from]) - local result = {pcall(fn)} - local success = table.remove(result, 1) - if not success then - irc.say(target, from .. ": Error running code: " .. code .. result[1]:match(".*(:.-)$")) - else - if result[1] == nil then - irc.say(target, from .. ": nil") - else - irc.say(target, from .. ": " .. table.concat(result, ", ")) - end - end - end - end, - clear = function(target, from) - irc.say(target, from .. ": Clearing your environment") - envs[from] = create_env() - end, - help = function(target, from, arg) - if arg == "" or not arg then - irc.say(target, from .. ": Commands: !clear, !eval, !help") - elseif arg == "eval" then - irc.say(target, from .. ": Evaluates a Lua statement in your own persistent environment") - elseif arg == "clear" then - irc.say(target, from .. ": Clears your personal environment") - end - end -} - -irc.register_callback("connect", function() - irc.join("#doytest") -end) - -irc.register_callback("channel_msg", function(channel, from, message) - message = message:gsub("^" .. nick .. "[:,>] ", "!eval ") - local is_cmd, cmd, arg = message:match("^(!)([%w_]+) ?(.-)$") - if is_cmd and commands[cmd] then - envs[from] = envs[from] or create_env() - commands[cmd](channel.name, from, arg) - end -end) - -irc.register_callback("private_msg", function(from, message) - message = message:gsub("^" .. nick .. "[:,>] ", "!eval ") - local is_cmd, cmd, arg = message:match("^(!)([%w_]+) ?(.-)$") - envs[from] = envs[from] or create_env() - if is_cmd and commands[cmd] then - commands[cmd](from, from, arg) - else - commands["eval"](from, from, message) - end -end) - -irc.register_callback("nick_change", function(from, old_nick) - if envs[old_nick] and not envs[from] then - envs[from] = envs[old_nick] - envs[old_nick] = nil - end -end) - -irc.connect{network = "irc.freenode.net", nick = nick, pass = "doylua"} diff --git a/etc/tests/luairc/test.lua b/etc/tests/luairc/test.lua deleted file mode 100755 index 865c5bc..0000000 --- a/etc/tests/luairc/test.lua +++ /dev/null @@ -1,228 +0,0 @@ -#!/usr/bin/lua - -local irc = require "irc" -local dcc = require "irc.dcc" - -irc.DEBUG = true - -local ip_prog = io.popen("get_ip") -local ip = ip_prog:read() -ip_prog:close() -irc.set_ip(ip) - -local function print_state() - for chan in irc.channels() do - print(chan..": Channel ops: "..table.concat(chan:ops(), " ")) - print(chan..": Channel voices: "..table.concat(chan:voices(), " ")) - print(chan..": Channel normal users: "..table.concat(chan:users(), " ")) - print(chan..": All channel members: "..table.concat(chan:members(), " ")) - end -end - -local function on_connect() - print("Joining channel #doytest...") - irc.join("#doytest") - print("Joining channel #doytest2...") - irc.join("#doytest2") -end -irc.register_callback("connect", on_connect) - -local function on_me_join(chan) - print("Join to " .. chan .. " complete.") - print(chan .. ": Channel type: " .. chan.chanmode) - if chan.topic.text and chan.topic.text ~= "" then - print(chan .. ": Channel topic: " .. chan.topic.text) - print(" Set by " .. chan.topic.user .. - " at " .. os.date("%c", chan.topic.time)) - end - irc.act(chan.name, "is here") - print_state() -end -irc.register_callback("me_join", on_me_join) - -local function on_join(chan, user) - print("I saw a join to " .. chan) - if tostring(user) ~= "doylua" then - irc.say(tostring(chan), "Hi, " .. user) - end - print_state() -end -irc.register_callback("join", on_join) - -local function on_part(chan, user, part_msg) - print("I saw a part from " .. chan .. " saying " .. part_msg) - print_state() -end -irc.register_callback("part", on_part) - -local function on_nick_change(new_nick, old_nick) - print("I saw a nick change: " .. old_nick .. " -> " .. new_nick) - print_state() -end -irc.register_callback("nick_change", on_nick_change) - -local function on_kick(chan, user) - print("I saw a kick in " .. chan) - print_state() -end -irc.register_callback("kick", on_kick) - -local function on_quit(chan, user) - print("I saw a quit from " .. chan) - print_state() -end -irc.register_callback("quit", on_quit) - -local function whois_cb(cb_data) - print("WHOIS data for " .. cb_data.nick) - if cb_data.user then print("Username: " .. cb_data.user) end - if cb_data.host then print("Host: " .. cb_data.host) end - if cb_data.realname then print("Realname: " .. cb_data.realname) end - if cb_data.server then print("Server: " .. cb_data.server) end - if cb_data.serverinfo then print("Serverinfo: " .. cb_data.serverinfo) end - if cb_data.away_msg then print("Awaymsg: " .. cb_data.away_msg) end - if cb_data.is_oper then print(nick .. "is an IRCop") end - if cb_data.idle_time then print("Idletime: " .. cb_data.idle_time) end - if cb_data.channels then - print("Channel list for " .. cb_data.nick .. ":") - for _, channel in ipairs(cb_data.channels) do print(channel) end - end -end - -local function serverversion_cb(cb_data) - print("VERSION data for " .. cb_data.server) - print("Version: " .. cb_data.version) - print("Comments: " .. cb_data.comments) -end - -local function ping_cb(cb_data) - print("CTCP PING for " .. cb_data.nick) - print("Roundtrip time: " .. cb_data.time .. "s") -end - -local function time_cb(cb_data) - print("CTCP TIME for " .. cb_data.nick) - print("Localtime: " .. cb_data.time) -end - -local function version_cb(cb_data) - print("CTCP VERSION for " .. cb_data.nick) - print("Version: " .. cb_data.version) -end - -local function stime_cb(cb_data) - print("TIME for " .. cb_data.server) - print("Server time: " .. cb_data.time) -end - -local function on_channel_msg(chan, from, msg) - if from == "doy" then - if msg == "leave" then - irc.part(chan.name) - return - elseif msg:sub(1, 3) == "op " then - chan:op(msg:sub(4)) - return - elseif msg:sub(1, 5) == "deop " then - chan:deop(msg:sub(6)) - return - elseif msg:sub(1, 6) == "voice " then - chan:voice(msg:sub(7)) - return - elseif msg:sub(1, 8) == "devoice " then - chan:devoice(msg:sub(9)) - return - elseif msg:sub(1, 5) == "kick " then - chan:kick(msg:sub(6)) - return - elseif msg:sub(1, 5) == "send " then - dcc.send(from, msg:sub(6)) - return - elseif msg:sub(1, 6) == "whois " then - irc.whois(whois_cb, msg:sub(7)) - return - elseif msg:sub(1, 8) == "sversion" then - irc.server_version(serverversion_cb) - return - elseif msg:sub(1, 5) == "ping " then - irc.ctcp_ping(ping_cb, msg:sub(6)) - return - elseif msg:sub(1, 5) == "time " then - irc.ctcp_time(time_cb, msg:sub(6)) - return - elseif msg:sub(1, 8) == "version " then - irc.ctcp_version(version_cb, msg:sub(9)) - return - elseif msg:sub(1, 5) == "stime" then - irc.server_time(stime_cb) - return - elseif msg:sub(1, 6) == "trace " then - irc.trace(trace_cb, msg:sub(7)) - return - elseif msg:sub(1, 5) == "trace" then - irc.trace(trace_cb) - return - end - end - if from ~= "doylua" then - irc.say(chan.name, from .. ": " .. msg) - end -end -irc.register_callback("channel_msg", on_channel_msg) - -local function on_private_msg(from, msg) - if from == "doy" then - if msg == "leave" then - irc.quit("gone") - return - elseif msg:sub(1, 5) == "send " then - dcc.send(from, msg:sub(6)) - return - end - end - if from ~= "doylua" then - irc.say(from, msg) - end -end -irc.register_callback("private_msg", on_private_msg) - -local function on_channel_act(chan, from, msg) - irc.act(chan.name, "jumps on " .. from) -end -irc.register_callback("channel_act", on_channel_act) - -local function on_private_act(from, msg) - irc.act(from, "jumps on you") -end -irc.register_callback("private_act", on_private_act) - -local function on_op(chan, from, nick) - print(nick .. " was opped in " .. chan .. " by " .. from) - print_state() -end -irc.register_callback("op", on_op) - -local function on_deop(chan, from, nick) - print(nick .. " was deopped in " .. chan .. " by " .. from) - print_state() -end -irc.register_callback("deop", on_deop) - -local function on_voice(chan, from, nick) - print(nick .. " was voiced in " .. chan .. " by " .. from) - print_state() -end -irc.register_callback("voice", on_voice) - -local function on_devoice(chan, from, nick) - print(nick .. " was devoiced in " .. chan .. " by " .. from) - print_state() -end -irc.register_callback("devoice", on_devoice) - -local function on_dcc_send() - return true -end -irc.register_callback("dcc_send", on_dcc_send) - -irc.connect{network = "irc.freenode.net", nick = "doylua"} diff --git a/etc/tests/luasocket/README b/etc/tests/luasocket/README deleted file mode 100644 index 180fa27..0000000 --- a/etc/tests/luasocket/README +++ /dev/null @@ -1,12 +0,0 @@ -This provides the automated test scripts used to make sure the library -is working properly. - -The files provided are: - - testsrvr.lua -- test server - testclnt.lua -- test client - -To run these tests, just run lua on the server and then on the client. - -Good luck, -Diego. diff --git a/etc/tests/luasocket/testclnt.lua b/etc/tests/luasocket/testclnt.lua deleted file mode 100644 index cf71c9f..0000000 --- a/etc/tests/luasocket/testclnt.lua +++ /dev/null @@ -1,655 +0,0 @@ -local socket = require"socket" - -host = host or "localhost" -port = port or "8383" - -function pass(...) - local s = string.format(unpack(arg)) - io.stderr:write(s, "\n") -end - -function fail(...) - local s = string.format(unpack(arg)) - io.stderr:write("ERROR: ", s, "!\n") -socket.sleep(3) - os.exit() -end - -function warn(...) - local s = string.format(unpack(arg)) - io.stderr:write("WARNING: ", s, "\n") -end - -function remote(...) - local s = string.format(unpack(arg)) - s = string.gsub(s, "\n", ";") - s = string.gsub(s, "%s+", " ") - s = string.gsub(s, "^%s*", "") - control:send(s .. "\n") - control:receive() -end - -function test(test) - io.stderr:write("----------------------------------------------\n", - "testing: ", test, "\n", - "----------------------------------------------\n") -end - -function check_timeout(tm, sl, elapsed, err, opp, mode, alldone) - if tm < sl then - if opp == "send" then - if not err then warn("must be buffered") - elseif err == "timeout" then pass("proper timeout") - else fail("unexpected error '%s'", err) end - else - if err ~= "timeout" then fail("should have timed out") - else pass("proper timeout") end - end - else - if mode == "total" then - if elapsed > tm then - if err ~= "timeout" then fail("should have timed out") - else pass("proper timeout") end - elseif elapsed < tm then - if err then fail(err) - else pass("ok") end - else - if alldone then - if err then fail("unexpected error '%s'", err) - else pass("ok") end - else - if err ~= "timeout" then fail(err) - else pass("proper timeoutk") end - end - end - else - if err then fail(err) - else pass("ok") end - end - end -end - -if not socket._DEBUG then - fail("Please define LUASOCKET_DEBUG and recompile LuaSocket") -end - -io.stderr:write("----------------------------------------------\n", -"LuaSocket Test Procedures\n", -"----------------------------------------------\n") - -start = socket.gettime() - -function reconnect() - io.stderr:write("attempting data connection... ") - if data then data:close() end - remote [[ - if data then data:close() data = nil end - data = server:accept() - data:setoption("tcp-nodelay", true) - ]] - data, err = socket.connect(host, port) - if not data then fail(err) - else pass("connected!") end - data:setoption("tcp-nodelay", true) -end - -pass("attempting control connection...") -control, err = socket.connect(host, port) -if err then fail(err) -else pass("connected!") end -control:setoption("tcp-nodelay", true) - ------------------------------------------------------------------------- -function test_methods(sock, methods) - for _, v in methods do - if type(sock[v]) ~= "function" then - fail(sock.class .. " method '" .. v .. "' not registered") - end - end - pass(sock.class .. " methods are ok") -end - ------------------------------------------------------------------------- -function test_mixed(len) - reconnect() - local inter = math.ceil(len/4) - local p1 = "unix " .. string.rep("x", inter) .. "line\n" - local p2 = "dos " .. string.rep("y", inter) .. "line\r\n" - local p3 = "raw " .. string.rep("z", inter) .. "bytes" - local p4 = "end" .. string.rep("w", inter) .. "bytes" - local bp1, bp2, bp3, bp4 -remote (string.format("str = data:receive(%d)", - string.len(p1)+string.len(p2)+string.len(p3)+string.len(p4))) - sent, err = data:send(p1..p2..p3..p4) - if err then fail(err) end -remote "data:send(str); data:close()" - bp1, err = data:receive() - if err then fail(err) end - bp2, err = data:receive() - if err then fail(err) end - bp3, err = data:receive(string.len(p3)) - if err then fail(err) end - bp4, err = data:receive("*a") - if err then fail(err) end - if bp1.."\n" == p1 and bp2.."\r\n" == p2 and bp3 == p3 and bp4 == p4 then - pass("patterns match") - else fail("patterns don't match") end -end - ------------------------------------------------------------------------- -function test_asciiline(len) - reconnect() - local str, str10, back, err - str = string.rep("x", math.mod(len, 10)) - str10 = string.rep("aZb.c#dAe?", math.floor(len/10)) - str = str .. str10 -remote "str = data:receive()" - sent, err = data:send(str.."\n") - if err then fail(err) end -remote "data:send(str ..'\\n')" - back, err = data:receive() - if err then fail(err) end - if back == str then pass("lines match") - else fail("lines don't match") end -end - ------------------------------------------------------------------------- -function test_rawline(len) - reconnect() - local str, str10, back, err - str = string.rep(string.char(47), math.mod(len, 10)) - str10 = string.rep(string.char(120,21,77,4,5,0,7,36,44,100), - math.floor(len/10)) - str = str .. str10 -remote "str = data:receive()" - sent, err = data:send(str.."\n") - if err then fail(err) end -remote "data:send(str..'\\n')" - back, err = data:receive() - if err then fail(err) end - if back == str then pass("lines match") - else fail("lines don't match") end -end - ------------------------------------------------------------------------- -function test_raw(len) - reconnect() - local half = math.floor(len/2) - local s1, s2, back, err - s1 = string.rep("x", half) - s2 = string.rep("y", len-half) -remote (string.format("str = data:receive(%d)", len)) - sent, err = data:send(s1) - if err then fail(err) end - sent, err = data:send(s2) - if err then fail(err) end -remote "data:send(str)" - back, err = data:receive(len) - if err then fail(err) end - if back == s1..s2 then pass("blocks match") - else fail("blocks don't match") end -end - ------------------------------------------------------------------------- -function test_totaltimeoutreceive(len, tm, sl) - reconnect() - local str, err, partial - pass("%d bytes, %ds total timeout, %ds pause", len, tm, sl) - remote (string.format ([[ - data:settimeout(%d) - str = string.rep('a', %d) - data:send(str) - print('server: sleeping for %ds') - socket.sleep(%d) - print('server: woke up') - data:send(str) - ]], 2*tm, len, sl, sl)) - data:settimeout(tm, "total") -local t = socket.gettime() - str, err, partial, elapsed = data:receive(2*len) - check_timeout(tm, sl, elapsed, err, "receive", "total", - string.len(str or partial) == 2*len) -end - ------------------------------------------------------------------------- -function test_totaltimeoutsend(len, tm, sl) - reconnect() - local str, err, total - pass("%d bytes, %ds total timeout, %ds pause", len, tm, sl) - remote (string.format ([[ - data:settimeout(%d) - str = data:receive(%d) - print('server: sleeping for %ds') - socket.sleep(%d) - print('server: woke up') - str = data:receive(%d) - ]], 2*tm, len, sl, sl, len)) - data:settimeout(tm, "total") - str = string.rep("a", 2*len) - total, err, partial, elapsed = data:send(str) - check_timeout(tm, sl, elapsed, err, "send", "total", - total == 2*len) -end - ------------------------------------------------------------------------- -function test_blockingtimeoutreceive(len, tm, sl) - reconnect() - local str, err, partial - pass("%d bytes, %ds blocking timeout, %ds pause", len, tm, sl) - remote (string.format ([[ - data:settimeout(%d) - str = string.rep('a', %d) - data:send(str) - print('server: sleeping for %ds') - socket.sleep(%d) - print('server: woke up') - data:send(str) - ]], 2*tm, len, sl, sl)) - data:settimeout(tm) - str, err, partial, elapsed = data:receive(2*len) - check_timeout(tm, sl, elapsed, err, "receive", "blocking", - string.len(str or partial) == 2*len) -end - ------------------------------------------------------------------------- -function test_blockingtimeoutsend(len, tm, sl) - reconnect() - local str, err, total - pass("%d bytes, %ds blocking timeout, %ds pause", len, tm, sl) - remote (string.format ([[ - data:settimeout(%d) - str = data:receive(%d) - print('server: sleeping for %ds') - socket.sleep(%d) - print('server: woke up') - str = data:receive(%d) - ]], 2*tm, len, sl, sl, len)) - data:settimeout(tm) - str = string.rep("a", 2*len) - total, err, partial, elapsed = data:send(str) - check_timeout(tm, sl, elapsed, err, "send", "blocking", - total == 2*len) -end - ------------------------------------------------------------------------- -function empty_connect() - reconnect() - if data then data:close() data = nil end - remote [[ - if data then data:close() data = nil end - data = server:accept() - ]] - data, err = socket.connect("", port) - if not data then - pass("ok") - data = socket.connect(host, port) - else - pass("gethostbyname returns localhost on empty string...") - end -end - ------------------------------------------------------------------------- -function isclosed(c) - return c:getfd() == -1 or c:getfd() == (2^32-1) -end - -function active_close() - reconnect() - if isclosed(data) then fail("should not be closed") end - data:close() - if not isclosed(data) then fail("should be closed") end - data = nil - local udp = socket.udp() - if isclosed(udp) then fail("should not be closed") end - udp:close() - if not isclosed(udp) then fail("should be closed") end - pass("ok") -end - ------------------------------------------------------------------------- -function test_closed() - local back, partial, err - local str = 'little string' - reconnect() - pass("trying read detection") - remote (string.format ([[ - data:send('%s') - data:close() - data = nil - ]], str)) - -- try to get a line - back, err, partial = data:receive() - if not err then fail("should have gotten 'closed'.") - elseif err ~= "closed" then fail("got '"..err.."' instead of 'closed'.") - elseif str ~= partial then fail("didn't receive partial result.") - else pass("graceful 'closed' received") end - reconnect() - pass("trying write detection") - remote [[ - data:close() - data = nil - ]] - total, err, partial = data:send(string.rep("ugauga", 100000)) - if not err then - pass("failed: output buffer is at least %d bytes long!", total) - elseif err ~= "closed" then - fail("got '"..err.."' instead of 'closed'.") - else - pass("graceful 'closed' received after %d bytes were sent", partial) - end -end - ------------------------------------------------------------------------- -function test_selectbugs() - local r, s, e = socket.select(nil, nil, 0.1) - assert(type(r) == "table" and type(s) == "table" and - (e == "timeout" or e == "error")) - pass("both nil: ok") - local udp = socket.udp() - udp:close() - r, s, e = socket.select({ udp }, { udp }, 0.1) - assert(type(r) == "table" and type(s) == "table" and - (e == "timeout" or e == "error")) - pass("closed sockets: ok") - e = pcall(socket.select, "wrong", 1, 0.1) - assert(e == false) - e = pcall(socket.select, {}, 1, 0.1) - assert(e == false) - pass("invalid input: ok") -end - ------------------------------------------------------------------------- -function accept_timeout() - io.stderr:write("accept with timeout (if it hangs, it failed): ") - local s, e = socket.bind("*", 0, 0) - assert(s, e) - local t = socket.gettime() - s:settimeout(1) - local c, e = s:accept() - assert(not c, "should not accept") - assert(e == "timeout", string.format("wrong error message (%s)", e)) - t = socket.gettime() - t - assert(t < 2, string.format("took to long to give up (%gs)", t)) - s:close() - pass("good") -end - ------------------------------------------------------------------------- -function connect_timeout() - io.stderr:write("connect with timeout (if it hangs, it failed!): ") - local t = socket.gettime() - local c, e = socket.tcp() - assert(c, e) - c:settimeout(0.1) - local t = socket.gettime() - local r, e = c:connect("10.0.0.1", 81) -print(r, e) - assert(not r, "should not connect") - assert(socket.gettime() - t < 2, "took too long to give up.") - c:close() - print("ok") -end - ------------------------------------------------------------------------- -function accept_errors() - io.stderr:write("not listening: ") - local d, e = socket.bind("*", 0) - assert(d, e); - local c, e = socket.tcp(); - assert(c, e); - d:setfd(c:getfd()) - d:settimeout(2) - local r, e = d:accept() - assert(not r and e) - print("ok: ", e) - io.stderr:write("not supported: ") - local c, e = socket.udp() - assert(c, e); - d:setfd(c:getfd()) - local r, e = d:accept() - assert(not r and e) - print("ok: ", e) -end - ------------------------------------------------------------------------- -function connect_errors() - io.stderr:write("connection refused: ") - local c, e = socket.connect("localhost", 1); - assert(not c and e) - print("ok: ", e) - io.stderr:write("host not found: ") - local c, e = socket.connect("host.is.invalid", 1); - assert(not c and e, e) - print("ok: ", e) -end - ------------------------------------------------------------------------- -function rebind_test() - local c = socket.bind("localhost", 0) - local i, p = c:getsockname() - local s, e = socket.tcp() - assert(s, e) - s:setoption("reuseaddr", false) - r, e = s:bind("localhost", p) - assert(not r, "managed to rebind!") - assert(e) - print("ok: ", e) -end - ------------------------------------------------------------------------- -function getstats_test() - reconnect() - local t = 0 - for i = 1, 25 do - local c = math.random(1, 100) - remote (string.format ([[ - str = data:receive(%d) - data:send(str) - ]], c)) - data:send(string.rep("a", c)) - data:receive(c) - t = t + c - local r, s, a = data:getstats() - assert(r == t, "received count failed" .. tostring(r) - .. "/" .. tostring(t)) - assert(s == t, "sent count failed" .. tostring(s) - .. "/" .. tostring(t)) - end - print("ok") -end - - ------------------------------------------------------------------------- -function test_nonblocking(size) - reconnect() -print("Testing " .. 2*size .. " bytes") -remote(string.format([[ - data:send(string.rep("a", %d)) - socket.sleep(0.5) - data:send(string.rep("b", %d) .. "\n") -]], size, size)) - local err = "timeout" - local part = "" - local str - data:settimeout(0) - while 1 do - str, err, part = data:receive("*l", part) - if err ~= "timeout" then break end - end - assert(str == (string.rep("a", size) .. string.rep("b", size))) - reconnect() -remote(string.format([[ - str = data:receive(%d) - socket.sleep(0.5) - str = data:receive(2*%d, str) - data:send(str) -]], size, size)) - data:settimeout(0) - local start = 0 - while 1 do - ret, err, start = data:send(str, start+1) - if err ~= "timeout" then break end - end - data:send("\n") - data:settimeout(-1) - local back = data:receive(2*size) - assert(back == str, "'" .. back .. "' vs '" .. str .. "'") - print("ok") -end - ------------------------------------------------------------------------- - - -test("method registration") -test_methods(socket.tcp(), { - "accept", - "bind", - "close", - "connect", - "dirty", - "getfd", - "getpeername", - "getsockname", - "getstats", - "setstats", - "listen", - "receive", - "send", - "setfd", - "setoption", - "setpeername", - "setsockname", - "settimeout", - "shutdown", -}) - -test_methods(socket.udp(), { - "close", - "getpeername", - "dirty", - "getfd", - "getpeername", - "getsockname", - "receive", - "receivefrom", - "send", - "sendto", - "setfd", - "setoption", - "setpeername", - "setsockname", - "settimeout" -}) - -test("select function") -test_selectbugs() - -test("connect function") -connect_timeout() -empty_connect() -connect_errors() - -test("rebinding: ") -rebind_test() - -test("active close: ") -active_close() - -test("closed connection detection: ") -test_closed() - -test("accept function: ") -accept_timeout() -accept_errors() - -test("getstats test") -getstats_test() - -test("character line") -test_asciiline(1) -test_asciiline(17) -test_asciiline(200) -test_asciiline(4091) -test_asciiline(80199) -test_asciiline(8000000) -test_asciiline(80199) -test_asciiline(4091) -test_asciiline(200) -test_asciiline(17) -test_asciiline(1) - -test("mixed patterns") -test_mixed(1) -test_mixed(17) -test_mixed(200) -test_mixed(4091) -test_mixed(801990) -test_mixed(4091) -test_mixed(200) -test_mixed(17) -test_mixed(1) - -test("binary line") -test_rawline(1) -test_rawline(17) -test_rawline(200) -test_rawline(4091) -test_rawline(80199) -test_rawline(8000000) -test_rawline(80199) -test_rawline(4091) -test_rawline(200) -test_rawline(17) -test_rawline(1) - -test("raw transfer") -test_raw(1) -test_raw(17) -test_raw(200) -test_raw(4091) -test_raw(80199) -test_raw(8000000) -test_raw(80199) -test_raw(4091) -test_raw(200) -test_raw(17) -test_raw(1) - -test("non-blocking transfer") -test_nonblocking(1) -test_nonblocking(17) -test_nonblocking(200) -test_nonblocking(4091) -test_nonblocking(80199) -test_nonblocking(800000) -test_nonblocking(80199) -test_nonblocking(4091) -test_nonblocking(200) -test_nonblocking(17) -test_nonblocking(1) - -test("total timeout on send") -test_totaltimeoutsend(800091, 1, 3) -test_totaltimeoutsend(800091, 2, 3) -test_totaltimeoutsend(800091, 5, 2) -test_totaltimeoutsend(800091, 3, 1) - -test("total timeout on receive") -test_totaltimeoutreceive(800091, 1, 3) -test_totaltimeoutreceive(800091, 2, 3) -test_totaltimeoutreceive(800091, 3, 2) -test_totaltimeoutreceive(800091, 3, 1) - -test("blocking timeout on send") -test_blockingtimeoutsend(800091, 1, 3) -test_blockingtimeoutsend(800091, 2, 3) -test_blockingtimeoutsend(800091, 3, 2) -test_blockingtimeoutsend(800091, 3, 1) - -test("blocking timeout on receive") -test_blockingtimeoutreceive(800091, 1, 3) -test_blockingtimeoutreceive(800091, 2, 3) -test_blockingtimeoutreceive(800091, 3, 2) -test_blockingtimeoutreceive(800091, 3, 1) - -test(string.format("done in %.2fs", socket.gettime() - start)) diff --git a/etc/tests/luasocket/testsrvr.lua b/etc/tests/luasocket/testsrvr.lua deleted file mode 100644 index f1972c2..0000000 --- a/etc/tests/luasocket/testsrvr.lua +++ /dev/null @@ -1,15 +0,0 @@ -socket = require("socket"); -host = host or "localhost"; -port = port or "8383"; -server = assert(socket.bind(host, port)); -ack = "\n"; -while 1 do - print("server: waiting for client connection..."); - control = assert(server:accept()); - while 1 do - command = assert(control:receive()); - assert(control:send(ack)); - print(command); - (loadstring(command))(); - end -end diff --git a/etc/tests/luasocket/testsupport.lua b/etc/tests/luasocket/testsupport.lua deleted file mode 100644 index acad8f5..0000000 --- a/etc/tests/luasocket/testsupport.lua +++ /dev/null @@ -1,37 +0,0 @@ -function readfile(name) - local f = io.open(name, "rb") - if not f then return nil end - local s = f:read("*a") - f:close() - return s -end - -function similar(s1, s2) - return string.lower(string.gsub(s1 or "", "%s", "")) == - string.lower(string.gsub(s2 or "", "%s", "")) -end - -function fail(msg) - msg = msg or "failed" - error(msg, 2) -end - -function compare(input, output) - local original = readfile(input) - local recovered = readfile(output) - if original ~= recovered then fail("comparison failed") - else print("ok") end -end - -local G = _G -local set = rawset -local warn = print - -local setglobal = function(table, key, value) - warn("changed " .. key) - set(table, key, value) -end - -setmetatable(G, { - __newindex = setglobal -}) diff --git a/etc/zipmod.sh b/etc/zipmod.sh deleted file mode 100755 index 9b509ee..0000000 --- a/etc/zipmod.sh +++ /dev/null @@ -1,45 +0,0 @@ -#! /bin/bash - -# ONLY FOR MAINTAINER USE!! - -t="`pwd`"; -cd "`dirname "$0"`/.."; -basedir="`pwd`"; -cd "$t"; - -ver=0.1.2; - -do_make() # [PLATFORM] -{ - - TC_FILE=''; - BLD_SFX=''; - - if [ "$1" ]; then - TC_FILE="-DCMAKE_TOOLCHAIN_FILE=cmake/x-$1.cmake"; - BLD_SFX="-$1"; - fi - - cd "$basedir"; - mkdir -p Build$BLD_SFX; - cd Build$BLD_SFX; - cmake $TC_FILE .. || exit; - make || exit; - make pack_mod || exit; - cd ..; - -} - -mkdir -p "$basedir/dists" - -# Native Version -(do_make \ - && cd Build \ - && tar cfz "$basedir/dists/Kaeza-irc-$ver-`uname -s`-`uname -p`.tar.gz" irc \ -) || exit; - -# Linux -> MinGW32 Crosscompiler -(do_make i586-mingw32msvc \ - && cd Build-i586-mingw32msvc \ - && zip -r "$basedir/dists/Kaeza-irc-$ver-Win32.zip" irc \ -) || exit; diff --git a/quick_install.sh b/quick_install.sh new file mode 100755 index 0000000..49cc4ab --- /dev/null +++ b/quick_install.sh @@ -0,0 +1,8 @@ +#! /bin/sh + +mkdir -p Build \ +&& cd Build \ +&& cmake .. \ +&& make \ +&& cd .. \ +&& cp -r Build/irc $1 diff --git a/src/API.txt b/src/API.txt new file mode 100644 index 0000000..2e0ff5b --- /dev/null +++ b/src/API.txt @@ -0,0 +1,87 @@ +IRC Mod API +----------- +This file documents the Minetest IRC mod API. + +BASICS +------ +In order to allow your mod to interface with this mod, you must add 'irc' + (without the quotes) to your mod's 'depends.txt' file. + + +REFERENCE +--------- + +mt_irc:say([name, ]message) +Sends to either the channel (if is nil or not specified), +or to the given user (if is specified). +Example: + mt_irc:say("Hello, Channel!") + mt_irc:say("john1234", "How are you?") + +mt_irc:register_bot_command(name, cmdDef) + Registers a new bot command named . + When an user sends a private message to the bot with the command name, the + command's function is called. + Here's the format of a command definition (): + cmdDef = { + params = " ...", -- A description of the command's parameters + description = "My command", -- A description of what the command does. (one-liner) + func = function(user, param) + -- This function gets called when the command is invoked. + -- is a user table for the user that ran the command. + -- (See the LuaIRC documentation for details.) + -- It contains fields such as 'nick' and 'ident' + -- is a string of parameters to the command (may be "") + end, + }; + Example: + mt_irc:register_bot_command("hello", { + params = "", + description = "Greet user", + func = function(user, param) + mt_irc:say(user.nick, "Hello!") + end, + }); + +mt_irc.joined_players[name] + This table holds the players who are currently on the channel (may be less + than the players in the game). It is modified by the /part and /join chat + commands. + Example: + if mt_irc.joined_players["joe"] then + -- Joe is talking on IRC + end + +mt_irc:register_hook(name, func) + Registers a function to be called when an event happens. is the name + of the event, and is the function to be called. See HOOKS below + for more information + Example: + mt_irc:register_hook("OnSend", function(line) + print("SEND: "..line) + end) + +This mod also supplies some utility functions: + +string.expandvars(string, vars) + Expands all occurrences of the pattern "$(varname)" with the value of + 'varname' in the table. Variable names not found on the table + are left verbatim in the string. + Example: + local tpl = "$(foo) $(bar) $(baz)" + local s = tpl:expandvars({ foo=1, bar="Hello" }) + assert(s == "1 Hello $(baz)") + +In addition, all the configuration options decribed in `README.txt' are +available to other mods, though they should be considered "read only". Do +not modify these settings at runtime or you will most likely crash the +server! + + +HOOKS +--------- +The 'mt_irc:register_hook' function can register functions to be called +when some events happen. The events supported are the same as the LuaIRC +ones with a few added (mostly for internal use). +See src/LuaIRC/doc/irc.luadoc for more information. + diff --git a/src/LICENSE.txt b/src/LICENSE.txt new file mode 100644 index 0000000..9af567d --- /dev/null +++ b/src/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright (c) 2013, Diego Martinez (kaeza) +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/src/LuaIRC b/src/LuaIRC new file mode 160000 index 0000000..bc79606 --- /dev/null +++ b/src/LuaIRC @@ -0,0 +1 @@ +Subproject commit bc79606de0348d1f6b4aef3f1c9ddf2fffbc8dd5 diff --git a/src/botcmds.lua b/src/botcmds.lua index 85a97d2..8356b52 100644 --- a/src/botcmds.lua +++ b/src/botcmds.lua @@ -1,91 +1,106 @@ +mt_irc.bot_commands = {} -mt_irc.bot_commands = { }; -mt_irc.bot_help = function ( from, cmdname ) - local cmd = mt_irc.bot_commands[cmdname]; - if (not cmd) then - irc.say(from, "Unknown command `"..cmdname.."'"); - return; +function mt_irc:bot_command(user, message) + local pos = message:find(" ", 1, true) + local cmd, args + if pos then + cmd = message:sub(1, pos - 1) + args = message:sub(pos + 1) + else + cmd = message + args = "" end - local usage = "Usage: !"..cmdname; - if (cmd.params) then usage = usage.." "..cmd.params; end - irc.say(from, usage); - if (cmd.description) then irc.say(from, " "..cmd.description); end + + if not self.bot_commands[cmd] then + self:say(user.nick, "Unknown command '"..cmd.."'. Try `!help'." + .." Or use @playername to send a private message") + return + end + + self.bot_commands[cmd].func(user, args) end -mt_irc.register_bot_command = function ( name, def ) - if ((not def.func) or (type(def.func) ~= "function")) then - error("Wrong bot command definition", 2); + +function mt_irc:register_bot_command(name, def) + if (not def.func) or (type(def.func) ~= "function") then + error("Erroneous bot command definition. def.func missing.", 2) end - mt_irc.bot_commands[name] = def; + self.bot_commands[name] = def end -mt_irc.register_bot_command("help", { - params = "[]"; - description = "Get help about a command"; - func = function ( from, args ) - if (args ~= "") then - mt_irc.bot_help(from, args); - else - local cmdlist = "Available commands:"; - for name,cmd in pairs(mt_irc.bot_commands) do - cmdlist = cmdlist.." "..name; - end - irc.say(from, cmdlist); - irc.say(from, "Use `!help ' to get help about a specific command."); - end - end; -}); -mt_irc.register_bot_command("who", { - params = nil; - description = "Tell who is playing"; - func = function ( from, args ) - local s = ""; - for k, v in pairs(mt_irc.connected_players) do - if (v) then - s = s.." "..k; - end +mt_irc:register_bot_command("help", { + params = "", + description = "Get help about a command", + func = function(user, args) + if args == "" then + mt_irc:say(user.nick, "No command name specified. Use 'list' for a list of cammands") + return end - irc.say(from, "Players On Channel:"..s); - end; -}); -mt_irc.register_bot_command("whereis", { - params = ""; - description = "Tell the location of "; - func = function ( from, args ) - if (args == "") then - mt_irc.bot_help(from, "whereis"); - return; + local cmd = mt_irc.bot_commands[args] + if not cmd then + mt_irc:say(user.nick, "Unknown command '"..cmdname.."'.") + return end - local list = minetest.env:get_objects_inside_radius({x=0,y=0,z=0}, 100000); - for _, obj in ipairs(list) do - if (obj:is_player() and (obj:get_player_name() == args)) then - local fmt = "Player %s is at (%.2f,%.2f,%.2f)"; - local pos = obj:getpos(); - irc.say(from, fmt:format(args, pos.x, pos.y, pos.z)); - return; - end + + local usage = ("Usage: %c%s %s -- %s"):format( + mt_irc.config.command_prefix, + args, + cmd.params or "", + cmd.description or "") + mt_irc:say(user.nick, usage) + end +}) + + +mt_irc:register_bot_command("list", { + params = "", + description = "List available commands.", + func = function(user, args) + local cmdlist = "Available commands: " + for name, cmd in pairs(mt_irc.bot_commands) do + cmdlist = cmdlist..name..", " end - irc.say(from, "There's No player named `"..args.."'"); - end; -}); + mt_irc:say(user.nick, cmdlist + .." -- Use 'help ' to get help about a specific command.") + end +}) -local starttime = os.time(); -mt_irc.register_bot_command("uptime", { - params = ""; - description = "Tell how much time the server has been up"; - privs = { shout=true; }; - func = function ( name, param ) - local t = os.time(); - local diff = os.difftime(t, starttime); - local fmt = "Server has been running for %d:%02d:%02d"; - irc.say(name, fmt:format( +mt_irc:register_bot_command("whereis", { + params = "", + description = "Tell the location of ", + func = function(user, args) + if args == "" then + mt_irc:bot_help(user, "whereis") + return + end + local player = minetest.env:get_player_by_name(args) + if player then + local fmt = "Player %s is at (%.2f,%.2f,%.2f)" + local pos = player:getpos() + mt_irc:say(user.nick, fmt:format(args, pos.x, pos.y, pos.z)) + return + end + mt_irc:say(user.nick, "There is No player named '"..args.."'") + end +}) + + +local starttime = os.time() +mt_irc:register_bot_command("uptime", { + description = "Tell how much time the server has been up", + func = function(user, args) + local cur_time = os.time() + local diff = os.difftime(cur_time, starttime) + local fmt = "Server has been running for %d:%02d:%02d" + mt_irc:say(user.nick, fmt:format( math.floor(diff / 60 / 60), math.mod(math.floor(diff / 60), 60), math.mod(math.floor(diff), 60) - )); - end; -}); + )) + end +}) + diff --git a/src/callback.lua b/src/callback.lua index 19b27c7..4a0d2ab 100644 --- a/src/callback.lua +++ b/src/callback.lua @@ -1,232 +1,35 @@ --- IRC Mod for Minetest --- By Diego Martínez --- --- This mod allows to tie a Minetest server to an IRC channel. --- --- This program is free software. It comes without any warranty, to --- the extent permitted by applicable law. You can redistribute it --- and/or modify it under the terms of the Do What The Fuck You Want --- To Public License, Version 2, as published by Sam Hocevar. See --- http://sam.zoy.org/wtfpl/COPYING for more details. --- +-- This file is licensed under the terms of the BSD 2-clause license. +-- See LICENSE.txt for details. -local irc = require("irc"); -mt_irc.callbacks = { }; - -mt_irc._callback = function ( name, breakonreturn, ... ) - local list = mt_irc.callbacks[name]; - if (not list) then return; end - for n = 1, #list do - local r = list[n](...); - if (breakonreturn and (r ~= nil)) then return r; end +minetest.register_on_joinplayer(function(player) + local name = player:get_player_name() + if mt_irc.connected then + mt_irc:say("*** "..name.." joined the game") end -end - -mt_irc.register_callback = function ( name, func ) - local list = mt_irc.callbacks[name]; - if (not list) then - list = { }; - mt_irc.callbacks[name] = list; - end - list[#list + 1] = func; -end - -minetest.register_on_joinplayer(function ( player ) - local name = player:get_player_name(); - mt_irc.connected_players[name] = mt_irc.auto_join; - if (not mt_irc.connect_ok) then return; end - mt_irc.say("*** "..name.." joined the game"); -end); - -minetest.register_on_leaveplayer(function ( player ) - local name = player:get_player_name(); - mt_irc.connected_players[name] = nil; - if (not mt_irc.connect_ok) then return; end - mt_irc.say("*** "..name.." left the game"); -end); - -irc.register_callback("connect", function ( ) - mt_irc.got_motd = true; - irc.join(mt_irc.channel); -end); - -irc.register_callback("channel_msg", function ( channel, from, message ) - if (not mt_irc.connect_ok) then return; end - local t = { - name=(from or ""); - message=(message or ""); - server=mt_irc.server; - port=mt_irc.port; - channel=mt_irc.channel; - }; - local text = mt_irc.message_format_in:gsub("%$%(([^)]+)%)", t) - if (mt_irc._callback("channel_msg", from, message, text)) then return; end - for k, v in pairs(mt_irc.connected_players) do - if (v) then minetest.chat_send_player(k, text); end - end -end); - -local function bot_command ( from, message ) - - local pos = message:find(" ", 1, true); - local cmd, args; - if (pos) then - cmd = message:sub(1, pos - 1); - args = message:sub(pos + 1); - else - cmd = message; - args = ""; - end - - if (not mt_irc.bot_commands[cmd]) then - mt_irc.say(from, "Unknown command `"..cmd.."'. Try `!help'."); - return; - end - - mt_irc.bot_commands[cmd].func(from, args); - -end - -irc.register_callback("private_msg", function ( from, message ) - if (not mt_irc.connect_ok) then return; end - local player_to; - local msg; - if (message:sub(1, 1) == "@") then - local pos = message:find(" ", 1, true); - if (not pos) then return; end - player_to = message:sub(2, pos - 1); - msg = message:sub(pos + 1); - elseif (message:sub(1, 1) == "!") then - bot_command(from, message:sub(2)); - return; - else - irc.say(from, 'Message not sent! Please use "!help" to see possible commands.'); - irc.say(from, ' Or use the "@playername Message" syntax to send a private message.'); - return; - end - if (not mt_irc.connected_players[player_to]) then - irc.say(from, "User `"..player_to.."' is not connected to IRC."); - return; - end - local t = { - name=(from or ""); - message=(msg or ""); - server=mt_irc.server; - port=mt_irc.port; - channel=mt_irc.channel; - }; - local text = mt_irc.message_format_in:expandvars(t); - if (mt_irc._callback("private_msg", from, player_to, message, text)) then return; end - minetest.chat_send_player(player_to, "PRIVATE: "..text); - mt_irc.say(from, "Message sent!") -end); - -irc.register_callback("kick", function(chaninfo, nick, kicker) - if nick == mt_irc.server_nick then - minetest.chat_send_all("IRC: Bot was kicked by "..kicker.."."); - mt_irc.got_motd = false; - mt_irc.connect_ok = false; - irc.quit("Kicked"); - end -end); - -irc.register_callback("nick_change", function ( from, old_nick ) - if (not mt_irc.connect_ok) then return; end - mt_irc._callback("nick_change", false, old_nick, from); - local text = "["..old_nick.." changed his nick to "..from.."]"; - for k, v in pairs(mt_irc.connected_players) do - if (v) then minetest.chat_send_player(k, text); end - end -end); - -irc.register_callback("join", function ( servinfo, from ) - local text = "*** "..from.." joined "..mt_irc.channel; - for k, v in pairs(mt_irc.connected_players) do - if (v) then minetest.chat_send_player(k, text); end - end -end); - -irc.register_callback("part", function ( servinfo, from, part_msg ) - mt_irc._callback("part", false, from, part_msg); - local text - if part_msg then - text = "*** "..from.." left "..mt_irc.channel.." ("..part_msg..")"; - else - text = "*** "..from.." left "..mt_irc.channel; - end - for k, v in pairs(mt_irc.connected_players) do - if (v) then minetest.chat_send_player(k, text); end - end -end); - -irc.register_callback("channel_act", function ( servinfo, from, message) - if (not mt_irc.connect_ok) then return; end - local text = "*** "..from.." "..message; - for k, v in pairs(mt_irc.connected_players) do - if (v) then minetest.chat_send_player(k, text); end - end -end); - -minetest.register_on_chat_message(function ( name, message ) - if (not mt_irc.connect_ok) then return; end - if (message:sub(1, 1) == "/") then return; end - if (not mt_irc.connected_players[name]) then return; end - if (not minetest.check_player_privs(name, {shout=true})) then - return; - end - if (not mt_irc.buffered_messages) then - mt_irc.buffered_messages = { }; - end - mt_irc.buffered_messages[#mt_irc.buffered_messages + 1] = { - name = name; - message = message; - }; -end); - -minetest.register_on_shutdown(function ( ) - irc.quit("Game shutting down."); - for n = 1, 5 do - irc.poll(); - end -end); - -irc.handlers.on_error = function (...) --( from, respond_to ) - for k, v in pairs(mt_irc.connected_players) do - if (v) then minetest.chat_send_player(k, "IRC: Bot had a network error. Reconnecting in 5 seconds..."); end - end - for _, v in ipairs({...}) do - minetest.chat_send_all(dump(v)); - end - irc.quit("Network error"); - for n = 1, 5 do - irc.poll(); - end - mt_irc.got_motd = false; - mt_irc.connect_ok = false; - minetest.after(5, mt_irc.connect); -end - -irc.handlers.on_err_nicknameinuse = function ( from, respond_to ) - irc.quit("Nick in use"); - for n = 1, 5 do - irc.poll(); - end - mt_irc.got_motd = false; - mt_irc.connect_ok = false; - local n = (tonumber(mt_irc.server_nick:sub(-1)) or 0) + 1; - if (n == 10) then n = 1; end - mt_irc.server_nick = mt_irc.server_nick:sub(1, -2)..n; - mt_irc.connect(); -end - --- TESTING ---[[ -mt_irc.register_callback("part", function ( nick, part_msg ) - mt_irc.say("TEST: "..nick.." has left the building!"); end) -mt_irc.register_callback("nick_change", function ( old_nick, new_nick ) - mt_irc.say("TEST: "..old_nick.." -> "..new_nick); + +minetest.register_on_leaveplayer(function(player) + local name = player:get_player_name() + if mt_irc.connected then + mt_irc:say("*** "..name.." left the game") + end end) -]] + + +minetest.register_on_chat_message(function(name, message) + if not mt_irc.connected + or message:sub(1, 1) == "/" + or not mt_irc.joined_players[name] + or (not minetest.check_player_privs(name, {shout=true})) then + return + end + mt_irc:queueMsg(mt_irc.msgs.playerMessage(mt_irc.config.channel, name, message)) +end) + + +minetest.register_on_shutdown(function() + mt_irc:disconnect("Game shutting down.") +end) + diff --git a/src/chatcmds.lua b/src/chatcmds.lua index 6fb9cb2..13c767a 100644 --- a/src/chatcmds.lua +++ b/src/chatcmds.lua @@ -1,124 +1,104 @@ +-- This file is licensed under the terms of the BSD 2-clause license. +-- See LICENSE.txt for details. --- IRC Mod for Minetest --- By Diego Martínez --- --- This mod allows to tie a Minetest server to an IRC channel. --- --- This program is free software. It comes without any warranty, to --- the extent permitted by applicable law. You can redistribute it --- and/or modify it under the terms of the Do What The Fuck You Want --- To Public License, Version 2, as published by Sam Hocevar. See --- http://sam.zoy.org/wtfpl/COPYING for more details. --- +-- Note: This file does NOT conatin every chat command, only general ones. +-- Feature-specific commands (like /join) are in their own files. -local irc = require("irc"); minetest.register_chatcommand("irc_msg", { - params = " "; - description = "Send a private message to an IRC user"; - privs = { shout=true; }; - func = function ( name, param ) - if (not mt_irc.connect_ok) then - minetest.chat_send_player(name, "IRC: You are not connected, use /irc_connect."); - return; - end - local found, _, toname, msg = param:find("^([^%s#]+)%s(.+)"); - if not found then - minetest.chat_send_player(name, "Invalid usage, see /help irc_msg."); - return; - end - local t = {name=name, message=msg}; - local text = mt_irc.message_format_out:expandvars(t); - mt_irc.say(toname, text); - minetest.chat_send_player(name, "Message sent!") - end; -}); - -minetest.register_chatcommand("irc_connect", { - params = ""; - description = "Connect to the IRC server"; - privs = { irc_admin=true; }; - func = function ( name, param ) - if (mt_irc.connect_ok) then - minetest.chat_send_player(name, "IRC: You are already connected."); - return; - end - mt_irc.connect(); - minetest.chat_send_player(name, "IRC: You are now connected."); - irc.say(mt_irc.channel, name.." joined the channel."); - end; -}); - -minetest.register_chatcommand("irc_disconnect", { - params = ""; - description = "Disconnect from the IRC server"; - privs = { irc_admin=true; }; - func = function ( name, param ) - if (not mt_irc.connect_ok) then - minetest.chat_send_player(name, "IRC: You are not connected."); - return; - end - irc.quit("Manual BOT Disconnection"); - minetest.chat_send_player(name, "IRC: You are now disconnected."); - mt_irc.connect_ok = false; - end; -}); - -minetest.register_chatcommand("irc_reconnect", { - params = ""; - description = "Reconnect to the IRC server"; - privs = { irc_admin=true; }; - func = function ( name, param ) - if (mt_irc.connect_ok) then - irc.quit("Reconnecting BOT..."); - minetest.chat_send_player(name, "IRC: Reconnecting bot..."); - mt_irc.got_motd = true; - mt_irc.connect_ok = false; - end - mt_irc.connect(); - end; -}); - -minetest.register_chatcommand("join", { - params = ""; - description = "Join the IRC channel"; - privs = { shout=true; }; - func = function ( name, param ) - mt_irc.join(name); - end; -}); - -minetest.register_chatcommand("part", { - params = ""; - description = "Part the IRC channel"; - privs = { shout=true; }; - func = function ( name, param ) - mt_irc.part(name); - end; -}); - -minetest.register_chatcommand("me", { - params = ""; - description = "chat action (eg. /me orders a pizza)"; - privs = { shout=true }; + params = " ", + description = "Send a private message to an IRC user", + privs = {shout=true}, func = function(name, param) - minetest.chat_send_all("* "..name.." "..param); - irc.say(mt_irc.channel, "* "..name.." "..param); - end, -}) - -minetest.register_chatcommand("who", { - -- TODO: This duplicates code from !who - params = ""; - description = "Tell who is currently on the channel"; - privs = { shout=true; }; - func = function ( name, param ) - local s = ""; - for k, v in pairs(mt_irc.connected_players) do - if (v) then - s = s.." "..k; + if not mt_irc.connected then + minetest.chat_send_player(name, "Not connected to IRC. Use /irc_connect to connect.") + return + end + local found, _, toname, message = param:find("^([^%s]+)%s(.+)") + if not found then + minetest.chat_send_player(name, "Invalid usage, see /help irc_msg.") + return + end + local validNick = false + for nick, user in pairs(mt_irc.conn.channels[mt_irc.config.channel].users) do + if nick:lower() == toname:lower() then + validNick = true + break end end - minetest.chat_send_player(name, "Players On Channel:"..s); - end; -}); + if toname:find("Serv|Bot") then + validNick = false + end + if not validNick then + minetest.chat_send_player(name, + "You can not message that user. (Hint: They have to be in the channel)") + return + end + mt_irc:queueMsg(mt_irc.msgs.playerMessage(toname, name, message)) + minetest.chat_send_player(name, "Message sent!") + end +}) + + +minetest.register_chatcommand("irc_connect", { + description = "Connect to the IRC server.", + privs = {irc_admin=true}, + func = function(name, param) + if mt_irc.connected then + minetest.chat_send_player(name, "You are already connected to IRC.") + return + end + minetest.chat_send_player(name, "IRC: Connecting...") + mt_irc:connect() + end +}) + + +minetest.register_chatcommand("irc_disconnect", { + description = "Disconnect from the IRC server.", + privs = {irc_admin=true}, + func = function(name, param) + if not mt_irc.connected then + minetest.chat_send_player(name, "You are not connected to IRC.") + return + end + mt_irc:disconnect("Manual disconnect.") + end +}) + + +minetest.register_chatcommand("irc_reconnect", { + description = "Reconnect to the IRC server.", + privs = {irc_admin=true}, + func = function(name, param) + if not mt_irc.connected then + minetest.chat_send_player(name, "You are not connected to IRC.") + return + end + mt_irc:disconnect("Reconnecting...") + mt_irc:connect() + end +}) + + +minetest.register_chatcommand("irc_quote", { + params = "", + description = "Send a raw command to the IRC server.", + privs = {irc_admin=true}, + func = function(name, param) + if not mt_irc.connected then + minetest.chat_send_player(name, "You are not connected to IRC.") + return + end + mt_irc:queueMsg(param) + minetest.chat_send_player(name, "Command sent!") + end +}) + + +local oldme = minetest.chatcommands["me"].func +minetest.chatcommands["me"].func = function(name, param) + oldme(name, param) + mt_irc:say(("* %s %s"):format(name, param)) +end + diff --git a/src/config.lua b/src/config.lua index cf2dcd7..0dd5bf8 100644 --- a/src/config.lua +++ b/src/config.lua @@ -1,72 +1,91 @@ --- IRC Mod for Minetest --- By Diego Martínez --- --- This mod allows to tie a Minetest server to an IRC channel. --- --- This program is free software. It comes without any warranty, to --- the extent permitted by applicable law. You can redistribute it --- and/or modify it under the terms of the Do What The Fuck You Want --- To Public License, Version 2, as published by Sam Hocevar. See --- http://sam.zoy.org/wtfpl/COPYING for more details. --- +-- This file is licensed under the terms of the BSD 2-clause license. +-- See LICENSE.txt for details. --- ************************* --- ** BASIC USER SETTINGS ** --- ************************* + +local config = {} + +------------------------- +-- BASIC USER SETTINGS -- +------------------------- + +-- Nickname (string, default "minetest-"..) +-- ( is a random string of 6 hexidecimal numbers). +config.nick = minetest.setting_get("irc.nick") -- Server to connect on joinplayer (string, default "irc.freenode.net") -mt_irc.server = minetest.setting_get("mt_irc.server") or "irc.freenode.net"; +config.server = minetest.setting_get("irc.server") or "irc.freenode.net" -- Port to connect on joinplayer (number, default 6667) -mt_irc.port = tonumber(minetest.setting_get("mt_irc.port")) or 6667; +config.port = tonumber(minetest.setting_get("irc.port")) or 6667 + +-- NickServ password +config.NSPass = minetest.setting_get("irc.NSPass") + +-- SASL password (Blank to disable SASL authentication) +config.SASLPass = minetest.setting_get("irc.SASLPass") -- Channel to connect on joinplayer (string, default "##mt-irc-mod") -mt_irc.channel = minetest.setting_get("mt_irc.channel") or "##mt-irc-mod"; +config.channel = minetest.setting_get("irc.channel") or "##mt-irc-mod" --- *********************** --- ** ADVANCED SETTINGS ** --- *********************** +-- Key for the channel (string, default nil) +config.key = minetest.setting_get("irc.key") --- Time between chat updates in seconds (number, default 0.2). -mt_irc.dtime = tonumber(minetest.setting_get("mt_irc.dtime")) or 0.2; + +----------------------- +-- ADVANCED SETTINGS -- +----------------------- + +-- Server password (string, default "") +config.password = minetest.setting_get("irc.password") + +-- SASL username +config.SASLUser = minetest.setting_get("irc.SASLUser") or config.nick + +-- Enable a TLS connection, requires LuaSEC (bool, default false) +config.secure = minetest.setting_getbool("irc.secure") + +-- Time between chat updates in seconds (number, default 2.1). Setting this too low can cause "Excess flood" disconnects. +config.interval = tonumber(minetest.setting_get("irc.interval")) or 2.0 -- Underlying socket timeout in seconds (number, default 60.0). -mt_irc.timeout = tonumber(minetest.setting_get("mt_irc.timeout")) or 60.0; +config.timeout = tonumber(minetest.setting_get("irc.timeout")) or 60.0 --- Nickname when using single conection (string, default "minetest-"..); --- ( is a random string of 6 hexidecimal numbers). -mt_irc.server_nick = minetest.setting_get("mt_irc.server_nick"); - --- Password to use when using single connection (string, default "") -mt_irc.password = minetest.setting_get("mt_irc.password"); +-- Prefix to use for bot commands (char, default '!') +config.command_prefix = minetest.setting_get("irc.command_prefix") or '!' +config.command_prefix = config.command_prefix:sub(1, 1) -- The format of messages sent to IRC server (string, default "<$(name)> $(message)") -- See `README.txt' for the macros supported here. -mt_irc.message_format_out = minetest.setting_get("mt_irc.message_format_out") or "<$(name)> $(message)"; +config.format_out = minetest.setting_get("irc.format_out") or "<$(name)> $(message)" -- The format of messages sent to IRC server (string, default "<$(name)@IRC> $(message)") -- See `README.txt' for the macros supported here. -mt_irc.message_format_in = minetest.setting_get("mt_irc.message_format_in") or "<$(name)@IRC> $(message)"; +config.format_in = minetest.setting_get("irc.format_in") or "<$(name)@IRC> $(message)" -- Enable debug output (boolean, default false) -mt_irc.debug = not minetest.setting_getbool("mt_irc.disable_debug"); +config.debug = minetest.setting_getbool("irc.debug") --- Whether to automatically join the channed when player joins +-- Whether to enable players joining and parting the channel +config.enable_player_part = not minetest.setting_getbool("irc.disable_player_part") + +-- Whether to automatically join the channel when player joins -- (boolean, default true) -mt_irc.auto_join = not minetest.setting_getbool("mt_irc.disable_auto_join"); +config.auto_join = not minetest.setting_getbool("irc.disable_auto_join") -- Whether to automatically connect to the server on mod load --- (boolean, default true) -mt_irc.auto_connect = not minetest.setting_getbool("mt_irc.disable_auto_connect"); +-- (boolean, default true) +config.auto_connect = not minetest.setting_getbool("irc.disable_auto_connect") -- Set default server nick if not specified. -if (not mt_irc.server_nick) then - local pr = PseudoRandom(os.time()); +if not config.nick then + local pr = PseudoRandom(os.time()) -- Workaround for bad distribution in minetest PRNG implementation. - local fmt = "minetest-%02X%02X%02X"; - mt_irc.server_nick = fmt:format( + config.nick = ("MT-%02X%02X%02X"):format( pr:next(0, 255), pr:next(0, 255), pr:next(0, 255) - ); + ) end + +mt_irc.config = config + diff --git a/src/friends.lua b/src/friends.lua deleted file mode 100644 index 6592195..0000000 --- a/src/friends.lua +++ /dev/null @@ -1,22 +0,0 @@ - --- IRC Mod for Minetest --- By Diego Martínez --- --- This mod allows to tie a Minetest server to an IRC channel. --- --- This program is free software. It comes without any warranty, to --- the extent permitted by applicable law. You can redistribute it --- and/or modify it under the terms of the Do What The Fuck You Want --- To Public License, Version 2, as published by Sam Hocevar. See --- http://sam.zoy.org/wtfpl/COPYING for more details. --- - --- TODO - ---[[ -local MODPATH = mt_irc.modpath; - -local function load_friends_list ( ) - -end -]] diff --git a/src/hooks.lua b/src/hooks.lua new file mode 100644 index 0000000..e5e3bca --- /dev/null +++ b/src/hooks.lua @@ -0,0 +1,211 @@ +-- This file is licensed under the terms of the BSD 2-clause license. +-- See LICENSE.txt for details. + + +mt_irc.hooks = {} +mt_irc.registered_hooks = {} + + +function mt_irc:doHook(conn) + for name, hook in pairs(self.registered_hooks) do + for _, func in pairs(hook) do + conn:hook(name, func) + end + end +end + + +function mt_irc:register_hook(name, func) + self.registered_hooks[name] = self.registered_hooks[name] or {} + table.insert(self.registered_hooks[name], func) +end + + +function mt_irc.hooks.raw(line) + if mt_irc.config.debug then + print("RECV: "..line) + end +end + + +function mt_irc.hooks.send(line) + if mt_irc.config.debug then + print("SEND: "..line) + end +end + + +function mt_irc.hooks.chat(user, channel, message) + -- Strip bold, underline, and colors + message = message:gsub('\2', '') + message = message:gsub('\31', '') + message = message:gsub('\3[0-9][0-9,]*', '') + if channel == mt_irc.conn.nick then + mt_irc.conn:invoke("PrivateMessage", user, message) + else + local c = string.char(1) + local found, _, action = message:find(("^%sACTION ([^%s]*)%s$"):format(c, c, c)) + if found then + mt_irc.conn:invoke("OnChannelAction", user, channel, action) + else + mt_irc.conn:invoke("OnChannelChat", user, channel, message) + end + end +end + + +function mt_irc.hooks.channelChat(user, channel, message) + local t = { + access=user.access, + name=user.nick, + message=message, + server=mt_irc.conn.host, + port=mt_irc.conn.port, + channel=channel + } + local text = mt_irc.config.format_in:expandvars(t) + mt_irc:sendLocal(text) +end + + +function mt_irc.hooks.pm(user, message) + local player_to + local msg + if message:sub(1, 1) == "@" then + local found, _, player_to, message = message:find("^.([^%s]+)%s(.+)$") + if not mt_irc.joined_players[player_to] then + mt_irc:say(user.nick, "User '"..player_to.."' has parted.") + return + elseif not minetest.get_player_by_name(player_to) then + mt_irc:say(user.nick, "User '"..player_to.."' is not in the game.") + return + end + local t = { + name=user.nick, + message=message, + server=mt_irc.server, + port=mt_irc.port, + channel=mt_irc.channel + } + local text = mt_irc.config.format_in:expandvars(t) + minetest.chat_send_player(player_to, "PM: "..text, false) + mt_irc:say(user.nick, "Message sent!") + elseif message:sub(1, 1) == "!" then + mt_irc:bot_command(user, message:sub(2)) + return + else + mt_irc:say(user.nick, "Invalid command. Use '" + ..mt_irc.config.command_prefix + .."list' to see possible commands.") + return + end +end + + +function mt_irc.hooks.kick(channel, target, prefix, reason) + if target == mt_irc.conn.nick then + minetest.chat_send_all("IRC: kicked from "..channel.." by "..prefix.nick..".") + mt_irc:disconnect("Kicked") + else + mt_irc:sendLocal(("-!- %s was kicked from %s by %s [%s]") + :format(target, channel, prefix.nick, reason)) + end +end + + +function mt_irc.hooks.notice(user, target, message) + if not user.nick then return end --Server NOTICEs + if target == mt_irc.conn.nick then return end + mt_irc:sendLocal("--"..user.nick.."@IRC-- "..message) +end + + +function mt_irc.hooks.mode(user, target, modes, ...) + local by = "" + if user.nick then + by = " by "..user.nick + end + local options = "" + for _, option in pairs({...}) do + options = options.." "..option + end + minetest.chat_send_all(("-!- mode/%s [%s%s]%s") + :format(target, modes, options, by)) +end + + +function mt_irc.hooks.nick(user, newNick) + mt_irc:sendLocal(("-!- %s is now known as %s") + :format(user.nick, newNick)) +end + + +function mt_irc.hooks.join(user, channel) + mt_irc:sendLocal(("-!- %s joined %s") + :format(user.nick, channel)) +end + + +function mt_irc.hooks.part(user, channel, reason) + reason = reason or "" + mt_irc:sendLocal(("-!- %s has left %s [%s]") + :format(user.nick, channel, reason)) +end + + +function mt_irc.hooks.quit(user, reason) + mt_irc:sendLocal(("-!- %s has quit [%s]") + :format(user.nick, reason)) +end + + +function mt_irc.hooks.action(user, channel, message) + mt_irc:sendLocal(("* %s@IRC %s") + :format(user.nick, message)) +end + + +function mt_irc.hooks.disconnect(message, isError) + mt_irc.connected = false + if isError then + minetest.log("error", "IRC: Error: Disconnected, reconnecting in one minute.") + minetest.chat_send_all("IRC: Error: Disconnected, reconnecting in one minute.") + minetest.after(60, mt_irc.connect) + else + minetest.log("action", "IRC: Disconnected.") + minetest.chat_send_all("IRC: Disconnected.") + end +end + + +function mt_irc.hooks.preregister(conn) + if not (mt_irc.config.SASLUser and mt_irc.config.SASLPass) then return end + local authString = mt_irc.b64e( + ("%s\x00%s\x00%s"):format( + mt_irc.config.SASLUser, + mt_irc.config.SASLUser, + mt_irc.config.SASLPass) + ) + conn:send("CAP REQ sasl") + conn:send("AUTHENTICATE PLAIN") + conn:send("AUTHENTICATE "..authString) + --LuaIRC will send CAP END +end + + +mt_irc:register_hook("PreRegister", mt_irc.hooks.preregister) +mt_irc:register_hook("OnRaw", mt_irc.hooks.raw) +mt_irc:register_hook("OnSend", mt_irc.hooks.send) +mt_irc:register_hook("OnChat", mt_irc.hooks.chat) +mt_irc:register_hook("OnPart", mt_irc.hooks.part) +mt_irc:register_hook("OnKick", mt_irc.hooks.kick) +mt_irc:register_hook("OnJoin", mt_irc.hooks.join) +mt_irc:register_hook("OnQuit", mt_irc.hooks.quit) +mt_irc:register_hook("NickChange", mt_irc.hooks.nick) +mt_irc:register_hook("OnChannelAction", mt_irc.hooks.action) +mt_irc:register_hook("PrivateMessage", mt_irc.hooks.pm) +mt_irc:register_hook("OnNotice", mt_irc.hooks.notice) +mt_irc:register_hook("OnChannelChat", mt_irc.hooks.channelChat) +mt_irc:register_hook("OnModeChange", mt_irc.hooks.mode) +mt_irc:register_hook("OnDisconnect", mt_irc.hooks.disconnect) + diff --git a/src/init.lua b/src/init.lua index b25aa85..464e9f3 100644 --- a/src/init.lua +++ b/src/init.lua @@ -1,127 +1,144 @@ +-- This file is licensed under the terms of the BSD 2-clause license. +-- See LICENSE.txt for details. --- IRC Mod for Minetest --- By Diego Martínez --- --- This mod allows to tie a Minetest server to an IRC channel. --- --- This program is free software. It comes without any warranty, to --- the extent permitted by applicable law. You can redistribute it --- and/or modify it under the terms of the Do What The Fuck You Want --- To Public License, Version 2, as published by Sam Hocevar. See --- http://sam.zoy.org/wtfpl/COPYING for more details. --- -local MODPATH = minetest.get_modpath("irc"); +mt_irc = { + connected = false, + cur_time = 0, + message_buffer = {}, + recent_message_count = 0, + joined_players = {}, + modpath = minetest.get_modpath("irc") +} -mt_irc = { }; +-- To find LuaIRC and LuaSocket +package.path = mt_irc.modpath.."/?/init.lua;" + ..mt_irc.modpath.."/irc/?.lua;" + ..mt_irc.modpath.."/?.lua;" + ..package.path +package.cpath = mt_irc.modpath.."/lib?.so;" + ..mt_irc.modpath.."/?.dll;" + ..package.cpath -dofile(MODPATH.."/config.lua"); +local irc = require('irc') -mt_irc.cur_time = 0; -mt_irc.buffered_messages = { }; -mt_irc.connected_players = { }; -mt_irc.modpath = MODPATH; - -package.path = MODPATH.."/?.lua;"..package.path; -package.cpath = MODPATH.."/lib?.so;"..MODPATH.."/?.dll;"..package.cpath; - -local irc = require 'irc'; - -irc.DEBUG = ((mt_irc.debug and true) or false); +dofile(mt_irc.modpath.."/config.lua") +dofile(mt_irc.modpath.."/messages.lua") +dofile(mt_irc.modpath.."/hooks.lua") +dofile(mt_irc.modpath.."/callback.lua") +dofile(mt_irc.modpath.."/chatcmds.lua") +dofile(mt_irc.modpath.."/botcmds.lua") +dofile(mt_irc.modpath.."/util.lua") +if mt_irc.config.enable_player_part then + dofile(mt_irc.modpath.."/player_part.lua") +else + setmetatable(mt_irc.joined_players, {__index = function(index) return true end}) +end minetest.register_privilege("irc_admin", { - description = "Allow IRC administrative tasks to be performed."; - give_to_singleplayer = true; -}); + description = "Allow IRC administrative tasks to be performed.", + give_to_singleplayer = true +}) -minetest.register_globalstep(function(dtime) - if (not mt_irc.connect_ok) then return end - mt_irc.cur_time = mt_irc.cur_time + dtime - if (mt_irc.cur_time >= mt_irc.dtime) then - if (mt_irc.buffered_messages) then - for _, msg in ipairs(mt_irc.buffered_messages) do - local t = { - name=(msg.name or ""), - message=(msg.message or "") - } - local text = mt_irc.message_format_out:expandvars(t) - irc.say(mt_irc.channel, text) - end - mt_irc.buffered_messages = nil + +minetest.register_globalstep(function(dtime) return mt_irc:step(dtime) end) + +function mt_irc:step(dtime) + if not self.connected then return end + + -- Tick down the recent message count + self.cur_time = self.cur_time + dtime + if self.cur_time >= self.config.interval then + if self.recent_message_count > 0 then + self.recent_message_count = self.recent_message_count - 1 end - irc.poll() - mt_irc.cur_time = mt_irc.cur_time - mt_irc.dtime + self.cur_time = self.cur_time - self.config.interval end -end) -mt_irc.part = function ( name ) - if (not mt_irc.connected_players[name]) then - minetest.chat_send_player(name, "IRC: You are not in the channel."); - return; + -- Hooks will manage incoming messages and errors + if not pcall(function() mt_irc.conn:think() end) then + return end - mt_irc.connected_players[name] = nil; - minetest.chat_send_player(name, "IRC: You are now out of the channel."); -end -mt_irc.join = function ( name ) - if (mt_irc.connected_players[name]) then - minetest.chat_send_player(name, "IRC: You are already in the channel."); - return; - end - mt_irc.connected_players[name] = true; - minetest.chat_send_player(name, "IRC: You are now in the channel."); -end - -mt_irc.connect = function ( ) - mt_irc.connect_ok = irc.connect({ - network = mt_irc.server; - port = mt_irc.port; - nick = mt_irc.server_nick; - pass = mt_irc.password; - timeout = mt_irc.timeout; - channel = mt_irc.channel; - }); - if (not mt_irc.connect_ok) then - local s = "DEBUG: irc.connect failed"; - minetest.debug(s); - minetest.chat_send_all(s); - return; - end - while (not mt_irc.got_motd) do - irc.poll(); + -- Send messages in the buffer + if #self.message_buffer > 10 then + minetest.log("error", "IRC: Message buffer overflow, clearing.") + self.message_buffer = {} + elseif #self.message_buffer > 0 then + for i=1, #self.message_buffer do + if self.recent_message_count > 4 then break end + self.recent_message_count = self.recent_message_count + 1 + local msg = table.remove(self.message_buffer, 1) --Pop the first message + self:send(msg) + end end end -mt_irc.say = function ( to, msg ) - if (not msg) then - msg = to; - to = mt_irc.channel; + +function mt_irc:connect() + if self.connected then + minetest.log("error", "IRC: Ignoring attempt to connect when already connected.") + return end - to = to or mt_irc.channel; - msg = msg or ""; - local msg2 = mt_irc._callback("msg_out", true, to, msg); - if ((type(msg2) == "boolean") and (not msg2)) then - return; - elseif (msg2 ~= nil) then - msg = tostring(msg); + self.conn = irc.new({ + nick = self.config.nick, + username = "Minetest", + realname = "Minetest", + }) + self:doHook(self.conn) + good, message = pcall(function() + mt_irc.conn:connect({ + host = mt_irc.config.server, + port = mt_irc.config.port, + pass = mt_irc.config.password, + timeout = mt_irc.config.timeout, + secure = mt_irc.config.secure + }) + end) + + if not good then + minetest.log("error", ("IRC: Connection error: %s: %s -- Reconnecting in ten minutes...") + :format(self.config.server, message)) + minetest.after(600, function() mt_irc:connect() end) + return end - irc.say(to, msg); + + if self.config.NSPass then + self:say("NickServ", "IDENTIFY "..self.config.NSPass) + end + + self.conn:join(self.config.channel, self.config.key) + self.connected = true + minetest.log("action", "IRC: Connected!") + minetest.chat_send_all("IRC: Connected!") end -mt_irc.irc = irc; --- Misc helpers - --- Requested by Exio -string.expandvars = function ( s, vars ) - return s:gsub("%$%(([^)]+)%)", vars); +function mt_irc:disconnect(message) + if self.connected then + --The OnDisconnect hook will clear self.connected and print a disconnect message + self.conn:disconnect(message) + end end -dofile(MODPATH.."/callback.lua"); -dofile(MODPATH.."/chatcmds.lua"); -dofile(MODPATH.."/botcmds.lua"); -dofile(MODPATH.."/friends.lua"); -if (mt_irc.auto_connect) then - mt_irc.connect() +function mt_irc:say(to, message) + if not message then + message = to + to = self.config.channel + end + to = to or self.config.channel + + self:queueMsg(self.msgs.privmsg(to, message)) end + + +function mt_irc:send(line) + self.conn:send(line) +end + + +if mt_irc.config.auto_connect then + mt_irc:connect() +end + diff --git a/src/luairc/irc.lua b/src/luairc/irc.lua deleted file mode 100644 index e070aa6..0000000 --- a/src/luairc/irc.lua +++ /dev/null @@ -1,1023 +0,0 @@ ---- --- Implementation of the main LuaIRC module - --- initialization {{{ -local base = _G -local constants = require 'irc.constants' -local ctcp = require 'irc.ctcp' -local c = ctcp._ctcp_quote -local irc_debug = require 'irc.debug' -local message = require 'irc.message' -local misc = require 'irc.misc' -local socket = require 'socket' -local os = require 'os' -local string = require 'string' -local table = require 'table' --- }}} - ---- --- LuaIRC - IRC framework written in Lua --- @release 0.3 -module 'irc' - --- constants {{{ -_VERSION = 'LuaIRC 0.3' --- }}} - --- classes {{{ -local Channel = base.require 'irc.channel' --- }}} - --- local variables {{{ -local irc_sock = nil -local rsockets = {} -local wsockets = {} -local rcallbacks = {} -local wcallbacks = {} -local icallbacks = { - whois = {}, - serverversion = {}, - servertime = {}, - ctcp_ping = {}, - ctcp_time = {}, - ctcp_version = {}, -} -local requestinfo = {whois = {}} -handlers = {} -ctcp_handlers = {} -user_handlers = {} -serverinfo = {} -ip = nil --- }}} - --- defaults {{{ -TIMEOUT = 60 -- connection timeout -NETWORK = "localhost" -- default network -PORT = 6667 -- default port -NICK = "luabot" -- default nick ---USERNAME = "LuaIRC" -- default username -USERNAME = "minetest" -- default username ---REALNAME = "LuaIRC" -- default realname -REALNAME = "minetest" -- default realname -DEBUG = false -- whether we want extra debug information -OUTFILE = nil -- file to send debug output to - nil is stdout --- }}} - --- private functions {{{ --- main_loop_iter {{{ -local function main_loop_iter() - if #rsockets == 0 and #wsockets == 0 then return false end - local rready, wready, err = socket.select(rsockets, wsockets) - if err then irc_debug._err(err); return false; end - - for _, sock in base.ipairs(rready) do - local cb = socket.protect(rcallbacks[sock]) - local ret, err = cb(sock) - if not ret then - irc_debug._warn("socket error: " .. err) - _unregister_socket(sock, 'r') - end - end - - for _, sock in base.ipairs(wready) do - local cb = socket.protect(wcallbacks[sock]) - local ret, err = cb(sock) - if not ret then - irc_debug._warn("socket error: " .. err) - _unregister_socket(sock, 'w') - end - end - - return true -end --- }}} - --- begin_main_loop {{{ -local function begin_main_loop() - --while main_loop_iter() do end -end --- }}} - -poll = main_loop_iter; - --- incoming_message {{{ -local function incoming_message(sock) - local rcvd = { sock:receive() }; - if ((rcvd[1] == nil) and (rcvd[2] == "timeout")) then return true; end - local raw_msg = socket.try(base.unpack(rcvd)) - irc_debug._message("RECV", raw_msg) - local msg = message._parse(raw_msg) - misc._try_call_warn("Unhandled server message: " .. msg.command, - handlers["on_" .. msg.command:lower()], - (misc._parse_user(msg.from)), base.unpack(msg.args)) - return true -end --- }}} - --- callback {{{ -local function callback(name, ...) - return misc._try_call(user_handlers[name], ...) -end --- }}} --- }}} - --- internal message handlers {{{ --- command handlers {{{ --- on_nick {{{ -function handlers.on_nick(from, new_nick) - for chan in channels() do - chan:_change_nick(from, new_nick) - end - callback("nick_change", new_nick, from) -end --- }}} - --- on_join {{{ -function handlers.on_join(from, chan) - chan = string.lower(chan); - base.assert(serverinfo.channels[chan], - "Received join message for unknown channel: " .. chan) - if serverinfo.channels[chan].join_complete then - serverinfo.channels[chan]:_add_user(from) - callback("join", serverinfo.channels[chan], from) - end -end --- }}} - --- on_part {{{ -function handlers.on_part(from, chan, part_msg) - -- don't assert on chan here, since we get part messages for ourselves - -- after we remove the channel from the channel list - if not serverinfo.channels[chan] then return end - if serverinfo.channels[chan].join_complete then - serverinfo.channels[chan]:_remove_user(from) - callback("part", serverinfo.channels[chan], from, part_msg) - end -end --- }}} - --- on_mode {{{ -function handlers.on_mode(from, to, mode_string, ...) - local dir = mode_string:sub(1, 1) - mode_string = mode_string:sub(2) - local args = {...} - to = string.lower(to); - - if to:sub(1, 1) == "#" then - -- handle channel mode requests {{{ - base.assert(serverinfo.channels[to], - "Received mode change for unknown channel: " .. to) - local chan = serverinfo.channels[to] - local ind = 1 - for i = 1, mode_string:len() do - local mode = mode_string:sub(i, i) - local target = args[ind] - -- channel modes other than op/voice will be implemented as - -- information request commands - if mode == "o" then -- channel op {{{ - chan:_change_status(target, dir == "+", "o") - callback(({["+"] = "op", ["-"] = "deop"})[dir], - chan, from, target) - ind = ind + 1 - -- }}} - elseif mode == "v" then -- voice {{{ - chan:_change_status(target, dir == "+", "v") - callback(({["+"] = "voice", ["-"] = "devoice"})[dir], - chan, from, target) - ind = ind + 1 - -- }}} - end - end - -- }}} - elseif from == to then - -- handle user mode requests {{{ - -- TODO: make users more easily accessible so this is actually - -- reasonably possible - for i = 1, mode_string:len() do - local mode = mode_string:sub(i, i) - if mode == "i" then -- invisible {{{ - -- }}} - elseif mode == "s" then -- server messages {{{ - -- }}} - elseif mode == "w" then -- wallops messages {{{ - -- }}} - elseif mode == "o" then -- ircop {{{ - -- }}} - end - end - -- }}} - end -end --- }}} - --- on_topic {{{ -function handlers.on_topic(from, chan, new_topic) - chan = string.lower(chan); - base.assert(serverinfo.channels[chan], - "Received topic message for unknown channel: " .. chan) - serverinfo.channels[chan]._topic.text = new_topic - serverinfo.channels[chan]._topic.user = from - serverinfo.channels[chan]._topic.time = os.time() - if serverinfo.channels[chan].join_complete then - callback("topic_change", serverinfo.channels[chan]) - end -end --- }}} - --- on_invite {{{ -function handlers.on_invite(from, to, chan) - chan = string.lower(chan); - callback("invite", from, chan) -end --- }}} - --- on_kick {{{ -function handlers.on_kick(from, chan, to) - chan = string.lower(chan); - base.assert(serverinfo.channels[chan], - "Received kick message for unknown channel: " .. chan) - if serverinfo.channels[chan].join_complete then - serverinfo.channels[chan]:_remove_user(to) - callback("kick", serverinfo.channels[chan], to, from) - end -end --- }}} - --- on_privmsg {{{ -function handlers.on_privmsg(from, to, msg) - local msgs = ctcp._ctcp_split(msg) - to = string.lower(to); - for _, v in base.ipairs(msgs) do - local msg = v.str - if v.ctcp then - -- ctcp message {{{ - local words = misc._split(msg) - local received_command = words[1] - local cb = "on_" .. received_command:lower() - table.remove(words, 1) - -- not using try_call here because the ctcp specification requires - -- an error response to nonexistant commands - if base.type(ctcp_handlers[cb]) == "function" then - ctcp_handlers[cb](from, to, table.concat(words, " ")) - else - notice(from, c("ERRMSG", received_command, ":Unknown query")) - end - -- }}} - else - -- normal message {{{ - if to:sub(1, 1) == "#" then - base.assert(serverinfo.channels[to], - "Received channel msg from unknown channel: " .. to) - callback("channel_msg", serverinfo.channels[to], from, msg) - else - callback("private_msg", from, msg) - end - -- }}} - end - end -end --- }}} - --- on_notice {{{ -function handlers.on_notice(from, to, msg) - local msgs = ctcp._ctcp_split(msg) - to = string.lower(to); - for _, v in base.ipairs(msgs) do - local msg = v.str - if v.ctcp then - -- ctcp message {{{ - local words = misc._split(msg) - local command = words[1]:lower() - table.remove(words, 1) - misc._try_call_warn("Unknown CTCP message: " .. command, - ctcp_handlers["on_rpl_"..command], from, to, - table.concat(words, ' ')) - -- }}} - else - -- normal message {{{ - if to:sub(1, 1) == "#" then - base.assert(serverinfo.channels[to], - "Received channel msg from unknown channel: " .. to) - callback("channel_notice", serverinfo.channels[to], from, msg) - else - callback("private_notice", from, msg) - end - -- }}} - end - end -end --- }}} - --- on_quit {{{ -function handlers.on_quit(from, quit_msg) - from = string.lower(from); - for name, chan in base.pairs(serverinfo.channels) do - chan:_remove_user(from) - end - callback("quit", from, quit_msg) -end --- }}} - --- on_ping {{{ --- respond to server pings to make sure it knows we are alive -function handlers.on_ping(from, respond_to) - send("PONG", respond_to) -end --- }}} --- }}} - --- server replies {{{ --- on_rpl_topic {{{ --- catch topic changes -function handlers.on_rpl_topic(from, chan, topic) - chan = string.lower(chan); - base.assert(serverinfo.channels[chan], - "Received topic information about unknown channel: " .. chan) - serverinfo.channels[chan]._topic.text = topic -end --- }}} - --- on_rpl_notopic {{{ -function handlers.on_rpl_notopic(from, chan) - chan = string.lower(chan); - base.assert(serverinfo.channels[chan], - "Received topic information about unknown channel: " .. chan) - serverinfo.channels[chan]._topic.text = "" -end --- }}} - --- on_rpl_topicdate {{{ --- "topic was set by at