├── .gitignore ├── .travis.yml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── luacjson ├── Cargo.toml ├── build.rs ├── cjson │ ├── fpconv.c │ ├── fpconv.h │ ├── lua_cjson.c │ ├── lua_cjson.h │ ├── strbuf.c │ └── strbuf.h ├── include │ ├── lapi.h │ ├── lauxlib.h │ ├── lua.h │ ├── luaconf.h │ └── lualib.h └── src │ └── lib.rs ├── luasocket ├── Cargo.toml ├── build.rs ├── include │ ├── lapi.h │ ├── lauxlib.h │ ├── lua.h │ ├── luaconf.h │ └── lualib.h ├── luasocket │ └── src │ │ ├── auxiliar.c │ │ ├── auxiliar.h │ │ ├── buffer.c │ │ ├── buffer.h │ │ ├── compat.c │ │ ├── compat.h │ │ ├── except.c │ │ ├── except.h │ │ ├── ftp.lua │ │ ├── headers.lua │ │ ├── http.lua │ │ ├── inet.c │ │ ├── inet.h │ │ ├── io.c │ │ ├── io.h │ │ ├── ltn12.lua │ │ ├── luasocket.c │ │ ├── luasocket.h │ │ ├── makefile │ │ ├── mbox.lua │ │ ├── mime.c │ │ ├── mime.h │ │ ├── mime.lua │ │ ├── options.c │ │ ├── options.h │ │ ├── pierror.h │ │ ├── select.c │ │ ├── select.h │ │ ├── serial.c │ │ ├── smtp.lua │ │ ├── socket.h │ │ ├── socket.lua │ │ ├── tcp.c │ │ ├── tcp.h │ │ ├── timeout.c │ │ ├── timeout.h │ │ ├── tp.lua │ │ ├── udp.c │ │ ├── udp.h │ │ ├── unix.c │ │ ├── unix.h │ │ ├── unixdgram.c │ │ ├── unixdgram.h │ │ ├── unixstream.c │ │ ├── unixstream.h │ │ ├── url.lua │ │ ├── usocket.c │ │ ├── usocket.h │ │ ├── wsocket.c │ │ └── wsocket.h └── src │ └── lib.rs ├── td_clua ├── Cargo.toml ├── build.rs ├── lua │ └── src │ │ ├── Makefile │ │ ├── lapi.c │ │ ├── lapi.h │ │ ├── lauxlib.c │ │ ├── lauxlib.h │ │ ├── lbaselib.c │ │ ├── lbitlib.c │ │ ├── lcode.c │ │ ├── lcode.h │ │ ├── lcorolib.c │ │ ├── lctype.c │ │ ├── lctype.h │ │ ├── ldblib.c │ │ ├── ldebug.c │ │ ├── ldebug.h │ │ ├── ldo.c │ │ ├── ldo.h │ │ ├── ldump.c │ │ ├── lfunc.c │ │ ├── lfunc.h │ │ ├── lgc.c │ │ ├── lgc.h │ │ ├── linit.c │ │ ├── liolib.c │ │ ├── llex.c │ │ ├── llex.h │ │ ├── llimits.h │ │ ├── lmathlib.c │ │ ├── lmem.c │ │ ├── lmem.h │ │ ├── loadlib.c │ │ ├── lobject.c │ │ ├── lobject.h │ │ ├── lopcodes.c │ │ ├── lopcodes.h │ │ ├── loslib.c │ │ ├── lparser.c │ │ ├── lparser.h │ │ ├── lprefix.h │ │ ├── lstate.c │ │ ├── lstate.h │ │ ├── lstring.c │ │ ├── lstring.h │ │ ├── lstrlib.c │ │ ├── ltable.c │ │ ├── ltable.h │ │ ├── ltablib.c │ │ ├── ltm.c │ │ ├── ltm.h │ │ ├── lua.c │ │ ├── lua.h │ │ ├── lua.hpp │ │ ├── luac.c │ │ ├── luaconf.h │ │ ├── lualib.h │ │ ├── lundump.c │ │ ├── lundump.h │ │ ├── lutf8lib.c │ │ ├── lvm.c │ │ ├── lvm.h │ │ ├── lzio.c │ │ └── lzio.h └── src │ └── lib.rs └── td_rlua ├── Cargo.toml ├── src ├── functions.rs ├── hotfix.rs ├── lib.rs ├── lua_tables.rs ├── rust_tables.rs ├── tuples.rs ├── userdata.rs └── values.rs └── tests ├── basic_types.rs ├── functions.rs ├── hotfix.rs ├── lua_tables.rs ├── rust_tables.rs └── userdata.rs /.gitignore: -------------------------------------------------------------------------------- 1 | *.lock 2 | */target/* -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | 3 | rust: 4 | - stable 5 | - beta 6 | - nightly 7 | 8 | script: 9 | - cargo test --manifest-path td_clua/Cargo.toml 10 | - cargo test --manifest-path td_rlua/Cargo.toml 11 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2006-2009 Graydon Hoare 2 | Copyright (c) 2009-2013 Mozilla Foundation 3 | 4 | Permission is hereby granted, free of charge, to any 5 | person obtaining a copy of this software and associated 6 | documentation files (the "Software"), to deal in the 7 | Software without restriction, including without 8 | limitation the rights to use, copy, modify, merge, 9 | publish, distribute, sublicense, and/or sell copies of 10 | the Software, and to permit persons to whom the Software 11 | is furnished to do so, subject to the following 12 | conditions: 13 | 14 | The above copyright notice and this permission notice 15 | shall be included in all copies or substantial portions 16 | of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 19 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 20 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 21 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 22 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 23 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 24 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 25 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 26 | DEALINGS IN THE SOFTWARE. 27 | -------------------------------------------------------------------------------- /luacjson/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "luacjson" 3 | version = "0.1.3" 4 | authors = [ "tickbh " ] 5 | description = "extend for Lua 5.3" 6 | repository = "https://github.com/tickbh/td_rlua" 7 | build = "build.rs" 8 | links = "luacjson" 9 | license = "MIT/Apache-2.0" 10 | 11 | [build-dependencies] 12 | pkg-config = "0.3" 13 | gcc = "0.3" 14 | 15 | [dependencies] 16 | libc = "^0.2" 17 | td_rlua = "0.3.0" 18 | -------------------------------------------------------------------------------- /luacjson/build.rs: -------------------------------------------------------------------------------- 1 | extern crate pkg_config; 2 | extern crate gcc; 3 | 4 | fn main() { 5 | gcc::Build::new() 6 | .file("cjson/fpconv.c") 7 | .file("cjson/lua_cjson.c") 8 | .file("cjson/strbuf.c") 9 | .include("cjson") 10 | .include("include") 11 | .compile("libluacjson.a"); 12 | } 13 | -------------------------------------------------------------------------------- /luacjson/cjson/fpconv.h: -------------------------------------------------------------------------------- 1 | /* Lua CJSON floating point conversion routines */ 2 | 3 | /* Buffer required to store the largest string representation of a double. 4 | * 5 | * Longest double printed with %.14g is 21 characters long: 6 | * -1.7976931348623e+308 */ 7 | # define FPCONV_G_FMT_BUFSIZE 32 8 | 9 | #ifdef _MSC_VER 10 | #define snprintf _snprintf 11 | #undef inline 12 | #define inline __inline 13 | #endif 14 | 15 | #ifdef USE_INTERNAL_FPCONV 16 | static inline void fpconv_init() 17 | { 18 | /* Do nothing - not required */ 19 | } 20 | #else 21 | extern inline void fpconv_init(); 22 | #endif 23 | 24 | extern int fpconv_g_fmt(char*, double, int); 25 | extern double fpconv_strtod(const char*, char**); 26 | 27 | /* vi:ai et sw=4 ts=4: 28 | */ 29 | -------------------------------------------------------------------------------- /luacjson/cjson/lua_cjson.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef __LUA_CJSON_H_ 3 | #define __LUA_CJSON_H_ 4 | 5 | #include "lua.h" 6 | 7 | #define USE_INTERNAL_FPCONV 8 | 9 | int luaopen_cjson(lua_State *l); 10 | 11 | #endif // __LUA_CJSON_H_ 12 | -------------------------------------------------------------------------------- /luacjson/cjson/strbuf.h: -------------------------------------------------------------------------------- 1 | /* strbuf - String buffer routines 2 | * 3 | * Copyright (c) 2010-2012 Mark Pulford 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining 6 | * a copy of this software and associated documentation files (the 7 | * "Software"), to deal in the Software without restriction, including 8 | * without limitation the rights to use, copy, modify, merge, publish, 9 | * distribute, sublicense, and/or sell copies of the Software, and to 10 | * permit persons to whom the Software is furnished to do so, subject to 11 | * the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be 14 | * included in all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 21 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 22 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 | */ 24 | 25 | #include 26 | #include 27 | 28 | /* Size: Total bytes allocated to *buf 29 | * Length: String length, excluding optional NULL terminator. 30 | * Increment: Allocation increments when resizing the string buffer. 31 | * Dynamic: True if created via strbuf_new() 32 | */ 33 | 34 | typedef struct { 35 | char *buf; 36 | int size; 37 | int length; 38 | int increment; 39 | int dynamic; 40 | int reallocs; 41 | int debug; 42 | } strbuf_t; 43 | 44 | #ifndef STRBUF_DEFAULT_SIZE 45 | #define STRBUF_DEFAULT_SIZE 1023 46 | #endif 47 | #ifndef STRBUF_DEFAULT_INCREMENT 48 | #define STRBUF_DEFAULT_INCREMENT -2 49 | #endif 50 | 51 | /* Initialise */ 52 | extern strbuf_t *strbuf_new(int len); 53 | extern void strbuf_init(strbuf_t *s, int len); 54 | extern void strbuf_set_increment(strbuf_t *s, int increment); 55 | 56 | /* Release */ 57 | extern void strbuf_free(strbuf_t *s); 58 | extern char *strbuf_free_to_string(strbuf_t *s, int *len); 59 | 60 | /* Management */ 61 | extern void strbuf_resize(strbuf_t *s, int len); 62 | static int strbuf_empty_length(strbuf_t *s); 63 | static int strbuf_length(strbuf_t *s); 64 | static char *strbuf_string(strbuf_t *s, int *len); 65 | static void strbuf_ensure_empty_length(strbuf_t *s, int len); 66 | static char *strbuf_empty_ptr(strbuf_t *s); 67 | static void strbuf_extend_length(strbuf_t *s, int len); 68 | 69 | /* Update */ 70 | extern void strbuf_append_fmt(strbuf_t *s, int len, const char *fmt, ...); 71 | extern void strbuf_append_fmt_retry(strbuf_t *s, const char *format, ...); 72 | static void strbuf_append_mem(strbuf_t *s, const char *c, int len); 73 | extern void strbuf_append_string(strbuf_t *s, const char *str); 74 | static void strbuf_append_char(strbuf_t *s, const char c); 75 | static void strbuf_ensure_null(strbuf_t *s); 76 | 77 | #ifdef _MSC_VER 78 | #define snprintf _snprintf 79 | #undef inline 80 | #define inline __inline 81 | #endif 82 | 83 | /* Reset string for before use */ 84 | static inline void strbuf_reset(strbuf_t *s) 85 | { 86 | s->length = 0; 87 | } 88 | 89 | static inline int strbuf_allocated(strbuf_t *s) 90 | { 91 | return s->buf != NULL; 92 | } 93 | 94 | /* Return bytes remaining in the string buffer 95 | * Ensure there is space for a NULL terminator. */ 96 | static inline int strbuf_empty_length(strbuf_t *s) 97 | { 98 | return s->size - s->length - 1; 99 | } 100 | 101 | static inline void strbuf_ensure_empty_length(strbuf_t *s, int len) 102 | { 103 | if (len > strbuf_empty_length(s)) 104 | strbuf_resize(s, s->length + len); 105 | } 106 | 107 | static inline char *strbuf_empty_ptr(strbuf_t *s) 108 | { 109 | return s->buf + s->length; 110 | } 111 | 112 | static inline void strbuf_extend_length(strbuf_t *s, int len) 113 | { 114 | s->length += len; 115 | } 116 | 117 | static inline int strbuf_length(strbuf_t *s) 118 | { 119 | return s->length; 120 | } 121 | 122 | static inline void strbuf_append_char(strbuf_t *s, const char c) 123 | { 124 | strbuf_ensure_empty_length(s, 1); 125 | s->buf[s->length++] = c; 126 | } 127 | 128 | static inline void strbuf_append_char_unsafe(strbuf_t *s, const char c) 129 | { 130 | s->buf[s->length++] = c; 131 | } 132 | 133 | static inline void strbuf_append_mem(strbuf_t *s, const char *c, int len) 134 | { 135 | strbuf_ensure_empty_length(s, len); 136 | memcpy(s->buf + s->length, c, len); 137 | s->length += len; 138 | } 139 | 140 | static inline void strbuf_append_mem_unsafe(strbuf_t *s, const char *c, int len) 141 | { 142 | memcpy(s->buf + s->length, c, len); 143 | s->length += len; 144 | } 145 | 146 | static inline void strbuf_ensure_null(strbuf_t *s) 147 | { 148 | s->buf[s->length] = 0; 149 | } 150 | 151 | static inline char *strbuf_string(strbuf_t *s, int *len) 152 | { 153 | if (len) 154 | *len = s->length; 155 | 156 | return s->buf; 157 | } 158 | 159 | /* vi:ai et sw=4 ts=4: 160 | */ 161 | -------------------------------------------------------------------------------- /luacjson/include/lapi.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lapi.h,v 2.9 2015/03/06 19:49:50 roberto Exp $ 3 | ** Auxiliary functions from Lua API 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef lapi_h 8 | #define lapi_h 9 | 10 | 11 | #include "llimits.h" 12 | #include "lstate.h" 13 | 14 | #define api_incr_top(L) {L->top++; api_check(L, L->top <= L->ci->top, \ 15 | "stack overflow");} 16 | 17 | #define adjustresults(L,nres) \ 18 | { if ((nres) == LUA_MULTRET && L->ci->top < L->top) L->ci->top = L->top; } 19 | 20 | #define api_checknelems(L,n) api_check(L, (n) < (L->top - L->ci->func), \ 21 | "not enough elements in the stack") 22 | 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /luacjson/include/lualib.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lualib.h,v 1.44 2014/02/06 17:32:33 roberto Exp $ 3 | ** Lua standard libraries 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | 8 | #ifndef lualib_h 9 | #define lualib_h 10 | 11 | #include "lua.h" 12 | 13 | 14 | 15 | LUAMOD_API int (luaopen_base) (lua_State *L); 16 | 17 | #define LUA_COLIBNAME "coroutine" 18 | LUAMOD_API int (luaopen_coroutine) (lua_State *L); 19 | 20 | #define LUA_TABLIBNAME "table" 21 | LUAMOD_API int (luaopen_table) (lua_State *L); 22 | 23 | #define LUA_IOLIBNAME "io" 24 | LUAMOD_API int (luaopen_io) (lua_State *L); 25 | 26 | #define LUA_OSLIBNAME "os" 27 | LUAMOD_API int (luaopen_os) (lua_State *L); 28 | 29 | #define LUA_STRLIBNAME "string" 30 | LUAMOD_API int (luaopen_string) (lua_State *L); 31 | 32 | #define LUA_UTF8LIBNAME "utf8" 33 | LUAMOD_API int (luaopen_utf8) (lua_State *L); 34 | 35 | #define LUA_BITLIBNAME "bit32" 36 | LUAMOD_API int (luaopen_bit32) (lua_State *L); 37 | 38 | #define LUA_MATHLIBNAME "math" 39 | LUAMOD_API int (luaopen_math) (lua_State *L); 40 | 41 | #define LUA_DBLIBNAME "debug" 42 | LUAMOD_API int (luaopen_debug) (lua_State *L); 43 | 44 | #define LUA_LOADLIBNAME "package" 45 | LUAMOD_API int (luaopen_package) (lua_State *L); 46 | 47 | 48 | /* open all previous libraries */ 49 | LUALIB_API void (luaL_openlibs) (lua_State *L); 50 | 51 | 52 | 53 | #if !defined(lua_assert) 54 | #define lua_assert(x) ((void)0) 55 | #endif 56 | 57 | 58 | #endif 59 | -------------------------------------------------------------------------------- /luacjson/src/lib.rs: -------------------------------------------------------------------------------- 1 | 2 | extern crate td_rlua; 3 | 4 | #[allow(improper_ctypes)] 5 | extern "C" { 6 | pub fn luaopen_cjson(L : *mut td_rlua::lua_State) -> libc::c_int ; 7 | } 8 | 9 | extern "C" fn safe_luaopen_cjson(lua: *mut td_rlua::lua_State) -> libc::c_int { 10 | unsafe { 11 | luaopen_cjson(lua) 12 | } 13 | } 14 | 15 | /// custom lua load func 16 | extern "C" fn load_func(lua: *mut td_rlua::lua_State) -> libc::c_int { 17 | let path:String = td_rlua::LuaRead::lua_read(lua).unwrap_or(String::new()); 18 | if &path == "cjson" { 19 | unsafe { 20 | td_rlua::lua_pushcfunction(lua, safe_luaopen_cjson); 21 | } 22 | return 1; 23 | } 24 | return 0; 25 | } 26 | 27 | pub fn enable_cjson(lua : &mut td_rlua::Lua) { 28 | lua.add_lualoader(load_func); 29 | } -------------------------------------------------------------------------------- /luasocket/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "luasocket" 3 | version = "0.1.10" 4 | authors = ["tickbh"] 5 | description = "luasocket Bindings for Lua 5.3" 6 | repository = "https://github.com/tickbh/td_rlua" 7 | build = "build.rs" 8 | links = "luasocket" 9 | license = "MIT/Apache-2.0" 10 | 11 | [build-dependencies] 12 | pkg-config = "0.3" 13 | gcc = "0.3" 14 | 15 | [dependencies] 16 | libc = "^0.2" 17 | td_rlua = "0.3.0" 18 | -------------------------------------------------------------------------------- /luasocket/build.rs: -------------------------------------------------------------------------------- 1 | extern crate pkg_config; 2 | extern crate gcc; 3 | 4 | fn main() { 5 | let mut build = gcc::Build::new(); 6 | 7 | if cfg!(unix) { 8 | build.file("luasocket/src/usocket.c"); 9 | build.file("luasocket/src/unix.c"); 10 | build.file("luasocket/src/unixdgram.c"); 11 | build.file("luasocket/src/unixstream.c"); 12 | } 13 | 14 | if cfg!(windows) { 15 | build.file("luasocket/src/wsocket.c"); 16 | } 17 | 18 | build.file("luasocket/src/auxiliar.c") 19 | .file("luasocket/src/buffer.c") 20 | .file("luasocket/src/compat.c") 21 | .file("luasocket/src/except.c") 22 | .file("luasocket/src/inet.c") 23 | .file("luasocket/src/io.c") 24 | .file("luasocket/src/luasocket.c") 25 | .file("luasocket/src/options.c") 26 | .file("luasocket/src/select.c") 27 | .file("luasocket/src/tcp.c") 28 | .file("luasocket/src/timeout.c") 29 | .file("luasocket/src/udp.c") 30 | .include("include") 31 | .include("luasocket/src"); 32 | 33 | if cfg!(windows) { 34 | build.define("LUA_USE_WINDOWS", "1"); 35 | } 36 | if cfg!(unix) { 37 | build.define("LUA_USE_LINUX", "1"); 38 | } 39 | if cfg!(macos) { 40 | build.define("LUA_USE_MACOSX", "1"); 41 | } 42 | 43 | build.compile("libluasocket.a"); 44 | } 45 | -------------------------------------------------------------------------------- /luasocket/include/lapi.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lapi.h,v 2.9.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Auxiliary functions from Lua API 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef lapi_h 8 | #define lapi_h 9 | 10 | 11 | #include "llimits.h" 12 | #include "lstate.h" 13 | 14 | #define api_incr_top(L) {L->top++; api_check(L, L->top <= L->ci->top, \ 15 | "stack overflow");} 16 | 17 | #define adjustresults(L,nres) \ 18 | { if ((nres) == LUA_MULTRET && L->ci->top < L->top) L->ci->top = L->top; } 19 | 20 | #define api_checknelems(L,n) api_check(L, (n) < (L->top - L->ci->func), \ 21 | "not enough elements in the stack") 22 | 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /luasocket/include/lualib.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lualib.h,v 1.45.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Lua standard libraries 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | 8 | #ifndef lualib_h 9 | #define lualib_h 10 | 11 | #include "lua.h" 12 | 13 | 14 | /* version suffix for environment variable names */ 15 | #define LUA_VERSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR 16 | 17 | 18 | LUAMOD_API int (luaopen_base) (lua_State *L); 19 | 20 | #define LUA_COLIBNAME "coroutine" 21 | LUAMOD_API int (luaopen_coroutine) (lua_State *L); 22 | 23 | #define LUA_TABLIBNAME "table" 24 | LUAMOD_API int (luaopen_table) (lua_State *L); 25 | 26 | #define LUA_IOLIBNAME "io" 27 | LUAMOD_API int (luaopen_io) (lua_State *L); 28 | 29 | #define LUA_OSLIBNAME "os" 30 | LUAMOD_API int (luaopen_os) (lua_State *L); 31 | 32 | #define LUA_STRLIBNAME "string" 33 | LUAMOD_API int (luaopen_string) (lua_State *L); 34 | 35 | #define LUA_UTF8LIBNAME "utf8" 36 | LUAMOD_API int (luaopen_utf8) (lua_State *L); 37 | 38 | #define LUA_BITLIBNAME "bit32" 39 | LUAMOD_API int (luaopen_bit32) (lua_State *L); 40 | 41 | #define LUA_MATHLIBNAME "math" 42 | LUAMOD_API int (luaopen_math) (lua_State *L); 43 | 44 | #define LUA_DBLIBNAME "debug" 45 | LUAMOD_API int (luaopen_debug) (lua_State *L); 46 | 47 | #define LUA_LOADLIBNAME "package" 48 | LUAMOD_API int (luaopen_package) (lua_State *L); 49 | 50 | 51 | /* open all previous libraries */ 52 | LUALIB_API void (luaL_openlibs) (lua_State *L); 53 | 54 | 55 | 56 | #if !defined(lua_assert) 57 | #define lua_assert(x) ((void)0) 58 | #endif 59 | 60 | 61 | #endif 62 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/auxiliar.c: -------------------------------------------------------------------------------- 1 | /*=========================================================================*\ 2 | * Auxiliar routines for class hierarchy manipulation 3 | * LuaSocket toolkit 4 | \*=========================================================================*/ 5 | #include "luasocket.h" 6 | #include "auxiliar.h" 7 | #include 8 | #include 9 | 10 | /*-------------------------------------------------------------------------*\ 11 | * Initializes the module 12 | \*-------------------------------------------------------------------------*/ 13 | int auxiliar_open(lua_State *L) { 14 | (void) L; 15 | return 0; 16 | } 17 | 18 | /*-------------------------------------------------------------------------*\ 19 | * Creates a new class with given methods 20 | * Methods whose names start with __ are passed directly to the metatable. 21 | \*-------------------------------------------------------------------------*/ 22 | void auxiliar_newclass(lua_State *L, const char *classname, luaL_Reg *func) { 23 | luaL_newmetatable(L, classname); /* mt */ 24 | /* create __index table to place methods */ 25 | lua_pushstring(L, "__index"); /* mt,"__index" */ 26 | lua_newtable(L); /* mt,"__index",it */ 27 | /* put class name into class metatable */ 28 | lua_pushstring(L, "class"); /* mt,"__index",it,"class" */ 29 | lua_pushstring(L, classname); /* mt,"__index",it,"class",classname */ 30 | lua_rawset(L, -3); /* mt,"__index",it */ 31 | /* pass all methods that start with _ to the metatable, and all others 32 | * to the index table */ 33 | for (; func->name; func++) { /* mt,"__index",it */ 34 | lua_pushstring(L, func->name); 35 | lua_pushcfunction(L, func->func); 36 | lua_rawset(L, func->name[0] == '_' ? -5: -3); 37 | } 38 | lua_rawset(L, -3); /* mt */ 39 | lua_pop(L, 1); 40 | } 41 | 42 | /*-------------------------------------------------------------------------*\ 43 | * Prints the value of a class in a nice way 44 | \*-------------------------------------------------------------------------*/ 45 | int auxiliar_tostring(lua_State *L) { 46 | char buf[32]; 47 | if (!lua_getmetatable(L, 1)) goto error; 48 | lua_pushstring(L, "__index"); 49 | lua_gettable(L, -2); 50 | if (!lua_istable(L, -1)) goto error; 51 | lua_pushstring(L, "class"); 52 | lua_gettable(L, -2); 53 | if (!lua_isstring(L, -1)) goto error; 54 | sprintf(buf, "%p", lua_touserdata(L, 1)); 55 | lua_pushfstring(L, "%s: %s", lua_tostring(L, -1), buf); 56 | return 1; 57 | error: 58 | lua_pushstring(L, "invalid object passed to 'auxiliar.c:__tostring'"); 59 | lua_error(L); 60 | return 1; 61 | } 62 | 63 | /*-------------------------------------------------------------------------*\ 64 | * Insert class into group 65 | \*-------------------------------------------------------------------------*/ 66 | void auxiliar_add2group(lua_State *L, const char *classname, const char *groupname) { 67 | luaL_getmetatable(L, classname); 68 | lua_pushstring(L, groupname); 69 | lua_pushboolean(L, 1); 70 | lua_rawset(L, -3); 71 | lua_pop(L, 1); 72 | } 73 | 74 | /*-------------------------------------------------------------------------*\ 75 | * Make sure argument is a boolean 76 | \*-------------------------------------------------------------------------*/ 77 | int auxiliar_checkboolean(lua_State *L, int objidx) { 78 | if (!lua_isboolean(L, objidx)) 79 | auxiliar_typeerror(L, objidx, lua_typename(L, LUA_TBOOLEAN)); 80 | return lua_toboolean(L, objidx); 81 | } 82 | 83 | /*-------------------------------------------------------------------------*\ 84 | * Return userdata pointer if object belongs to a given class, abort with 85 | * error otherwise 86 | \*-------------------------------------------------------------------------*/ 87 | void *auxiliar_checkclass(lua_State *L, const char *classname, int objidx) { 88 | void *data = auxiliar_getclassudata(L, classname, objidx); 89 | if (!data) { 90 | char msg[45]; 91 | sprintf(msg, "%.35s expected", classname); 92 | luaL_argerror(L, objidx, msg); 93 | } 94 | return data; 95 | } 96 | 97 | /*-------------------------------------------------------------------------*\ 98 | * Return userdata pointer if object belongs to a given group, abort with 99 | * error otherwise 100 | \*-------------------------------------------------------------------------*/ 101 | void *auxiliar_checkgroup(lua_State *L, const char *groupname, int objidx) { 102 | void *data = auxiliar_getgroupudata(L, groupname, objidx); 103 | if (!data) { 104 | char msg[45]; 105 | sprintf(msg, "%.35s expected", groupname); 106 | luaL_argerror(L, objidx, msg); 107 | } 108 | return data; 109 | } 110 | 111 | /*-------------------------------------------------------------------------*\ 112 | * Set object class 113 | \*-------------------------------------------------------------------------*/ 114 | void auxiliar_setclass(lua_State *L, const char *classname, int objidx) { 115 | luaL_getmetatable(L, classname); 116 | if (objidx < 0) objidx--; 117 | lua_setmetatable(L, objidx); 118 | } 119 | 120 | /*-------------------------------------------------------------------------*\ 121 | * Get a userdata pointer if object belongs to a given group. Return NULL 122 | * otherwise 123 | \*-------------------------------------------------------------------------*/ 124 | void *auxiliar_getgroupudata(lua_State *L, const char *groupname, int objidx) { 125 | if (!lua_getmetatable(L, objidx)) 126 | return NULL; 127 | lua_pushstring(L, groupname); 128 | lua_rawget(L, -2); 129 | if (lua_isnil(L, -1)) { 130 | lua_pop(L, 2); 131 | return NULL; 132 | } else { 133 | lua_pop(L, 2); 134 | return lua_touserdata(L, objidx); 135 | } 136 | } 137 | 138 | /*-------------------------------------------------------------------------*\ 139 | * Get a userdata pointer if object belongs to a given class. Return NULL 140 | * otherwise 141 | \*-------------------------------------------------------------------------*/ 142 | void *auxiliar_getclassudata(lua_State *L, const char *classname, int objidx) { 143 | return luaL_testudata(L, objidx, classname); 144 | } 145 | 146 | /*-------------------------------------------------------------------------*\ 147 | * Throws error when argument does not have correct type. 148 | * Used to be part of lauxlib in Lua 5.1, was dropped from 5.2. 149 | \*-------------------------------------------------------------------------*/ 150 | int auxiliar_typeerror (lua_State *L, int narg, const char *tname) { 151 | const char *msg = lua_pushfstring(L, "%s expected, got %s", tname, 152 | luaL_typename(L, narg)); 153 | return luaL_argerror(L, narg, msg); 154 | } 155 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/auxiliar.h: -------------------------------------------------------------------------------- 1 | #ifndef AUXILIAR_H 2 | #define AUXILIAR_H 3 | /*=========================================================================*\ 4 | * Auxiliar routines for class hierarchy manipulation 5 | * LuaSocket toolkit (but completely independent of other LuaSocket modules) 6 | * 7 | * A LuaSocket class is a name associated with Lua metatables. A LuaSocket 8 | * group is a name associated with a class. A class can belong to any number 9 | * of groups. This module provides the functionality to: 10 | * 11 | * - create new classes 12 | * - add classes to groups 13 | * - set the class of objects 14 | * - check if an object belongs to a given class or group 15 | * - get the userdata associated to objects 16 | * - print objects in a pretty way 17 | * 18 | * LuaSocket class names follow the convention {}. Modules 19 | * can define any number of classes and groups. The module tcp.c, for 20 | * example, defines the classes tcp{master}, tcp{client} and tcp{server} and 21 | * the groups tcp{client,server} and tcp{any}. Module functions can then 22 | * perform type-checking on their arguments by either class or group. 23 | * 24 | * LuaSocket metatables define the __index metamethod as being a table. This 25 | * table has one field for each method supported by the class, and a field 26 | * "class" with the class name. 27 | * 28 | * The mapping from class name to the corresponding metatable and the 29 | * reverse mapping are done using lauxlib. 30 | \*=========================================================================*/ 31 | 32 | #include "luasocket.h" 33 | 34 | #ifndef _WIN32 35 | #pragma GCC visibility push(hidden) 36 | #endif 37 | 38 | int auxiliar_open(lua_State *L); 39 | void auxiliar_newclass(lua_State *L, const char *classname, luaL_Reg *func); 40 | int auxiliar_tostring(lua_State *L); 41 | void auxiliar_add2group(lua_State *L, const char *classname, const char *group); 42 | int auxiliar_checkboolean(lua_State *L, int objidx); 43 | void *auxiliar_checkclass(lua_State *L, const char *classname, int objidx); 44 | void *auxiliar_checkgroup(lua_State *L, const char *groupname, int objidx); 45 | void auxiliar_setclass(lua_State *L, const char *classname, int objidx); 46 | void *auxiliar_getgroupudata(lua_State *L, const char *groupname, int objidx); 47 | void *auxiliar_getclassudata(lua_State *L, const char *groupname, int objidx); 48 | int auxiliar_typeerror(lua_State *L, int narg, const char *tname); 49 | 50 | #ifndef _WIN32 51 | #pragma GCC visibility pop 52 | #endif 53 | 54 | #endif /* AUXILIAR_H */ 55 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/buffer.h: -------------------------------------------------------------------------------- 1 | #ifndef BUF_H 2 | #define BUF_H 3 | /*=========================================================================*\ 4 | * Input/Output interface for Lua programs 5 | * LuaSocket toolkit 6 | * 7 | * Line patterns require buffering. Reading one character at a time involves 8 | * too many system calls and is very slow. This module implements the 9 | * LuaSocket interface for input/output on connected objects, as seen by 10 | * Lua programs. 11 | * 12 | * Input is buffered. Output is *not* buffered because there was no simple 13 | * way of making sure the buffered output data would ever be sent. 14 | * 15 | * The module is built on top of the I/O abstraction defined in io.h and the 16 | * timeout management is done with the timeout.h interface. 17 | \*=========================================================================*/ 18 | #include "luasocket.h" 19 | #include "io.h" 20 | #include "timeout.h" 21 | 22 | /* buffer size in bytes */ 23 | #define BUF_SIZE 8192 24 | 25 | /* buffer control structure */ 26 | typedef struct t_buffer_ { 27 | double birthday; /* throttle support info: creation time, */ 28 | size_t sent, received; /* bytes sent, and bytes received */ 29 | p_io io; /* IO driver used for this buffer */ 30 | p_timeout tm; /* timeout management for this buffer */ 31 | size_t first, last; /* index of first and last bytes of stored data */ 32 | char data[BUF_SIZE]; /* storage space for buffer data */ 33 | } t_buffer; 34 | typedef t_buffer *p_buffer; 35 | 36 | #ifndef _WIN32 37 | #pragma GCC visibility push(hidden) 38 | #endif 39 | 40 | int buffer_open(lua_State *L); 41 | void buffer_init(p_buffer buf, p_io io, p_timeout tm); 42 | int buffer_meth_getstats(lua_State *L, p_buffer buf); 43 | int buffer_meth_setstats(lua_State *L, p_buffer buf); 44 | int buffer_meth_send(lua_State *L, p_buffer buf); 45 | int buffer_meth_receive(lua_State *L, p_buffer buf); 46 | int buffer_isempty(p_buffer buf); 47 | 48 | #ifndef _WIN32 49 | #pragma GCC visibility pop 50 | #endif 51 | 52 | #endif /* BUF_H */ 53 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/compat.c: -------------------------------------------------------------------------------- 1 | #include "luasocket.h" 2 | #include "compat.h" 3 | 4 | #if LUA_VERSION_NUM==501 5 | 6 | /* 7 | ** Adapted from Lua 5.2 8 | */ 9 | void luasocket_setfuncs (lua_State *L, const luaL_Reg *l, int nup) { 10 | luaL_checkstack(L, nup+1, "too many upvalues"); 11 | for (; l->name != NULL; l++) { /* fill the table with given functions */ 12 | int i; 13 | lua_pushstring(L, l->name); 14 | for (i = 0; i < nup; i++) /* copy upvalues to the top */ 15 | lua_pushvalue(L, -(nup+1)); 16 | lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */ 17 | lua_settable(L, -(nup + 3)); 18 | } 19 | lua_pop(L, nup); /* remove upvalues */ 20 | } 21 | 22 | /* 23 | ** Duplicated from Lua 5.2 24 | */ 25 | void *luasocket_testudata (lua_State *L, int ud, const char *tname) { 26 | void *p = lua_touserdata(L, ud); 27 | if (p != NULL) { /* value is a userdata? */ 28 | if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ 29 | luaL_getmetatable(L, tname); /* get correct metatable */ 30 | if (!lua_rawequal(L, -1, -2)) /* not the same? */ 31 | p = NULL; /* value is a userdata with wrong metatable */ 32 | lua_pop(L, 2); /* remove both metatables */ 33 | return p; 34 | } 35 | } 36 | return NULL; /* value is not a userdata with a metatable */ 37 | } 38 | 39 | #endif 40 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/compat.h: -------------------------------------------------------------------------------- 1 | #ifndef COMPAT_H 2 | #define COMPAT_H 3 | 4 | #if LUA_VERSION_NUM==501 5 | 6 | #ifndef _WIN32 7 | #pragma GCC visibility push(hidden) 8 | #endif 9 | 10 | void luasocket_setfuncs (lua_State *L, const luaL_Reg *l, int nup); 11 | void *luasocket_testudata ( lua_State *L, int arg, const char *tname); 12 | 13 | #ifndef _WIN32 14 | #pragma GCC visibility pop 15 | #endif 16 | 17 | #define luaL_setfuncs luasocket_setfuncs 18 | #define luaL_testudata luasocket_testudata 19 | 20 | #endif 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/except.c: -------------------------------------------------------------------------------- 1 | /*=========================================================================*\ 2 | * Simple exception support 3 | * LuaSocket toolkit 4 | \*=========================================================================*/ 5 | #include "luasocket.h" 6 | #include "except.h" 7 | #include 8 | 9 | #if LUA_VERSION_NUM < 502 10 | #define lua_pcallk(L, na, nr, err, ctx, cont) \ 11 | (((void)ctx),((void)cont),lua_pcall(L, na, nr, err)) 12 | #endif 13 | 14 | #if LUA_VERSION_NUM < 503 15 | typedef int lua_KContext; 16 | #endif 17 | 18 | /*=========================================================================*\ 19 | * Internal function prototypes. 20 | \*=========================================================================*/ 21 | static int global_protect(lua_State *L); 22 | static int global_newtry(lua_State *L); 23 | static int protected_(lua_State *L); 24 | static int finalize(lua_State *L); 25 | static int do_nothing(lua_State *L); 26 | 27 | /* except functions */ 28 | static luaL_Reg func[] = { 29 | {"newtry", global_newtry}, 30 | {"protect", global_protect}, 31 | {NULL, NULL} 32 | }; 33 | 34 | /*-------------------------------------------------------------------------*\ 35 | * Try factory 36 | \*-------------------------------------------------------------------------*/ 37 | static void wrap(lua_State *L) { 38 | lua_createtable(L, 1, 0); 39 | lua_pushvalue(L, -2); 40 | lua_rawseti(L, -2, 1); 41 | lua_pushvalue(L, lua_upvalueindex(1)); 42 | lua_setmetatable(L, -2); 43 | } 44 | 45 | static int finalize(lua_State *L) { 46 | if (!lua_toboolean(L, 1)) { 47 | lua_pushvalue(L, lua_upvalueindex(2)); 48 | lua_call(L, 0, 0); 49 | lua_settop(L, 2); 50 | wrap(L); 51 | lua_error(L); 52 | return 0; 53 | } else return lua_gettop(L); 54 | } 55 | 56 | static int do_nothing(lua_State *L) { 57 | (void) L; 58 | return 0; 59 | } 60 | 61 | static int global_newtry(lua_State *L) { 62 | lua_settop(L, 1); 63 | if (lua_isnil(L, 1)) lua_pushcfunction(L, do_nothing); 64 | lua_pushvalue(L, lua_upvalueindex(1)); 65 | lua_insert(L, -2); 66 | lua_pushcclosure(L, finalize, 2); 67 | return 1; 68 | } 69 | 70 | /*-------------------------------------------------------------------------*\ 71 | * Protect factory 72 | \*-------------------------------------------------------------------------*/ 73 | static int unwrap(lua_State *L) { 74 | if (lua_istable(L, -1) && lua_getmetatable(L, -1)) { 75 | int r = lua_rawequal(L, -1, lua_upvalueindex(1)); 76 | lua_pop(L, 1); 77 | if (r) { 78 | lua_pushnil(L); 79 | lua_rawgeti(L, -2, 1); 80 | return 1; 81 | } 82 | } 83 | return 0; 84 | } 85 | 86 | static int protected_finish(lua_State *L, int status, lua_KContext ctx) { 87 | (void)ctx; 88 | if (status != 0 && status != LUA_YIELD) { 89 | if (unwrap(L)) return 2; 90 | else return lua_error(L); 91 | } else return lua_gettop(L); 92 | } 93 | 94 | #if LUA_VERSION_NUM == 502 95 | static int protected_cont(lua_State *L) { 96 | int ctx = 0; 97 | int status = lua_getctx(L, &ctx); 98 | return protected_finish(L, status, ctx); 99 | } 100 | #else 101 | #define protected_cont protected_finish 102 | #endif 103 | 104 | static int protected_(lua_State *L) { 105 | int status; 106 | lua_pushvalue(L, lua_upvalueindex(2)); 107 | lua_insert(L, 1); 108 | status = lua_pcallk(L, lua_gettop(L) - 1, LUA_MULTRET, 0, 0, protected_cont); 109 | return protected_finish(L, status, 0); 110 | } 111 | 112 | static int global_protect(lua_State *L) { 113 | lua_settop(L, 1); 114 | lua_pushvalue(L, lua_upvalueindex(1)); 115 | lua_insert(L, 1); 116 | lua_pushcclosure(L, protected_, 2); 117 | return 1; 118 | } 119 | 120 | /*-------------------------------------------------------------------------*\ 121 | * Init module 122 | \*-------------------------------------------------------------------------*/ 123 | int except_open(lua_State *L) { 124 | lua_newtable(L); /* metatable for wrapped exceptions */ 125 | lua_pushboolean(L, 0); 126 | lua_setfield(L, -2, "__metatable"); 127 | luaL_setfuncs(L, func, 1); 128 | return 0; 129 | } 130 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/except.h: -------------------------------------------------------------------------------- 1 | #ifndef EXCEPT_H 2 | #define EXCEPT_H 3 | /*=========================================================================*\ 4 | * Exception control 5 | * LuaSocket toolkit (but completely independent from other modules) 6 | * 7 | * This provides support for simple exceptions in Lua. During the 8 | * development of the HTTP/FTP/SMTP support, it became aparent that 9 | * error checking was taking a substantial amount of the coding. These 10 | * function greatly simplify the task of checking errors. 11 | * 12 | * The main idea is that functions should return nil as their first return 13 | * values when they find an error, and return an error message (or value) 14 | * following nil. In case of success, as long as the first value is not nil, 15 | * the other values don't matter. 16 | * 17 | * The idea is to nest function calls with the "try" function. This function 18 | * checks the first value, and, if it's falsy, wraps the second value in a 19 | * table with metatable and calls "error" on it. Otherwise, it returns all 20 | * values it received. Basically, it works like the Lua "assert" function, 21 | * but it creates errors targeted specifically at "protect". 22 | * 23 | * The "newtry" function is a factory for "try" functions that call a 24 | * finalizer in protected mode before calling "error". 25 | * 26 | * The "protect" function returns a new function that behaves exactly like 27 | * the function it receives, but the new function catches exceptions thrown 28 | * by "try" functions and returns nil followed by the error message instead. 29 | * 30 | * With these three functions, it's easy to write functions that throw 31 | * exceptions on error, but that don't interrupt the user script. 32 | \*=========================================================================*/ 33 | 34 | #include "luasocket.h" 35 | 36 | #ifndef _WIN32 37 | #pragma GCC visibility push(hidden) 38 | #endif 39 | 40 | int except_open(lua_State *L); 41 | 42 | #ifndef _WIN32 43 | #pragma GCC visibility pop 44 | #endif 45 | 46 | #endif 47 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/headers.lua: -------------------------------------------------------------------------------- 1 | ----------------------------------------------------------------------------- 2 | -- Canonic header field capitalization 3 | -- LuaSocket toolkit. 4 | -- Author: Diego Nehab 5 | ----------------------------------------------------------------------------- 6 | local socket = require("socket") 7 | socket.headers = {} 8 | local _M = socket.headers 9 | 10 | _M.canonic = { 11 | ["accept"] = "Accept", 12 | ["accept-charset"] = "Accept-Charset", 13 | ["accept-encoding"] = "Accept-Encoding", 14 | ["accept-language"] = "Accept-Language", 15 | ["accept-ranges"] = "Accept-Ranges", 16 | ["action"] = "Action", 17 | ["alternate-recipient"] = "Alternate-Recipient", 18 | ["age"] = "Age", 19 | ["allow"] = "Allow", 20 | ["arrival-date"] = "Arrival-Date", 21 | ["authorization"] = "Authorization", 22 | ["bcc"] = "Bcc", 23 | ["cache-control"] = "Cache-Control", 24 | ["cc"] = "Cc", 25 | ["comments"] = "Comments", 26 | ["connection"] = "Connection", 27 | ["content-description"] = "Content-Description", 28 | ["content-disposition"] = "Content-Disposition", 29 | ["content-encoding"] = "Content-Encoding", 30 | ["content-id"] = "Content-ID", 31 | ["content-language"] = "Content-Language", 32 | ["content-length"] = "Content-Length", 33 | ["content-location"] = "Content-Location", 34 | ["content-md5"] = "Content-MD5", 35 | ["content-range"] = "Content-Range", 36 | ["content-transfer-encoding"] = "Content-Transfer-Encoding", 37 | ["content-type"] = "Content-Type", 38 | ["cookie"] = "Cookie", 39 | ["date"] = "Date", 40 | ["diagnostic-code"] = "Diagnostic-Code", 41 | ["dsn-gateway"] = "DSN-Gateway", 42 | ["etag"] = "ETag", 43 | ["expect"] = "Expect", 44 | ["expires"] = "Expires", 45 | ["final-log-id"] = "Final-Log-ID", 46 | ["final-recipient"] = "Final-Recipient", 47 | ["from"] = "From", 48 | ["host"] = "Host", 49 | ["if-match"] = "If-Match", 50 | ["if-modified-since"] = "If-Modified-Since", 51 | ["if-none-match"] = "If-None-Match", 52 | ["if-range"] = "If-Range", 53 | ["if-unmodified-since"] = "If-Unmodified-Since", 54 | ["in-reply-to"] = "In-Reply-To", 55 | ["keywords"] = "Keywords", 56 | ["last-attempt-date"] = "Last-Attempt-Date", 57 | ["last-modified"] = "Last-Modified", 58 | ["location"] = "Location", 59 | ["max-forwards"] = "Max-Forwards", 60 | ["message-id"] = "Message-ID", 61 | ["mime-version"] = "MIME-Version", 62 | ["original-envelope-id"] = "Original-Envelope-ID", 63 | ["original-recipient"] = "Original-Recipient", 64 | ["pragma"] = "Pragma", 65 | ["proxy-authenticate"] = "Proxy-Authenticate", 66 | ["proxy-authorization"] = "Proxy-Authorization", 67 | ["range"] = "Range", 68 | ["received"] = "Received", 69 | ["received-from-mta"] = "Received-From-MTA", 70 | ["references"] = "References", 71 | ["referer"] = "Referer", 72 | ["remote-mta"] = "Remote-MTA", 73 | ["reply-to"] = "Reply-To", 74 | ["reporting-mta"] = "Reporting-MTA", 75 | ["resent-bcc"] = "Resent-Bcc", 76 | ["resent-cc"] = "Resent-Cc", 77 | ["resent-date"] = "Resent-Date", 78 | ["resent-from"] = "Resent-From", 79 | ["resent-message-id"] = "Resent-Message-ID", 80 | ["resent-reply-to"] = "Resent-Reply-To", 81 | ["resent-sender"] = "Resent-Sender", 82 | ["resent-to"] = "Resent-To", 83 | ["retry-after"] = "Retry-After", 84 | ["return-path"] = "Return-Path", 85 | ["sender"] = "Sender", 86 | ["server"] = "Server", 87 | ["smtp-remote-recipient"] = "SMTP-Remote-Recipient", 88 | ["status"] = "Status", 89 | ["subject"] = "Subject", 90 | ["te"] = "TE", 91 | ["to"] = "To", 92 | ["trailer"] = "Trailer", 93 | ["transfer-encoding"] = "Transfer-Encoding", 94 | ["upgrade"] = "Upgrade", 95 | ["user-agent"] = "User-Agent", 96 | ["vary"] = "Vary", 97 | ["via"] = "Via", 98 | ["warning"] = "Warning", 99 | ["will-retry-until"] = "Will-Retry-Until", 100 | ["www-authenticate"] = "WWW-Authenticate", 101 | ["x-mailer"] = "X-Mailer", 102 | } 103 | 104 | return _M -------------------------------------------------------------------------------- /luasocket/luasocket/src/inet.h: -------------------------------------------------------------------------------- 1 | #ifndef INET_H 2 | #define INET_H 3 | /*=========================================================================*\ 4 | * Internet domain functions 5 | * LuaSocket toolkit 6 | * 7 | * This module implements the creation and connection of internet domain 8 | * sockets, on top of the socket.h interface, and the interface of with the 9 | * resolver. 10 | * 11 | * The function inet_aton is provided for the platforms where it is not 12 | * available. The module also implements the interface of the internet 13 | * getpeername and getsockname functions as seen by Lua programs. 14 | * 15 | * The Lua functions toip and tohostname are also implemented here. 16 | \*=========================================================================*/ 17 | #include "luasocket.h" 18 | #include "socket.h" 19 | #include "timeout.h" 20 | 21 | #ifdef _WIN32 22 | #define LUASOCKET_INET_ATON 23 | #endif 24 | 25 | #ifndef _WIN32 26 | #pragma GCC visibility push(hidden) 27 | #endif 28 | 29 | int inet_open(lua_State *L); 30 | 31 | int inet_optfamily(lua_State* L, int narg, const char* def); 32 | int inet_optsocktype(lua_State* L, int narg, const char* def); 33 | 34 | int inet_meth_getpeername(lua_State *L, p_socket ps, int family); 35 | int inet_meth_getsockname(lua_State *L, p_socket ps, int family); 36 | 37 | const char *inet_trycreate(p_socket ps, int family, int type, int protocol); 38 | const char *inet_trydisconnect(p_socket ps, int family, p_timeout tm); 39 | const char *inet_tryconnect(p_socket ps, int *family, const char *address, const char *serv, p_timeout tm, struct addrinfo *connecthints); 40 | const char *inet_tryaccept(p_socket server, int family, p_socket client, p_timeout tm); 41 | const char *inet_trybind(p_socket ps, int *family, const char *address, const char *serv, struct addrinfo *bindhints); 42 | 43 | #ifdef LUASOCKET_INET_ATON 44 | int inet_aton(const char *cp, struct in_addr *inp); 45 | #endif 46 | 47 | #ifdef LUASOCKET_INET_PTON 48 | const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt); 49 | int inet_pton(int af, const char *src, void *dst); 50 | #endif 51 | 52 | #ifndef _WIN32 53 | #pragma GCC visibility pop 54 | #endif 55 | 56 | #endif /* INET_H */ 57 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/io.c: -------------------------------------------------------------------------------- 1 | /*=========================================================================*\ 2 | * Input/Output abstraction 3 | * LuaSocket toolkit 4 | \*=========================================================================*/ 5 | #include "luasocket.h" 6 | #include "io.h" 7 | 8 | /*-------------------------------------------------------------------------*\ 9 | * Initializes C structure 10 | \*-------------------------------------------------------------------------*/ 11 | void io_init(p_io io, p_send send, p_recv recv, p_error error, void *ctx) { 12 | io->send = send; 13 | io->recv = recv; 14 | io->error = error; 15 | io->ctx = ctx; 16 | } 17 | 18 | /*-------------------------------------------------------------------------*\ 19 | * I/O error strings 20 | \*-------------------------------------------------------------------------*/ 21 | const char *io_strerror(int err) { 22 | switch (err) { 23 | case IO_DONE: return NULL; 24 | case IO_CLOSED: return "closed"; 25 | case IO_TIMEOUT: return "timeout"; 26 | default: return "unknown error"; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/io.h: -------------------------------------------------------------------------------- 1 | #ifndef IO_H 2 | #define IO_H 3 | /*=========================================================================*\ 4 | * Input/Output abstraction 5 | * LuaSocket toolkit 6 | * 7 | * This module defines the interface that LuaSocket expects from the 8 | * transport layer for streamed input/output. The idea is that if any 9 | * transport implements this interface, then the buffer.c functions 10 | * automatically work on it. 11 | * 12 | * The module socket.h implements this interface, and thus the module tcp.h 13 | * is very simple. 14 | \*=========================================================================*/ 15 | #include "luasocket.h" 16 | #include "timeout.h" 17 | 18 | /* IO error codes */ 19 | enum { 20 | IO_DONE = 0, /* operation completed successfully */ 21 | IO_TIMEOUT = -1, /* operation timed out */ 22 | IO_CLOSED = -2, /* the connection has been closed */ 23 | IO_UNKNOWN = -3 24 | }; 25 | 26 | /* interface to error message function */ 27 | typedef const char *(*p_error) ( 28 | void *ctx, /* context needed by send */ 29 | int err /* error code */ 30 | ); 31 | 32 | /* interface to send function */ 33 | typedef int (*p_send) ( 34 | void *ctx, /* context needed by send */ 35 | const char *data, /* pointer to buffer with data to send */ 36 | size_t count, /* number of bytes to send from buffer */ 37 | size_t *sent, /* number of bytes sent uppon return */ 38 | p_timeout tm /* timeout control */ 39 | ); 40 | 41 | /* interface to recv function */ 42 | typedef int (*p_recv) ( 43 | void *ctx, /* context needed by recv */ 44 | char *data, /* pointer to buffer where data will be writen */ 45 | size_t count, /* number of bytes to receive into buffer */ 46 | size_t *got, /* number of bytes received uppon return */ 47 | p_timeout tm /* timeout control */ 48 | ); 49 | 50 | /* IO driver definition */ 51 | typedef struct t_io_ { 52 | void *ctx; /* context needed by send/recv */ 53 | p_send send; /* send function pointer */ 54 | p_recv recv; /* receive function pointer */ 55 | p_error error; /* strerror function */ 56 | } t_io; 57 | typedef t_io *p_io; 58 | 59 | #ifndef _WIN32 60 | #pragma GCC visibility push(hidden) 61 | #endif 62 | 63 | void io_init(p_io io, p_send send, p_recv recv, p_error error, void *ctx); 64 | const char *io_strerror(int err); 65 | 66 | #ifndef _WIN32 67 | #pragma GCC visibility pop 68 | #endif 69 | 70 | #endif /* IO_H */ 71 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/luasocket.c: -------------------------------------------------------------------------------- 1 | /*=========================================================================*\ 2 | * LuaSocket toolkit 3 | * Networking support for the Lua language 4 | * Diego Nehab 5 | * 26/11/1999 6 | * 7 | * This library is part of an effort to progressively increase the network 8 | * connectivity of the Lua language. The Lua interface to networking 9 | * functions follows the Sockets API closely, trying to simplify all tasks 10 | * involved in setting up both client and server connections. The provided 11 | * IO routines, however, follow the Lua style, being very similar to the 12 | * standard Lua read and write functions. 13 | \*=========================================================================*/ 14 | 15 | #include "luasocket.h" 16 | #include "auxiliar.h" 17 | #include "except.h" 18 | #include "timeout.h" 19 | #include "buffer.h" 20 | #include "inet.h" 21 | #include "tcp.h" 22 | #include "udp.h" 23 | #include "select.h" 24 | 25 | /*-------------------------------------------------------------------------*\ 26 | * Internal function prototypes 27 | \*-------------------------------------------------------------------------*/ 28 | static int global_skip(lua_State *L); 29 | static int global_unload(lua_State *L); 30 | static int base_open(lua_State *L); 31 | 32 | /*-------------------------------------------------------------------------*\ 33 | * Modules and functions 34 | \*-------------------------------------------------------------------------*/ 35 | static const luaL_Reg mod[] = { 36 | {"auxiliar", auxiliar_open}, 37 | {"except", except_open}, 38 | {"timeout", timeout_open}, 39 | {"buffer", buffer_open}, 40 | {"inet", inet_open}, 41 | {"tcp", tcp_open}, 42 | {"udp", udp_open}, 43 | {"select", select_open}, 44 | {NULL, NULL} 45 | }; 46 | 47 | static luaL_Reg func[] = { 48 | {"skip", global_skip}, 49 | {"__unload", global_unload}, 50 | {NULL, NULL} 51 | }; 52 | 53 | /*-------------------------------------------------------------------------*\ 54 | * Skip a few arguments 55 | \*-------------------------------------------------------------------------*/ 56 | static int global_skip(lua_State *L) { 57 | int amount = (int) luaL_checkinteger(L, 1); 58 | int ret = lua_gettop(L) - amount - 1; 59 | return ret >= 0 ? ret : 0; 60 | } 61 | 62 | /*-------------------------------------------------------------------------*\ 63 | * Unloads the library 64 | \*-------------------------------------------------------------------------*/ 65 | static int global_unload(lua_State *L) { 66 | (void) L; 67 | socket_close(); 68 | return 0; 69 | } 70 | 71 | /*-------------------------------------------------------------------------*\ 72 | * Setup basic stuff. 73 | \*-------------------------------------------------------------------------*/ 74 | static int base_open(lua_State *L) { 75 | if (socket_open()) { 76 | /* export functions (and leave namespace table on top of stack) */ 77 | lua_newtable(L); 78 | luaL_setfuncs(L, func, 0); 79 | #ifdef LUASOCKET_DEBUG 80 | lua_pushstring(L, "_DEBUG"); 81 | lua_pushboolean(L, 1); 82 | lua_rawset(L, -3); 83 | #endif 84 | /* make version string available to scripts */ 85 | lua_pushstring(L, "_VERSION"); 86 | lua_pushstring(L, LUASOCKET_VERSION); 87 | lua_rawset(L, -3); 88 | return 1; 89 | } else { 90 | lua_pushstring(L, "unable to initialize library"); 91 | lua_error(L); 92 | return 0; 93 | } 94 | } 95 | 96 | /*-------------------------------------------------------------------------*\ 97 | * Initializes all library modules. 98 | \*-------------------------------------------------------------------------*/ 99 | LUASOCKET_API int luaopen_socket_core(lua_State *L) { 100 | int i; 101 | base_open(L); 102 | for (i = 0; mod[i].name; i++) mod[i].func(L); 103 | return 1; 104 | } 105 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/luasocket.h: -------------------------------------------------------------------------------- 1 | #ifndef LUASOCKET_H 2 | #define LUASOCKET_H 3 | /*=========================================================================*\ 4 | * LuaSocket toolkit 5 | * Networking support for the Lua language 6 | * Diego Nehab 7 | * 9/11/1999 8 | \*=========================================================================*/ 9 | 10 | /*-------------------------------------------------------------------------* \ 11 | * Current socket library version 12 | \*-------------------------------------------------------------------------*/ 13 | #define LUASOCKET_VERSION "LuaSocket 3.0.0" 14 | #define LUASOCKET_COPYRIGHT "Copyright (C) 1999-2013 Diego Nehab" 15 | 16 | /*-------------------------------------------------------------------------*\ 17 | * This macro prefixes all exported API functions 18 | \*-------------------------------------------------------------------------*/ 19 | #ifndef LUASOCKET_API 20 | #ifdef _WIN32 21 | #define LUASOCKET_API __declspec(dllexport) 22 | #else 23 | #define LUASOCKET_API __attribute__ ((visibility ("default"))) 24 | #endif 25 | #endif 26 | 27 | #include "lua.h" 28 | #include "lauxlib.h" 29 | #include "compat.h" 30 | 31 | /*-------------------------------------------------------------------------*\ 32 | * Initializes the library. 33 | \*-------------------------------------------------------------------------*/ 34 | LUASOCKET_API int luaopen_socket_core(lua_State *L); 35 | 36 | #endif /* LUASOCKET_H */ 37 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/mbox.lua: -------------------------------------------------------------------------------- 1 | local _M = {} 2 | 3 | if module then 4 | mbox = _M -- luacheck: ignore 5 | end 6 | 7 | function _M.split_message(message_s) 8 | local message = {} 9 | message_s = string.gsub(message_s, "\r\n", "\n") 10 | string.gsub(message_s, "^(.-\n)\n", function (h) message.headers = h end) 11 | string.gsub(message_s, "^.-\n\n(.*)", function (b) message.body = b end) 12 | if not message.body then 13 | string.gsub(message_s, "^\n(.*)", function (b) message.body = b end) 14 | end 15 | if not message.headers and not message.body then 16 | message.headers = message_s 17 | end 18 | return message.headers or "", message.body or "" 19 | end 20 | 21 | function _M.split_headers(headers_s) 22 | local headers = {} 23 | headers_s = string.gsub(headers_s, "\r\n", "\n") 24 | headers_s = string.gsub(headers_s, "\n[ ]+", " ") 25 | string.gsub("\n" .. headers_s, "\n([^\n]+)", function (h) table.insert(headers, h) end) 26 | return headers 27 | end 28 | 29 | function _M.parse_header(header_s) 30 | header_s = string.gsub(header_s, "\n[ ]+", " ") 31 | header_s = string.gsub(header_s, "\n+", "") 32 | local _, _, name, value = string.find(header_s, "([^%s:]-):%s*(.*)") 33 | return name, value 34 | end 35 | 36 | function _M.parse_headers(headers_s) 37 | local headers_t = _M.split_headers(headers_s) 38 | local headers = {} 39 | for i = 1, #headers_t do 40 | local name, value = _M.parse_header(headers_t[i]) 41 | if name then 42 | name = string.lower(name) 43 | if headers[name] then 44 | headers[name] = headers[name] .. ", " .. value 45 | else headers[name] = value end 46 | end 47 | end 48 | return headers 49 | end 50 | 51 | function _M.parse_from(from) 52 | local _, _, name, address = string.find(from, "^%s*(.-)%s*%<(.-)%>") 53 | if not address then 54 | _, _, address = string.find(from, "%s*(.+)%s*") 55 | end 56 | name = name or "" 57 | address = address or "" 58 | if name == "" then name = address end 59 | name = string.gsub(name, '"', "") 60 | return name, address 61 | end 62 | 63 | function _M.split_mbox(mbox_s) 64 | local mbox = {} 65 | mbox_s = string.gsub(mbox_s, "\r\n", "\n") .."\n\nFrom \n" 66 | local nj, i 67 | local j = 1 68 | while 1 do 69 | i, nj = string.find(mbox_s, "\n\nFrom .-\n", j) 70 | if not i then break end 71 | local message = string.sub(mbox_s, j, i-1) 72 | table.insert(mbox, message) 73 | j = nj+1 74 | end 75 | return mbox 76 | end 77 | 78 | function _M.parse(mbox_s) 79 | local mbox = _M.split_mbox(mbox_s) 80 | for i = 1, #mbox do 81 | mbox[i] = _M.parse_message(mbox[i]) 82 | end 83 | return mbox 84 | end 85 | 86 | function _M.parse_message(message_s) 87 | local message = {} 88 | message.headers, message.body = _M.split_message(message_s) 89 | message.headers = _M.parse_headers(message.headers) 90 | return message 91 | end 92 | 93 | return _M 94 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/mime.h: -------------------------------------------------------------------------------- 1 | #ifndef MIME_H 2 | #define MIME_H 3 | /*=========================================================================*\ 4 | * Core MIME support 5 | * LuaSocket toolkit 6 | * 7 | * This module provides functions to implement transfer content encodings 8 | * and formatting conforming to RFC 2045. It is used by mime.lua, which 9 | * provide a higher level interface to this functionality. 10 | \*=========================================================================*/ 11 | #include "luasocket.h" 12 | 13 | /*-------------------------------------------------------------------------*\ 14 | * Current MIME library version 15 | \*-------------------------------------------------------------------------*/ 16 | #define MIME_VERSION "MIME 1.0.3" 17 | #define MIME_COPYRIGHT "Copyright (C) 2004-2013 Diego Nehab" 18 | #define MIME_AUTHORS "Diego Nehab" 19 | 20 | LUASOCKET_API int luaopen_mime_core(lua_State *L); 21 | 22 | #endif /* MIME_H */ 23 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/mime.lua: -------------------------------------------------------------------------------- 1 | ----------------------------------------------------------------------------- 2 | -- MIME support for the Lua language. 3 | -- Author: Diego Nehab 4 | -- Conforming to RFCs 2045-2049 5 | ----------------------------------------------------------------------------- 6 | 7 | ----------------------------------------------------------------------------- 8 | -- Declare module and import dependencies 9 | ----------------------------------------------------------------------------- 10 | local base = _G 11 | local ltn12 = require("ltn12") 12 | local mime = require("mime.core") 13 | local _M = mime 14 | 15 | -- encode, decode and wrap algorithm tables 16 | local encodet, decodet, wrapt = {},{},{} 17 | 18 | _M.encodet = encodet 19 | _M.decodet = decodet 20 | _M.wrapt = wrapt 21 | 22 | -- creates a function that chooses a filter by name from a given table 23 | local function choose(table) 24 | return function(name, opt1, opt2) 25 | if base.type(name) ~= "string" then 26 | name, opt1, opt2 = "default", name, opt1 27 | end 28 | local f = table[name or "nil"] 29 | if not f then 30 | base.error("unknown key (" .. base.tostring(name) .. ")", 3) 31 | else return f(opt1, opt2) end 32 | end 33 | end 34 | 35 | -- define the encoding filters 36 | encodet['base64'] = function() 37 | return ltn12.filter.cycle(_M.b64, "") 38 | end 39 | 40 | encodet['quoted-printable'] = function(mode) 41 | return ltn12.filter.cycle(_M.qp, "", 42 | (mode == "binary") and "=0D=0A" or "\r\n") 43 | end 44 | 45 | -- define the decoding filters 46 | decodet['base64'] = function() 47 | return ltn12.filter.cycle(_M.unb64, "") 48 | end 49 | 50 | decodet['quoted-printable'] = function() 51 | return ltn12.filter.cycle(_M.unqp, "") 52 | end 53 | 54 | -- define the line-wrap filters 55 | wrapt['text'] = function(length) 56 | length = length or 76 57 | return ltn12.filter.cycle(_M.wrp, length, length) 58 | end 59 | wrapt['base64'] = wrapt['text'] 60 | wrapt['default'] = wrapt['text'] 61 | 62 | wrapt['quoted-printable'] = function() 63 | return ltn12.filter.cycle(_M.qpwrp, 76, 76) 64 | end 65 | 66 | -- function that choose the encoding, decoding or wrap algorithm 67 | _M.encode = choose(encodet) 68 | _M.decode = choose(decodet) 69 | _M.wrap = choose(wrapt) 70 | 71 | -- define the end-of-line normalization filter 72 | function _M.normalize(marker) 73 | return ltn12.filter.cycle(_M.eol, 0, marker) 74 | end 75 | 76 | -- high level stuffing filter 77 | function _M.stuff() 78 | return ltn12.filter.cycle(_M.dot, 2) 79 | end 80 | 81 | return _M 82 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/options.h: -------------------------------------------------------------------------------- 1 | #ifndef OPTIONS_H 2 | #define OPTIONS_H 3 | /*=========================================================================*\ 4 | * Common option interface 5 | * LuaSocket toolkit 6 | * 7 | * This module provides a common interface to socket options, used mainly by 8 | * modules UDP and TCP. 9 | \*=========================================================================*/ 10 | 11 | #include "luasocket.h" 12 | #include "socket.h" 13 | 14 | /* option registry */ 15 | typedef struct t_opt { 16 | const char *name; 17 | int (*func)(lua_State *L, p_socket ps); 18 | } t_opt; 19 | typedef t_opt *p_opt; 20 | 21 | #ifndef _WIN32 22 | #pragma GCC visibility push(hidden) 23 | #endif 24 | 25 | int opt_meth_setoption(lua_State *L, p_opt opt, p_socket ps); 26 | int opt_meth_getoption(lua_State *L, p_opt opt, p_socket ps); 27 | 28 | int opt_set_reuseaddr(lua_State *L, p_socket ps); 29 | int opt_get_reuseaddr(lua_State *L, p_socket ps); 30 | 31 | int opt_set_reuseport(lua_State *L, p_socket ps); 32 | int opt_get_reuseport(lua_State *L, p_socket ps); 33 | 34 | int opt_set_tcp_nodelay(lua_State *L, p_socket ps); 35 | int opt_get_tcp_nodelay(lua_State *L, p_socket ps); 36 | 37 | #ifdef TCP_KEEPIDLE 38 | int opt_set_tcp_keepidle(lua_State *L, p_socket ps); 39 | int opt_get_tcp_keepidle(lua_State *L, p_socket ps); 40 | #endif 41 | 42 | #ifdef TCP_KEEPCNT 43 | int opt_set_tcp_keepcnt(lua_State *L, p_socket ps); 44 | int opt_get_tcp_keepcnt(lua_State *L, p_socket ps); 45 | #endif 46 | 47 | #ifdef TCP_KEEPINTVL 48 | int opt_set_tcp_keepintvl(lua_State *L, p_socket ps); 49 | int opt_get_tcp_keepintvl(lua_State *L, p_socket ps); 50 | #endif 51 | 52 | int opt_set_keepalive(lua_State *L, p_socket ps); 53 | int opt_get_keepalive(lua_State *L, p_socket ps); 54 | 55 | int opt_set_dontroute(lua_State *L, p_socket ps); 56 | int opt_get_dontroute(lua_State *L, p_socket ps); 57 | 58 | int opt_set_broadcast(lua_State *L, p_socket ps); 59 | int opt_get_broadcast(lua_State *L, p_socket ps); 60 | 61 | int opt_set_recv_buf_size(lua_State *L, p_socket ps); 62 | int opt_get_recv_buf_size(lua_State *L, p_socket ps); 63 | 64 | int opt_set_send_buf_size(lua_State *L, p_socket ps); 65 | int opt_get_send_buf_size(lua_State *L, p_socket ps); 66 | 67 | int opt_set_ip6_unicast_hops(lua_State *L, p_socket ps); 68 | int opt_get_ip6_unicast_hops(lua_State *L, p_socket ps); 69 | 70 | int opt_set_ip6_multicast_hops(lua_State *L, p_socket ps); 71 | int opt_get_ip6_multicast_hops(lua_State *L, p_socket ps); 72 | 73 | int opt_set_ip_multicast_loop(lua_State *L, p_socket ps); 74 | int opt_get_ip_multicast_loop(lua_State *L, p_socket ps); 75 | 76 | int opt_set_ip6_multicast_loop(lua_State *L, p_socket ps); 77 | int opt_get_ip6_multicast_loop(lua_State *L, p_socket ps); 78 | 79 | int opt_set_linger(lua_State *L, p_socket ps); 80 | int opt_get_linger(lua_State *L, p_socket ps); 81 | 82 | int opt_set_ip_multicast_ttl(lua_State *L, p_socket ps); 83 | 84 | int opt_set_ip_multicast_if(lua_State *L, p_socket ps); 85 | int opt_get_ip_multicast_if(lua_State *L, p_socket ps); 86 | 87 | int opt_set_ip_add_membership(lua_State *L, p_socket ps); 88 | int opt_set_ip_drop_membersip(lua_State *L, p_socket ps); 89 | 90 | int opt_set_ip6_add_membership(lua_State *L, p_socket ps); 91 | int opt_set_ip6_drop_membersip(lua_State *L, p_socket ps); 92 | 93 | int opt_set_ip6_v6only(lua_State *L, p_socket ps); 94 | int opt_get_ip6_v6only(lua_State *L, p_socket ps); 95 | 96 | int opt_get_error(lua_State *L, p_socket ps); 97 | 98 | #ifndef _WIN32 99 | #pragma GCC visibility pop 100 | #endif 101 | 102 | #endif 103 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/pierror.h: -------------------------------------------------------------------------------- 1 | #ifndef PIERROR_H 2 | #define PIERROR_H 3 | /*=========================================================================*\ 4 | * Error messages 5 | * Defines platform independent error messages 6 | \*=========================================================================*/ 7 | 8 | #define PIE_HOST_NOT_FOUND "host not found" 9 | #define PIE_ADDRINUSE "address already in use" 10 | #define PIE_ISCONN "already connected" 11 | #define PIE_ACCESS "permission denied" 12 | #define PIE_CONNREFUSED "connection refused" 13 | #define PIE_CONNABORTED "closed" 14 | #define PIE_CONNRESET "closed" 15 | #define PIE_TIMEDOUT "timeout" 16 | #define PIE_AGAIN "temporary failure in name resolution" 17 | #define PIE_BADFLAGS "invalid value for ai_flags" 18 | #define PIE_BADHINTS "invalid value for hints" 19 | #define PIE_FAIL "non-recoverable failure in name resolution" 20 | #define PIE_FAMILY "ai_family not supported" 21 | #define PIE_MEMORY "memory allocation failure" 22 | #define PIE_NONAME "host or service not provided, or not known" 23 | #define PIE_OVERFLOW "argument buffer overflow" 24 | #define PIE_PROTOCOL "resolved protocol is unknown" 25 | #define PIE_SERVICE "service not supported for socket type" 26 | #define PIE_SOCKTYPE "ai_socktype not supported" 27 | 28 | #endif 29 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/select.h: -------------------------------------------------------------------------------- 1 | #ifndef SELECT_H 2 | #define SELECT_H 3 | /*=========================================================================*\ 4 | * Select implementation 5 | * LuaSocket toolkit 6 | * 7 | * Each object that can be passed to the select function has to export 8 | * method getfd() which returns the descriptor to be passed to the 9 | * underlying select function. Another method, dirty(), should return 10 | * true if there is data ready for reading (required for buffered input). 11 | \*=========================================================================*/ 12 | 13 | #ifndef _WIN32 14 | #pragma GCC visibility push(hidden) 15 | #endif 16 | 17 | int select_open(lua_State *L); 18 | 19 | #ifndef _WIN32 20 | #pragma GCC visibility pop 21 | #endif 22 | 23 | #endif /* SELECT_H */ 24 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/serial.c: -------------------------------------------------------------------------------- 1 | /*=========================================================================*\ 2 | * Serial stream 3 | * LuaSocket toolkit 4 | \*=========================================================================*/ 5 | #include "luasocket.h" 6 | 7 | #include "auxiliar.h" 8 | #include "socket.h" 9 | #include "options.h" 10 | #include "unix.h" 11 | 12 | #include 13 | #include 14 | 15 | /* 16 | Reuses userdata definition from unix.h, since it is useful for all 17 | stream-like objects. 18 | 19 | If we stored the serial path for use in error messages or userdata 20 | printing, we might need our own userdata definition. 21 | 22 | Group usage is semi-inherited from unix.c, but unnecessary since we 23 | have only one object type. 24 | */ 25 | 26 | /*=========================================================================*\ 27 | * Internal function prototypes 28 | \*=========================================================================*/ 29 | static int global_create(lua_State *L); 30 | static int meth_send(lua_State *L); 31 | static int meth_receive(lua_State *L); 32 | static int meth_close(lua_State *L); 33 | static int meth_settimeout(lua_State *L); 34 | static int meth_getfd(lua_State *L); 35 | static int meth_setfd(lua_State *L); 36 | static int meth_dirty(lua_State *L); 37 | static int meth_getstats(lua_State *L); 38 | static int meth_setstats(lua_State *L); 39 | 40 | /* serial object methods */ 41 | static luaL_Reg serial_methods[] = { 42 | {"__gc", meth_close}, 43 | {"__tostring", auxiliar_tostring}, 44 | {"close", meth_close}, 45 | {"dirty", meth_dirty}, 46 | {"getfd", meth_getfd}, 47 | {"getstats", meth_getstats}, 48 | {"setstats", meth_setstats}, 49 | {"receive", meth_receive}, 50 | {"send", meth_send}, 51 | {"setfd", meth_setfd}, 52 | {"settimeout", meth_settimeout}, 53 | {NULL, NULL} 54 | }; 55 | 56 | /*-------------------------------------------------------------------------*\ 57 | * Initializes module 58 | \*-------------------------------------------------------------------------*/ 59 | LUASOCKET_API int luaopen_socket_serial(lua_State *L) { 60 | /* create classes */ 61 | auxiliar_newclass(L, "serial{client}", serial_methods); 62 | /* create class groups */ 63 | auxiliar_add2group(L, "serial{client}", "serial{any}"); 64 | lua_pushcfunction(L, global_create); 65 | return 1; 66 | } 67 | 68 | /*=========================================================================*\ 69 | * Lua methods 70 | \*=========================================================================*/ 71 | /*-------------------------------------------------------------------------*\ 72 | * Just call buffered IO methods 73 | \*-------------------------------------------------------------------------*/ 74 | static int meth_send(lua_State *L) { 75 | p_unix un = (p_unix) auxiliar_checkclass(L, "serial{client}", 1); 76 | return buffer_meth_send(L, &un->buf); 77 | } 78 | 79 | static int meth_receive(lua_State *L) { 80 | p_unix un = (p_unix) auxiliar_checkclass(L, "serial{client}", 1); 81 | return buffer_meth_receive(L, &un->buf); 82 | } 83 | 84 | static int meth_getstats(lua_State *L) { 85 | p_unix un = (p_unix) auxiliar_checkclass(L, "serial{client}", 1); 86 | return buffer_meth_getstats(L, &un->buf); 87 | } 88 | 89 | static int meth_setstats(lua_State *L) { 90 | p_unix un = (p_unix) auxiliar_checkclass(L, "serial{client}", 1); 91 | return buffer_meth_setstats(L, &un->buf); 92 | } 93 | 94 | /*-------------------------------------------------------------------------*\ 95 | * Select support methods 96 | \*-------------------------------------------------------------------------*/ 97 | static int meth_getfd(lua_State *L) { 98 | p_unix un = (p_unix) auxiliar_checkgroup(L, "serial{any}", 1); 99 | lua_pushnumber(L, (int) un->sock); 100 | return 1; 101 | } 102 | 103 | /* this is very dangerous, but can be handy for those that are brave enough */ 104 | static int meth_setfd(lua_State *L) { 105 | p_unix un = (p_unix) auxiliar_checkgroup(L, "serial{any}", 1); 106 | un->sock = (t_socket) luaL_checknumber(L, 2); 107 | return 0; 108 | } 109 | 110 | static int meth_dirty(lua_State *L) { 111 | p_unix un = (p_unix) auxiliar_checkgroup(L, "serial{any}", 1); 112 | lua_pushboolean(L, !buffer_isempty(&un->buf)); 113 | return 1; 114 | } 115 | 116 | /*-------------------------------------------------------------------------*\ 117 | * Closes socket used by object 118 | \*-------------------------------------------------------------------------*/ 119 | static int meth_close(lua_State *L) 120 | { 121 | p_unix un = (p_unix) auxiliar_checkgroup(L, "serial{any}", 1); 122 | socket_destroy(&un->sock); 123 | lua_pushnumber(L, 1); 124 | return 1; 125 | } 126 | 127 | 128 | /*-------------------------------------------------------------------------*\ 129 | * Just call tm methods 130 | \*-------------------------------------------------------------------------*/ 131 | static int meth_settimeout(lua_State *L) { 132 | p_unix un = (p_unix) auxiliar_checkgroup(L, "serial{any}", 1); 133 | return timeout_meth_settimeout(L, &un->tm); 134 | } 135 | 136 | /*=========================================================================*\ 137 | * Library functions 138 | \*=========================================================================*/ 139 | 140 | 141 | /*-------------------------------------------------------------------------*\ 142 | * Creates a serial object 143 | \*-------------------------------------------------------------------------*/ 144 | static int global_create(lua_State *L) { 145 | const char* path = luaL_checkstring(L, 1); 146 | 147 | /* allocate unix object */ 148 | p_unix un = (p_unix) lua_newuserdata(L, sizeof(t_unix)); 149 | 150 | /* open serial device */ 151 | t_socket sock = open(path, O_NOCTTY|O_RDWR); 152 | 153 | /*printf("open %s on %d\n", path, sock);*/ 154 | 155 | if (sock < 0) { 156 | lua_pushnil(L); 157 | lua_pushstring(L, socket_strerror(errno)); 158 | lua_pushnumber(L, errno); 159 | return 3; 160 | } 161 | /* set its type as client object */ 162 | auxiliar_setclass(L, "serial{client}", -1); 163 | /* initialize remaining structure fields */ 164 | socket_setnonblocking(&sock); 165 | un->sock = sock; 166 | io_init(&un->io, (p_send) socket_write, (p_recv) socket_read, 167 | (p_error) socket_ioerror, &un->sock); 168 | timeout_init(&un->tm, -1, -1); 169 | buffer_init(&un->buf, &un->io, &un->tm); 170 | return 1; 171 | } 172 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/socket.h: -------------------------------------------------------------------------------- 1 | #ifndef SOCKET_H 2 | #define SOCKET_H 3 | /*=========================================================================*\ 4 | * Socket compatibilization module 5 | * LuaSocket toolkit 6 | * 7 | * BSD Sockets and WinSock are similar, but there are a few irritating 8 | * differences. Also, not all *nix platforms behave the same. This module 9 | * (and the associated usocket.h and wsocket.h) factor these differences and 10 | * creates a interface compatible with the io.h module. 11 | \*=========================================================================*/ 12 | #include "io.h" 13 | 14 | /*=========================================================================*\ 15 | * Platform specific compatibilization 16 | \*=========================================================================*/ 17 | #ifdef _WIN32 18 | #include "wsocket.h" 19 | #else 20 | #include "usocket.h" 21 | #endif 22 | 23 | /*=========================================================================*\ 24 | * The connect and accept functions accept a timeout and their 25 | * implementations are somewhat complicated. We chose to move 26 | * the timeout control into this module for these functions in 27 | * order to simplify the modules that use them. 28 | \*=========================================================================*/ 29 | #include "timeout.h" 30 | 31 | /* convenient shorthand */ 32 | typedef struct sockaddr SA; 33 | 34 | /*=========================================================================*\ 35 | * Functions bellow implement a comfortable platform independent 36 | * interface to sockets 37 | \*=========================================================================*/ 38 | 39 | #ifndef _WIN32 40 | #pragma GCC visibility push(hidden) 41 | #endif 42 | 43 | int socket_waitfd(p_socket ps, int sw, p_timeout tm); 44 | int socket_open(void); 45 | int socket_close(void); 46 | void socket_destroy(p_socket ps); 47 | int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds, p_timeout tm); 48 | int socket_create(p_socket ps, int domain, int type, int protocol); 49 | int socket_bind(p_socket ps, SA *addr, socklen_t addr_len); 50 | int socket_listen(p_socket ps, int backlog); 51 | void socket_shutdown(p_socket ps, int how); 52 | int socket_connect(p_socket ps, SA *addr, socklen_t addr_len, p_timeout tm); 53 | int socket_accept(p_socket ps, p_socket pa, SA *addr, socklen_t *addr_len, p_timeout tm); 54 | int socket_send(p_socket ps, const char *data, size_t count, size_t *sent, p_timeout tm); 55 | int socket_sendto(p_socket ps, const char *data, size_t count, size_t *sent, SA *addr, socklen_t addr_len, p_timeout tm); 56 | int socket_recv(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm); 57 | int socket_recvfrom(p_socket ps, char *data, size_t count, size_t *got, SA *addr, socklen_t *addr_len, p_timeout tm); 58 | int socket_write(p_socket ps, const char *data, size_t count, size_t *sent, p_timeout tm); 59 | int socket_read(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm); 60 | void socket_setblocking(p_socket ps); 61 | void socket_setnonblocking(p_socket ps); 62 | int socket_gethostbyaddr(const char *addr, socklen_t len, struct hostent **hp); 63 | int socket_gethostbyname(const char *addr, struct hostent **hp); 64 | const char *socket_hoststrerror(int err); 65 | const char *socket_strerror(int err); 66 | const char *socket_ioerror(p_socket ps, int err); 67 | const char *socket_gaistrerror(int err); 68 | 69 | #ifndef _WIN32 70 | #pragma GCC visibility pop 71 | #endif 72 | 73 | #endif /* SOCKET_H */ 74 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/socket.lua: -------------------------------------------------------------------------------- 1 | ----------------------------------------------------------------------------- 2 | -- LuaSocket helper module 3 | -- Author: Diego Nehab 4 | ----------------------------------------------------------------------------- 5 | 6 | ----------------------------------------------------------------------------- 7 | -- Declare module and import dependencies 8 | ----------------------------------------------------------------------------- 9 | local base = _G 10 | local string = require("string") 11 | local math = require("math") 12 | local socket = require("socket.core") 13 | 14 | local _M = socket 15 | 16 | ----------------------------------------------------------------------------- 17 | -- Exported auxiliar functions 18 | ----------------------------------------------------------------------------- 19 | function _M.connect4(address, port, laddress, lport) 20 | return socket.connect(address, port, laddress, lport, "inet") 21 | end 22 | 23 | function _M.connect6(address, port, laddress, lport) 24 | return socket.connect(address, port, laddress, lport, "inet6") 25 | end 26 | 27 | function _M.bind(host, port, backlog) 28 | if host == "*" then host = "0.0.0.0" end 29 | local addrinfo, err = socket.dns.getaddrinfo(host); 30 | if not addrinfo then return nil, err end 31 | local sock, res 32 | err = "no info on address" 33 | for i, alt in base.ipairs(addrinfo) do 34 | if alt.family == "inet" then 35 | sock, err = socket.tcp4() 36 | else 37 | sock, err = socket.tcp6() 38 | end 39 | if not sock then return nil, err end 40 | sock:setoption("reuseaddr", true) 41 | res, err = sock:bind(alt.addr, port) 42 | if not res then 43 | sock:close() 44 | else 45 | res, err = sock:listen(backlog) 46 | if not res then 47 | sock:close() 48 | else 49 | return sock 50 | end 51 | end 52 | end 53 | return nil, err 54 | end 55 | 56 | _M.try = _M.newtry() 57 | 58 | function _M.choose(table) 59 | return function(name, opt1, opt2) 60 | if base.type(name) ~= "string" then 61 | name, opt1, opt2 = "default", name, opt1 62 | end 63 | local f = table[name or "nil"] 64 | if not f then base.error("unknown key (".. base.tostring(name) ..")", 3) 65 | else return f(opt1, opt2) end 66 | end 67 | end 68 | 69 | ----------------------------------------------------------------------------- 70 | -- Socket sources and sinks, conforming to LTN12 71 | ----------------------------------------------------------------------------- 72 | -- create namespaces inside LuaSocket namespace 73 | local sourcet, sinkt = {}, {} 74 | _M.sourcet = sourcet 75 | _M.sinkt = sinkt 76 | 77 | _M.BLOCKSIZE = 2048 78 | 79 | sinkt["close-when-done"] = function(sock) 80 | return base.setmetatable({ 81 | getfd = function() return sock:getfd() end, 82 | dirty = function() return sock:dirty() end 83 | }, { 84 | __call = function(self, chunk, err) 85 | if not chunk then 86 | sock:close() 87 | return 1 88 | else return sock:send(chunk) end 89 | end 90 | }) 91 | end 92 | 93 | sinkt["keep-open"] = function(sock) 94 | return base.setmetatable({ 95 | getfd = function() return sock:getfd() end, 96 | dirty = function() return sock:dirty() end 97 | }, { 98 | __call = function(self, chunk, err) 99 | if chunk then return sock:send(chunk) 100 | else return 1 end 101 | end 102 | }) 103 | end 104 | 105 | sinkt["default"] = sinkt["keep-open"] 106 | 107 | _M.sink = _M.choose(sinkt) 108 | 109 | sourcet["by-length"] = function(sock, length) 110 | return base.setmetatable({ 111 | getfd = function() return sock:getfd() end, 112 | dirty = function() return sock:dirty() end 113 | }, { 114 | __call = function() 115 | if length <= 0 then return nil end 116 | local size = math.min(socket.BLOCKSIZE, length) 117 | local chunk, err = sock:receive(size) 118 | if err then return nil, err end 119 | length = length - string.len(chunk) 120 | return chunk 121 | end 122 | }) 123 | end 124 | 125 | sourcet["until-closed"] = function(sock) 126 | local done 127 | return base.setmetatable({ 128 | getfd = function() return sock:getfd() end, 129 | dirty = function() return sock:dirty() end 130 | }, { 131 | __call = function() 132 | if done then return nil end 133 | local chunk, err, partial = sock:receive(socket.BLOCKSIZE) 134 | if not err then return chunk 135 | elseif err == "closed" then 136 | sock:close() 137 | done = 1 138 | return partial 139 | else return nil, err end 140 | end 141 | }) 142 | end 143 | 144 | 145 | sourcet["default"] = sourcet["until-closed"] 146 | 147 | _M.source = _M.choose(sourcet) 148 | 149 | return _M 150 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/tcp.h: -------------------------------------------------------------------------------- 1 | #ifndef TCP_H 2 | #define TCP_H 3 | /*=========================================================================*\ 4 | * TCP object 5 | * LuaSocket toolkit 6 | * 7 | * The tcp.h module is basicly a glue that puts together modules buffer.h, 8 | * timeout.h socket.h and inet.h to provide the LuaSocket TCP (AF_INET, 9 | * SOCK_STREAM) support. 10 | * 11 | * Three classes are defined: master, client and server. The master class is 12 | * a newly created tcp object, that has not been bound or connected. Server 13 | * objects are tcp objects bound to some local address. Client objects are 14 | * tcp objects either connected to some address or returned by the accept 15 | * method of a server object. 16 | \*=========================================================================*/ 17 | #include "luasocket.h" 18 | 19 | #include "buffer.h" 20 | #include "timeout.h" 21 | #include "socket.h" 22 | 23 | typedef struct t_tcp_ { 24 | t_socket sock; 25 | t_io io; 26 | t_buffer buf; 27 | t_timeout tm; 28 | int family; 29 | } t_tcp; 30 | 31 | typedef t_tcp *p_tcp; 32 | 33 | #ifndef _WIN32 34 | #pragma GCC visibility push(hidden) 35 | #endif 36 | 37 | int tcp_open(lua_State *L); 38 | 39 | #ifndef _WIN32 40 | #pragma GCC visibility pop 41 | #endif 42 | 43 | #endif /* TCP_H */ 44 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/timeout.h: -------------------------------------------------------------------------------- 1 | #ifndef TIMEOUT_H 2 | #define TIMEOUT_H 3 | /*=========================================================================*\ 4 | * Timeout management functions 5 | * LuaSocket toolkit 6 | \*=========================================================================*/ 7 | #include "luasocket.h" 8 | 9 | /* timeout control structure */ 10 | typedef struct t_timeout_ { 11 | double block; /* maximum time for blocking calls */ 12 | double total; /* total number of miliseconds for operation */ 13 | double start; /* time of start of operation */ 14 | } t_timeout; 15 | typedef t_timeout *p_timeout; 16 | 17 | #ifndef _WIN32 18 | #pragma GCC visibility push(hidden) 19 | #endif 20 | 21 | void timeout_init(p_timeout tm, double block, double total); 22 | double timeout_get(p_timeout tm); 23 | double timeout_getstart(p_timeout tm); 24 | double timeout_getretry(p_timeout tm); 25 | p_timeout timeout_markstart(p_timeout tm); 26 | 27 | double timeout_gettime(void); 28 | 29 | int timeout_open(lua_State *L); 30 | 31 | int timeout_meth_settimeout(lua_State *L, p_timeout tm); 32 | int timeout_meth_gettimeout(lua_State *L, p_timeout tm); 33 | 34 | #ifndef _WIN32 35 | #pragma GCC visibility pop 36 | #endif 37 | 38 | #define timeout_iszero(tm) ((tm)->block == 0.0) 39 | 40 | #endif /* TIMEOUT_H */ 41 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/tp.lua: -------------------------------------------------------------------------------- 1 | ----------------------------------------------------------------------------- 2 | -- Unified SMTP/FTP subsystem 3 | -- LuaSocket toolkit. 4 | -- Author: Diego Nehab 5 | ----------------------------------------------------------------------------- 6 | 7 | ----------------------------------------------------------------------------- 8 | -- Declare module and import dependencies 9 | ----------------------------------------------------------------------------- 10 | local base = _G 11 | local string = require("string") 12 | local socket = require("socket") 13 | local ltn12 = require("ltn12") 14 | 15 | socket.tp = {} 16 | local _M = socket.tp 17 | 18 | ----------------------------------------------------------------------------- 19 | -- Program constants 20 | ----------------------------------------------------------------------------- 21 | _M.TIMEOUT = 60 22 | 23 | ----------------------------------------------------------------------------- 24 | -- Implementation 25 | ----------------------------------------------------------------------------- 26 | -- gets server reply (works for SMTP and FTP) 27 | local function get_reply(c) 28 | local code, current, sep 29 | local line, err = c:receive() 30 | local reply = line 31 | if err then return nil, err end 32 | code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) 33 | if not code then return nil, "invalid server reply" end 34 | if sep == "-" then -- reply is multiline 35 | repeat 36 | line, err = c:receive() 37 | if err then return nil, err end 38 | current, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) 39 | reply = reply .. "\n" .. line 40 | -- reply ends with same code 41 | until code == current and sep == " " 42 | end 43 | return code, reply 44 | end 45 | 46 | -- metatable for sock object 47 | local metat = { __index = {} } 48 | 49 | function metat.__index:getpeername() 50 | return self.c:getpeername() 51 | end 52 | 53 | function metat.__index:getsockname() 54 | return self.c:getpeername() 55 | end 56 | 57 | function metat.__index:check(ok) 58 | local code, reply = get_reply(self.c) 59 | if not code then return nil, reply end 60 | if base.type(ok) ~= "function" then 61 | if base.type(ok) == "table" then 62 | for i, v in base.ipairs(ok) do 63 | if string.find(code, v) then 64 | return base.tonumber(code), reply 65 | end 66 | end 67 | return nil, reply 68 | else 69 | if string.find(code, ok) then return base.tonumber(code), reply 70 | else return nil, reply end 71 | end 72 | else return ok(base.tonumber(code), reply) end 73 | end 74 | 75 | function metat.__index:command(cmd, arg) 76 | cmd = string.upper(cmd) 77 | if arg then 78 | return self.c:send(cmd .. " " .. arg.. "\r\n") 79 | else 80 | return self.c:send(cmd .. "\r\n") 81 | end 82 | end 83 | 84 | function metat.__index:sink(snk, pat) 85 | local chunk, err = self.c:receive(pat) 86 | return snk(chunk, err) 87 | end 88 | 89 | function metat.__index:send(data) 90 | return self.c:send(data) 91 | end 92 | 93 | function metat.__index:receive(pat) 94 | return self.c:receive(pat) 95 | end 96 | 97 | function metat.__index:getfd() 98 | return self.c:getfd() 99 | end 100 | 101 | function metat.__index:dirty() 102 | return self.c:dirty() 103 | end 104 | 105 | function metat.__index:getcontrol() 106 | return self.c 107 | end 108 | 109 | function metat.__index:source(source, step) 110 | local sink = socket.sink("keep-open", self.c) 111 | local ret, err = ltn12.pump.all(source, sink, step or ltn12.pump.step) 112 | return ret, err 113 | end 114 | 115 | -- closes the underlying c 116 | function metat.__index:close() 117 | self.c:close() 118 | return 1 119 | end 120 | 121 | -- connect with server and return c object 122 | function _M.connect(host, port, timeout, create) 123 | local c, e = (create or socket.tcp)() 124 | if not c then return nil, e end 125 | c:settimeout(timeout or _M.TIMEOUT) 126 | local r, e = c:connect(host, port) 127 | if not r then 128 | c:close() 129 | return nil, e 130 | end 131 | return base.setmetatable({c = c}, metat) 132 | end 133 | 134 | return _M 135 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/udp.h: -------------------------------------------------------------------------------- 1 | #ifndef UDP_H 2 | #define UDP_H 3 | /*=========================================================================*\ 4 | * UDP object 5 | * LuaSocket toolkit 6 | * 7 | * The udp.h module provides LuaSocket with support for UDP protocol 8 | * (AF_INET, SOCK_DGRAM). 9 | * 10 | * Two classes are defined: connected and unconnected. UDP objects are 11 | * originally unconnected. They can be "connected" to a given address 12 | * with a call to the setpeername function. The same function can be used to 13 | * break the connection. 14 | \*=========================================================================*/ 15 | #include "luasocket.h" 16 | 17 | #include "timeout.h" 18 | #include "socket.h" 19 | 20 | #define UDP_DATAGRAMSIZE 8192 21 | 22 | typedef struct t_udp_ { 23 | t_socket sock; 24 | t_timeout tm; 25 | int family; 26 | } t_udp; 27 | typedef t_udp *p_udp; 28 | 29 | #ifndef _WIN32 30 | #pragma GCC visibility push(hidden) 31 | #endif 32 | 33 | int udp_open(lua_State *L); 34 | 35 | #ifndef _WIN32 36 | #pragma GCC visibility pop 37 | #endif 38 | 39 | #endif /* UDP_H */ 40 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/unix.c: -------------------------------------------------------------------------------- 1 | /*=========================================================================*\ 2 | * Unix domain socket 3 | * LuaSocket toolkit 4 | \*=========================================================================*/ 5 | #include "luasocket.h" 6 | 7 | #include "unixstream.h" 8 | #include "unixdgram.h" 9 | 10 | /*-------------------------------------------------------------------------*\ 11 | * Modules and functions 12 | \*-------------------------------------------------------------------------*/ 13 | static const luaL_Reg mod[] = { 14 | {"stream", unixstream_open}, 15 | {"dgram", unixdgram_open}, 16 | {NULL, NULL} 17 | }; 18 | 19 | static void add_alias(lua_State *L, int index, const char *name, const char *target) 20 | { 21 | lua_getfield(L, index, target); 22 | lua_setfield(L, index, name); 23 | } 24 | 25 | static int compat_socket_unix_call(lua_State *L) 26 | { 27 | /* Look up socket.unix.stream in the socket.unix table (which is the first 28 | * argument). */ 29 | lua_getfield(L, 1, "stream"); 30 | 31 | /* Replace the stack entry for the socket.unix table with the 32 | * socket.unix.stream function. */ 33 | lua_replace(L, 1); 34 | 35 | /* Call socket.unix.stream, passing along any arguments. */ 36 | int n = lua_gettop(L); 37 | lua_call(L, n-1, LUA_MULTRET); 38 | 39 | /* Pass along the return values from socket.unix.stream. */ 40 | n = lua_gettop(L); 41 | return n; 42 | } 43 | 44 | /*-------------------------------------------------------------------------*\ 45 | * Initializes module 46 | \*-------------------------------------------------------------------------*/ 47 | LUASOCKET_API int luaopen_socket_unix(lua_State *L) 48 | { 49 | int i; 50 | lua_newtable(L); 51 | int socket_unix_table = lua_gettop(L); 52 | 53 | for (i = 0; mod[i].name; i++) 54 | mod[i].func(L); 55 | 56 | /* Add backwards compatibility aliases "tcp" and "udp" for the "stream" and 57 | * "dgram" functions. */ 58 | add_alias(L, socket_unix_table, "tcp", "stream"); 59 | add_alias(L, socket_unix_table, "udp", "dgram"); 60 | 61 | /* Add a backwards compatibility function and a metatable setup to call it 62 | * for the old socket.unix() interface. */ 63 | lua_pushcfunction(L, compat_socket_unix_call); 64 | lua_setfield(L, socket_unix_table, "__call"); 65 | lua_pushvalue(L, socket_unix_table); 66 | lua_setmetatable(L, socket_unix_table); 67 | 68 | return 1; 69 | } 70 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/unix.h: -------------------------------------------------------------------------------- 1 | #ifndef UNIX_H 2 | #define UNIX_H 3 | /*=========================================================================*\ 4 | * Unix domain object 5 | * LuaSocket toolkit 6 | * 7 | * This module is just an example of how to extend LuaSocket with a new 8 | * domain. 9 | \*=========================================================================*/ 10 | #include "luasocket.h" 11 | 12 | #include "buffer.h" 13 | #include "timeout.h" 14 | #include "socket.h" 15 | 16 | typedef struct t_unix_ { 17 | t_socket sock; 18 | t_io io; 19 | t_buffer buf; 20 | t_timeout tm; 21 | } t_unix; 22 | typedef t_unix *p_unix; 23 | 24 | LUASOCKET_API int luaopen_socket_unix(lua_State *L); 25 | 26 | #endif /* UNIX_H */ 27 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/unixdgram.h: -------------------------------------------------------------------------------- 1 | #ifndef UNIXDGRAM_H 2 | #define UNIXDGRAM_H 3 | /*=========================================================================*\ 4 | * DGRAM object 5 | * LuaSocket toolkit 6 | * 7 | * The dgram.h module provides LuaSocket with support for DGRAM protocol 8 | * (AF_INET, SOCK_DGRAM). 9 | * 10 | * Two classes are defined: connected and unconnected. DGRAM objects are 11 | * originally unconnected. They can be "connected" to a given address 12 | * with a call to the setpeername function. The same function can be used to 13 | * break the connection. 14 | \*=========================================================================*/ 15 | 16 | #include "unix.h" 17 | 18 | #ifndef _WIN32 19 | #pragma GCC visibility push(hidden) 20 | #endif 21 | 22 | int unixdgram_open(lua_State *L); 23 | 24 | #ifndef _WIN32 25 | #pragma GCC visibility pop 26 | #endif 27 | 28 | #endif /* UNIXDGRAM_H */ 29 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/unixstream.h: -------------------------------------------------------------------------------- 1 | #ifndef UNIXSTREAM_H 2 | #define UNIXSTREAM_H 3 | /*=========================================================================*\ 4 | * UNIX STREAM object 5 | * LuaSocket toolkit 6 | * 7 | * The unixstream.h module is basicly a glue that puts together modules buffer.h, 8 | * timeout.h socket.h and inet.h to provide the LuaSocket UNIX STREAM (AF_UNIX, 9 | * SOCK_STREAM) support. 10 | * 11 | * Three classes are defined: master, client and server. The master class is 12 | * a newly created unixstream object, that has not been bound or connected. Server 13 | * objects are unixstream objects bound to some local address. Client objects are 14 | * unixstream objects either connected to some address or returned by the accept 15 | * method of a server object. 16 | \*=========================================================================*/ 17 | #include "unix.h" 18 | 19 | #ifndef _WIN32 20 | #pragma GCC visibility push(hidden) 21 | #endif 22 | 23 | int unixstream_open(lua_State *L); 24 | 25 | #ifndef _WIN32 26 | #pragma GCC visibility pop 27 | #endif 28 | 29 | #endif /* UNIXSTREAM_H */ 30 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/usocket.h: -------------------------------------------------------------------------------- 1 | #ifndef USOCKET_H 2 | #define USOCKET_H 3 | /*=========================================================================*\ 4 | * Socket compatibilization module for Unix 5 | * LuaSocket toolkit 6 | \*=========================================================================*/ 7 | 8 | /*=========================================================================*\ 9 | * BSD include files 10 | \*=========================================================================*/ 11 | /* error codes */ 12 | #include 13 | /* close function */ 14 | #include 15 | /* fnctnl function and associated constants */ 16 | #include 17 | /* struct sockaddr */ 18 | #include 19 | /* socket function */ 20 | #include 21 | /* struct timeval */ 22 | #include 23 | /* gethostbyname and gethostbyaddr functions */ 24 | #include 25 | /* sigpipe handling */ 26 | #include 27 | /* IP stuff*/ 28 | #include 29 | #include 30 | /* TCP options (nagle algorithm disable) */ 31 | #include 32 | #include 33 | 34 | #ifndef SO_REUSEPORT 35 | #define SO_REUSEPORT SO_REUSEADDR 36 | #endif 37 | 38 | /* Some platforms use IPV6_JOIN_GROUP instead if 39 | * IPV6_ADD_MEMBERSHIP. The semantics are same, though. */ 40 | #ifndef IPV6_ADD_MEMBERSHIP 41 | #ifdef IPV6_JOIN_GROUP 42 | #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP 43 | #endif /* IPV6_JOIN_GROUP */ 44 | #endif /* !IPV6_ADD_MEMBERSHIP */ 45 | 46 | /* Same with IPV6_DROP_MEMBERSHIP / IPV6_LEAVE_GROUP. */ 47 | #ifndef IPV6_DROP_MEMBERSHIP 48 | #ifdef IPV6_LEAVE_GROUP 49 | #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP 50 | #endif /* IPV6_LEAVE_GROUP */ 51 | #endif /* !IPV6_DROP_MEMBERSHIP */ 52 | 53 | typedef int t_socket; 54 | typedef t_socket *p_socket; 55 | typedef struct sockaddr_storage t_sockaddr_storage; 56 | 57 | #define SOCKET_INVALID (-1) 58 | 59 | #endif /* USOCKET_H */ 60 | -------------------------------------------------------------------------------- /luasocket/luasocket/src/wsocket.h: -------------------------------------------------------------------------------- 1 | #ifndef WSOCKET_H 2 | #define WSOCKET_H 3 | /*=========================================================================*\ 4 | * Socket compatibilization module for Win32 5 | * LuaSocket toolkit 6 | \*=========================================================================*/ 7 | 8 | /*=========================================================================*\ 9 | * WinSock include files 10 | \*=========================================================================*/ 11 | #include 12 | #include 13 | 14 | typedef int socklen_t; 15 | typedef SOCKADDR_STORAGE t_sockaddr_storage; 16 | typedef SOCKET t_socket; 17 | typedef t_socket *p_socket; 18 | 19 | #ifndef IPV6_V6ONLY 20 | #define IPV6_V6ONLY 27 21 | #endif 22 | 23 | #define SOCKET_INVALID (INVALID_SOCKET) 24 | 25 | #ifndef SO_REUSEPORT 26 | #define SO_REUSEPORT SO_REUSEADDR 27 | #endif 28 | 29 | #ifndef AI_NUMERICSERV 30 | #define AI_NUMERICSERV (0) 31 | #endif 32 | 33 | #endif /* WSOCKET_H */ 34 | -------------------------------------------------------------------------------- /luasocket/src/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate td_rlua; 2 | 3 | #[allow(improper_ctypes)] 4 | extern "C" { 5 | pub fn luaopen_socket_core(L : *mut td_rlua::lua_State) -> libc::c_int; 6 | } 7 | 8 | extern "C" fn safe_luaopen_socket_core(lua: *mut td_rlua::lua_State) -> libc::c_int { 9 | unsafe { 10 | luaopen_socket_core(lua) 11 | } 12 | } 13 | 14 | /// custom lua load func 15 | extern "C" fn load_func(lua: *mut td_rlua::lua_State) -> libc::c_int { 16 | let path:String = td_rlua::LuaRead::lua_read(lua).unwrap_or(String::new()); 17 | if &path == "socket.core" || &path == "luasocket" || &path == "socket" { 18 | unsafe { 19 | td_rlua::lua_pushcfunction(lua, safe_luaopen_socket_core); 20 | } 21 | return 1; 22 | } 23 | return 0; 24 | } 25 | 26 | pub fn enable_socket_core(lua : &mut td_rlua::Lua) { 27 | lua.add_lualoader(load_func); 28 | } -------------------------------------------------------------------------------- /td_clua/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "td_clua" 3 | version = "0.1.3" 4 | authors = ["wugd"] 5 | description = "Bindings for Lua 5.3" 6 | repository = "https://github.com/tickbh/td_rlua" 7 | build = "build.rs" 8 | links = "lua" 9 | license = "MIT/Apache-2.0" 10 | 11 | [build-dependencies] 12 | pkg-config = "0.3" 13 | gcc = "0.3" 14 | 15 | [dependencies] 16 | libc = "^0.2.1" 17 | -------------------------------------------------------------------------------- /td_clua/build.rs: -------------------------------------------------------------------------------- 1 | extern crate pkg_config; 2 | extern crate gcc; 3 | 4 | fn main() { 5 | let mut build = gcc::Config::new(); 6 | 7 | build.file("lua/src/lapi.c") 8 | .file("lua/src/lcode.c") 9 | .file("lua/src/lctype.c") 10 | .file("lua/src/ldebug.c") 11 | .file("lua/src/ldo.c") 12 | .file("lua/src/ldump.c") 13 | .file("lua/src/lfunc.c") 14 | .file("lua/src/lgc.c") 15 | .file("lua/src/llex.c") 16 | .file("lua/src/lmem.c") 17 | .file("lua/src/lobject.c") 18 | .file("lua/src/lopcodes.c") 19 | .file("lua/src/lparser.c") 20 | .file("lua/src/lstate.c") 21 | .file("lua/src/lstring.c") 22 | .file("lua/src/ltable.c") 23 | .file("lua/src/ltm.c") 24 | .file("lua/src/lundump.c") 25 | .file("lua/src/lvm.c") 26 | .file("lua/src/lzio.c") 27 | .file("lua/src/lauxlib.c") 28 | .file("lua/src/lbaselib.c") 29 | .file("lua/src/lbitlib.c") 30 | .file("lua/src/lcorolib.c") 31 | .file("lua/src/ldblib.c") 32 | .file("lua/src/liolib.c") 33 | .file("lua/src/lmathlib.c") 34 | .file("lua/src/loslib.c") 35 | .file("lua/src/lstrlib.c") 36 | .file("lua/src/ltablib.c") 37 | .file("lua/src/loadlib.c") 38 | .file("lua/src/linit.c") 39 | .file("lua/src/lutf8lib.c") 40 | .define("LUA_COMPAT_ALL", None) 41 | .define("LUA_COMPAT_MODULE", None) 42 | .define("LUA_COMPAT_BITLIB", None) 43 | .define("LUA_COMPAT_LOADSTRING", None); 44 | 45 | if cfg!(windows) { 46 | build.define("LUA_USE_WINDOWS", "1"); 47 | } 48 | if cfg!(unix) { 49 | build.define("LUA_USE_LINUX", "1"); 50 | } 51 | if cfg!(macos) { 52 | build.define("LUA_USE_MACOSX", "1"); 53 | } 54 | 55 | build.include("lua/src") 56 | .compile("liblua.a"); 57 | } 58 | -------------------------------------------------------------------------------- /td_clua/lua/src/lapi.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lapi.h,v 2.9.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Auxiliary functions from Lua API 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef lapi_h 8 | #define lapi_h 9 | 10 | 11 | #include "llimits.h" 12 | #include "lstate.h" 13 | 14 | #define api_incr_top(L) {L->top++; api_check(L, L->top <= L->ci->top, \ 15 | "stack overflow");} 16 | 17 | #define adjustresults(L,nres) \ 18 | { if ((nres) == LUA_MULTRET && L->ci->top < L->top) L->ci->top = L->top; } 19 | 20 | #define api_checknelems(L,n) api_check(L, (n) < (L->top - L->ci->func), \ 21 | "not enough elements in the stack") 22 | 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /td_clua/lua/src/lbitlib.c: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lbitlib.c,v 1.30.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Standard library for bitwise operations 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #define lbitlib_c 8 | #define LUA_LIB 9 | 10 | #include "lprefix.h" 11 | 12 | 13 | #include "lua.h" 14 | 15 | #include "lauxlib.h" 16 | #include "lualib.h" 17 | 18 | 19 | #if defined(LUA_COMPAT_BITLIB) /* { */ 20 | 21 | 22 | #define pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n)) 23 | #define checkunsigned(L,i) ((lua_Unsigned)luaL_checkinteger(L,i)) 24 | 25 | 26 | /* number of bits to consider in a number */ 27 | #if !defined(LUA_NBITS) 28 | #define LUA_NBITS 32 29 | #endif 30 | 31 | 32 | /* 33 | ** a lua_Unsigned with its first LUA_NBITS bits equal to 1. (Shift must 34 | ** be made in two parts to avoid problems when LUA_NBITS is equal to the 35 | ** number of bits in a lua_Unsigned.) 36 | */ 37 | #define ALLONES (~(((~(lua_Unsigned)0) << (LUA_NBITS - 1)) << 1)) 38 | 39 | 40 | /* macro to trim extra bits */ 41 | #define trim(x) ((x) & ALLONES) 42 | 43 | 44 | /* builds a number with 'n' ones (1 <= n <= LUA_NBITS) */ 45 | #define mask(n) (~((ALLONES << 1) << ((n) - 1))) 46 | 47 | 48 | 49 | static lua_Unsigned andaux (lua_State *L) { 50 | int i, n = lua_gettop(L); 51 | lua_Unsigned r = ~(lua_Unsigned)0; 52 | for (i = 1; i <= n; i++) 53 | r &= checkunsigned(L, i); 54 | return trim(r); 55 | } 56 | 57 | 58 | static int b_and (lua_State *L) { 59 | lua_Unsigned r = andaux(L); 60 | pushunsigned(L, r); 61 | return 1; 62 | } 63 | 64 | 65 | static int b_test (lua_State *L) { 66 | lua_Unsigned r = andaux(L); 67 | lua_pushboolean(L, r != 0); 68 | return 1; 69 | } 70 | 71 | 72 | static int b_or (lua_State *L) { 73 | int i, n = lua_gettop(L); 74 | lua_Unsigned r = 0; 75 | for (i = 1; i <= n; i++) 76 | r |= checkunsigned(L, i); 77 | pushunsigned(L, trim(r)); 78 | return 1; 79 | } 80 | 81 | 82 | static int b_xor (lua_State *L) { 83 | int i, n = lua_gettop(L); 84 | lua_Unsigned r = 0; 85 | for (i = 1; i <= n; i++) 86 | r ^= checkunsigned(L, i); 87 | pushunsigned(L, trim(r)); 88 | return 1; 89 | } 90 | 91 | 92 | static int b_not (lua_State *L) { 93 | lua_Unsigned r = ~checkunsigned(L, 1); 94 | pushunsigned(L, trim(r)); 95 | return 1; 96 | } 97 | 98 | 99 | static int b_shift (lua_State *L, lua_Unsigned r, lua_Integer i) { 100 | if (i < 0) { /* shift right? */ 101 | i = -i; 102 | r = trim(r); 103 | if (i >= LUA_NBITS) r = 0; 104 | else r >>= i; 105 | } 106 | else { /* shift left */ 107 | if (i >= LUA_NBITS) r = 0; 108 | else r <<= i; 109 | r = trim(r); 110 | } 111 | pushunsigned(L, r); 112 | return 1; 113 | } 114 | 115 | 116 | static int b_lshift (lua_State *L) { 117 | return b_shift(L, checkunsigned(L, 1), luaL_checkinteger(L, 2)); 118 | } 119 | 120 | 121 | static int b_rshift (lua_State *L) { 122 | return b_shift(L, checkunsigned(L, 1), -luaL_checkinteger(L, 2)); 123 | } 124 | 125 | 126 | static int b_arshift (lua_State *L) { 127 | lua_Unsigned r = checkunsigned(L, 1); 128 | lua_Integer i = luaL_checkinteger(L, 2); 129 | if (i < 0 || !(r & ((lua_Unsigned)1 << (LUA_NBITS - 1)))) 130 | return b_shift(L, r, -i); 131 | else { /* arithmetic shift for 'negative' number */ 132 | if (i >= LUA_NBITS) r = ALLONES; 133 | else 134 | r = trim((r >> i) | ~(trim(~(lua_Unsigned)0) >> i)); /* add signal bit */ 135 | pushunsigned(L, r); 136 | return 1; 137 | } 138 | } 139 | 140 | 141 | static int b_rot (lua_State *L, lua_Integer d) { 142 | lua_Unsigned r = checkunsigned(L, 1); 143 | int i = d & (LUA_NBITS - 1); /* i = d % NBITS */ 144 | r = trim(r); 145 | if (i != 0) /* avoid undefined shift of LUA_NBITS when i == 0 */ 146 | r = (r << i) | (r >> (LUA_NBITS - i)); 147 | pushunsigned(L, trim(r)); 148 | return 1; 149 | } 150 | 151 | 152 | static int b_lrot (lua_State *L) { 153 | return b_rot(L, luaL_checkinteger(L, 2)); 154 | } 155 | 156 | 157 | static int b_rrot (lua_State *L) { 158 | return b_rot(L, -luaL_checkinteger(L, 2)); 159 | } 160 | 161 | 162 | /* 163 | ** get field and width arguments for field-manipulation functions, 164 | ** checking whether they are valid. 165 | ** ('luaL_error' called without 'return' to avoid later warnings about 166 | ** 'width' being used uninitialized.) 167 | */ 168 | static int fieldargs (lua_State *L, int farg, int *width) { 169 | lua_Integer f = luaL_checkinteger(L, farg); 170 | lua_Integer w = luaL_optinteger(L, farg + 1, 1); 171 | luaL_argcheck(L, 0 <= f, farg, "field cannot be negative"); 172 | luaL_argcheck(L, 0 < w, farg + 1, "width must be positive"); 173 | if (f + w > LUA_NBITS) 174 | luaL_error(L, "trying to access non-existent bits"); 175 | *width = (int)w; 176 | return (int)f; 177 | } 178 | 179 | 180 | static int b_extract (lua_State *L) { 181 | int w; 182 | lua_Unsigned r = trim(checkunsigned(L, 1)); 183 | int f = fieldargs(L, 2, &w); 184 | r = (r >> f) & mask(w); 185 | pushunsigned(L, r); 186 | return 1; 187 | } 188 | 189 | 190 | static int b_replace (lua_State *L) { 191 | int w; 192 | lua_Unsigned r = trim(checkunsigned(L, 1)); 193 | lua_Unsigned v = trim(checkunsigned(L, 2)); 194 | int f = fieldargs(L, 3, &w); 195 | lua_Unsigned m = mask(w); 196 | r = (r & ~(m << f)) | ((v & m) << f); 197 | pushunsigned(L, r); 198 | return 1; 199 | } 200 | 201 | 202 | static const luaL_Reg bitlib[] = { 203 | {"arshift", b_arshift}, 204 | {"band", b_and}, 205 | {"bnot", b_not}, 206 | {"bor", b_or}, 207 | {"bxor", b_xor}, 208 | {"btest", b_test}, 209 | {"extract", b_extract}, 210 | {"lrotate", b_lrot}, 211 | {"lshift", b_lshift}, 212 | {"replace", b_replace}, 213 | {"rrotate", b_rrot}, 214 | {"rshift", b_rshift}, 215 | {NULL, NULL} 216 | }; 217 | 218 | 219 | 220 | LUAMOD_API int luaopen_bit32 (lua_State *L) { 221 | luaL_newlib(L, bitlib); 222 | return 1; 223 | } 224 | 225 | 226 | #else /* }{ */ 227 | 228 | 229 | LUAMOD_API int luaopen_bit32 (lua_State *L) { 230 | return luaL_error(L, "library 'bit32' has been deprecated"); 231 | } 232 | 233 | #endif /* } */ 234 | -------------------------------------------------------------------------------- /td_clua/lua/src/lcode.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lcode.h,v 1.64.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Code generator for Lua 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef lcode_h 8 | #define lcode_h 9 | 10 | #include "llex.h" 11 | #include "lobject.h" 12 | #include "lopcodes.h" 13 | #include "lparser.h" 14 | 15 | 16 | /* 17 | ** Marks the end of a patch list. It is an invalid value both as an absolute 18 | ** address, and as a list link (would link an element to itself). 19 | */ 20 | #define NO_JUMP (-1) 21 | 22 | 23 | /* 24 | ** grep "ORDER OPR" if you change these enums (ORDER OP) 25 | */ 26 | typedef enum BinOpr { 27 | OPR_ADD, OPR_SUB, OPR_MUL, OPR_MOD, OPR_POW, 28 | OPR_DIV, 29 | OPR_IDIV, 30 | OPR_BAND, OPR_BOR, OPR_BXOR, 31 | OPR_SHL, OPR_SHR, 32 | OPR_CONCAT, 33 | OPR_EQ, OPR_LT, OPR_LE, 34 | OPR_NE, OPR_GT, OPR_GE, 35 | OPR_AND, OPR_OR, 36 | OPR_NOBINOPR 37 | } BinOpr; 38 | 39 | 40 | typedef enum UnOpr { OPR_MINUS, OPR_BNOT, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr; 41 | 42 | 43 | /* get (pointer to) instruction of given 'expdesc' */ 44 | #define getinstruction(fs,e) ((fs)->f->code[(e)->u.info]) 45 | 46 | #define luaK_codeAsBx(fs,o,A,sBx) luaK_codeABx(fs,o,A,(sBx)+MAXARG_sBx) 47 | 48 | #define luaK_setmultret(fs,e) luaK_setreturns(fs, e, LUA_MULTRET) 49 | 50 | #define luaK_jumpto(fs,t) luaK_patchlist(fs, luaK_jump(fs), t) 51 | 52 | LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx); 53 | LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C); 54 | LUAI_FUNC int luaK_codek (FuncState *fs, int reg, int k); 55 | LUAI_FUNC void luaK_fixline (FuncState *fs, int line); 56 | LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n); 57 | LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n); 58 | LUAI_FUNC void luaK_checkstack (FuncState *fs, int n); 59 | LUAI_FUNC int luaK_stringK (FuncState *fs, TString *s); 60 | LUAI_FUNC int luaK_intK (FuncState *fs, lua_Integer n); 61 | LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e); 62 | LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e); 63 | LUAI_FUNC void luaK_exp2anyregup (FuncState *fs, expdesc *e); 64 | LUAI_FUNC void luaK_exp2nextreg (FuncState *fs, expdesc *e); 65 | LUAI_FUNC void luaK_exp2val (FuncState *fs, expdesc *e); 66 | LUAI_FUNC int luaK_exp2RK (FuncState *fs, expdesc *e); 67 | LUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key); 68 | LUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k); 69 | LUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e); 70 | LUAI_FUNC void luaK_goiffalse (FuncState *fs, expdesc *e); 71 | LUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e); 72 | LUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults); 73 | LUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e); 74 | LUAI_FUNC int luaK_jump (FuncState *fs); 75 | LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret); 76 | LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target); 77 | LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list); 78 | LUAI_FUNC void luaK_patchclose (FuncState *fs, int list, int level); 79 | LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2); 80 | LUAI_FUNC int luaK_getlabel (FuncState *fs); 81 | LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line); 82 | LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v); 83 | LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1, 84 | expdesc *v2, int line); 85 | LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore); 86 | 87 | 88 | #endif 89 | -------------------------------------------------------------------------------- /td_clua/lua/src/lcorolib.c: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lcorolib.c,v 1.10.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Coroutine Library 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #define lcorolib_c 8 | #define LUA_LIB 9 | 10 | #include "lprefix.h" 11 | 12 | 13 | #include 14 | 15 | #include "lua.h" 16 | 17 | #include "lauxlib.h" 18 | #include "lualib.h" 19 | 20 | 21 | static lua_State *getco (lua_State *L) { 22 | lua_State *co = lua_tothread(L, 1); 23 | luaL_argcheck(L, co, 1, "thread expected"); 24 | return co; 25 | } 26 | 27 | 28 | static int auxresume (lua_State *L, lua_State *co, int narg) { 29 | int status; 30 | if (!lua_checkstack(co, narg)) { 31 | lua_pushliteral(L, "too many arguments to resume"); 32 | return -1; /* error flag */ 33 | } 34 | if (lua_status(co) == LUA_OK && lua_gettop(co) == 0) { 35 | lua_pushliteral(L, "cannot resume dead coroutine"); 36 | return -1; /* error flag */ 37 | } 38 | lua_xmove(L, co, narg); 39 | status = lua_resume(co, L, narg); 40 | if (status == LUA_OK || status == LUA_YIELD) { 41 | int nres = lua_gettop(co); 42 | if (!lua_checkstack(L, nres + 1)) { 43 | lua_pop(co, nres); /* remove results anyway */ 44 | lua_pushliteral(L, "too many results to resume"); 45 | return -1; /* error flag */ 46 | } 47 | lua_xmove(co, L, nres); /* move yielded values */ 48 | return nres; 49 | } 50 | else { 51 | lua_xmove(co, L, 1); /* move error message */ 52 | return -1; /* error flag */ 53 | } 54 | } 55 | 56 | 57 | static int luaB_coresume (lua_State *L) { 58 | lua_State *co = getco(L); 59 | int r; 60 | r = auxresume(L, co, lua_gettop(L) - 1); 61 | if (r < 0) { 62 | lua_pushboolean(L, 0); 63 | lua_insert(L, -2); 64 | return 2; /* return false + error message */ 65 | } 66 | else { 67 | lua_pushboolean(L, 1); 68 | lua_insert(L, -(r + 1)); 69 | return r + 1; /* return true + 'resume' returns */ 70 | } 71 | } 72 | 73 | 74 | static int luaB_auxwrap (lua_State *L) { 75 | lua_State *co = lua_tothread(L, lua_upvalueindex(1)); 76 | int r = auxresume(L, co, lua_gettop(L)); 77 | if (r < 0) { 78 | if (lua_type(L, -1) == LUA_TSTRING) { /* error object is a string? */ 79 | luaL_where(L, 1); /* add extra info */ 80 | lua_insert(L, -2); 81 | lua_concat(L, 2); 82 | } 83 | return lua_error(L); /* propagate error */ 84 | } 85 | return r; 86 | } 87 | 88 | 89 | static int luaB_cocreate (lua_State *L) { 90 | lua_State *NL; 91 | luaL_checktype(L, 1, LUA_TFUNCTION); 92 | NL = lua_newthread(L); 93 | lua_pushvalue(L, 1); /* move function to top */ 94 | lua_xmove(L, NL, 1); /* move function from L to NL */ 95 | return 1; 96 | } 97 | 98 | 99 | static int luaB_cowrap (lua_State *L) { 100 | luaB_cocreate(L); 101 | lua_pushcclosure(L, luaB_auxwrap, 1); 102 | return 1; 103 | } 104 | 105 | 106 | static int luaB_yield (lua_State *L) { 107 | return lua_yield(L, lua_gettop(L)); 108 | } 109 | 110 | 111 | static int luaB_costatus (lua_State *L) { 112 | lua_State *co = getco(L); 113 | if (L == co) lua_pushliteral(L, "running"); 114 | else { 115 | switch (lua_status(co)) { 116 | case LUA_YIELD: 117 | lua_pushliteral(L, "suspended"); 118 | break; 119 | case LUA_OK: { 120 | lua_Debug ar; 121 | if (lua_getstack(co, 0, &ar) > 0) /* does it have frames? */ 122 | lua_pushliteral(L, "normal"); /* it is running */ 123 | else if (lua_gettop(co) == 0) 124 | lua_pushliteral(L, "dead"); 125 | else 126 | lua_pushliteral(L, "suspended"); /* initial state */ 127 | break; 128 | } 129 | default: /* some error occurred */ 130 | lua_pushliteral(L, "dead"); 131 | break; 132 | } 133 | } 134 | return 1; 135 | } 136 | 137 | 138 | static int luaB_yieldable (lua_State *L) { 139 | lua_pushboolean(L, lua_isyieldable(L)); 140 | return 1; 141 | } 142 | 143 | 144 | static int luaB_corunning (lua_State *L) { 145 | int ismain = lua_pushthread(L); 146 | lua_pushboolean(L, ismain); 147 | return 2; 148 | } 149 | 150 | 151 | static const luaL_Reg co_funcs[] = { 152 | {"create", luaB_cocreate}, 153 | {"resume", luaB_coresume}, 154 | {"running", luaB_corunning}, 155 | {"status", luaB_costatus}, 156 | {"wrap", luaB_cowrap}, 157 | {"yield", luaB_yield}, 158 | {"isyieldable", luaB_yieldable}, 159 | {NULL, NULL} 160 | }; 161 | 162 | 163 | 164 | LUAMOD_API int luaopen_coroutine (lua_State *L) { 165 | luaL_newlib(L, co_funcs); 166 | return 1; 167 | } 168 | 169 | -------------------------------------------------------------------------------- /td_clua/lua/src/lctype.c: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lctype.c,v 1.12.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** 'ctype' functions for Lua 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #define lctype_c 8 | #define LUA_CORE 9 | 10 | #include "lprefix.h" 11 | 12 | 13 | #include "lctype.h" 14 | 15 | #if !LUA_USE_CTYPE /* { */ 16 | 17 | #include 18 | 19 | LUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = { 20 | 0x00, /* EOZ */ 21 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0. */ 22 | 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, 23 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1. */ 24 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 25 | 0x0c, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, /* 2. */ 26 | 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 27 | 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, /* 3. */ 28 | 0x16, 0x16, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 29 | 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 4. */ 30 | 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 31 | 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 5. */ 32 | 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x05, 33 | 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 6. */ 34 | 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 35 | 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 7. */ 36 | 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x00, 37 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 8. */ 38 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 39 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 9. */ 40 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 41 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a. */ 42 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 43 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* b. */ 44 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 45 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c. */ 46 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 47 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d. */ 48 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 49 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* e. */ 50 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 51 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* f. */ 52 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 53 | }; 54 | 55 | #endif /* } */ 56 | -------------------------------------------------------------------------------- /td_clua/lua/src/lctype.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lctype.h,v 1.12.1.1 2013/04/12 18:48:47 roberto Exp $ 3 | ** 'ctype' functions for Lua 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef lctype_h 8 | #define lctype_h 9 | 10 | #include "lua.h" 11 | 12 | 13 | /* 14 | ** WARNING: the functions defined here do not necessarily correspond 15 | ** to the similar functions in the standard C ctype.h. They are 16 | ** optimized for the specific needs of Lua 17 | */ 18 | 19 | #if !defined(LUA_USE_CTYPE) 20 | 21 | #if 'A' == 65 && '0' == 48 22 | /* ASCII case: can use its own tables; faster and fixed */ 23 | #define LUA_USE_CTYPE 0 24 | #else 25 | /* must use standard C ctype */ 26 | #define LUA_USE_CTYPE 1 27 | #endif 28 | 29 | #endif 30 | 31 | 32 | #if !LUA_USE_CTYPE /* { */ 33 | 34 | #include 35 | 36 | #include "llimits.h" 37 | 38 | 39 | #define ALPHABIT 0 40 | #define DIGITBIT 1 41 | #define PRINTBIT 2 42 | #define SPACEBIT 3 43 | #define XDIGITBIT 4 44 | 45 | 46 | #define MASK(B) (1 << (B)) 47 | 48 | 49 | /* 50 | ** add 1 to char to allow index -1 (EOZ) 51 | */ 52 | #define testprop(c,p) (luai_ctype_[(c)+1] & (p)) 53 | 54 | /* 55 | ** 'lalpha' (Lua alphabetic) and 'lalnum' (Lua alphanumeric) both include '_' 56 | */ 57 | #define lislalpha(c) testprop(c, MASK(ALPHABIT)) 58 | #define lislalnum(c) testprop(c, (MASK(ALPHABIT) | MASK(DIGITBIT))) 59 | #define lisdigit(c) testprop(c, MASK(DIGITBIT)) 60 | #define lisspace(c) testprop(c, MASK(SPACEBIT)) 61 | #define lisprint(c) testprop(c, MASK(PRINTBIT)) 62 | #define lisxdigit(c) testprop(c, MASK(XDIGITBIT)) 63 | 64 | /* 65 | ** this 'ltolower' only works for alphabetic characters 66 | */ 67 | #define ltolower(c) ((c) | ('A' ^ 'a')) 68 | 69 | 70 | /* two more entries for 0 and -1 (EOZ) */ 71 | LUAI_DDEC const lu_byte luai_ctype_[UCHAR_MAX + 2]; 72 | 73 | 74 | #else /* }{ */ 75 | 76 | /* 77 | ** use standard C ctypes 78 | */ 79 | 80 | #include 81 | 82 | 83 | #define lislalpha(c) (isalpha(c) || (c) == '_') 84 | #define lislalnum(c) (isalnum(c) || (c) == '_') 85 | #define lisdigit(c) (isdigit(c)) 86 | #define lisspace(c) (isspace(c)) 87 | #define lisprint(c) (isprint(c)) 88 | #define lisxdigit(c) (isxdigit(c)) 89 | 90 | #define ltolower(c) (tolower(c)) 91 | 92 | #endif /* } */ 93 | 94 | #endif 95 | 96 | -------------------------------------------------------------------------------- /td_clua/lua/src/ldebug.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: ldebug.h,v 2.14.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Auxiliary functions from Debug Interface module 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef ldebug_h 8 | #define ldebug_h 9 | 10 | 11 | #include "lstate.h" 12 | 13 | 14 | #define pcRel(pc, p) (cast(int, (pc) - (p)->code) - 1) 15 | 16 | #define getfuncline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : -1) 17 | 18 | #define resethookcount(L) (L->hookcount = L->basehookcount) 19 | 20 | 21 | LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o, 22 | const char *opname); 23 | LUAI_FUNC l_noret luaG_concaterror (lua_State *L, const TValue *p1, 24 | const TValue *p2); 25 | LUAI_FUNC l_noret luaG_opinterror (lua_State *L, const TValue *p1, 26 | const TValue *p2, 27 | const char *msg); 28 | LUAI_FUNC l_noret luaG_tointerror (lua_State *L, const TValue *p1, 29 | const TValue *p2); 30 | LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1, 31 | const TValue *p2); 32 | LUAI_FUNC l_noret luaG_runerror (lua_State *L, const char *fmt, ...); 33 | LUAI_FUNC const char *luaG_addinfo (lua_State *L, const char *msg, 34 | TString *src, int line); 35 | LUAI_FUNC l_noret luaG_errormsg (lua_State *L); 36 | LUAI_FUNC void luaG_traceexec (lua_State *L); 37 | 38 | 39 | #endif 40 | -------------------------------------------------------------------------------- /td_clua/lua/src/ldo.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: ldo.h,v 2.29.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Stack and Call structure of Lua 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef ldo_h 8 | #define ldo_h 9 | 10 | 11 | #include "lobject.h" 12 | #include "lstate.h" 13 | #include "lzio.h" 14 | 15 | 16 | /* 17 | ** Macro to check stack size and grow stack if needed. Parameters 18 | ** 'pre'/'pos' allow the macro to preserve a pointer into the 19 | ** stack across reallocations, doing the work only when needed. 20 | ** 'condmovestack' is used in heavy tests to force a stack reallocation 21 | ** at every check. 22 | */ 23 | #define luaD_checkstackaux(L,n,pre,pos) \ 24 | if (L->stack_last - L->top <= (n)) \ 25 | { pre; luaD_growstack(L, n); pos; } else { condmovestack(L,pre,pos); } 26 | 27 | /* In general, 'pre'/'pos' are empty (nothing to save) */ 28 | #define luaD_checkstack(L,n) luaD_checkstackaux(L,n,(void)0,(void)0) 29 | 30 | 31 | 32 | #define savestack(L,p) ((char *)(p) - (char *)L->stack) 33 | #define restorestack(L,n) ((TValue *)((char *)L->stack + (n))) 34 | 35 | 36 | /* type of protected functions, to be ran by 'runprotected' */ 37 | typedef void (*Pfunc) (lua_State *L, void *ud); 38 | 39 | LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name, 40 | const char *mode); 41 | LUAI_FUNC void luaD_hook (lua_State *L, int event, int line); 42 | LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults); 43 | LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults); 44 | LUAI_FUNC void luaD_callnoyield (lua_State *L, StkId func, int nResults); 45 | LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u, 46 | ptrdiff_t oldtop, ptrdiff_t ef); 47 | LUAI_FUNC int luaD_poscall (lua_State *L, CallInfo *ci, StkId firstResult, 48 | int nres); 49 | LUAI_FUNC void luaD_reallocstack (lua_State *L, int newsize); 50 | LUAI_FUNC void luaD_growstack (lua_State *L, int n); 51 | LUAI_FUNC void luaD_shrinkstack (lua_State *L); 52 | LUAI_FUNC void luaD_inctop (lua_State *L); 53 | 54 | LUAI_FUNC l_noret luaD_throw (lua_State *L, int errcode); 55 | LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud); 56 | 57 | #endif 58 | 59 | -------------------------------------------------------------------------------- /td_clua/lua/src/ldump.c: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: ldump.c,v 2.37.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** save precompiled Lua chunks 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #define ldump_c 8 | #define LUA_CORE 9 | 10 | #include "lprefix.h" 11 | 12 | 13 | #include 14 | 15 | #include "lua.h" 16 | 17 | #include "lobject.h" 18 | #include "lstate.h" 19 | #include "lundump.h" 20 | 21 | 22 | typedef struct { 23 | lua_State *L; 24 | lua_Writer writer; 25 | void *data; 26 | int strip; 27 | int status; 28 | } DumpState; 29 | 30 | 31 | /* 32 | ** All high-level dumps go through DumpVector; you can change it to 33 | ** change the endianness of the result 34 | */ 35 | #define DumpVector(v,n,D) DumpBlock(v,(n)*sizeof((v)[0]),D) 36 | 37 | #define DumpLiteral(s,D) DumpBlock(s, sizeof(s) - sizeof(char), D) 38 | 39 | 40 | static void DumpBlock (const void *b, size_t size, DumpState *D) { 41 | if (D->status == 0 && size > 0) { 42 | lua_unlock(D->L); 43 | D->status = (*D->writer)(D->L, b, size, D->data); 44 | lua_lock(D->L); 45 | } 46 | } 47 | 48 | 49 | #define DumpVar(x,D) DumpVector(&x,1,D) 50 | 51 | 52 | static void DumpByte (int y, DumpState *D) { 53 | lu_byte x = (lu_byte)y; 54 | DumpVar(x, D); 55 | } 56 | 57 | 58 | static void DumpInt (int x, DumpState *D) { 59 | DumpVar(x, D); 60 | } 61 | 62 | 63 | static void DumpNumber (lua_Number x, DumpState *D) { 64 | DumpVar(x, D); 65 | } 66 | 67 | 68 | static void DumpInteger (lua_Integer x, DumpState *D) { 69 | DumpVar(x, D); 70 | } 71 | 72 | 73 | static void DumpString (const TString *s, DumpState *D) { 74 | if (s == NULL) 75 | DumpByte(0, D); 76 | else { 77 | size_t size = tsslen(s) + 1; /* include trailing '\0' */ 78 | const char *str = getstr(s); 79 | if (size < 0xFF) 80 | DumpByte(cast_int(size), D); 81 | else { 82 | DumpByte(0xFF, D); 83 | DumpVar(size, D); 84 | } 85 | DumpVector(str, size - 1, D); /* no need to save '\0' */ 86 | } 87 | } 88 | 89 | 90 | static void DumpCode (const Proto *f, DumpState *D) { 91 | DumpInt(f->sizecode, D); 92 | DumpVector(f->code, f->sizecode, D); 93 | } 94 | 95 | 96 | static void DumpFunction(const Proto *f, TString *psource, DumpState *D); 97 | 98 | static void DumpConstants (const Proto *f, DumpState *D) { 99 | int i; 100 | int n = f->sizek; 101 | DumpInt(n, D); 102 | for (i = 0; i < n; i++) { 103 | const TValue *o = &f->k[i]; 104 | DumpByte(ttype(o), D); 105 | switch (ttype(o)) { 106 | case LUA_TNIL: 107 | break; 108 | case LUA_TBOOLEAN: 109 | DumpByte(bvalue(o), D); 110 | break; 111 | case LUA_TNUMFLT: 112 | DumpNumber(fltvalue(o), D); 113 | break; 114 | case LUA_TNUMINT: 115 | DumpInteger(ivalue(o), D); 116 | break; 117 | case LUA_TSHRSTR: 118 | case LUA_TLNGSTR: 119 | DumpString(tsvalue(o), D); 120 | break; 121 | default: 122 | lua_assert(0); 123 | } 124 | } 125 | } 126 | 127 | 128 | static void DumpProtos (const Proto *f, DumpState *D) { 129 | int i; 130 | int n = f->sizep; 131 | DumpInt(n, D); 132 | for (i = 0; i < n; i++) 133 | DumpFunction(f->p[i], f->source, D); 134 | } 135 | 136 | 137 | static void DumpUpvalues (const Proto *f, DumpState *D) { 138 | int i, n = f->sizeupvalues; 139 | DumpInt(n, D); 140 | for (i = 0; i < n; i++) { 141 | DumpByte(f->upvalues[i].instack, D); 142 | DumpByte(f->upvalues[i].idx, D); 143 | } 144 | } 145 | 146 | 147 | static void DumpDebug (const Proto *f, DumpState *D) { 148 | int i, n; 149 | n = (D->strip) ? 0 : f->sizelineinfo; 150 | DumpInt(n, D); 151 | DumpVector(f->lineinfo, n, D); 152 | n = (D->strip) ? 0 : f->sizelocvars; 153 | DumpInt(n, D); 154 | for (i = 0; i < n; i++) { 155 | DumpString(f->locvars[i].varname, D); 156 | DumpInt(f->locvars[i].startpc, D); 157 | DumpInt(f->locvars[i].endpc, D); 158 | } 159 | n = (D->strip) ? 0 : f->sizeupvalues; 160 | DumpInt(n, D); 161 | for (i = 0; i < n; i++) 162 | DumpString(f->upvalues[i].name, D); 163 | } 164 | 165 | 166 | static void DumpFunction (const Proto *f, TString *psource, DumpState *D) { 167 | if (D->strip || f->source == psource) 168 | DumpString(NULL, D); /* no debug info or same source as its parent */ 169 | else 170 | DumpString(f->source, D); 171 | DumpInt(f->linedefined, D); 172 | DumpInt(f->lastlinedefined, D); 173 | DumpByte(f->numparams, D); 174 | DumpByte(f->is_vararg, D); 175 | DumpByte(f->maxstacksize, D); 176 | DumpCode(f, D); 177 | DumpConstants(f, D); 178 | DumpUpvalues(f, D); 179 | DumpProtos(f, D); 180 | DumpDebug(f, D); 181 | } 182 | 183 | 184 | static void DumpHeader (DumpState *D) { 185 | DumpLiteral(LUA_SIGNATURE, D); 186 | DumpByte(LUAC_VERSION, D); 187 | DumpByte(LUAC_FORMAT, D); 188 | DumpLiteral(LUAC_DATA, D); 189 | DumpByte(sizeof(int), D); 190 | DumpByte(sizeof(size_t), D); 191 | DumpByte(sizeof(Instruction), D); 192 | DumpByte(sizeof(lua_Integer), D); 193 | DumpByte(sizeof(lua_Number), D); 194 | DumpInteger(LUAC_INT, D); 195 | DumpNumber(LUAC_NUM, D); 196 | } 197 | 198 | 199 | /* 200 | ** dump Lua function as precompiled chunk 201 | */ 202 | int luaU_dump(lua_State *L, const Proto *f, lua_Writer w, void *data, 203 | int strip) { 204 | DumpState D; 205 | D.L = L; 206 | D.writer = w; 207 | D.data = data; 208 | D.strip = strip; 209 | D.status = 0; 210 | DumpHeader(&D); 211 | DumpByte(f->sizeupvalues, &D); 212 | DumpFunction(f, NULL, &D); 213 | return D.status; 214 | } 215 | 216 | -------------------------------------------------------------------------------- /td_clua/lua/src/lfunc.c: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lfunc.c,v 2.45.1.1 2017/04/19 17:39:34 roberto Exp $ 3 | ** Auxiliary functions to manipulate prototypes and closures 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #define lfunc_c 8 | #define LUA_CORE 9 | 10 | #include "lprefix.h" 11 | 12 | 13 | #include 14 | 15 | #include "lua.h" 16 | 17 | #include "lfunc.h" 18 | #include "lgc.h" 19 | #include "lmem.h" 20 | #include "lobject.h" 21 | #include "lstate.h" 22 | 23 | 24 | 25 | CClosure *luaF_newCclosure (lua_State *L, int n) { 26 | GCObject *o = luaC_newobj(L, LUA_TCCL, sizeCclosure(n)); 27 | CClosure *c = gco2ccl(o); 28 | c->nupvalues = cast_byte(n); 29 | return c; 30 | } 31 | 32 | 33 | LClosure *luaF_newLclosure (lua_State *L, int n) { 34 | GCObject *o = luaC_newobj(L, LUA_TLCL, sizeLclosure(n)); 35 | LClosure *c = gco2lcl(o); 36 | c->p = NULL; 37 | c->nupvalues = cast_byte(n); 38 | while (n--) c->upvals[n] = NULL; 39 | return c; 40 | } 41 | 42 | /* 43 | ** fill a closure with new closed upvalues 44 | */ 45 | void luaF_initupvals (lua_State *L, LClosure *cl) { 46 | int i; 47 | for (i = 0; i < cl->nupvalues; i++) { 48 | UpVal *uv = luaM_new(L, UpVal); 49 | uv->refcount = 1; 50 | uv->v = &uv->u.value; /* make it closed */ 51 | setnilvalue(uv->v); 52 | cl->upvals[i] = uv; 53 | } 54 | } 55 | 56 | 57 | UpVal *luaF_findupval (lua_State *L, StkId level) { 58 | UpVal **pp = &L->openupval; 59 | UpVal *p; 60 | UpVal *uv; 61 | lua_assert(isintwups(L) || L->openupval == NULL); 62 | while (*pp != NULL && (p = *pp)->v >= level) { 63 | lua_assert(upisopen(p)); 64 | if (p->v == level) /* found a corresponding upvalue? */ 65 | return p; /* return it */ 66 | pp = &p->u.open.next; 67 | } 68 | /* not found: create a new upvalue */ 69 | uv = luaM_new(L, UpVal); 70 | uv->refcount = 0; 71 | uv->u.open.next = *pp; /* link it to list of open upvalues */ 72 | uv->u.open.touched = 1; 73 | *pp = uv; 74 | uv->v = level; /* current value lives in the stack */ 75 | if (!isintwups(L)) { /* thread not in list of threads with upvalues? */ 76 | L->twups = G(L)->twups; /* link it to the list */ 77 | G(L)->twups = L; 78 | } 79 | return uv; 80 | } 81 | 82 | 83 | void luaF_close (lua_State *L, StkId level) { 84 | UpVal *uv; 85 | while (L->openupval != NULL && (uv = L->openupval)->v >= level) { 86 | lua_assert(upisopen(uv)); 87 | L->openupval = uv->u.open.next; /* remove from 'open' list */ 88 | if (uv->refcount == 0) /* no references? */ 89 | luaM_free(L, uv); /* free upvalue */ 90 | else { 91 | setobj(L, &uv->u.value, uv->v); /* move value to upvalue slot */ 92 | uv->v = &uv->u.value; /* now current value lives here */ 93 | luaC_upvalbarrier(L, uv); 94 | } 95 | } 96 | } 97 | 98 | 99 | Proto *luaF_newproto (lua_State *L) { 100 | GCObject *o = luaC_newobj(L, LUA_TPROTO, sizeof(Proto)); 101 | Proto *f = gco2p(o); 102 | f->k = NULL; 103 | f->sizek = 0; 104 | f->p = NULL; 105 | f->sizep = 0; 106 | f->code = NULL; 107 | f->cache = NULL; 108 | f->sizecode = 0; 109 | f->lineinfo = NULL; 110 | f->sizelineinfo = 0; 111 | f->upvalues = NULL; 112 | f->sizeupvalues = 0; 113 | f->numparams = 0; 114 | f->is_vararg = 0; 115 | f->maxstacksize = 0; 116 | f->locvars = NULL; 117 | f->sizelocvars = 0; 118 | f->linedefined = 0; 119 | f->lastlinedefined = 0; 120 | f->source = NULL; 121 | return f; 122 | } 123 | 124 | 125 | void luaF_freeproto (lua_State *L, Proto *f) { 126 | luaM_freearray(L, f->code, f->sizecode); 127 | luaM_freearray(L, f->p, f->sizep); 128 | luaM_freearray(L, f->k, f->sizek); 129 | luaM_freearray(L, f->lineinfo, f->sizelineinfo); 130 | luaM_freearray(L, f->locvars, f->sizelocvars); 131 | luaM_freearray(L, f->upvalues, f->sizeupvalues); 132 | luaM_free(L, f); 133 | } 134 | 135 | 136 | /* 137 | ** Look for n-th local variable at line 'line' in function 'func'. 138 | ** Returns NULL if not found. 139 | */ 140 | const char *luaF_getlocalname (const Proto *f, int local_number, int pc) { 141 | int i; 142 | for (i = 0; isizelocvars && f->locvars[i].startpc <= pc; i++) { 143 | if (pc < f->locvars[i].endpc) { /* is variable active? */ 144 | local_number--; 145 | if (local_number == 0) 146 | return getstr(f->locvars[i].varname); 147 | } 148 | } 149 | return NULL; /* not found */ 150 | } 151 | 152 | -------------------------------------------------------------------------------- /td_clua/lua/src/lfunc.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lfunc.h,v 2.15.1.1 2017/04/19 17:39:34 roberto Exp $ 3 | ** Auxiliary functions to manipulate prototypes and closures 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef lfunc_h 8 | #define lfunc_h 9 | 10 | 11 | #include "lobject.h" 12 | 13 | 14 | #define sizeCclosure(n) (cast(int, sizeof(CClosure)) + \ 15 | cast(int, sizeof(TValue)*((n)-1))) 16 | 17 | #define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \ 18 | cast(int, sizeof(TValue *)*((n)-1))) 19 | 20 | 21 | /* test whether thread is in 'twups' list */ 22 | #define isintwups(L) (L->twups != L) 23 | 24 | 25 | /* 26 | ** maximum number of upvalues in a closure (both C and Lua). (Value 27 | ** must fit in a VM register.) 28 | */ 29 | #define MAXUPVAL 255 30 | 31 | 32 | /* 33 | ** Upvalues for Lua closures 34 | */ 35 | struct UpVal { 36 | TValue *v; /* points to stack or to its own value */ 37 | lu_mem refcount; /* reference counter */ 38 | union { 39 | struct { /* (when open) */ 40 | UpVal *next; /* linked list */ 41 | int touched; /* mark to avoid cycles with dead threads */ 42 | } open; 43 | TValue value; /* the value (when closed) */ 44 | } u; 45 | }; 46 | 47 | #define upisopen(up) ((up)->v != &(up)->u.value) 48 | 49 | 50 | LUAI_FUNC Proto *luaF_newproto (lua_State *L); 51 | LUAI_FUNC CClosure *luaF_newCclosure (lua_State *L, int nelems); 52 | LUAI_FUNC LClosure *luaF_newLclosure (lua_State *L, int nelems); 53 | LUAI_FUNC void luaF_initupvals (lua_State *L, LClosure *cl); 54 | LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level); 55 | LUAI_FUNC void luaF_close (lua_State *L, StkId level); 56 | LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f); 57 | LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number, 58 | int pc); 59 | 60 | 61 | #endif 62 | -------------------------------------------------------------------------------- /td_clua/lua/src/lgc.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lgc.h,v 2.91.1.1 2017/04/19 17:39:34 roberto Exp $ 3 | ** Garbage Collector 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef lgc_h 8 | #define lgc_h 9 | 10 | 11 | #include "lobject.h" 12 | #include "lstate.h" 13 | 14 | /* 15 | ** Collectable objects may have one of three colors: white, which 16 | ** means the object is not marked; gray, which means the 17 | ** object is marked, but its references may be not marked; and 18 | ** black, which means that the object and all its references are marked. 19 | ** The main invariant of the garbage collector, while marking objects, 20 | ** is that a black object can never point to a white one. Moreover, 21 | ** any gray object must be in a "gray list" (gray, grayagain, weak, 22 | ** allweak, ephemeron) so that it can be visited again before finishing 23 | ** the collection cycle. These lists have no meaning when the invariant 24 | ** is not being enforced (e.g., sweep phase). 25 | */ 26 | 27 | 28 | 29 | /* how much to allocate before next GC step */ 30 | #if !defined(GCSTEPSIZE) 31 | /* ~100 small strings */ 32 | #define GCSTEPSIZE (cast_int(100 * sizeof(TString))) 33 | #endif 34 | 35 | 36 | /* 37 | ** Possible states of the Garbage Collector 38 | */ 39 | #define GCSpropagate 0 40 | #define GCSatomic 1 41 | #define GCSswpallgc 2 42 | #define GCSswpfinobj 3 43 | #define GCSswptobefnz 4 44 | #define GCSswpend 5 45 | #define GCScallfin 6 46 | #define GCSpause 7 47 | 48 | 49 | #define issweepphase(g) \ 50 | (GCSswpallgc <= (g)->gcstate && (g)->gcstate <= GCSswpend) 51 | 52 | 53 | /* 54 | ** macro to tell when main invariant (white objects cannot point to black 55 | ** ones) must be kept. During a collection, the sweep 56 | ** phase may break the invariant, as objects turned white may point to 57 | ** still-black objects. The invariant is restored when sweep ends and 58 | ** all objects are white again. 59 | */ 60 | 61 | #define keepinvariant(g) ((g)->gcstate <= GCSatomic) 62 | 63 | 64 | /* 65 | ** some useful bit tricks 66 | */ 67 | #define resetbits(x,m) ((x) &= cast(lu_byte, ~(m))) 68 | #define setbits(x,m) ((x) |= (m)) 69 | #define testbits(x,m) ((x) & (m)) 70 | #define bitmask(b) (1<<(b)) 71 | #define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2)) 72 | #define l_setbit(x,b) setbits(x, bitmask(b)) 73 | #define resetbit(x,b) resetbits(x, bitmask(b)) 74 | #define testbit(x,b) testbits(x, bitmask(b)) 75 | 76 | 77 | /* Layout for bit use in 'marked' field: */ 78 | #define WHITE0BIT 0 /* object is white (type 0) */ 79 | #define WHITE1BIT 1 /* object is white (type 1) */ 80 | #define BLACKBIT 2 /* object is black */ 81 | #define FINALIZEDBIT 3 /* object has been marked for finalization */ 82 | /* bit 7 is currently used by tests (luaL_checkmemory) */ 83 | 84 | #define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT) 85 | 86 | 87 | #define iswhite(x) testbits((x)->marked, WHITEBITS) 88 | #define isblack(x) testbit((x)->marked, BLACKBIT) 89 | #define isgray(x) /* neither white nor black */ \ 90 | (!testbits((x)->marked, WHITEBITS | bitmask(BLACKBIT))) 91 | 92 | #define tofinalize(x) testbit((x)->marked, FINALIZEDBIT) 93 | 94 | #define otherwhite(g) ((g)->currentwhite ^ WHITEBITS) 95 | #define isdeadm(ow,m) (!(((m) ^ WHITEBITS) & (ow))) 96 | #define isdead(g,v) isdeadm(otherwhite(g), (v)->marked) 97 | 98 | #define changewhite(x) ((x)->marked ^= WHITEBITS) 99 | #define gray2black(x) l_setbit((x)->marked, BLACKBIT) 100 | 101 | #define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS) 102 | 103 | 104 | /* 105 | ** Does one step of collection when debt becomes positive. 'pre'/'pos' 106 | ** allows some adjustments to be done only when needed. macro 107 | ** 'condchangemem' is used only for heavy tests (forcing a full 108 | ** GC cycle on every opportunity) 109 | */ 110 | #define luaC_condGC(L,pre,pos) \ 111 | { if (G(L)->GCdebt > 0) { pre; luaC_step(L); pos;}; \ 112 | condchangemem(L,pre,pos); } 113 | 114 | /* more often than not, 'pre'/'pos' are empty */ 115 | #define luaC_checkGC(L) luaC_condGC(L,(void)0,(void)0) 116 | 117 | 118 | #define luaC_barrier(L,p,v) ( \ 119 | (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) ? \ 120 | luaC_barrier_(L,obj2gco(p),gcvalue(v)) : cast_void(0)) 121 | 122 | #define luaC_barrierback(L,p,v) ( \ 123 | (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) ? \ 124 | luaC_barrierback_(L,p) : cast_void(0)) 125 | 126 | #define luaC_objbarrier(L,p,o) ( \ 127 | (isblack(p) && iswhite(o)) ? \ 128 | luaC_barrier_(L,obj2gco(p),obj2gco(o)) : cast_void(0)) 129 | 130 | #define luaC_upvalbarrier(L,uv) ( \ 131 | (iscollectable((uv)->v) && !upisopen(uv)) ? \ 132 | luaC_upvalbarrier_(L,uv) : cast_void(0)) 133 | 134 | LUAI_FUNC void luaC_fix (lua_State *L, GCObject *o); 135 | LUAI_FUNC void luaC_freeallobjects (lua_State *L); 136 | LUAI_FUNC void luaC_step (lua_State *L); 137 | LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask); 138 | LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency); 139 | LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz); 140 | LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v); 141 | LUAI_FUNC void luaC_barrierback_ (lua_State *L, Table *o); 142 | LUAI_FUNC void luaC_upvalbarrier_ (lua_State *L, UpVal *uv); 143 | LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt); 144 | LUAI_FUNC void luaC_upvdeccount (lua_State *L, UpVal *uv); 145 | 146 | 147 | #endif 148 | -------------------------------------------------------------------------------- /td_clua/lua/src/linit.c: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: linit.c,v 1.39.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Initialization of libraries for lua.c and other clients 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | 8 | #define linit_c 9 | #define LUA_LIB 10 | 11 | /* 12 | ** If you embed Lua in your program and need to open the standard 13 | ** libraries, call luaL_openlibs in your program. If you need a 14 | ** different set of libraries, copy this file to your project and edit 15 | ** it to suit your needs. 16 | ** 17 | ** You can also *preload* libraries, so that a later 'require' can 18 | ** open the library, which is already linked to the application. 19 | ** For that, do the following code: 20 | ** 21 | ** luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); 22 | ** lua_pushcfunction(L, luaopen_modname); 23 | ** lua_setfield(L, -2, modname); 24 | ** lua_pop(L, 1); // remove PRELOAD table 25 | */ 26 | 27 | #include "lprefix.h" 28 | 29 | 30 | #include 31 | 32 | #include "lua.h" 33 | 34 | #include "lualib.h" 35 | #include "lauxlib.h" 36 | 37 | 38 | /* 39 | ** these libs are loaded by lua.c and are readily available to any Lua 40 | ** program 41 | */ 42 | static const luaL_Reg loadedlibs[] = { 43 | {"_G", luaopen_base}, 44 | {LUA_LOADLIBNAME, luaopen_package}, 45 | {LUA_COLIBNAME, luaopen_coroutine}, 46 | {LUA_TABLIBNAME, luaopen_table}, 47 | {LUA_IOLIBNAME, luaopen_io}, 48 | {LUA_OSLIBNAME, luaopen_os}, 49 | {LUA_STRLIBNAME, luaopen_string}, 50 | {LUA_MATHLIBNAME, luaopen_math}, 51 | {LUA_UTF8LIBNAME, luaopen_utf8}, 52 | {LUA_DBLIBNAME, luaopen_debug}, 53 | #if defined(LUA_COMPAT_BITLIB) 54 | {LUA_BITLIBNAME, luaopen_bit32}, 55 | #endif 56 | {NULL, NULL} 57 | }; 58 | 59 | 60 | LUALIB_API void luaL_openlibs (lua_State *L) { 61 | const luaL_Reg *lib; 62 | /* "require" functions from 'loadedlibs' and set results to global table */ 63 | for (lib = loadedlibs; lib->func; lib++) { 64 | luaL_requiref(L, lib->name, lib->func, 1); 65 | lua_pop(L, 1); /* remove lib */ 66 | } 67 | } 68 | 69 | -------------------------------------------------------------------------------- /td_clua/lua/src/llex.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: llex.h,v 1.79.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Lexical Analyzer 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef llex_h 8 | #define llex_h 9 | 10 | #include "lobject.h" 11 | #include "lzio.h" 12 | 13 | 14 | #define FIRST_RESERVED 257 15 | 16 | 17 | #if !defined(LUA_ENV) 18 | #define LUA_ENV "_ENV" 19 | #endif 20 | 21 | 22 | /* 23 | * WARNING: if you change the order of this enumeration, 24 | * grep "ORDER RESERVED" 25 | */ 26 | enum RESERVED { 27 | /* terminal symbols denoted by reserved words */ 28 | TK_AND = FIRST_RESERVED, TK_BREAK, 29 | TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION, 30 | TK_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT, 31 | TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE, 32 | /* other terminal symbols */ 33 | TK_IDIV, TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, 34 | TK_SHL, TK_SHR, 35 | TK_DBCOLON, TK_EOS, 36 | TK_FLT, TK_INT, TK_NAME, TK_STRING 37 | }; 38 | 39 | /* number of reserved words */ 40 | #define NUM_RESERVED (cast(int, TK_WHILE-FIRST_RESERVED+1)) 41 | 42 | 43 | typedef union { 44 | lua_Number r; 45 | lua_Integer i; 46 | TString *ts; 47 | } SemInfo; /* semantics information */ 48 | 49 | 50 | typedef struct Token { 51 | int token; 52 | SemInfo seminfo; 53 | } Token; 54 | 55 | 56 | /* state of the lexer plus state of the parser when shared by all 57 | functions */ 58 | typedef struct LexState { 59 | int current; /* current character (charint) */ 60 | int linenumber; /* input line counter */ 61 | int lastline; /* line of last token 'consumed' */ 62 | Token t; /* current token */ 63 | Token lookahead; /* look ahead token */ 64 | struct FuncState *fs; /* current function (parser) */ 65 | struct lua_State *L; 66 | ZIO *z; /* input stream */ 67 | Mbuffer *buff; /* buffer for tokens */ 68 | Table *h; /* to avoid collection/reuse strings */ 69 | struct Dyndata *dyd; /* dynamic structures used by the parser */ 70 | TString *source; /* current source name */ 71 | TString *envn; /* environment variable name */ 72 | } LexState; 73 | 74 | 75 | LUAI_FUNC void luaX_init (lua_State *L); 76 | LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, 77 | TString *source, int firstchar); 78 | LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l); 79 | LUAI_FUNC void luaX_next (LexState *ls); 80 | LUAI_FUNC int luaX_lookahead (LexState *ls); 81 | LUAI_FUNC l_noret luaX_syntaxerror (LexState *ls, const char *s); 82 | LUAI_FUNC const char *luaX_token2str (LexState *ls, int token); 83 | 84 | 85 | #endif 86 | -------------------------------------------------------------------------------- /td_clua/lua/src/lmem.c: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lmem.c,v 1.91.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Interface to Memory Manager 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #define lmem_c 8 | #define LUA_CORE 9 | 10 | #include "lprefix.h" 11 | 12 | 13 | #include 14 | 15 | #include "lua.h" 16 | 17 | #include "ldebug.h" 18 | #include "ldo.h" 19 | #include "lgc.h" 20 | #include "lmem.h" 21 | #include "lobject.h" 22 | #include "lstate.h" 23 | 24 | 25 | 26 | /* 27 | ** About the realloc function: 28 | ** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize); 29 | ** ('osize' is the old size, 'nsize' is the new size) 30 | ** 31 | ** * frealloc(ud, NULL, x, s) creates a new block of size 's' (no 32 | ** matter 'x'). 33 | ** 34 | ** * frealloc(ud, p, x, 0) frees the block 'p' 35 | ** (in this specific case, frealloc must return NULL); 36 | ** particularly, frealloc(ud, NULL, 0, 0) does nothing 37 | ** (which is equivalent to free(NULL) in ISO C) 38 | ** 39 | ** frealloc returns NULL if it cannot create or reallocate the area 40 | ** (any reallocation to an equal or smaller size cannot fail!) 41 | */ 42 | 43 | 44 | 45 | #define MINSIZEARRAY 4 46 | 47 | 48 | void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems, 49 | int limit, const char *what) { 50 | void *newblock; 51 | int newsize; 52 | if (*size >= limit/2) { /* cannot double it? */ 53 | if (*size >= limit) /* cannot grow even a little? */ 54 | luaG_runerror(L, "too many %s (limit is %d)", what, limit); 55 | newsize = limit; /* still have at least one free place */ 56 | } 57 | else { 58 | newsize = (*size)*2; 59 | if (newsize < MINSIZEARRAY) 60 | newsize = MINSIZEARRAY; /* minimum size */ 61 | } 62 | newblock = luaM_reallocv(L, block, *size, newsize, size_elems); 63 | *size = newsize; /* update only when everything else is OK */ 64 | return newblock; 65 | } 66 | 67 | 68 | l_noret luaM_toobig (lua_State *L) { 69 | luaG_runerror(L, "memory allocation error: block too big"); 70 | } 71 | 72 | 73 | 74 | /* 75 | ** generic allocation routine. 76 | */ 77 | void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { 78 | void *newblock; 79 | global_State *g = G(L); 80 | size_t realosize = (block) ? osize : 0; 81 | lua_assert((realosize == 0) == (block == NULL)); 82 | #if defined(HARDMEMTESTS) 83 | if (nsize > realosize && g->gcrunning) 84 | luaC_fullgc(L, 1); /* force a GC whenever possible */ 85 | #endif 86 | newblock = (*g->frealloc)(g->ud, block, osize, nsize); 87 | if (newblock == NULL && nsize > 0) { 88 | lua_assert(nsize > realosize); /* cannot fail when shrinking a block */ 89 | if (g->version) { /* is state fully built? */ 90 | luaC_fullgc(L, 1); /* try to free some memory... */ 91 | newblock = (*g->frealloc)(g->ud, block, osize, nsize); /* try again */ 92 | } 93 | if (newblock == NULL) 94 | luaD_throw(L, LUA_ERRMEM); 95 | } 96 | lua_assert((nsize == 0) == (newblock == NULL)); 97 | g->GCdebt = (g->GCdebt + nsize) - realosize; 98 | return newblock; 99 | } 100 | 101 | -------------------------------------------------------------------------------- /td_clua/lua/src/lmem.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lmem.h,v 1.43.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Interface to Memory Manager 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef lmem_h 8 | #define lmem_h 9 | 10 | 11 | #include 12 | 13 | #include "llimits.h" 14 | #include "lua.h" 15 | 16 | 17 | /* 18 | ** This macro reallocs a vector 'b' from 'on' to 'n' elements, where 19 | ** each element has size 'e'. In case of arithmetic overflow of the 20 | ** product 'n'*'e', it raises an error (calling 'luaM_toobig'). Because 21 | ** 'e' is always constant, it avoids the runtime division MAX_SIZET/(e). 22 | ** 23 | ** (The macro is somewhat complex to avoid warnings: The 'sizeof' 24 | ** comparison avoids a runtime comparison when overflow cannot occur. 25 | ** The compiler should be able to optimize the real test by itself, but 26 | ** when it does it, it may give a warning about "comparison is always 27 | ** false due to limited range of data type"; the +1 tricks the compiler, 28 | ** avoiding this warning but also this optimization.) 29 | */ 30 | #define luaM_reallocv(L,b,on,n,e) \ 31 | (((sizeof(n) >= sizeof(size_t) && cast(size_t, (n)) + 1 > MAX_SIZET/(e)) \ 32 | ? luaM_toobig(L) : cast_void(0)) , \ 33 | luaM_realloc_(L, (b), (on)*(e), (n)*(e))) 34 | 35 | /* 36 | ** Arrays of chars do not need any test 37 | */ 38 | #define luaM_reallocvchar(L,b,on,n) \ 39 | cast(char *, luaM_realloc_(L, (b), (on)*sizeof(char), (n)*sizeof(char))) 40 | 41 | #define luaM_freemem(L, b, s) luaM_realloc_(L, (b), (s), 0) 42 | #define luaM_free(L, b) luaM_realloc_(L, (b), sizeof(*(b)), 0) 43 | #define luaM_freearray(L, b, n) luaM_realloc_(L, (b), (n)*sizeof(*(b)), 0) 44 | 45 | #define luaM_malloc(L,s) luaM_realloc_(L, NULL, 0, (s)) 46 | #define luaM_new(L,t) cast(t *, luaM_malloc(L, sizeof(t))) 47 | #define luaM_newvector(L,n,t) \ 48 | cast(t *, luaM_reallocv(L, NULL, 0, n, sizeof(t))) 49 | 50 | #define luaM_newobject(L,tag,s) luaM_realloc_(L, NULL, tag, (s)) 51 | 52 | #define luaM_growvector(L,v,nelems,size,t,limit,e) \ 53 | if ((nelems)+1 > (size)) \ 54 | ((v)=cast(t *, luaM_growaux_(L,v,&(size),sizeof(t),limit,e))) 55 | 56 | #define luaM_reallocvector(L, v,oldn,n,t) \ 57 | ((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t)))) 58 | 59 | LUAI_FUNC l_noret luaM_toobig (lua_State *L); 60 | 61 | /* not to be called directly */ 62 | LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize, 63 | size_t size); 64 | LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int *size, 65 | size_t size_elem, int limit, 66 | const char *what); 67 | 68 | #endif 69 | 70 | -------------------------------------------------------------------------------- /td_clua/lua/src/lopcodes.c: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lopcodes.c,v 1.55.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Opcodes for Lua virtual machine 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #define lopcodes_c 8 | #define LUA_CORE 9 | 10 | #include "lprefix.h" 11 | 12 | 13 | #include 14 | 15 | #include "lopcodes.h" 16 | 17 | 18 | /* ORDER OP */ 19 | 20 | LUAI_DDEF const char *const luaP_opnames[NUM_OPCODES+1] = { 21 | "MOVE", 22 | "LOADK", 23 | "LOADKX", 24 | "LOADBOOL", 25 | "LOADNIL", 26 | "GETUPVAL", 27 | "GETTABUP", 28 | "GETTABLE", 29 | "SETTABUP", 30 | "SETUPVAL", 31 | "SETTABLE", 32 | "NEWTABLE", 33 | "SELF", 34 | "ADD", 35 | "SUB", 36 | "MUL", 37 | "MOD", 38 | "POW", 39 | "DIV", 40 | "IDIV", 41 | "BAND", 42 | "BOR", 43 | "BXOR", 44 | "SHL", 45 | "SHR", 46 | "UNM", 47 | "BNOT", 48 | "NOT", 49 | "LEN", 50 | "CONCAT", 51 | "JMP", 52 | "EQ", 53 | "LT", 54 | "LE", 55 | "TEST", 56 | "TESTSET", 57 | "CALL", 58 | "TAILCALL", 59 | "RETURN", 60 | "FORLOOP", 61 | "FORPREP", 62 | "TFORCALL", 63 | "TFORLOOP", 64 | "SETLIST", 65 | "CLOSURE", 66 | "VARARG", 67 | "EXTRAARG", 68 | NULL 69 | }; 70 | 71 | 72 | #define opmode(t,a,b,c,m) (((t)<<7) | ((a)<<6) | ((b)<<4) | ((c)<<2) | (m)) 73 | 74 | LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = { 75 | /* T A B C mode opcode */ 76 | opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_MOVE */ 77 | ,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_LOADK */ 78 | ,opmode(0, 1, OpArgN, OpArgN, iABx) /* OP_LOADKX */ 79 | ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_LOADBOOL */ 80 | ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_LOADNIL */ 81 | ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_GETUPVAL */ 82 | ,opmode(0, 1, OpArgU, OpArgK, iABC) /* OP_GETTABUP */ 83 | ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_GETTABLE */ 84 | ,opmode(0, 0, OpArgK, OpArgK, iABC) /* OP_SETTABUP */ 85 | ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_SETUPVAL */ 86 | ,opmode(0, 0, OpArgK, OpArgK, iABC) /* OP_SETTABLE */ 87 | ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_NEWTABLE */ 88 | ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_SELF */ 89 | ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_ADD */ 90 | ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SUB */ 91 | ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MUL */ 92 | ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MOD */ 93 | ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_POW */ 94 | ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_DIV */ 95 | ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_IDIV */ 96 | ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BAND */ 97 | ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BOR */ 98 | ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BXOR */ 99 | ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SHL */ 100 | ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SHR */ 101 | ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_UNM */ 102 | ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_BNOT */ 103 | ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_NOT */ 104 | ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LEN */ 105 | ,opmode(0, 1, OpArgR, OpArgR, iABC) /* OP_CONCAT */ 106 | ,opmode(0, 0, OpArgR, OpArgN, iAsBx) /* OP_JMP */ 107 | ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_EQ */ 108 | ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LT */ 109 | ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LE */ 110 | ,opmode(1, 0, OpArgN, OpArgU, iABC) /* OP_TEST */ 111 | ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TESTSET */ 112 | ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_CALL */ 113 | ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_TAILCALL */ 114 | ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_RETURN */ 115 | ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORLOOP */ 116 | ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORPREP */ 117 | ,opmode(0, 0, OpArgN, OpArgU, iABC) /* OP_TFORCALL */ 118 | ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_TFORLOOP */ 119 | ,opmode(0, 0, OpArgU, OpArgU, iABC) /* OP_SETLIST */ 120 | ,opmode(0, 1, OpArgU, OpArgN, iABx) /* OP_CLOSURE */ 121 | ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_VARARG */ 122 | ,opmode(0, 0, OpArgU, OpArgU, iAx) /* OP_EXTRAARG */ 123 | }; 124 | 125 | -------------------------------------------------------------------------------- /td_clua/lua/src/lparser.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lparser.h,v 1.76.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Lua Parser 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef lparser_h 8 | #define lparser_h 9 | 10 | #include "llimits.h" 11 | #include "lobject.h" 12 | #include "lzio.h" 13 | 14 | 15 | /* 16 | ** Expression and variable descriptor. 17 | ** Code generation for variables and expressions can be delayed to allow 18 | ** optimizations; An 'expdesc' structure describes a potentially-delayed 19 | ** variable/expression. It has a description of its "main" value plus a 20 | ** list of conditional jumps that can also produce its value (generated 21 | ** by short-circuit operators 'and'/'or'). 22 | */ 23 | 24 | /* kinds of variables/expressions */ 25 | typedef enum { 26 | VVOID, /* when 'expdesc' describes the last expression a list, 27 | this kind means an empty list (so, no expression) */ 28 | VNIL, /* constant nil */ 29 | VTRUE, /* constant true */ 30 | VFALSE, /* constant false */ 31 | VK, /* constant in 'k'; info = index of constant in 'k' */ 32 | VKFLT, /* floating constant; nval = numerical float value */ 33 | VKINT, /* integer constant; nval = numerical integer value */ 34 | VNONRELOC, /* expression has its value in a fixed register; 35 | info = result register */ 36 | VLOCAL, /* local variable; info = local register */ 37 | VUPVAL, /* upvalue variable; info = index of upvalue in 'upvalues' */ 38 | VINDEXED, /* indexed variable; 39 | ind.vt = whether 't' is register or upvalue; 40 | ind.t = table register or upvalue; 41 | ind.idx = key's R/K index */ 42 | VJMP, /* expression is a test/comparison; 43 | info = pc of corresponding jump instruction */ 44 | VRELOCABLE, /* expression can put result in any register; 45 | info = instruction pc */ 46 | VCALL, /* expression is a function call; info = instruction pc */ 47 | VVARARG /* vararg expression; info = instruction pc */ 48 | } expkind; 49 | 50 | 51 | #define vkisvar(k) (VLOCAL <= (k) && (k) <= VINDEXED) 52 | #define vkisinreg(k) ((k) == VNONRELOC || (k) == VLOCAL) 53 | 54 | typedef struct expdesc { 55 | expkind k; 56 | union { 57 | lua_Integer ival; /* for VKINT */ 58 | lua_Number nval; /* for VKFLT */ 59 | int info; /* for generic use */ 60 | struct { /* for indexed variables (VINDEXED) */ 61 | short idx; /* index (R/K) */ 62 | lu_byte t; /* table (register or upvalue) */ 63 | lu_byte vt; /* whether 't' is register (VLOCAL) or upvalue (VUPVAL) */ 64 | } ind; 65 | } u; 66 | int t; /* patch list of 'exit when true' */ 67 | int f; /* patch list of 'exit when false' */ 68 | } expdesc; 69 | 70 | 71 | /* description of active local variable */ 72 | typedef struct Vardesc { 73 | short idx; /* variable index in stack */ 74 | } Vardesc; 75 | 76 | 77 | /* description of pending goto statements and label statements */ 78 | typedef struct Labeldesc { 79 | TString *name; /* label identifier */ 80 | int pc; /* position in code */ 81 | int line; /* line where it appeared */ 82 | lu_byte nactvar; /* local level where it appears in current block */ 83 | } Labeldesc; 84 | 85 | 86 | /* list of labels or gotos */ 87 | typedef struct Labellist { 88 | Labeldesc *arr; /* array */ 89 | int n; /* number of entries in use */ 90 | int size; /* array size */ 91 | } Labellist; 92 | 93 | 94 | /* dynamic structures used by the parser */ 95 | typedef struct Dyndata { 96 | struct { /* list of active local variables */ 97 | Vardesc *arr; 98 | int n; 99 | int size; 100 | } actvar; 101 | Labellist gt; /* list of pending gotos */ 102 | Labellist label; /* list of active labels */ 103 | } Dyndata; 104 | 105 | 106 | /* control of blocks */ 107 | struct BlockCnt; /* defined in lparser.c */ 108 | 109 | 110 | /* state needed to generate code for a given function */ 111 | typedef struct FuncState { 112 | Proto *f; /* current function header */ 113 | struct FuncState *prev; /* enclosing function */ 114 | struct LexState *ls; /* lexical state */ 115 | struct BlockCnt *bl; /* chain of current blocks */ 116 | int pc; /* next position to code (equivalent to 'ncode') */ 117 | int lasttarget; /* 'label' of last 'jump label' */ 118 | int jpc; /* list of pending jumps to 'pc' */ 119 | int nk; /* number of elements in 'k' */ 120 | int np; /* number of elements in 'p' */ 121 | int firstlocal; /* index of first local var (in Dyndata array) */ 122 | short nlocvars; /* number of elements in 'f->locvars' */ 123 | lu_byte nactvar; /* number of active local variables */ 124 | lu_byte nups; /* number of upvalues */ 125 | lu_byte freereg; /* first free register */ 126 | } FuncState; 127 | 128 | 129 | LUAI_FUNC LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, 130 | Dyndata *dyd, const char *name, int firstchar); 131 | 132 | 133 | #endif 134 | -------------------------------------------------------------------------------- /td_clua/lua/src/lprefix.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lprefix.h,v 1.2.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Definitions for Lua code that must come before any other header file 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef lprefix_h 8 | #define lprefix_h 9 | 10 | 11 | /* 12 | ** Allows POSIX/XSI stuff 13 | */ 14 | #if !defined(LUA_USE_C89) /* { */ 15 | 16 | #if !defined(_XOPEN_SOURCE) 17 | #define _XOPEN_SOURCE 600 18 | #elif _XOPEN_SOURCE == 0 19 | #undef _XOPEN_SOURCE /* use -D_XOPEN_SOURCE=0 to undefine it */ 20 | #endif 21 | 22 | /* 23 | ** Allows manipulation of large files in gcc and some other compilers 24 | */ 25 | #if !defined(LUA_32BITS) && !defined(_FILE_OFFSET_BITS) 26 | #define _LARGEFILE_SOURCE 1 27 | #define _FILE_OFFSET_BITS 64 28 | #endif 29 | 30 | #endif /* } */ 31 | 32 | 33 | /* 34 | ** Windows stuff 35 | */ 36 | #if defined(_WIN32) /* { */ 37 | 38 | #if !defined(_CRT_SECURE_NO_WARNINGS) 39 | #define _CRT_SECURE_NO_WARNINGS /* avoid warnings about ISO C functions */ 40 | #endif 41 | 42 | #endif /* } */ 43 | 44 | #endif 45 | 46 | -------------------------------------------------------------------------------- /td_clua/lua/src/lstring.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lstring.h,v 1.61.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** String table (keep all strings handled by Lua) 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef lstring_h 8 | #define lstring_h 9 | 10 | #include "lgc.h" 11 | #include "lobject.h" 12 | #include "lstate.h" 13 | 14 | 15 | #define sizelstring(l) (sizeof(union UTString) + ((l) + 1) * sizeof(char)) 16 | 17 | #define sizeludata(l) (sizeof(union UUdata) + (l)) 18 | #define sizeudata(u) sizeludata((u)->len) 19 | 20 | #define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \ 21 | (sizeof(s)/sizeof(char))-1)) 22 | 23 | 24 | /* 25 | ** test whether a string is a reserved word 26 | */ 27 | #define isreserved(s) ((s)->tt == LUA_TSHRSTR && (s)->extra > 0) 28 | 29 | 30 | /* 31 | ** equality for short strings, which are always internalized 32 | */ 33 | #define eqshrstr(a,b) check_exp((a)->tt == LUA_TSHRSTR, (a) == (b)) 34 | 35 | 36 | LUAI_FUNC unsigned int luaS_hash (const char *str, size_t l, unsigned int seed); 37 | LUAI_FUNC unsigned int luaS_hashlongstr (TString *ts); 38 | LUAI_FUNC int luaS_eqlngstr (TString *a, TString *b); 39 | LUAI_FUNC void luaS_resize (lua_State *L, int newsize); 40 | LUAI_FUNC void luaS_clearcache (global_State *g); 41 | LUAI_FUNC void luaS_init (lua_State *L); 42 | LUAI_FUNC void luaS_remove (lua_State *L, TString *ts); 43 | LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s); 44 | LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l); 45 | LUAI_FUNC TString *luaS_new (lua_State *L, const char *str); 46 | LUAI_FUNC TString *luaS_createlngstrobj (lua_State *L, size_t l); 47 | 48 | 49 | #endif 50 | -------------------------------------------------------------------------------- /td_clua/lua/src/ltable.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: ltable.h,v 2.23.1.2 2018/05/24 19:39:05 roberto Exp $ 3 | ** Lua tables (hash) 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef ltable_h 8 | #define ltable_h 9 | 10 | #include "lobject.h" 11 | 12 | 13 | #define gnode(t,i) (&(t)->node[i]) 14 | #define gval(n) (&(n)->i_val) 15 | #define gnext(n) ((n)->i_key.nk.next) 16 | 17 | 18 | /* 'const' to avoid wrong writings that can mess up field 'next' */ 19 | #define gkey(n) cast(const TValue*, (&(n)->i_key.tvk)) 20 | 21 | /* 22 | ** writable version of 'gkey'; allows updates to individual fields, 23 | ** but not to the whole (which has incompatible type) 24 | */ 25 | #define wgkey(n) (&(n)->i_key.nk) 26 | 27 | #define invalidateTMcache(t) ((t)->flags = 0) 28 | 29 | 30 | /* true when 't' is using 'dummynode' as its hash part */ 31 | #define isdummy(t) ((t)->lastfree == NULL) 32 | 33 | 34 | /* allocated size for hash nodes */ 35 | #define allocsizenode(t) (isdummy(t) ? 0 : sizenode(t)) 36 | 37 | 38 | /* returns the key, given the value of a table entry */ 39 | #define keyfromval(v) \ 40 | (gkey(cast(Node *, cast(char *, (v)) - offsetof(Node, i_val)))) 41 | 42 | 43 | LUAI_FUNC const TValue *luaH_getint (Table *t, lua_Integer key); 44 | LUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key, 45 | TValue *value); 46 | LUAI_FUNC const TValue *luaH_getshortstr (Table *t, TString *key); 47 | LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key); 48 | LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key); 49 | LUAI_FUNC TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key); 50 | LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key); 51 | LUAI_FUNC Table *luaH_new (lua_State *L); 52 | LUAI_FUNC void luaH_resize (lua_State *L, Table *t, unsigned int nasize, 53 | unsigned int nhsize); 54 | LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize); 55 | LUAI_FUNC void luaH_free (lua_State *L, Table *t); 56 | LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key); 57 | LUAI_FUNC lua_Unsigned luaH_getn (Table *t); 58 | 59 | 60 | #if defined(LUA_DEBUG) 61 | LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key); 62 | LUAI_FUNC int luaH_isdummy (const Table *t); 63 | #endif 64 | 65 | 66 | #endif 67 | -------------------------------------------------------------------------------- /td_clua/lua/src/ltm.c: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: ltm.c,v 2.38.1.1 2017/04/19 17:39:34 roberto Exp $ 3 | ** Tag methods 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #define ltm_c 8 | #define LUA_CORE 9 | 10 | #include "lprefix.h" 11 | 12 | 13 | #include 14 | 15 | #include "lua.h" 16 | 17 | #include "ldebug.h" 18 | #include "ldo.h" 19 | #include "lobject.h" 20 | #include "lstate.h" 21 | #include "lstring.h" 22 | #include "ltable.h" 23 | #include "ltm.h" 24 | #include "lvm.h" 25 | 26 | 27 | static const char udatatypename[] = "userdata"; 28 | 29 | LUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTAGS] = { 30 | "no value", 31 | "nil", "boolean", udatatypename, "number", 32 | "string", "table", "function", udatatypename, "thread", 33 | "proto" /* this last case is used for tests only */ 34 | }; 35 | 36 | 37 | void luaT_init (lua_State *L) { 38 | static const char *const luaT_eventname[] = { /* ORDER TM */ 39 | "__index", "__newindex", 40 | "__gc", "__mode", "__len", "__eq", 41 | "__add", "__sub", "__mul", "__mod", "__pow", 42 | "__div", "__idiv", 43 | "__band", "__bor", "__bxor", "__shl", "__shr", 44 | "__unm", "__bnot", "__lt", "__le", 45 | "__concat", "__call" 46 | }; 47 | int i; 48 | for (i=0; itmname[i] = luaS_new(L, luaT_eventname[i]); 50 | luaC_fix(L, obj2gco(G(L)->tmname[i])); /* never collect these names */ 51 | } 52 | } 53 | 54 | 55 | /* 56 | ** function to be used with macro "fasttm": optimized for absence of 57 | ** tag methods 58 | */ 59 | const TValue *luaT_gettm (Table *events, TMS event, TString *ename) { 60 | const TValue *tm = luaH_getshortstr(events, ename); 61 | lua_assert(event <= TM_EQ); 62 | if (ttisnil(tm)) { /* no tag method? */ 63 | events->flags |= cast_byte(1u<metatable; 75 | break; 76 | case LUA_TUSERDATA: 77 | mt = uvalue(o)->metatable; 78 | break; 79 | default: 80 | mt = G(L)->mt[ttnov(o)]; 81 | } 82 | return (mt ? luaH_getshortstr(mt, G(L)->tmname[event]) : luaO_nilobject); 83 | } 84 | 85 | 86 | /* 87 | ** Return the name of the type of an object. For tables and userdata 88 | ** with metatable, use their '__name' metafield, if present. 89 | */ 90 | const char *luaT_objtypename (lua_State *L, const TValue *o) { 91 | Table *mt; 92 | if ((ttistable(o) && (mt = hvalue(o)->metatable) != NULL) || 93 | (ttisfulluserdata(o) && (mt = uvalue(o)->metatable) != NULL)) { 94 | const TValue *name = luaH_getshortstr(mt, luaS_new(L, "__name")); 95 | if (ttisstring(name)) /* is '__name' a string? */ 96 | return getstr(tsvalue(name)); /* use it as type name */ 97 | } 98 | return ttypename(ttnov(o)); /* else use standard type name */ 99 | } 100 | 101 | 102 | void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1, 103 | const TValue *p2, TValue *p3, int hasres) { 104 | ptrdiff_t result = savestack(L, p3); 105 | StkId func = L->top; 106 | setobj2s(L, func, f); /* push function (assume EXTRA_STACK) */ 107 | setobj2s(L, func + 1, p1); /* 1st argument */ 108 | setobj2s(L, func + 2, p2); /* 2nd argument */ 109 | L->top += 3; 110 | if (!hasres) /* no result? 'p3' is third argument */ 111 | setobj2s(L, L->top++, p3); /* 3rd argument */ 112 | /* metamethod may yield only when called from Lua code */ 113 | if (isLua(L->ci)) 114 | luaD_call(L, func, hasres); 115 | else 116 | luaD_callnoyield(L, func, hasres); 117 | if (hasres) { /* if has result, move it to its place */ 118 | p3 = restorestack(L, result); 119 | setobjs2s(L, p3, --L->top); 120 | } 121 | } 122 | 123 | 124 | int luaT_callbinTM (lua_State *L, const TValue *p1, const TValue *p2, 125 | StkId res, TMS event) { 126 | const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */ 127 | if (ttisnil(tm)) 128 | tm = luaT_gettmbyobj(L, p2, event); /* try second operand */ 129 | if (ttisnil(tm)) return 0; 130 | luaT_callTM(L, tm, p1, p2, res, 1); 131 | return 1; 132 | } 133 | 134 | 135 | void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2, 136 | StkId res, TMS event) { 137 | if (!luaT_callbinTM(L, p1, p2, res, event)) { 138 | switch (event) { 139 | case TM_CONCAT: 140 | luaG_concaterror(L, p1, p2); 141 | /* call never returns, but to avoid warnings: *//* FALLTHROUGH */ 142 | case TM_BAND: case TM_BOR: case TM_BXOR: 143 | case TM_SHL: case TM_SHR: case TM_BNOT: { 144 | lua_Number dummy; 145 | if (tonumber(p1, &dummy) && tonumber(p2, &dummy)) 146 | luaG_tointerror(L, p1, p2); 147 | else 148 | luaG_opinterror(L, p1, p2, "perform bitwise operation on"); 149 | } 150 | /* calls never return, but to avoid warnings: *//* FALLTHROUGH */ 151 | default: 152 | luaG_opinterror(L, p1, p2, "perform arithmetic on"); 153 | } 154 | } 155 | } 156 | 157 | 158 | int luaT_callorderTM (lua_State *L, const TValue *p1, const TValue *p2, 159 | TMS event) { 160 | if (!luaT_callbinTM(L, p1, p2, L->top, event)) 161 | return -1; /* no metamethod */ 162 | else 163 | return !l_isfalse(L->top); 164 | } 165 | 166 | -------------------------------------------------------------------------------- /td_clua/lua/src/ltm.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: ltm.h,v 2.22.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Tag methods 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef ltm_h 8 | #define ltm_h 9 | 10 | 11 | #include "lobject.h" 12 | 13 | 14 | /* 15 | * WARNING: if you change the order of this enumeration, 16 | * grep "ORDER TM" and "ORDER OP" 17 | */ 18 | typedef enum { 19 | TM_INDEX, 20 | TM_NEWINDEX, 21 | TM_GC, 22 | TM_MODE, 23 | TM_LEN, 24 | TM_EQ, /* last tag method with fast access */ 25 | TM_ADD, 26 | TM_SUB, 27 | TM_MUL, 28 | TM_MOD, 29 | TM_POW, 30 | TM_DIV, 31 | TM_IDIV, 32 | TM_BAND, 33 | TM_BOR, 34 | TM_BXOR, 35 | TM_SHL, 36 | TM_SHR, 37 | TM_UNM, 38 | TM_BNOT, 39 | TM_LT, 40 | TM_LE, 41 | TM_CONCAT, 42 | TM_CALL, 43 | TM_N /* number of elements in the enum */ 44 | } TMS; 45 | 46 | 47 | 48 | #define gfasttm(g,et,e) ((et) == NULL ? NULL : \ 49 | ((et)->flags & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e])) 50 | 51 | #define fasttm(l,et,e) gfasttm(G(l), et, e) 52 | 53 | #define ttypename(x) luaT_typenames_[(x) + 1] 54 | 55 | LUAI_DDEC const char *const luaT_typenames_[LUA_TOTALTAGS]; 56 | 57 | 58 | LUAI_FUNC const char *luaT_objtypename (lua_State *L, const TValue *o); 59 | 60 | LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename); 61 | LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, 62 | TMS event); 63 | LUAI_FUNC void luaT_init (lua_State *L); 64 | 65 | LUAI_FUNC void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1, 66 | const TValue *p2, TValue *p3, int hasres); 67 | LUAI_FUNC int luaT_callbinTM (lua_State *L, const TValue *p1, const TValue *p2, 68 | StkId res, TMS event); 69 | LUAI_FUNC void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2, 70 | StkId res, TMS event); 71 | LUAI_FUNC int luaT_callorderTM (lua_State *L, const TValue *p1, 72 | const TValue *p2, TMS event); 73 | 74 | 75 | 76 | #endif 77 | -------------------------------------------------------------------------------- /td_clua/lua/src/lua.hpp: -------------------------------------------------------------------------------- 1 | // lua.hpp 2 | // Lua header files for C++ 3 | // <> not supplied automatically because Lua also compiles as C++ 4 | 5 | extern "C" { 6 | #include "lua.h" 7 | #include "lualib.h" 8 | #include "lauxlib.h" 9 | } 10 | -------------------------------------------------------------------------------- /td_clua/lua/src/lualib.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lualib.h,v 1.45.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Lua standard libraries 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | 8 | #ifndef lualib_h 9 | #define lualib_h 10 | 11 | #include "lua.h" 12 | 13 | 14 | /* version suffix for environment variable names */ 15 | #define LUA_VERSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR 16 | 17 | 18 | LUAMOD_API int (luaopen_base) (lua_State *L); 19 | 20 | #define LUA_COLIBNAME "coroutine" 21 | LUAMOD_API int (luaopen_coroutine) (lua_State *L); 22 | 23 | #define LUA_TABLIBNAME "table" 24 | LUAMOD_API int (luaopen_table) (lua_State *L); 25 | 26 | #define LUA_IOLIBNAME "io" 27 | LUAMOD_API int (luaopen_io) (lua_State *L); 28 | 29 | #define LUA_OSLIBNAME "os" 30 | LUAMOD_API int (luaopen_os) (lua_State *L); 31 | 32 | #define LUA_STRLIBNAME "string" 33 | LUAMOD_API int (luaopen_string) (lua_State *L); 34 | 35 | #define LUA_UTF8LIBNAME "utf8" 36 | LUAMOD_API int (luaopen_utf8) (lua_State *L); 37 | 38 | #define LUA_BITLIBNAME "bit32" 39 | LUAMOD_API int (luaopen_bit32) (lua_State *L); 40 | 41 | #define LUA_MATHLIBNAME "math" 42 | LUAMOD_API int (luaopen_math) (lua_State *L); 43 | 44 | #define LUA_DBLIBNAME "debug" 45 | LUAMOD_API int (luaopen_debug) (lua_State *L); 46 | 47 | #define LUA_LOADLIBNAME "package" 48 | LUAMOD_API int (luaopen_package) (lua_State *L); 49 | 50 | 51 | /* open all previous libraries */ 52 | LUALIB_API void (luaL_openlibs) (lua_State *L); 53 | 54 | 55 | 56 | #if !defined(lua_assert) 57 | #define lua_assert(x) ((void)0) 58 | #endif 59 | 60 | 61 | #endif 62 | -------------------------------------------------------------------------------- /td_clua/lua/src/lundump.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lundump.h,v 1.45.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** load precompiled Lua chunks 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef lundump_h 8 | #define lundump_h 9 | 10 | #include "llimits.h" 11 | #include "lobject.h" 12 | #include "lzio.h" 13 | 14 | 15 | /* data to catch conversion errors */ 16 | #define LUAC_DATA "\x19\x93\r\n\x1a\n" 17 | 18 | #define LUAC_INT 0x5678 19 | #define LUAC_NUM cast_num(370.5) 20 | 21 | #define MYINT(s) (s[0]-'0') 22 | #define LUAC_VERSION (MYINT(LUA_VERSION_MAJOR)*16+MYINT(LUA_VERSION_MINOR)) 23 | #define LUAC_FORMAT 0 /* this is the official format */ 24 | 25 | /* load one chunk; from lundump.c */ 26 | LUAI_FUNC LClosure* luaU_undump (lua_State* L, ZIO* Z, const char* name); 27 | 28 | /* dump one chunk; from ldump.c */ 29 | LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, 30 | void* data, int strip); 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /td_clua/lua/src/lvm.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lvm.h,v 2.41.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Lua virtual machine 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #ifndef lvm_h 8 | #define lvm_h 9 | 10 | 11 | #include "ldo.h" 12 | #include "lobject.h" 13 | #include "ltm.h" 14 | 15 | 16 | #if !defined(LUA_NOCVTN2S) 17 | #define cvt2str(o) ttisnumber(o) 18 | #else 19 | #define cvt2str(o) 0 /* no conversion from numbers to strings */ 20 | #endif 21 | 22 | 23 | #if !defined(LUA_NOCVTS2N) 24 | #define cvt2num(o) ttisstring(o) 25 | #else 26 | #define cvt2num(o) 0 /* no conversion from strings to numbers */ 27 | #endif 28 | 29 | 30 | /* 31 | ** You can define LUA_FLOORN2I if you want to convert floats to integers 32 | ** by flooring them (instead of raising an error if they are not 33 | ** integral values) 34 | */ 35 | #if !defined(LUA_FLOORN2I) 36 | #define LUA_FLOORN2I 0 37 | #endif 38 | 39 | 40 | #define tonumber(o,n) \ 41 | (ttisfloat(o) ? (*(n) = fltvalue(o), 1) : luaV_tonumber_(o,n)) 42 | 43 | #define tointeger(o,i) \ 44 | (ttisinteger(o) ? (*(i) = ivalue(o), 1) : luaV_tointeger(o,i,LUA_FLOORN2I)) 45 | 46 | #define intop(op,v1,v2) l_castU2S(l_castS2U(v1) op l_castS2U(v2)) 47 | 48 | #define luaV_rawequalobj(t1,t2) luaV_equalobj(NULL,t1,t2) 49 | 50 | 51 | /* 52 | ** fast track for 'gettable': if 't' is a table and 't[k]' is not nil, 53 | ** return 1 with 'slot' pointing to 't[k]' (final result). Otherwise, 54 | ** return 0 (meaning it will have to check metamethod) with 'slot' 55 | ** pointing to a nil 't[k]' (if 't' is a table) or NULL (otherwise). 56 | ** 'f' is the raw get function to use. 57 | */ 58 | #define luaV_fastget(L,t,k,slot,f) \ 59 | (!ttistable(t) \ 60 | ? (slot = NULL, 0) /* not a table; 'slot' is NULL and result is 0 */ \ 61 | : (slot = f(hvalue(t), k), /* else, do raw access */ \ 62 | !ttisnil(slot))) /* result not nil? */ 63 | 64 | /* 65 | ** standard implementation for 'gettable' 66 | */ 67 | #define luaV_gettable(L,t,k,v) { const TValue *slot; \ 68 | if (luaV_fastget(L,t,k,slot,luaH_get)) { setobj2s(L, v, slot); } \ 69 | else luaV_finishget(L,t,k,v,slot); } 70 | 71 | 72 | /* 73 | ** Fast track for set table. If 't' is a table and 't[k]' is not nil, 74 | ** call GC barrier, do a raw 't[k]=v', and return true; otherwise, 75 | ** return false with 'slot' equal to NULL (if 't' is not a table) or 76 | ** 'nil'. (This is needed by 'luaV_finishget'.) Note that, if the macro 77 | ** returns true, there is no need to 'invalidateTMcache', because the 78 | ** call is not creating a new entry. 79 | */ 80 | #define luaV_fastset(L,t,k,slot,f,v) \ 81 | (!ttistable(t) \ 82 | ? (slot = NULL, 0) \ 83 | : (slot = f(hvalue(t), k), \ 84 | ttisnil(slot) ? 0 \ 85 | : (luaC_barrierback(L, hvalue(t), v), \ 86 | setobj2t(L, cast(TValue *,slot), v), \ 87 | 1))) 88 | 89 | 90 | #define luaV_settable(L,t,k,v) { const TValue *slot; \ 91 | if (!luaV_fastset(L,t,k,slot,luaH_get,v)) \ 92 | luaV_finishset(L,t,k,v,slot); } 93 | 94 | 95 | 96 | LUAI_FUNC int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2); 97 | LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r); 98 | LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r); 99 | LUAI_FUNC int luaV_tonumber_ (const TValue *obj, lua_Number *n); 100 | LUAI_FUNC int luaV_tointeger (const TValue *obj, lua_Integer *p, int mode); 101 | LUAI_FUNC void luaV_finishget (lua_State *L, const TValue *t, TValue *key, 102 | StkId val, const TValue *slot); 103 | LUAI_FUNC void luaV_finishset (lua_State *L, const TValue *t, TValue *key, 104 | StkId val, const TValue *slot); 105 | LUAI_FUNC void luaV_finishOp (lua_State *L); 106 | LUAI_FUNC void luaV_execute (lua_State *L); 107 | LUAI_FUNC void luaV_concat (lua_State *L, int total); 108 | LUAI_FUNC lua_Integer luaV_div (lua_State *L, lua_Integer x, lua_Integer y); 109 | LUAI_FUNC lua_Integer luaV_mod (lua_State *L, lua_Integer x, lua_Integer y); 110 | LUAI_FUNC lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y); 111 | LUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb); 112 | 113 | #endif 114 | -------------------------------------------------------------------------------- /td_clua/lua/src/lzio.c: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lzio.c,v 1.37.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Buffered streams 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | #define lzio_c 8 | #define LUA_CORE 9 | 10 | #include "lprefix.h" 11 | 12 | 13 | #include 14 | 15 | #include "lua.h" 16 | 17 | #include "llimits.h" 18 | #include "lmem.h" 19 | #include "lstate.h" 20 | #include "lzio.h" 21 | 22 | 23 | int luaZ_fill (ZIO *z) { 24 | size_t size; 25 | lua_State *L = z->L; 26 | const char *buff; 27 | lua_unlock(L); 28 | buff = z->reader(L, z->data, &size); 29 | lua_lock(L); 30 | if (buff == NULL || size == 0) 31 | return EOZ; 32 | z->n = size - 1; /* discount char being returned */ 33 | z->p = buff; 34 | return cast_uchar(*(z->p++)); 35 | } 36 | 37 | 38 | void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) { 39 | z->L = L; 40 | z->reader = reader; 41 | z->data = data; 42 | z->n = 0; 43 | z->p = NULL; 44 | } 45 | 46 | 47 | /* --------------------------------------------------------------- read --- */ 48 | size_t luaZ_read (ZIO *z, void *b, size_t n) { 49 | while (n) { 50 | size_t m; 51 | if (z->n == 0) { /* no bytes in buffer? */ 52 | if (luaZ_fill(z) == EOZ) /* try to read more */ 53 | return n; /* no more input; return number of missing bytes */ 54 | else { 55 | z->n++; /* luaZ_fill consumed first byte; put it back */ 56 | z->p--; 57 | } 58 | } 59 | m = (n <= z->n) ? n : z->n; /* min. between n and z->n */ 60 | memcpy(b, z->p, m); 61 | z->n -= m; 62 | z->p += m; 63 | b = (char *)b + m; 64 | n -= m; 65 | } 66 | return 0; 67 | } 68 | 69 | -------------------------------------------------------------------------------- /td_clua/lua/src/lzio.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** $Id: lzio.h,v 1.31.1.1 2017/04/19 17:20:42 roberto Exp $ 3 | ** Buffered streams 4 | ** See Copyright Notice in lua.h 5 | */ 6 | 7 | 8 | #ifndef lzio_h 9 | #define lzio_h 10 | 11 | #include "lua.h" 12 | 13 | #include "lmem.h" 14 | 15 | 16 | #define EOZ (-1) /* end of stream */ 17 | 18 | typedef struct Zio ZIO; 19 | 20 | #define zgetc(z) (((z)->n--)>0 ? cast_uchar(*(z)->p++) : luaZ_fill(z)) 21 | 22 | 23 | typedef struct Mbuffer { 24 | char *buffer; 25 | size_t n; 26 | size_t buffsize; 27 | } Mbuffer; 28 | 29 | #define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0) 30 | 31 | #define luaZ_buffer(buff) ((buff)->buffer) 32 | #define luaZ_sizebuffer(buff) ((buff)->buffsize) 33 | #define luaZ_bufflen(buff) ((buff)->n) 34 | 35 | #define luaZ_buffremove(buff,i) ((buff)->n -= (i)) 36 | #define luaZ_resetbuffer(buff) ((buff)->n = 0) 37 | 38 | 39 | #define luaZ_resizebuffer(L, buff, size) \ 40 | ((buff)->buffer = luaM_reallocvchar(L, (buff)->buffer, \ 41 | (buff)->buffsize, size), \ 42 | (buff)->buffsize = size) 43 | 44 | #define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0) 45 | 46 | 47 | LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, 48 | void *data); 49 | LUAI_FUNC size_t luaZ_read (ZIO* z, void *b, size_t n); /* read next n bytes */ 50 | 51 | 52 | 53 | /* --------- Private Part ------------------ */ 54 | 55 | struct Zio { 56 | size_t n; /* bytes still unread */ 57 | const char *p; /* current position in buffer */ 58 | lua_Reader reader; /* reader function */ 59 | void *data; /* additional data */ 60 | lua_State *L; /* Lua state (for reader) */ 61 | }; 62 | 63 | 64 | LUAI_FUNC int luaZ_fill (ZIO *z); 65 | 66 | #endif 67 | -------------------------------------------------------------------------------- /td_rlua/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "td_rlua" 3 | version = "0.3.4" 4 | authors = [ "tickbh " ] 5 | description = "Zero-cost high-level lua 5.3 wrapper for Rust" 6 | repository = "https://github.com/tickbh/td_rlua" 7 | license = "MIT/Apache-2.0" 8 | keywords = ["lua", "wrapper"] 9 | [dependencies] 10 | libc = "^0.2.1" 11 | td_clua = "0.1.3" 12 | 13 | -------------------------------------------------------------------------------- /td_rlua/src/functions.rs: -------------------------------------------------------------------------------- 1 | use libc; 2 | use td_clua::{self, lua_State}; 3 | use LuaRead; 4 | use LuaPush; 5 | 6 | use std::marker::PhantomData; 7 | use std::mem; 8 | use std::ptr; 9 | 10 | macro_rules! impl_function { 11 | ($name:ident, $($p:ident),*) => ( 12 | /// Wraps a type that implements `FnMut` so that it can be used by hlua. 13 | /// 14 | /// This is only needed because of a limitation in Rust's inferrence system. 15 | pub fn $name(f: Z) -> Function where Z: FnMut($($p),*) -> R { 16 | Function { 17 | function: f, 18 | marker: PhantomData, 19 | } 20 | } 21 | ) 22 | } 23 | 24 | impl_function!(function0,); 25 | impl_function!(function1, A); 26 | impl_function!(function2, A, B); 27 | impl_function!(function3, A, B, C); 28 | impl_function!(function4, A, B, C, D); 29 | impl_function!(function5, A, B, C, D, E); 30 | impl_function!(function6, A, B, C, D, E, F); 31 | impl_function!(function7, A, B, C, D, E, F, G); 32 | impl_function!(function8, A, B, C, D, E, F, G, H); 33 | impl_function!(function9, A, B, C, D, E, F, G, H, I); 34 | impl_function!(function10, A, B, C, D, E, F, G, H, I, J); 35 | 36 | /// Opaque type containing a Rust function or closure. 37 | pub struct Function { 38 | function: F, 39 | marker: PhantomData<(P, R)>, 40 | } 41 | 42 | /// Trait implemented on `Function` to mimic `FnMut`. 43 | pub trait FunctionExt

{ 44 | type Output; 45 | 46 | fn call_mut(&mut self, params: P) -> Self::Output; 47 | } 48 | 49 | macro_rules! impl_function_ext { 50 | () => ( 51 | impl FunctionExt<()> for Function where Z: FnMut() -> R { 52 | type Output = R; 53 | 54 | #[allow(non_snake_case)] 55 | fn call_mut(&mut self, _: ()) -> Self::Output { 56 | (self.function)() 57 | } 58 | } 59 | 60 | impl LuaPush for Function 61 | where Z: FnMut() -> R, 62 | R: LuaPush + 'static 63 | { 64 | fn push_to_lua(self, lua: *mut lua_State) -> i32 { 65 | unsafe { 66 | // pushing the function pointer as a userdata 67 | let lua_data = td_clua::lua_newuserdata(lua, mem::size_of::() as libc::size_t); 68 | let lua_data: *mut Z = mem::transmute(lua_data); 69 | ptr::write(lua_data, self.function); 70 | 71 | // pushing wrapper as a closure 72 | let wrapper: extern fn(*mut td_clua::lua_State) -> libc::c_int = wrapper::; 73 | td_clua::lua_pushcclosure(lua, wrapper, 1); 74 | 1 75 | } 76 | } 77 | } 78 | ); 79 | 80 | ($($p:ident),+) => ( 81 | impl FunctionExt<($($p,)*)> for Function where Z: FnMut($($p),*) -> R { 82 | type Output = R; 83 | 84 | #[allow(non_snake_case)] 85 | fn call_mut(&mut self, params: ($($p,)*)) -> Self::Output { 86 | let ($($p,)*) = params; 87 | (self.function)($($p),*) 88 | } 89 | } 90 | 91 | impl LuaPush for Function 92 | where Z: FnMut($($p),*) -> R, 93 | ($($p,)*): LuaRead, 94 | R: LuaPush + 'static 95 | { 96 | fn push_to_lua(self, lua: *mut lua_State) -> i32 { 97 | unsafe { 98 | // pushing the function pointer as a userdata 99 | let lua_data = td_clua::lua_newuserdata(lua, mem::size_of::() as libc::size_t); 100 | let lua_data: *mut Z = mem::transmute(lua_data); 101 | ptr::write(lua_data, self.function); 102 | 103 | // pushing wrapper as a closure 104 | let wrapper: extern fn(*mut td_clua::lua_State) -> libc::c_int = wrapper::; 105 | td_clua::lua_pushcclosure(lua, wrapper, 1); 106 | 1 107 | } 108 | } 109 | } 110 | ) 111 | } 112 | 113 | impl_function_ext!(); 114 | impl_function_ext!(A); 115 | impl_function_ext!(A, B); 116 | impl_function_ext!(A, B, C); 117 | impl_function_ext!(A, B, C, D); 118 | impl_function_ext!(A, B, C, D, E); 119 | impl_function_ext!(A, B, C, D, E, F); 120 | impl_function_ext!(A, B, C, D, E, F, G); 121 | impl_function_ext!(A, B, C, D, E, F, G, H); 122 | impl_function_ext!(A, B, C, D, E, F, G, H, I); 123 | impl_function_ext!(A, B, C, D, E, F, G, H, I, J); 124 | 125 | // this function is called when Lua wants to call one of our functions 126 | extern "C" fn wrapper(lua: *mut td_clua::lua_State) -> libc::c_int 127 | where T: FunctionExt, 128 | P: LuaRead + 'static, 129 | R: LuaPush 130 | { 131 | // loading the object that we want to call from the Lua context 132 | let data_raw = unsafe { td_clua::lua_touserdata(lua, td_clua::lua_upvalueindex(1)) }; 133 | let data: &mut T = unsafe { mem::transmute(data_raw) }; 134 | 135 | // trying to read the arguments 136 | let arguments_count = unsafe { td_clua::lua_gettop(lua) } as i32; 137 | let args = match LuaRead::lua_read_at_position(lua, -arguments_count as libc::c_int) { // TODO: what if the user has the wrong params? 138 | Some(a) => a, 139 | _ => { 140 | let err_msg = format!("wrong parameter types for callback function arguments_count \ 141 | is {}", 142 | arguments_count); 143 | err_msg.push_to_lua(lua); 144 | unsafe { 145 | td_clua::lua_error(lua); 146 | } 147 | unreachable!() 148 | } 149 | 150 | }; 151 | 152 | let ret_value = data.call_mut(args); 153 | 154 | // pushing back the result of the function on the stack 155 | let nb = ret_value.push_to_lua(lua); 156 | nb as libc::c_int 157 | } 158 | -------------------------------------------------------------------------------- /td_rlua/src/hotfix.rs: -------------------------------------------------------------------------------- 1 | use super::Lua; 2 | 3 | // hot fix mod 4 | 5 | ///in runtime call hotfix func(reload code) or hotfix_file func(reload file) 6 | ///we will keep the old data but function, but hotfix not support change name, 7 | ///if we add new upvalue, it'a also support 8 | ///so after hotfix, the function is new and the data is old, so we success hotfix 9 | pub fn load_hot_fix(lua: &mut Lua) { 10 | 11 | let func = r" 12 | function hotfix(chunk, check_name) 13 | check_name = check_name or 'hotfix' 14 | local env = {} 15 | setmetatable(env, { __index = _G }) 16 | local _ENV = env 17 | local f, err = load(chunk, check_name, 't', env) 18 | assert(f,err) 19 | local ok, err = pcall(f) 20 | assert(ok,err) 21 | 22 | local protection = { 23 | setmetatable = true, 24 | pairs = true, 25 | ipairs = true, 26 | next = true, 27 | require = true, 28 | _ENV = true, 29 | } 30 | local visited_sig = {} 31 | function update_table(env_t, g_t, name, deep) 32 | if protection[env_t] or protection[g_t] then return end 33 | if env_t == g_t then return end 34 | local signature = tostring(g_t)..tostring(env_t) 35 | if visited_sig[signature] then return end 36 | visited_sig[signature] = true 37 | for name, value in pairs(env_t) do 38 | local old_value = g_t[name] 39 | if type(value) == type(old_value) then 40 | if type(value) == 'function' then 41 | update_func(value, old_value, name, deep..' '..name..' ') 42 | g_t[name] = value 43 | elseif type(value) == 'table' then 44 | update_table(value, old_value, name, deep..' '..name..' ') 45 | end 46 | else 47 | g_t[name] = value 48 | end 49 | end 50 | 51 | local old_meta = debug.getmetatable(g_t) 52 | local new_meta = debug.getmetatable(env_t) 53 | if type(old_meta) == 'table' and type(new_meta) == 'table' then 54 | update_table(new_meta, old_meta, name..'s Meta', deep..' '..name..'s Meta'..' ' ) 55 | end 56 | end 57 | 58 | function update_func(env_f, g_f, name, deep) 59 | local signature = tostring(env_f)..tostring(g_f) 60 | if visited_sig[signature] then return end 61 | visited_sig[signature] = true 62 | local old_upvalue_map = {} 63 | for i = 1, math.huge do 64 | local name, value = debug.getupvalue(g_f, i) 65 | if not name then break end 66 | old_upvalue_map[name] = value 67 | end 68 | 69 | for i = 1, math.huge do 70 | local name, value = debug.getupvalue(env_f, i) 71 | if not name then break end 72 | local old_value = old_upvalue_map[name] 73 | if old_value then 74 | if type(old_value) ~= type(value) then 75 | debug.setupvalue(env_f, i, old_value) 76 | elseif type(old_value) == 'function' then 77 | update_func(value, old_value, name, deep..' '..name..' ') 78 | elseif type(old_value) == 'table' then 79 | update_table(value, old_value, name, deep..' '..name..' ') 80 | debug.setupvalue(env_f, i, old_value) 81 | else 82 | debug.setupvalue(env_f, i, old_value) 83 | end 84 | end 85 | end 86 | end 87 | 88 | for name,value in pairs(env) do 89 | local g_value = _G[name] 90 | if type(g_value) ~= type(value) then 91 | _G[name] = value 92 | elseif type(value) == 'function' then 93 | update_func(value, g_value, name, 'G'..' ') 94 | _G[name] = value 95 | elseif type(value) == 'table' then 96 | update_table(value, g_value, name, 'G'..' ') 97 | end 98 | end 99 | return 0 100 | end 101 | 102 | function hotfix_file(name) 103 | local file_str 104 | local fp = io.open(name) 105 | if fp then 106 | file_str = fp:read('*all') 107 | io.close(fp) 108 | end 109 | 110 | if not file_str then 111 | return -1 112 | end 113 | return hotfix(file_str, name) 114 | end"; 115 | let _: Option<()> = lua.exec_string(func); 116 | } 117 | -------------------------------------------------------------------------------- /td_rlua/src/lua_tables.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | 3 | use libc; 4 | 5 | use td_clua::{self, lua_State}; 6 | use LuaPush; 7 | use LuaRead; 8 | 9 | /// Represents a table stored in the Lua context. 10 | /// 11 | /// Loading this type mutably borrows the Lua context. 12 | pub struct LuaTable { 13 | table: *mut lua_State, 14 | pop : i32, 15 | index : i32, 16 | } 17 | 18 | impl LuaRead for LuaTable { 19 | fn lua_read_with_pop_impl(lua: *mut lua_State, index: i32, pop: i32) -> Option { 20 | if unsafe { td_clua::lua_istable(lua, index) } { 21 | for _ in 0 .. pop { 22 | unsafe { td_clua::lua_pushnil(lua); } 23 | } 24 | Some(LuaTable { table: lua, pop : pop, index : index }) 25 | } else { 26 | None 27 | } 28 | } 29 | } 30 | 31 | impl Drop for LuaTable { 32 | fn drop(&mut self) { 33 | if self.pop != 0 { 34 | unsafe { td_clua::lua_pop(self.table, self.pop); }; 35 | self.pop = 0; 36 | } 37 | } 38 | } 39 | 40 | /// Iterator that enumerates the content of a Lua table. 41 | // while the LuaTableIterator is active, the current key is constantly pushed over the table 42 | pub struct LuaTableIterator<'t, K, V> { 43 | table: &'t mut LuaTable, 44 | finished: bool, // if true, the key is not on the stack anymore 45 | marker: PhantomData<(K, V)>, 46 | } 47 | 48 | impl LuaTable { 49 | /// Destroys the LuaTable and returns its inner Lua context. Useful when it takes Lua by value. 50 | pub fn into_inner(self) -> *mut lua_State { 51 | self.table 52 | } 53 | 54 | /// Iterates over the elements inside the table. 55 | pub fn iter(&mut self) -> LuaTableIterator { 56 | unsafe { td_clua::lua_pushnil(self.table) }; 57 | 58 | LuaTableIterator { 59 | table: self, 60 | finished: false, 61 | marker: PhantomData, 62 | } 63 | } 64 | 65 | /// Loads a value in the table given its index. 66 | pub fn query<'a, R, I>(&'a mut self, index: I) -> Option 67 | where R: LuaRead, 68 | I: LuaPush 69 | { 70 | index.push_to_lua(self.table); 71 | unsafe { td_clua::lua_gettable(self.table, if self.index > 0 { self.index } else {self.index - 1}); } 72 | LuaRead::lua_read_with_pop(self.table, -1, 1) 73 | } 74 | 75 | /// Inserts or modifies an elements of the table. 76 | pub fn set(&mut self, index: I, value: V) 77 | where I: LuaPush, 78 | V: LuaPush 79 | { 80 | index.push_to_lua(self.table); 81 | value.push_to_lua(self.table); 82 | unsafe { td_clua::lua_settable(self.table, if self.index > 0 { self.index } else {self.index - 2}); } 83 | } 84 | 85 | /// Inserts or modifies an elements of the table. 86 | pub fn register(&mut self, index: I, func : extern "C" fn(*mut lua_State) -> libc::c_int) 87 | where I: LuaPush 88 | { 89 | index.push_to_lua(self.table); 90 | unsafe { 91 | td_clua::lua_pushcfunction(self.table, func); 92 | td_clua::lua_settable(self.table, if self.index > 0 { self.index } else {self.index - 2}); 93 | } 94 | } 95 | 96 | 97 | // /// Inserts an empty table, then loads it. 98 | pub fn empty_table(&mut self, index: I) -> LuaTable 99 | where I: LuaPush + Clone 100 | { 101 | index.clone().push_to_lua(self.table); 102 | unsafe { 103 | td_clua::lua_newtable(self.table); 104 | td_clua::lua_settable(self.table, if self.index > 0 { self.index } else {self.index - 2}); 105 | } 106 | self.query(index).unwrap() 107 | } 108 | 109 | pub fn table_len(&mut self) -> usize { 110 | unsafe { 111 | td_clua::lua_rawlen(self.table, self.index) 112 | } 113 | } 114 | 115 | // /// Obtains or create the metatable of the table. 116 | pub fn get_or_create_metatable(&mut self) -> LuaTable { 117 | let result = unsafe { td_clua::lua_getmetatable(self.table, self.index) }; 118 | 119 | if result == 0 { 120 | unsafe { 121 | td_clua::lua_newtable(self.table); 122 | td_clua::lua_setmetatable(self.table, -2); 123 | let r = td_clua::lua_getmetatable(self.table, self.index); 124 | assert!(r != 0); 125 | } 126 | } 127 | 128 | LuaTable { 129 | table: self.table, 130 | pop: 1, 131 | index : -1, 132 | } 133 | } 134 | } 135 | 136 | impl<'t, K, V> Iterator for LuaTableIterator<'t, K, V> 137 | where K: LuaRead + 'static, 138 | V: LuaRead + 'static 139 | { 140 | type Item = Option<(K, V)>; 141 | 142 | fn next(&mut self) -> Option> { 143 | if self.finished { 144 | return None; 145 | } 146 | let state = self.table.table; 147 | // this call pushes the next key and value on the stack 148 | if unsafe { !td_clua::lua_istable(state, -2) || td_clua::lua_next(state, -2) == 0 } { 149 | self.finished = true; 150 | return None; 151 | } 152 | 153 | let key = LuaRead::lua_read_at_position(state, -2); 154 | let value = LuaRead::lua_read_at_position(state, -1); 155 | // removing the value, leaving only the key on the top of the stack 156 | unsafe { td_clua::lua_pop(state, 1) }; 157 | 158 | if key.is_none() || value.is_none() { 159 | Some(None) 160 | } else { 161 | Some(Some((key.unwrap(), value.unwrap()))) 162 | } 163 | } 164 | } 165 | 166 | impl<'t, K, V> Drop for LuaTableIterator<'t, K, V> { 167 | fn drop(&mut self) { 168 | if !self.finished { 169 | unsafe { td_clua::lua_pop(self.table.table, 1) } 170 | } 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /td_rlua/src/rust_tables.rs: -------------------------------------------------------------------------------- 1 | use td_clua; 2 | use td_clua::lua_State; 3 | 4 | use LuaPush; 5 | use LuaRead; 6 | use LuaTable; 7 | 8 | use std::collections::{HashMap, HashSet}; 9 | use std::hash::Hash; 10 | 11 | fn push_iter(lua: *mut lua_State, iterator: I) -> i32 12 | where V: LuaPush, I: Iterator 13 | { 14 | // creating empty table 15 | unsafe { td_clua::lua_newtable(lua) }; 16 | 17 | for (elem, index) in iterator.zip(1..) { 18 | let size = elem.push_to_lua(lua); 19 | 20 | match size { 21 | 0 => continue, 22 | 1 => { 23 | let index = index as u32; 24 | index.push_to_lua(lua); 25 | unsafe { td_clua::lua_insert(lua, -2) } 26 | unsafe { td_clua::lua_settable(lua, -3) } 27 | }, 28 | 2 => unsafe { td_clua::lua_settable(lua, -3) }, 29 | _ => unreachable!() 30 | } 31 | } 32 | 33 | 1 34 | } 35 | 36 | fn push_rec_iter(lua: *mut lua_State, iterator: I) -> i32 37 | where V: LuaPush, I: Iterator 38 | { 39 | let (nrec, _) = iterator.size_hint(); 40 | 41 | // creating empty table with pre-allocated non-array elements 42 | unsafe { td_clua::lua_createtable(lua, 0, nrec as i32) }; 43 | 44 | for elem in iterator { 45 | let size = elem.push_to_lua(lua); 46 | 47 | match size { 48 | 0 => continue, 49 | 2 => unsafe { td_clua::lua_settable(lua, -3) }, 50 | _ => unreachable!() 51 | } 52 | } 53 | 54 | 1 55 | } 56 | 57 | impl LuaPush for Vec where T: LuaPush { 58 | fn push_to_lua(self, lua: *mut lua_State) -> i32 { 59 | push_iter(lua, self.into_iter()) 60 | } 61 | } 62 | 63 | impl<'a, T> LuaPush for &'a [T] where T: Clone + LuaPush { 64 | fn push_to_lua(self, lua: *mut lua_State) -> i32 { 65 | push_iter(lua, self.iter().map(|e| e.clone())) 66 | } 67 | } 68 | 69 | impl LuaPush for HashMap where K: LuaPush + Eq + Hash, 70 | V: LuaPush 71 | { 72 | fn push_to_lua(self, lua: *mut lua_State) -> i32 { 73 | push_rec_iter(lua, self.into_iter()) 74 | } 75 | } 76 | 77 | impl LuaPush for HashSet where K: LuaPush + Eq + Hash 78 | { 79 | fn push_to_lua(self, lua: *mut lua_State) -> i32 { 80 | use std::iter; 81 | push_rec_iter(lua, self.into_iter().zip(iter::repeat(true))) 82 | } 83 | } 84 | 85 | impl LuaRead for Vec where T : LuaRead { 86 | fn lua_read_with_pop_impl(lua: *mut lua_State, index: i32, _pop : i32) -> Option> { 87 | let mut lua_table : LuaTable = unwrap_or!(LuaRead::lua_read_at_position(lua, index), return None); 88 | let mut result = vec![]; 89 | let len = lua_table.table_len(); 90 | for i in 1 .. (len + 1) { 91 | let val : T = unwrap_or!(lua_table.query(i), return None); 92 | result.push(val); 93 | } 94 | Some(result) 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /td_rlua/src/tuples.rs: -------------------------------------------------------------------------------- 1 | use td_clua; 2 | 3 | use LuaPush; 4 | use LuaRead; 5 | 6 | macro_rules! tuple_impl { 7 | ($ty:ident) => ( 8 | impl<$ty> LuaPush for ($ty,) where $ty: LuaPush { 9 | fn push_to_lua(self, lua: *mut td_clua::lua_State) -> i32 { 10 | self.0.push_to_lua(lua) 11 | } 12 | } 13 | 14 | impl<$ty> LuaRead for ($ty,) where $ty: LuaRead { 15 | fn lua_read_with_pop_impl(lua: *mut td_clua::lua_State, index: i32, _pop: i32) -> Option<($ty,)> { 16 | LuaRead::lua_read_at_position(lua, index).map(|v| (v,)) 17 | } 18 | } 19 | ); 20 | 21 | ($first:ident, $($other:ident),+) => ( 22 | #[allow(non_snake_case)] 23 | impl<$first: LuaPush, $($other: LuaPush),+> 24 | LuaPush for ($first, $($other),+) 25 | { 26 | fn push_to_lua(self, lua: *mut td_clua::lua_State) -> i32 { 27 | match self { 28 | ($first, $($other),+) => { 29 | let mut total = $first.push_to_lua(lua); 30 | 31 | $( 32 | total += $other.push_to_lua(lua); 33 | )+ 34 | 35 | total 36 | } 37 | } 38 | } 39 | } 40 | 41 | // TODO: what if T or U are also tuples? indices won't match 42 | #[allow(unused_assignments)] 43 | #[allow(non_snake_case)] 44 | impl<$first: LuaRead, $($other: LuaRead),+> 45 | LuaRead for ($first, $($other),+) 46 | { 47 | fn lua_read_with_pop_impl(lua: *mut td_clua::lua_State, index: i32, _pop: i32) -> Option<($first, $($other),+)> { 48 | let mut i = index; 49 | let $first: $first = match LuaRead::lua_read_at_position(lua, i) { 50 | Some(v) => v, 51 | None => return None 52 | }; 53 | 54 | i += 1; 55 | 56 | $( 57 | let $other: $other = match LuaRead::lua_read_at_position(lua, i) { 58 | Some(v) => v, 59 | None => return None 60 | }; 61 | i += 1; 62 | )+ 63 | 64 | Some(($first, $($other),+)) 65 | 66 | } 67 | } 68 | 69 | tuple_impl!($($other),+); 70 | ); 71 | } 72 | 73 | tuple_impl!(A, B, C, D, E, F, G, H, I, J, K, L, M); 74 | -------------------------------------------------------------------------------- /td_rlua/src/values.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::CString; 2 | 3 | use libc; 4 | use td_clua; 5 | use td_clua::lua_State; 6 | 7 | use LuaPush; 8 | use LuaRead; 9 | 10 | pub struct RawString(pub Vec); 11 | 12 | macro_rules! integer_impl( 13 | ($t:ident) => ( 14 | impl LuaPush for $t { 15 | fn push_to_lua(self, lua: *mut lua_State) -> i32 { 16 | unsafe { td_clua::lua_pushinteger(lua, self as td_clua::lua_Integer) }; 17 | 1 18 | } 19 | } 20 | 21 | impl LuaRead for $t { 22 | fn lua_read_with_pop_impl(lua: *mut lua_State, index: i32, _pop: i32) -> Option<$t> { 23 | let mut success = 0; 24 | let val = unsafe { td_clua::lua_tointegerx(lua, index, &mut success) }; 25 | match success { 26 | 0 => None, 27 | _ => Some(val as $t) 28 | } 29 | } 30 | } 31 | ); 32 | ); 33 | 34 | integer_impl!(i8); 35 | integer_impl!(i16); 36 | integer_impl!(i32); 37 | integer_impl!(i64); 38 | integer_impl!(u8); 39 | integer_impl!(u16); 40 | integer_impl!(u32); 41 | integer_impl!(u64); 42 | integer_impl!(usize); 43 | 44 | macro_rules! numeric_impl( 45 | ($t:ident) => ( 46 | impl LuaPush for $t { 47 | fn push_to_lua(self, lua: *mut lua_State) -> i32 { 48 | unsafe { td_clua::lua_pushnumber(lua, self as f64) }; 49 | 1 50 | } 51 | } 52 | 53 | impl LuaRead for $t { 54 | fn lua_read_with_pop_impl(lua: *mut lua_State, index: i32, _pop: i32) -> Option<$t> { 55 | let mut success = 0; 56 | let val = unsafe { td_clua::lua_tonumberx(lua, index, &mut success) }; 57 | match success { 58 | 0 => None, 59 | _ => Some(val as $t) 60 | } 61 | } 62 | } 63 | ); 64 | ); 65 | 66 | numeric_impl!(f32); 67 | numeric_impl!(f64); 68 | 69 | impl LuaPush for String { 70 | fn push_to_lua(self, lua: *mut lua_State) -> i32 { 71 | if let Some(value) = CString::new(&self[..]).ok() { 72 | unsafe { td_clua::lua_pushstring(lua, value.as_ptr()) }; 73 | 1 74 | } else { 75 | let value = CString::new(&"UNVAILED STRING"[..]).unwrap(); 76 | unsafe { td_clua::lua_pushstring(lua, value.as_ptr()) }; 77 | 1 78 | } 79 | } 80 | } 81 | 82 | impl LuaRead for String { 83 | fn lua_read_with_pop_impl(lua: *mut lua_State, index: i32, _pop: i32) -> Option { 84 | let mut size = 0; 85 | let data = unsafe { td_clua::lua_tolstring(lua, index, &mut size) }; 86 | let bytes = unsafe { std::slice::from_raw_parts(data as *const u8, size) }; 87 | match std::str::from_utf8(bytes) { 88 | Ok(v) => Some(v.to_string()), 89 | Err(_) => None, 90 | } 91 | } 92 | } 93 | 94 | impl<'s> LuaPush for &'s str { 95 | fn push_to_lua(self, lua: *mut lua_State) -> i32 { 96 | if let Some(value) = CString::new(&self[..]).ok() { 97 | unsafe { td_clua::lua_pushstring(lua, value.as_ptr()) }; 98 | 1 99 | } else { 100 | let value = CString::new(&"UNVAILED STRING"[..]).unwrap(); 101 | unsafe { td_clua::lua_pushstring(lua, value.as_ptr()) }; 102 | 1 103 | } 104 | } 105 | } 106 | 107 | impl LuaPush for bool { 108 | fn push_to_lua(self, lua: *mut lua_State) -> i32 { 109 | unsafe { td_clua::lua_pushboolean(lua, self.clone() as libc::c_int) }; 110 | 1 111 | } 112 | } 113 | 114 | impl LuaRead for bool { 115 | fn lua_read_with_pop_impl(lua: *mut lua_State, index: i32, _pop: i32) -> Option { 116 | if unsafe { td_clua::lua_isboolean(lua, index) } != true { 117 | return None; 118 | } 119 | 120 | Some(unsafe { td_clua::lua_toboolean(lua, index) != 0 }) 121 | } 122 | } 123 | 124 | impl LuaPush for () { 125 | fn push_to_lua(self, lua: *mut lua_State) -> i32 { 126 | unsafe { td_clua::lua_pushnil(lua) }; 127 | 1 128 | } 129 | } 130 | 131 | impl LuaRead for () { 132 | fn lua_read_with_pop_impl(_: *mut lua_State, _: i32, _pop: i32) -> Option<()> { 133 | Some(()) 134 | } 135 | } 136 | 137 | impl LuaPush for &RawString { 138 | fn push_to_lua(self, lua: *mut lua_State) -> i32 { 139 | unsafe { td_clua::lua_pushlstring(lua, self.0.as_ptr() as *const i8, self.0.len()) }; 140 | 1 141 | } 142 | } 143 | 144 | impl LuaPush for RawString { 145 | fn push_to_lua(self, lua: *mut lua_State) -> i32 { 146 | unsafe { td_clua::lua_pushlstring(lua, self.0.as_ptr() as *const i8, self.0.len()) }; 147 | 1 148 | } 149 | } 150 | 151 | impl LuaRead for RawString { 152 | fn lua_read_with_pop_impl(lua: *mut lua_State, index: i32, _pop: i32) -> Option { 153 | let mut size: libc::size_t = 0; 154 | let c_str_raw = unsafe { td_clua::lua_tolstring(lua, index, &mut size) }; 155 | if c_str_raw.is_null() { 156 | return None; 157 | } 158 | 159 | let value = unsafe { Vec::from_raw_parts(c_str_raw as *mut u8, size, size) }; 160 | Some(RawString(value)) 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /td_rlua/tests/basic_types.rs: -------------------------------------------------------------------------------- 1 | extern crate td_rlua; 2 | 3 | use td_rlua::Lua; 4 | 5 | #[test] 6 | fn read_i32s() { 7 | let mut lua = Lua::new(); 8 | 9 | lua.set("a", 2); 10 | 11 | let x: i32 = lua.query("a").unwrap(); 12 | assert_eq!(lua.get_top(), 0); 13 | assert_eq!(x, 2); 14 | 15 | let y: i8 = lua.query("a").unwrap(); 16 | assert_eq!(lua.get_top(), 0); 17 | assert_eq!(y, 2); 18 | 19 | let z: i16 = lua.query("a").unwrap(); 20 | assert_eq!(lua.get_top(), 0); 21 | assert_eq!(z, 2); 22 | 23 | let w: i32 = lua.query("a").unwrap(); 24 | assert_eq!(lua.get_top(), 0); 25 | assert_eq!(w, 2); 26 | 27 | let a: u32 = lua.query("a").unwrap(); 28 | assert_eq!(lua.get_top(), 0); 29 | assert_eq!(a, 2); 30 | 31 | let b: u8 = lua.query("a").unwrap(); 32 | assert_eq!(lua.get_top(), 0); 33 | assert_eq!(b, 2); 34 | 35 | let c: u16 = lua.query("a").unwrap(); 36 | assert_eq!(lua.get_top(), 0); 37 | assert_eq!(c, 2); 38 | 39 | let d : () = lua.query("a").unwrap(); 40 | assert_eq!(lua.get_top(), 0); 41 | assert_eq!(d, ()); 42 | } 43 | 44 | #[test] 45 | fn write_i32s() { 46 | // TODO: 47 | 48 | let mut lua = Lua::new(); 49 | 50 | lua.set("a", 2); 51 | let x: i32 = lua.query("a").unwrap(); 52 | assert_eq!(lua.get_top(), 0); 53 | assert_eq!(x, 2); 54 | } 55 | 56 | #[test] 57 | fn readwrite_floats() { 58 | let mut lua = Lua::new(); 59 | 60 | lua.set("a", 2.51234 as f32); 61 | lua.set("b", 3.4123456789 as f64); 62 | 63 | let x: f32 = lua.query("a").unwrap(); 64 | assert_eq!(lua.get_top(), 0); 65 | assert!(x - 2.51234 < 0.000001); 66 | 67 | let y: f64 = lua.query("a").unwrap(); 68 | assert_eq!(lua.get_top(), 0); 69 | assert!(y - 2.51234 < 0.000001); 70 | 71 | let z: f32 = lua.query("b").unwrap(); 72 | assert_eq!(lua.get_top(), 0); 73 | assert!(z - 3.4123456789 < 0.000001); 74 | 75 | let w: f64 = lua.query("b").unwrap(); 76 | assert_eq!(lua.get_top(), 0); 77 | assert!(w - 3.4123456789 < 0.000001); 78 | } 79 | 80 | #[test] 81 | fn readwrite_bools() { 82 | let mut lua = Lua::new(); 83 | 84 | lua.set("a", true); 85 | lua.set("b", false); 86 | 87 | let x: bool = lua.query("a").unwrap(); 88 | assert_eq!(lua.get_top(), 0); 89 | assert_eq!(x, true); 90 | 91 | let y: bool = lua.query("b").unwrap(); 92 | assert_eq!(lua.get_top(), 0); 93 | assert_eq!(y, false); 94 | } 95 | 96 | #[test] 97 | fn readwrite_strings() { 98 | let mut lua = Lua::new(); 99 | 100 | lua.set("a", "hello"); 101 | lua.set("b", "hello".to_string()); 102 | let unvaild = String::from_utf8_lossy(&[8, 0, 34, 0, 3, 0, 58, 0, 0, 0, 33, 0, 40, 0, 34, 0, 3, 0, 26, 0, 0, 0, 34, 0, 127, 0, 35, 0, 0, 0, 35, 0, 14]).to_string(); 103 | lua.set("c", unvaild); 104 | 105 | let x: String = lua.query("a").unwrap(); 106 | assert_eq!(lua.get_top(), 0); 107 | assert_eq!(x, "hello"); 108 | 109 | let y: String = lua.query("b").unwrap(); 110 | assert_eq!(lua.get_top(), 0); 111 | assert_eq!(y, "hello"); 112 | 113 | let z: String = lua.query("c").unwrap(); 114 | assert_eq!(lua.get_top(), 0); 115 | assert_eq!(z, "UNVAILED STRING"); 116 | } 117 | 118 | #[test] 119 | fn i32_to_string() { 120 | let mut lua = Lua::new(); 121 | 122 | lua.set("a", 2); 123 | 124 | let x: String = lua.query("a").unwrap(); 125 | assert_eq!(lua.get_top(), 0); 126 | assert_eq!(x, "2"); 127 | } 128 | 129 | #[test] 130 | fn string_to_i32() { 131 | let mut lua = Lua::new(); 132 | 133 | lua.set("a", "2"); 134 | lua.set("b", "aaa"); 135 | 136 | let x: i32 = lua.query("a").unwrap(); 137 | assert_eq!(lua.get_top(), 0); 138 | assert_eq!(x, 2); 139 | 140 | let y: Option = lua.query("b"); 141 | assert_eq!(lua.get_top(), 0); 142 | assert!(y.is_none()); 143 | } 144 | -------------------------------------------------------------------------------- /td_rlua/tests/functions.rs: -------------------------------------------------------------------------------- 1 | extern crate td_rlua; 2 | extern crate libc; 3 | use td_rlua::Lua; 4 | use td_rlua::LuaPush; 5 | use td_rlua::LuaTable; 6 | 7 | #[test] 8 | fn basic() { 9 | let mut lua = Lua::new(); 10 | { 11 | let val: Option = lua.exec_string("return 5;"); 12 | assert_eq!(lua.get_top(), 0); 13 | assert_eq!(val.unwrap(), 5); 14 | } 15 | 16 | { 17 | let val: Option = lua.exec_string("return a5;"); 18 | assert_eq!(lua.get_top(), 0); 19 | assert!(val.is_none()); 20 | } 21 | } 22 | 23 | #[test] 24 | fn syntax_error() { 25 | let mut lua = Lua::new(); 26 | let val : Option<()> = lua.exec_string("td_rlua"); 27 | assert_eq!(lua.get_top(), 0); 28 | assert!(val.is_none()); 29 | } 30 | 31 | #[test] 32 | fn execution_error() { 33 | let mut lua = Lua::new(); 34 | 35 | let val : Option<()> = lua.exec_string("return a:hello()"); 36 | assert_eq!(lua.get_top(), 0); 37 | assert!(val.is_none()); 38 | } 39 | 40 | #[test] 41 | fn call_and_read_table() { 42 | let mut lua = Lua::new(); 43 | let mut val: LuaTable = lua.exec_string("return {1, 2, 3};").unwrap(); 44 | assert_eq!(lua.get_top(), 1); 45 | assert_eq!(val.query::(1).unwrap(), 1); 46 | assert_eq!(lua.get_top(), 1); 47 | assert_eq!(val.query::(2).unwrap(), 2); 48 | assert_eq!(lua.get_top(), 1); 49 | assert_eq!(val.query::(3).unwrap(), 3); 50 | drop(val); 51 | assert_eq!(lua.get_top(), 0); 52 | } 53 | 54 | 55 | #[test] 56 | fn simple_function() { 57 | let mut lua = Lua::new(); 58 | 59 | fn ret5() -> i32 { 5 } 60 | lua.set("ret5", td_rlua::function0(ret5)); 61 | 62 | let val: i32 = lua.exec_string("return ret5()").unwrap(); 63 | assert_eq!(lua.get_top(), 0); 64 | 65 | assert_eq!(val, 5); 66 | } 67 | 68 | #[test] 69 | fn one_argument() { 70 | let mut lua = Lua::new(); 71 | 72 | fn plus_one(val: i32) -> i32 { val + 1 } 73 | lua.set("plus_one", td_rlua::function1(plus_one)); 74 | 75 | let val: i32 = lua.exec_string("return plus_one(3)").unwrap(); 76 | assert_eq!(lua.get_top(), 0); 77 | 78 | assert_eq!(val, 4); 79 | } 80 | 81 | #[test] 82 | fn two_arguments() { 83 | let mut lua = Lua::new(); 84 | 85 | fn add(val1: i32, val2: i32) -> i32 { val1 + val2 } 86 | lua.set("add", td_rlua::function2(add)); 87 | 88 | let val: i32 = lua.exec_string("return add(3, 7)").unwrap(); 89 | assert_eq!(lua.get_top(), 0); 90 | 91 | assert_eq!(val, 10); 92 | } 93 | 94 | #[test] 95 | fn wrong_arguments_types() { 96 | let mut lua = Lua::new(); 97 | 98 | fn add(val1: i32, val2: i32) -> i32 { val1 + val2 } 99 | lua.set("add", td_rlua::function2(add)); 100 | let val : Option = lua.exec_string("return add(3, \"hello\")"); 101 | assert_eq!(lua.get_top(), 0); 102 | 103 | match val { 104 | None => (), 105 | _ => panic!() 106 | } 107 | } 108 | 109 | 110 | #[test] 111 | fn closures() { 112 | let mut lua = Lua::new(); 113 | 114 | lua.set("add", td_rlua::function2(|a:i32, b:i32| a + b)); 115 | lua.set("sub", td_rlua::function2(|a:i32, b:i32| a - b)); 116 | 117 | let val1: i32 = lua.exec_string("return add(3, 7)").unwrap(); 118 | assert_eq!(lua.get_top(), 0); 119 | assert_eq!(val1, 10); 120 | 121 | let val2: i32 = lua.exec_string("return sub(5, 2)").unwrap(); 122 | assert_eq!(lua.get_top(), 0); 123 | assert_eq!(val2, 3); 124 | } 125 | 126 | #[test] 127 | fn closures_lifetime() { 128 | fn t(f: F) where F: Fn(i32, i32) -> i32 { 129 | let mut lua = Lua::new(); 130 | 131 | lua.set("add", td_rlua::function2(f)); 132 | 133 | let val1: i32 = lua.exec_string("return add(3, 7)").unwrap(); 134 | assert_eq!(lua.get_top(), 0); 135 | assert_eq!(val1, 10); 136 | } 137 | 138 | t(|a, b| a + b); 139 | } 140 | 141 | #[test] 142 | fn closures_extern_access() { 143 | let mut a = 5; 144 | 145 | { 146 | let mut lua = Lua::new(); 147 | 148 | lua.set("inc", td_rlua::function0(|| a += 1)); 149 | for _ in 0 .. 15 { 150 | let _: () = lua.exec_string("inc()").unwrap(); 151 | assert_eq!(lua.get_top(), 0); 152 | } 153 | } 154 | 155 | assert_eq!(a, 20) 156 | } 157 | 158 | #[test] 159 | fn test_exec_func() { 160 | let mut lua = Lua::new(); 161 | { 162 | let mut index = 5; 163 | lua.set("add", td_rlua::function1(|a:i32| index += a)); 164 | let success: i32 = lua.exec_func1("add", 3); 165 | assert_eq!(lua.get_top(), 0); 166 | assert!(success == 0); 167 | assert_eq!(index, 8); 168 | } 169 | { 170 | let mut index = 5; 171 | lua.set("sub", td_rlua::function3(|a:i32, b:u32, _c : String| index -= a + b as i32)); 172 | let success: i32 = lua.exec_func3("sub", 3, 1, "".to_string()); 173 | assert_eq!(lua.get_top(), 0); 174 | assert!(success == 0); 175 | assert_eq!(index, 1); 176 | } 177 | } 178 | 179 | #[test] 180 | fn test_exec_func_by_param() { 181 | let mut lua = Lua::new(); 182 | lua.openlibs(); 183 | let func = r" 184 | function test() 185 | return testRust(1, 2, 3); 186 | end 187 | 188 | function test2(...) 189 | local t = {...} 190 | local sum = 0 191 | for _,v in ipairs(t) do 192 | sum = sum + v 193 | end 194 | return sum 195 | end 196 | "; 197 | 198 | extern "C" fn test_rust(lua: *mut td_rlua::lua_State) -> libc::c_int { 199 | let mut lua_ob = Lua::from_existing_state(lua, false); 200 | let val: Option = lua_ob.exec_func("test2"); 201 | assert_eq!(lua_ob.get_top(), 0); 202 | val.unwrap().push_to_lua(lua); 203 | 1 204 | } 205 | lua.register("testRust", test_rust); 206 | let _: Option<()> = lua.exec_string(func); 207 | assert_eq!(lua.get_top(), 0); 208 | let ret: Option = lua.exec_string("return test();"); 209 | assert_eq!(lua.get_top(), 0); 210 | assert_eq!(ret.unwrap(), 6); 211 | } -------------------------------------------------------------------------------- /td_rlua/tests/lua_tables.rs: -------------------------------------------------------------------------------- 1 | extern crate td_rlua; 2 | 3 | use td_rlua::{Lua, LuaTable}; 4 | 5 | #[test] 6 | fn iterable() { 7 | let mut lua = Lua::new(); 8 | 9 | let _:() = lua.exec_string("a = { 9, 8, 7 }").unwrap(); 10 | 11 | let mut table : LuaTable = lua.query("a").unwrap(); 12 | let mut counter = 0; 13 | 14 | for (key, value) in table.iter().filter_map(|e| e) { 15 | let _: u32 = key; 16 | let _: u32 = value; 17 | assert_eq!(key + value, 10); 18 | counter += 1; 19 | } 20 | 21 | assert_eq!(counter, 3); 22 | } 23 | 24 | #[test] 25 | fn iterable_multipletimes() { 26 | let mut lua = Lua::new(); 27 | 28 | let _:() = lua.exec_string("a = { 9, 8, 7 }").unwrap(); 29 | 30 | let mut table : LuaTable = lua.query("a").unwrap(); 31 | 32 | for _ in 0 .. 10 { 33 | let table_content: Vec> = table.iter().collect(); 34 | assert_eq!(table_content, vec![ Some((1,9)), Some((2,8)), Some((3,7)) ]); 35 | } 36 | } 37 | 38 | #[test] 39 | fn get_set() { 40 | let mut lua = Lua::new(); 41 | 42 | let _:() = lua.exec_string("a = { 9, 8, 7 }").unwrap(); 43 | let mut table : LuaTable = lua.query("a").unwrap(); 44 | 45 | let x: i32 = table.query(2).unwrap(); 46 | assert_eq!(x, 8); 47 | 48 | table.set(3, "hello"); 49 | let y: String = table.query(3).unwrap(); 50 | assert_eq!(y, "hello"); 51 | 52 | let z: i32 = table.query(1).unwrap(); 53 | assert_eq!(z, 9); 54 | } 55 | 56 | #[test] 57 | fn table_over_table() { 58 | let mut lua = Lua::new(); 59 | 60 | let _:() = lua.exec_string("a = { 10, { 8, 7 }, 6 }").unwrap(); 61 | let mut table : LuaTable = lua.query("a").unwrap(); 62 | assert_eq!(lua.get_top(), 1); 63 | 64 | let x: i32 = table.query(1).unwrap(); 65 | assert_eq!(lua.get_top(), 1); 66 | assert_eq!(x, 10); 67 | 68 | { 69 | let mut subtable : LuaTable = table.query(2).unwrap(); 70 | 71 | assert_eq!(lua.get_top(), 2); 72 | let y: i32 = subtable.query(1).unwrap(); 73 | assert_eq!(lua.get_top(), 2); 74 | assert_eq!(y, 8); 75 | 76 | let z: i32 = subtable.query(2).unwrap(); 77 | assert_eq!(lua.get_top(), 2); 78 | assert_eq!(z, 7); 79 | } 80 | 81 | let w: i32 = table.query(3).unwrap(); 82 | assert_eq!(lua.get_top(), 1); 83 | assert_eq!(w, 6); 84 | } 85 | 86 | #[test] 87 | fn metatable() { 88 | let mut lua = Lua::new(); 89 | 90 | let _:() = lua.exec_string("a = { 9, 8, 7 }").unwrap(); 91 | 92 | { 93 | let mut table : LuaTable = lua.query("a").unwrap(); 94 | 95 | assert_eq!(lua.get_top(), 1); 96 | let mut metatable = table.get_or_create_metatable(); 97 | fn handler() -> i32 { 5 } 98 | metatable.set("__add".to_string(), td_rlua::function0(handler)); 99 | } 100 | 101 | let r: i32 = lua.exec_string("return a + a").unwrap(); 102 | assert_eq!(lua.get_top(), 0); 103 | assert_eq!(r, 5); 104 | } 105 | 106 | #[test] 107 | fn empty_array() { 108 | let mut lua = Lua::new(); 109 | 110 | { 111 | let mut array = lua.empty_table("a"); 112 | assert_eq!(lua.get_top(), 1); 113 | array.set("b", 3) 114 | } 115 | 116 | let mut table: LuaTable = lua.query("a").unwrap(); 117 | assert_eq!(lua.get_top(), 1); 118 | assert!(3 == table.query("b").unwrap()); 119 | } 120 | -------------------------------------------------------------------------------- /td_rlua/tests/rust_tables.rs: -------------------------------------------------------------------------------- 1 | extern crate td_rlua; 2 | 3 | use td_rlua::{Lua, LuaTable}; 4 | use std::collections::{HashMap, HashSet}; 5 | 6 | #[test] 7 | fn write() { 8 | let mut lua = Lua::new(); 9 | 10 | lua.set("a", vec![9, 8, 7]); 11 | 12 | let mut table: LuaTable = lua.query("a").unwrap(); 13 | assert_eq!(lua.get_top(), 1); 14 | 15 | let values: Vec<(i32, i32)> = table.iter().filter_map(|e| e).collect(); 16 | assert_eq!(values, vec!( (1, 9), (2, 8), (3, 7) )); 17 | } 18 | 19 | #[test] 20 | fn write_map() { 21 | let mut lua = Lua::new(); 22 | 23 | let mut map = HashMap::new(); 24 | map.insert(5, 8); 25 | map.insert(13, 21); 26 | map.insert(34, 55); 27 | 28 | lua.set("a", map.clone()); 29 | 30 | let mut table: LuaTable = lua.query("a").unwrap(); 31 | assert_eq!(lua.get_top(), 1); 32 | 33 | let values: HashMap = table.iter().filter_map(|e| e).collect(); 34 | assert_eq!(values, map); 35 | } 36 | 37 | #[test] 38 | fn write_set() { 39 | let mut lua = Lua::new(); 40 | 41 | let mut set = HashSet::new(); 42 | set.insert(5); 43 | set.insert(8); 44 | set.insert(13); 45 | set.insert(21); 46 | set.insert(34); 47 | set.insert(55); 48 | 49 | lua.set("a", set.clone()); 50 | 51 | let mut table: LuaTable = lua.query("a").unwrap(); 52 | assert_eq!(lua.get_top(), 1); 53 | 54 | let values: HashSet = table.iter().filter_map(|e| e) 55 | .map(|(elem, set): (i32, bool)| { 56 | assert!(set); 57 | elem 58 | }).collect(); 59 | 60 | assert_eq!(values, set); 61 | } 62 | --------------------------------------------------------------------------------