static void net_server_connected(void *arg) // for tcp only { NODE_DBG("net_server_connected is called.\n"); struct espconn *pesp_conn = arg; int i = 0; lnet_userdata *skt = NULL; if(pesp_conn == NULL) return; #if 0 char temp[20] = {0}; c_sprintf(temp, IPSTR, IP2STR( &(pesp_conn->proto.tcp->remote_ip) ) ); NODE_DBG("remote "); NODE_DBG(temp); NODE_DBG(":"); NODE_DBG("%d",pesp_conn->proto.tcp->remote_port); NODE_DBG(" connected.\n"); #endif for(i=0;i<MAX_SOCKET;i++){ if(socket[i] == LUA_NOREF) // found empty slot { break; } } if(i>=MAX_SOCKET) // can't create more socket { NODE_ERR("MAX_SOCKET\n"); pesp_conn->reverse = NULL; // not accept this conn if(pesp_conn->proto.tcp->remote_port || pesp_conn->proto.tcp->local_port) espconn_disconnect(pesp_conn); return; } if(tcpserver_cb_connect_ref == LUA_NOREF) return; if(!gL) return; lua_rawgeti(gL, LUA_REGISTRYINDEX, tcpserver_cb_connect_ref); // get function // create a new client object skt = (lnet_userdata *)lua_newuserdata(gL, sizeof(lnet_userdata)); if(!skt){ NODE_ERR("can't newudata\n"); lua_pop(gL, 1); return; } // set its metatable luaL_getmetatable(gL, "net.socket"); lua_setmetatable(gL, -2); // pre-initialize it, in case of errors skt->self_ref = LUA_NOREF; lua_pushvalue(gL, -1); // copy the top of stack skt->self_ref = luaL_ref(gL, LUA_REGISTRYINDEX); // ref to it self, for module api to find the userdata socket[i] = skt->self_ref; // save to socket array socket_num++; skt->cb_connect_ref = LUA_NOREF; // this socket already connected skt->cb_reconnect_ref = LUA_NOREF; skt->cb_disconnect_ref = LUA_NOREF; skt->cb_receive_ref = LUA_NOREF; skt->cb_send_ref = LUA_NOREF; skt->cb_dns_found_ref = LUA_NOREF; #ifdef CLIENT_SSL_ENABLE skt->secure = 0; // as a server SSL is not supported. #endif skt->pesp_conn = pesp_conn; // point to the espconn made by low level sdk pesp_conn->reverse = skt; // let espcon carray the info of this userdata(net.socket) espconn_regist_recvcb(pesp_conn, net_socket_received); espconn_regist_sentcb(pesp_conn, net_socket_sent); espconn_regist_disconcb(pesp_conn, net_server_disconnected); espconn_regist_reconcb(pesp_conn, net_server_reconnected); // now socket[i] has the client ref, and stack top has the userdata lua_call(gL, 1, 0); // function(conn) }
/* ////////////////////////////////////////////////////////////////////////////////////// * private implementation */ static tb_bool_t xm_os_find_walk(tb_char_t const* path, tb_file_info_t const* info, tb_cpointer_t priv) { // check tb_value_ref_t tuple = (tb_value_ref_t)priv; tb_assert_and_check_return_val(path && info && tuple, tb_false); // the lua lua_State* lua = (lua_State*)tuple[0].ptr; tb_assert_and_check_return_val(lua, tb_false); // the pattern tb_char_t const* pattern = (tb_char_t const*)tuple[1].cstr; tb_assert_and_check_return_val(pattern, tb_false); // remove ./ for path if (path[0] == '.' && (path[1] == '/' || path[1] == '\\')) path = path + 2; // the match mode tb_long_t mode = tuple[2].l; // the count tb_size_t* pcount = &(tuple[3].ul); // trace tb_trace_d("path[%c]: %s", info->type == TB_FILE_TYPE_DIRECTORY? 'd' : 'f', path); // find file or directory? tb_size_t match = (mode == 1)? TB_FILE_TYPE_DIRECTORY : ((mode == 0)? TB_FILE_TYPE_FILE : (TB_FILE_TYPE_FILE | TB_FILE_TYPE_DIRECTORY)); if (info->type & match) { // done path:match(pattern) lua_getfield(lua, -1, "match"); lua_pushstring(lua, path); lua_pushstring(lua, pattern); if (lua_pcall(lua, 2, 1, 0)) { // trace tb_printf("error: call string.match(%s, %s) failed: %s!\n", path, pattern, lua_tostring(lua, -1)); // failed return tb_false; } // match ok? if (lua_isstring(lua, -1) && !tb_strcmp(path, lua_tostring(lua, -1))) { // exists excludes? tb_bool_t excluded = tb_false; if (lua_istable(lua, 5)) { // the root directory size_t rootlen = 0; tb_char_t const* rootdir = luaL_checklstring(lua, 1, &rootlen); tb_assert_and_check_return_val(rootdir && rootlen, tb_false); // check tb_assert(!tb_strcmp(path, rootdir)); tb_assert(rootlen + 1 <= tb_strlen(path)); // skip the rootdir if not "." if (tb_strcmp(rootdir, ".")) path += rootlen + 1; // exclude pathes tb_int_t i = 0; tb_int_t count = (tb_int_t)lua_objlen(lua, 5); for (i = 0; i < count && !excluded; i++) { // get exclude lua_rawgeti(lua, 5, i + 1); tb_char_t const* exclude = lua_tostring(lua, -1); if (exclude) { // done path:match(exclude) lua_getfield(lua, -3, "match"); lua_pushstring(lua, path); lua_pushstring(lua, exclude); if (lua_pcall(lua, 2, 1, 0)) { // trace tb_printf("error: call string.match(%s, %s) failed: %s!\n", path, exclude, lua_tostring(lua, -1)); } // matched? excluded = lua_isstring(lua, -1) && !tb_strcmp(path, lua_tostring(lua, -1)); // pop the match result lua_pop(lua, 1); } // pop exclude lua_pop(lua, 1); } } // does not exclude this path? if (!excluded) { // save it lua_rawseti(lua, -3, (tb_int_t)(++*pcount)); // do callback function if (lua_isfunction(lua, 6)) { // do callback(path, isdir) lua_pushvalue(lua, 6); lua_pushstring(lua, path); lua_pushboolean(lua, info->type == TB_FILE_TYPE_DIRECTORY); lua_call(lua, 2, 1); // is continue? tb_bool_t is_continue = lua_toboolean(lua, -1); lua_pop(lua, 1); if (!is_continue) return tb_false; } } // pop this return value else lua_pop(lua, 1); } // pop this return value else lua_pop(lua, 1); } // continue return tb_true; }
/* ** This function has all type names as upvalues, to maximize performance. */ static int luaB_type (lua_State *L) { luaL_checkany(L, 1); lua_pushvalue(L, lua_upvalueindex(lua_type(L, 1) + 1)); return 1; }
TMODENTRY int luaopen_tek_lib_exec(lua_State *L) { struct TExecBase *TExecBase; struct LuaExecTask *lexec; TTAGITEM tags[2]; luaL_newmetatable(L, TEK_LIB_EXEC_CLASSNAME); tek_lua_register(L, NULL, tek_lib_exec_methods, 0); /* execmeta */ #if defined(ENABLE_TASKS) luaL_newmetatable(L, TEK_LIB_TASK_CLASSNAME); /* execmeta, taskmeta */ lua_pushvalue(L, -2); /* execmeta, taskmeta, execmeta */ tek_lua_register(L, NULL, tek_lib_exec_child_methods, 1); lua_pushvalue(L, -1); /* execmeta, taskmeta, taskmeta */ lua_setfield(L, -2, "__index"); lua_pop(L, 1); /* execmeta */ #endif lexec = (struct LuaExecTask *)lua_newuserdata(L, sizeof(struct LuaExecTask)); /* execmeta, luaexec */ lexec->exec = TNULL; lua_pushvalue(L, -1); /* execmeta, luaexec, luaexec */ lua_pushvalue(L, -3); /* execmeta, luaexec, luaexec, execmeta */ tek_lua_register(L, "tek.lib.exec", tek_lib_exec_funcs, 2); /* execmeta, luaexec, libtab */ lua_pushvalue(L, -2); /* execmeta, luaexec, libtab, libtab */ lua_pushvalue(L, -4); /* execmeta, luaexec, libtab, libtab, execmeta */ lua_remove(L, -4); lua_remove(L, -4); /* libtab, libtab, execmeta */ lua_setmetatable(L, -2); /* libtab, libtab */ lua_setfield(L, -2, "base"); /* libtab */ tags[0].tti_Tag = TExecBase_ModInit; tags[0].tti_Value = (TTAG) tek_lib_exec_initmodules; tags[1].tti_Tag = TTAG_DONE; lexec->task = TEKCreate(tags); if (lexec->task == TNULL) luaL_error(L, "Failed to initialize TEKlib"); lexec->exec = TExecBase = (struct TExecBase *)TGetExecBase(lexec->task); #if defined(ENABLE_TASKS) if (!tek_lib_exec_init_link_to_parent(L, lexec)) { lua_pop(L, 1); return 0; } #endif return 1; }
static int tek_lib_exec_run(lua_State *L) { struct LuaExecTask *lexec = tek_lib_exec_check(L); struct TExecBase *TExecBase = lexec->exec; struct LuaExecChild *ctx; const char *fname = TNULL; const char *chunk = TNULL; const char *taskname = TNULL; size_t extralen = 0; struct THook hook; TTAGITEM tags[2]; int nremove = 1; TBOOL abort = TTRUE; for (;;) { if (lua_istable(L, 1)) { lua_getfield(L, 1, "abort"); if (lua_isboolean(L, -1)) abort = lua_toboolean(L, -1); lua_pop(L, 1); lua_getfield(L, 1, "taskname"); taskname = lua_tostring(L, -1); nremove = 2; lua_getfield(L, 1, "func"); if (!lua_isnoneornil(L, -1)) break; lua_pop(L, 1); lua_getfield(L, 1, "filename"); if (!lua_isnoneornil(L, -1)) break; lua_pop(L, 1); lua_getfield(L, 1, "chunk"); if (!lua_isnoneornil(L, -1)) { chunk = luaL_checklstring(L, -1, &extralen); break; } luaL_error(L, "required argument missing"); } lua_pushvalue(L, 1); break; } if (!chunk) { if (lua_type(L, -1) == LUA_TSTRING) fname = luaL_checklstring(L, -1, &extralen); else if (lua_isfunction(L, -1) && !lua_iscfunction(L, -1)) chunk = tek_lib_exec_dump(L, &extralen); else luaL_error(L, "not a Lua function, filename or table"); } ctx = lua_newuserdata(L, sizeof(struct LuaExecChild) + extralen + 1); memset(ctx, 0, sizeof *ctx); ctx->exec = lexec->exec; ctx->parent = lexec; ctx->taskname = tek_lib_exec_taskname(ctx->atomname, taskname); ctx->abort = abort; if (fname) { ctx->fname = (char *) (ctx + 1); strcpy(ctx->fname, (char *) fname); } else if (chunk) { memcpy(ctx + 1, chunk, extralen); ctx->chunklen = extralen; } /* remove arguments under userdata */ while (nremove--) lua_remove(L, -2); ctx->numargs = lua_gettop(L) - 2; /* push arg[0] on the stack, will be extraarg */ lua_getglobal(L, "arg"); if (lua_istable(L, -1)) { lua_rawgeti(L, -1, 0); lua_remove(L, -2); } if (lua_type(L, -1) != LUA_TSTRING) { lua_pop(L, 1); lua_pushnil(L); } ctx->args = tek_lib_exec_getargs(L, TExecBase, 2, ctx->numargs++, 1); lua_pop(L, 1); ctx->L = lua_newstate(tek_lib_exec_allocf, TExecBase); if (ctx->L == TNULL) { tek_lib_exec_freeargs(TExecBase, ctx->args, ctx->numargs); luaL_error(L, "cannot create interpreter"); } tags[0].tti_Tag = TTask_UserData; tags[0].tti_Value = (TTAG) ctx; tags[1].tti_Tag = TTAG_DONE; TInitHook(&hook, tek_lib_exec_run_dispatch, ctx); ctx->task = TCreateTask(&hook, tags); if (ctx->task == TNULL) { tek_lib_exec_freectxargs(ctx); lua_pop(L, 1); lua_pushnil(L); return 1; } lua_getfield(L, LUA_REGISTRYINDEX, TEK_LIB_TASK_CLASSNAME); lua_setmetatable(L, -2); lua_pushvalue(L, -1); ctx->ref = luaL_ref(L, lua_upvalueindex(2)); if (ctx->abort) tek_lib_exec_register_task_hook(L, TExecBase); return 1; }
static int db_getregistry (lua_State *L) { lua_pushvalue(L, LUA_REGISTRYINDEX); return 1; }
/* Class index function * If the object is a userdata (ie, an object), it searches the field in * the alternative table stored in the corresponding "peer" table. */ static int class_index_event (lua_State* L) { int t = lua_type(L,1); if (t == LUA_TUSERDATA) { /* Access alternative table */ lua_pushstring(L,"tolua_peer"); lua_rawget(L,LUA_REGISTRYINDEX); /* stack: obj key peer */ lua_pushvalue(L,1); lua_rawget(L,-2); /* stack: obj key peer peer[u] */ if (lua_istable(L,-1)) { lua_pushvalue(L,2); /* key */ lua_rawget(L,-2); /* stack: obj key peer peer[u] value */ if (!lua_isnil(L,-1)) return 1; } lua_settop(L,2); /* stack: obj key */ /* Try metatables */ lua_pushvalue(L,1); /* stack: obj key obj */ while (lua_getmetatable(L,-1)) { /* stack: obj key obj mt */ lua_remove(L,-2); /* stack: obj key mt */ if (lua_isnumber(L,2)) /* check if key is a numeric value */ { /* try operator[] */ lua_pushstring(L,".geti"); lua_rawget(L,-2); /* stack: obj key mt func */ if (lua_isfunction(L,-1)) { lua_pushvalue(L,1); lua_pushvalue(L,2); lua_call(L,2,1); return 1; } } else { lua_pushvalue(L,2); /* stack: obj key mt key */ lua_rawget(L,-2); /* stack: obj key mt value */ if (!lua_isnil(L,-1)) return 1; else lua_pop(L,1); /* try C/C++ variable */ lua_pushstring(L,".get"); lua_rawget(L,-2); /* stack: obj key mt tget */ if (lua_istable(L,-1)) { lua_pushvalue(L,2); lua_rawget(L,-2); /* stack: obj key mt value */ if (lua_iscfunction(L,-1)) { lua_pushvalue(L,1); lua_pushvalue(L,2); lua_call(L,2,1); return 1; } else if (lua_istable(L,-1)) { /* deal with array: create table to be returned and cache it in peer */ void* u = *((void**)lua_touserdata(L,1)); lua_newtable(L); /* stack: obj key mt value table */ lua_pushstring(L,".self"); lua_pushlightuserdata(L,u); lua_rawset(L,-3); /* store usertype in ".self" */ lua_insert(L,-2); /* stack: obj key mt table value */ lua_setmetatable(L,-2); /* set stored value as metatable */ lua_pushvalue(L,-1); /* stack: obj key met table table */ lua_pushvalue(L,2); /* stack: obj key mt table table key */ lua_insert(L,-2); /* stack: obj key mt table key table */ storeatpeer(L,1); /* stack: obj key mt table */ return 1; } } } lua_settop(L,3); } lua_pushnil(L); return 1; } else if (t== LUA_TTABLE) { module_index_event(L); return 1; } lua_pushnil(L); return 1; }
int NativeDelegate::__op_minusassignment(lua_State *L) { NativeDelegate *delegate = (NativeDelegate *)lualoom_getnativepointer(L, 1, "system.NativeDelegate"); if (!delegate) { LSError("Unable to get native delegate on += operator"); } if (!delegate->_callbackCount) { return 0; } delegate->setVM(L); delegate->getCallbacks(L); int tidx = lua_gettop(L); if (!lua_istable(L, tidx)) { LSError("Bad native delegates table"); } if (lua_isfunction(L, 2) || lua_iscfunction(L, 2)) { int idx = -1; for (int i = 0; i < delegate->_callbackCount; i++) { lua_rawgeti(L, tidx, i); if (lua_equal(L, 2, -1)) { idx = i; lua_pop(L, 1); break; } lua_pop(L, 1); } // this function was never added in the first place if (idx == -1) { return 0; } // shift the other delegates down lua_pushnumber(L, (double)idx); lua_pushnil(L); lua_settable(L, tidx); int ntable = 0; if (delegate->_callbackCount > 1) { // temp table lua_newtable(L); ntable = lua_gettop(L); int c = 0; for (int nidx = 0; nidx < delegate->_callbackCount; nidx++) { lua_pushnumber(L, (double)nidx); lua_gettable(L, tidx); if (lua_isnil(L, -1)) { lua_pop(L, 1); continue; } lua_pushnumber(L, (double)c); lua_pushvalue(L, -2); lua_settable(L, ntable); // pop lua_function lua_pop(L, 1); c++; } } // clear it delegate->_callbackCount--; // and copy from new temp table for (int nidx = 0; nidx < delegate->_callbackCount; nidx++) { lua_pushnumber(L, (double)nidx); lua_pushnumber(L, (double)nidx); lua_gettable(L, ntable); lua_settable(L, tidx); } } else { LSError("Unknown type on NativeDelegate -= operator"); } return 0; }
int gt_lua_open_encseq(lua_State *L) { #ifndef NDEBUG int stack_size; #endif gt_assert(L); #ifndef NDEBUG stack_size = lua_gettop(L); #endif luaL_newmetatable(L, ENCSEQ_METATABLE); lua_pushvalue(L, -1); /* duplicate the metatable */ lua_setfield(L, -2, "__index"); lua_pushstring(L, "__gc"); lua_pushcfunction(L, encseq_lua_delete); lua_settable(L, -3); luaL_register(L, NULL, encseq_lib_m); gt_lua_export_metatable(L, ENCSEQ_METATABLE); luaL_newmetatable(L, ENCSEQ_BUFFER_METATABLE); lua_pushcfunction(L, encseq_lua_index_buffer); lua_setfield(L, -2, "__index"); lua_pushstring(L, "__gc"); lua_pushcfunction(L, encseq_lua_delete_buffer); lua_settable(L, -3); lua_pop(L, 1); luaL_newmetatable(L, ENCSEQ_READER_METATABLE); lua_pushvalue(L, -1); /* duplicate the metatable */ lua_setfield(L, -2, "__index"); lua_pushstring(L, "__gc"); lua_pushcfunction(L, encseq_reader_lua_delete); lua_settable(L, -3); luaL_register(L, NULL, encseq_reader_lib_m); gt_lua_export_metatable(L, ENCSEQ_READER_METATABLE); luaL_newmetatable(L, ENCSEQ_ENCODER_METATABLE); lua_pushvalue(L, -1); /* duplicate the metatable */ lua_setfield(L, -2, "__index"); lua_pushstring(L, "__gc"); lua_pushcfunction(L, encseq_encoder_lua_delete); lua_settable(L, -3); luaL_register(L, NULL, encseq_encoder_lib_m); gt_lua_export_metatable(L, ENCSEQ_ENCODER_METATABLE); luaL_newmetatable(L, ENCSEQ_LOADER_METATABLE); lua_pushvalue(L, -1); /* duplicate the metatable */ lua_setfield(L, -2, "__index"); lua_pushstring(L, "__gc"); lua_pushcfunction(L, encseq_loader_lua_delete); lua_settable(L, -3); luaL_register(L, NULL, encseq_loader_lib_m); gt_lua_export_metatable(L, ENCSEQ_LOADER_METATABLE); luaL_newmetatable(L, ENCSEQ_BUILDER_METATABLE); lua_pushvalue(L, -1); /* duplicate the metatable */ lua_setfield(L, -2, "__index"); lua_pushstring(L, "__gc"); lua_pushcfunction(L, encseq_builder_lua_delete); lua_settable(L, -3); luaL_register(L, NULL, encseq_builder_lib_m); gt_lua_export_metatable(L, ENCSEQ_BUILDER_METATABLE); luaL_register(L, "gt", encseq_lib_f); lua_pop(L, 1); gt_assert(lua_gettop(L) == stack_size); return 1; }
int ngx_http_lua_coroutine_create_helper(lua_State *L, ngx_http_request_t *r, ngx_http_lua_ctx_t *ctx, ngx_http_lua_co_ctx_t **pcoctx) { lua_State *vm; /* the Lua VM */ lua_State *co; /* new coroutine to be created */ ngx_http_lua_co_ctx_t *coctx; /* co ctx for the new coroutine */ luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1, "Lua function expected"); ngx_http_lua_check_context(L, ctx, NGX_HTTP_LUA_CONTEXT_REWRITE | NGX_HTTP_LUA_CONTEXT_ACCESS | NGX_HTTP_LUA_CONTEXT_CONTENT | NGX_HTTP_LUA_CONTEXT_TIMER | NGX_HTTP_LUA_CONTEXT_SSL_CERT); vm = ngx_http_lua_get_lua_vm(r, ctx); /* create new coroutine on root Lua state, so it always yields * to main Lua thread */ co = lua_newthread(vm); ngx_http_lua_probe_user_coroutine_create(r, L, co); coctx = ngx_http_lua_get_co_ctx(co, ctx); if (coctx == NULL) { coctx = ngx_http_lua_create_co_ctx(r, ctx); if (coctx == NULL) { return luaL_error(L, "no memory"); } } else { ngx_memzero(coctx, sizeof(ngx_http_lua_co_ctx_t)); coctx->co_ref = LUA_NOREF; } coctx->co = co; coctx->co_status = NGX_HTTP_LUA_CO_SUSPENDED; /* make new coroutine share globals of the parent coroutine. * NOTE: globals don't have to be separated! */ ngx_http_lua_get_globals_table(L); lua_xmove(L, co, 1); ngx_http_lua_set_globals_table(co); lua_xmove(vm, L, 1); /* move coroutine from main thread to L */ lua_pushvalue(L, 1); /* copy entry function to top of L*/ lua_xmove(L, co, 1); /* move entry function from L to co */ if (pcoctx) { *pcoctx = coctx; } #ifdef NGX_LUA_USE_ASSERT coctx->co_top = 1; #endif return 1; /* return new coroutine to Lua */ }
/// Wrapper around lua_pushvalue. /// /// \param index The second parameter to lua_pushvalue. void lutok::state::push_value(const int index) { lua_pushvalue(_pimpl->lua_state, index); }
// Lua: socket/udpserver:on( "method", function(s) ) static int net_on( lua_State* L, const char* mt ) { NODE_DBG("net_on is called.\n"); bool isserver = false; lnet_userdata *nud; size_t sl; nud = (lnet_userdata *)luaL_checkudata(L, 1, mt); luaL_argcheck(L, nud, 1, "Server/Socket expected"); if(nud==NULL){ NODE_DBG("userdata is nil.\n"); return 0; } if (mt!=NULL && c_strcmp(mt, "net.server")==0) isserver = true; else if (mt!=NULL && c_strcmp(mt, "net.socket")==0) isserver = false; else { NODE_DBG("wrong metatable for net_on.\n"); return 0; } const char *method = luaL_checklstring( L, 2, &sl ); if (method == NULL) return luaL_error( L, "wrong arg type" ); luaL_checkanyfunction(L, 3); lua_pushvalue(L, 3); // copy argument (func) to the top of stack if(!isserver && nud->pesp_conn->type == ESPCONN_TCP && sl == 10 && c_strcmp(method, "connection") == 0){ if(nud->cb_connect_ref != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, nud->cb_connect_ref); nud->cb_connect_ref = luaL_ref(L, LUA_REGISTRYINDEX); }else if(!isserver && nud->pesp_conn->type == ESPCONN_TCP && sl == 12 && c_strcmp(method, "reconnection") == 0){ if(nud->cb_reconnect_ref != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, nud->cb_reconnect_ref); nud->cb_reconnect_ref = luaL_ref(L, LUA_REGISTRYINDEX); }else if(!isserver && nud->pesp_conn->type == ESPCONN_TCP && sl == 13 && c_strcmp(method, "disconnection") == 0){ if(nud->cb_disconnect_ref != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, nud->cb_disconnect_ref); nud->cb_disconnect_ref = luaL_ref(L, LUA_REGISTRYINDEX); }else if((!isserver || nud->pesp_conn->type == ESPCONN_UDP) && sl == 7 && c_strcmp(method, "receive") == 0){ if(nud->cb_receive_ref != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, nud->cb_receive_ref); nud->cb_receive_ref = luaL_ref(L, LUA_REGISTRYINDEX); }else if((!isserver || nud->pesp_conn->type == ESPCONN_UDP) && sl == 4 && c_strcmp(method, "sent") == 0){ if(nud->cb_send_ref != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, nud->cb_send_ref); nud->cb_send_ref = luaL_ref(L, LUA_REGISTRYINDEX); }else if(!isserver && nud->pesp_conn->type == ESPCONN_TCP && sl == 3 && c_strcmp(method, "dns") == 0){ if(nud->cb_dns_found_ref != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, nud->cb_dns_found_ref); nud->cb_dns_found_ref = luaL_ref(L, LUA_REGISTRYINDEX); }else{ lua_pop(L, 1); return luaL_error( L, "method not supported" ); } return 0; }
// Lua: server:listen( port, ip, function(con) ) // Lua: socket:connect( port, ip, function(con) ) static int net_start( lua_State* L, const char* mt ) { NODE_DBG("net_start is called.\n"); struct espconn *pesp_conn = NULL; lnet_userdata *nud; unsigned port; size_t il; bool isserver = false; ip_addr_t ipaddr; const char *domain; uint8_t stack = 1; if (mt!=NULL && c_strcmp(mt, "net.server")==0) isserver = true; else if (mt!=NULL && c_strcmp(mt, "net.socket")==0) isserver = false; else { NODE_DBG("wrong metatable for net_start.\n"); return 0; } nud = (lnet_userdata *)luaL_checkudata(L, stack, mt); luaL_argcheck(L, nud, stack, "Server/Socket expected"); stack++; if(nud==NULL){ NODE_DBG("userdata is nil.\n"); return 0; } if(nud->pesp_conn == NULL){ NODE_DBG("nud->pesp_conn is NULL.\n"); return 0; } pesp_conn = nud->pesp_conn; port = luaL_checkinteger( L, stack ); stack++; if( pesp_conn->type == ESPCONN_TCP ) { if(isserver) pesp_conn->proto.tcp->local_port = port; else{ pesp_conn->proto.tcp->remote_port = port; pesp_conn->proto.tcp->local_port = espconn_port(); } NODE_DBG("TCP port is set: %d.\n", port); } else if (pesp_conn->type == ESPCONN_UDP) { if(isserver) pesp_conn->proto.udp->local_port = port; else{ pesp_conn->proto.udp->remote_port = port; pesp_conn->proto.udp->local_port = espconn_port(); } NODE_DBG("UDP port is set: %d.\n", port); } if( lua_isstring(L,stack) ) // deal with the domain string { domain = luaL_checklstring( L, stack, &il ); stack++; if (domain == NULL) { if(isserver) domain = "0.0.0.0"; else domain = "127.0.0.1"; } ipaddr.addr = ipaddr_addr(domain); if( pesp_conn->type == ESPCONN_TCP ) { if(isserver) c_memcpy(pesp_conn->proto.tcp->local_ip, &ipaddr.addr, 4); else c_memcpy(pesp_conn->proto.tcp->remote_ip, &ipaddr.addr, 4); NODE_DBG("TCP ip is set: "); NODE_DBG(IPSTR, IP2STR(&ipaddr.addr)); NODE_DBG("\n"); } else if (pesp_conn->type == ESPCONN_UDP) { if(isserver) c_memcpy(pesp_conn->proto.udp->local_ip, &ipaddr.addr, 4); else c_memcpy(pesp_conn->proto.udp->remote_ip, &ipaddr.addr, 4); NODE_DBG("UDP ip is set: "); NODE_DBG(IPSTR, IP2STR(&ipaddr.addr)); NODE_DBG("\n"); } } // call back function when a connection is obtained, tcp only if ( pesp_conn->type == ESPCONN_TCP ) { if (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION){ lua_pushvalue(L, stack); // copy argument (func) to the top of stack if(isserver) // for tcp server connected callback { if(tcpserver_cb_connect_ref != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, tcpserver_cb_connect_ref); tcpserver_cb_connect_ref = luaL_ref(L, LUA_REGISTRYINDEX); } else { if(nud->cb_connect_ref != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, nud->cb_connect_ref); nud->cb_connect_ref = luaL_ref(L, LUA_REGISTRYINDEX); } } } if(!isserver || pesp_conn->type == ESPCONN_UDP){ // self_ref is only needed by socket userdata, or udp server lua_pushvalue(L, 1); // copy to the top of stack if(nud->self_ref != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, nud->self_ref); nud->self_ref = luaL_ref(L, LUA_REGISTRYINDEX); } if( pesp_conn->type == ESPCONN_TCP ) { if(isserver){ // no secure server support for now espconn_regist_connectcb(pesp_conn, net_server_connected); // tcp server, SSL is not supported #ifdef CLIENT_SSL_ENABLE // if(nud->secure) // espconn_secure_accept(pesp_conn); // else #endif espconn_accept(pesp_conn); // if it's a server, no need to dns. espconn_regist_time(pesp_conn, tcp_server_timeover, 0); } else{ espconn_regist_connectcb(pesp_conn, net_socket_connected); espconn_regist_reconcb(pesp_conn, net_socket_reconnected); #ifdef CLIENT_SSL_ENABLE if(nud->secure){ if(pesp_conn->proto.tcp->remote_port || pesp_conn->proto.tcp->local_port) espconn_secure_disconnect(pesp_conn); // espconn_secure_connect(pesp_conn); } else #endif { if(pesp_conn->proto.tcp->remote_port || pesp_conn->proto.tcp->local_port) espconn_disconnect(pesp_conn); // espconn_connect(pesp_conn); } } } else if (pesp_conn->type == ESPCONN_UDP) { espconn_regist_recvcb(pesp_conn, net_socket_received); espconn_regist_sentcb(pesp_conn, net_socket_sent); if(pesp_conn->proto.tcp->remote_port || pesp_conn->proto.tcp->local_port) espconn_delete(pesp_conn); if(isserver) espconn_create(pesp_conn); // if it's a server, no need to dns. } if(!isserver){ if((ipaddr.addr == IPADDR_NONE) && (c_memcmp(domain,"255.255.255.255",16) != 0)) { host_ip.addr = 0; dns_reconn_count = 0; if(ESPCONN_OK == espconn_gethostbyname(pesp_conn, domain, &host_ip, socket_dns_found)){ socket_dns_found(domain, &host_ip, pesp_conn); // ip is returned in host_ip. } } else { socket_connect(pesp_conn); } } return 0; }
// Lua: s = net.create(type, secure/timeout, function(conn)) static int net_create( lua_State* L, const char* mt ) { NODE_DBG("net_create is called.\n"); struct espconn *pesp_conn = NULL; lnet_userdata *nud, *temp = NULL; unsigned type; #ifdef CLIENT_SSL_ENABLE unsigned secure = 0; #endif uint8_t stack = 1; bool isserver = false; if (mt!=NULL && c_strcmp(mt, "net.server")==0) isserver = true; else if (mt!=NULL && c_strcmp(mt, "net.socket")==0) isserver = false; else { NODE_DBG("wrong metatable for net_create.\n"); return 0; } type = luaL_checkinteger( L, stack ); if ( type != ESPCONN_TCP && type != ESPCONN_UDP ) return luaL_error( L, "wrong arg type" ); stack++; #ifdef CLIENT_SSL_ENABLE if(!isserver){ if ( lua_isnumber(L, stack) ) { secure = lua_tointeger(L, stack); stack++; if ( secure != 0 && secure != 1 ){ return luaL_error( L, "wrong arg type" ); } } else { secure = 0; // default to 0 } } #endif if(isserver && type == ESPCONN_TCP){ if ( lua_isnumber(L, stack) ) { unsigned to = lua_tointeger(L, stack); stack++; if ( to < 1 || to > 28800 ){ return luaL_error( L, "wrong arg type" ); } tcp_server_timeover = (uint16_t)to; } else { tcp_server_timeover = 30; // default to 30 } } // create a object nud = (lnet_userdata *)lua_newuserdata(L, sizeof(lnet_userdata)); // pre-initialize it, in case of errors nud->self_ref = LUA_NOREF; nud->cb_connect_ref = LUA_NOREF; nud->cb_reconnect_ref = LUA_NOREF; nud->cb_disconnect_ref = LUA_NOREF; nud->cb_receive_ref = LUA_NOREF; nud->cb_send_ref = LUA_NOREF; nud->cb_dns_found_ref = LUA_NOREF; nud->pesp_conn = NULL; #ifdef CLIENT_SSL_ENABLE nud->secure = secure; #endif // set its metatable luaL_getmetatable(L, mt); lua_setmetatable(L, -2); // create the espconn struct if(isserver && type==ESPCONN_TCP && pTcpServer){ if(tcpserver_cb_connect_ref != LUA_NOREF){ // self_ref should be unref in close() lua_pop(L,1); return luaL_error(L, "only one tcp server allowed"); } pesp_conn = nud->pesp_conn = pTcpServer; } else if(isserver && type==ESPCONN_UDP && pUdpServer){ temp = (lnet_userdata *)pUdpServer->reverse; if(temp && temp->self_ref != LUA_NOREF){ lua_pop(L,1); return luaL_error(L, "only one udp server allowed"); } pesp_conn = nud->pesp_conn = pUdpServer; } else { pesp_conn = nud->pesp_conn = (struct espconn *)c_zalloc(sizeof(struct espconn)); if(!pesp_conn) return luaL_error(L, "not enough memory"); pesp_conn->proto.tcp = NULL; pesp_conn->proto.udp = NULL; pesp_conn->reverse = NULL; if( type==ESPCONN_TCP ) { pesp_conn->proto.tcp = (esp_tcp *)c_zalloc(sizeof(esp_tcp)); if(!pesp_conn->proto.tcp){ c_free(pesp_conn); pesp_conn = nud->pesp_conn = NULL; return luaL_error(L, "not enough memory"); } NODE_DBG("TCP server/socket is set.\n"); } else if( type==ESPCONN_UDP ) { pesp_conn->proto.udp = (esp_udp *)c_zalloc(sizeof(esp_udp)); if(!pesp_conn->proto.udp){ c_free(pesp_conn); pesp_conn = nud->pesp_conn = NULL; return luaL_error(L, "not enough memory"); } NODE_DBG("UDP server/socket is set.\n"); } } pesp_conn->type = type; pesp_conn->state = ESPCONN_NONE; // reverse is for the callback function pesp_conn->reverse = nud; if(isserver && type==ESPCONN_TCP && pTcpServer==NULL){ pTcpServer = pesp_conn; } else if(isserver && type==ESPCONN_UDP && pUdpServer==NULL){ pUdpServer = pesp_conn; } gL = L; // global L for net module. // if call back function is specified, call it with para userdata // luaL_checkanyfunction(L, 2); if (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION){ lua_pushvalue(L, stack); // copy argument (func) to the top of stack lua_pushvalue(L, -2); // copy the self_ref(userdata) to the top lua_call(L, 1, 0); } return 1; }
int luaopen_libnn(lua_State *L) { lua_newtable(L); lua_pushvalue(L, -1); lua_setglobal(L, "nn"); nn_FloatSqrt_init(L); nn_FloatSquare_init(L); nn_FloatLogSoftMax_init(L); nn_FloatMSECriterion_init(L); nn_FloatSmoothL1Criterion_init(L); nn_FloatMarginCriterion_init(L); nn_FloatLogSigmoid_init(L); nn_FloatSigmoid_init(L); nn_FloatSoftMax_init(L); nn_FloatSoftPlus_init(L); nn_FloatTanh_init(L); nn_FloatSoftShrink_init(L); nn_FloatThreshold_init(L); nn_FloatPReLU_init(L); nn_FloatRReLU_init(L); nn_FloatELU_init(L); nn_FloatLeakyReLU_init(L); nn_FloatSparseLinear_init(L); nn_FloatTemporalConvolution_init(L); nn_FloatTemporalSubSampling_init(L); nn_FloatTemporalMaxPooling_init(L); nn_FloatSpatialConvolution_init(L); nn_FloatSpatialFullConvolution_init(L); nn_FloatSpatialFullConvolutionMap_init(L); nn_FloatSpatialConvolutionMM_init(L); nn_FloatSpatialConvolutionMap_init(L); nn_FloatSpatialSubSampling_init(L); nn_FloatSpatialMaxPooling_init(L); nn_FloatSpatialMaxUnpooling_init(L); nn_FloatSpatialFractionalMaxPooling_init(L); nn_FloatSpatialAveragePooling_init(L); nn_FloatSpatialAdaptiveMaxPooling_init(L); nn_FloatVolumetricConvolution_init(L); nn_FloatVolumetricConvolutionMM_init(L); nn_FloatVolumetricFullConvolution_init(L); nn_FloatVolumetricMaxPooling_init(L); nn_FloatVolumetricAveragePooling_init(L); nn_FloatMultiMarginCriterion_init(L); nn_FloatMultiLabelMarginCriterion_init(L); nn_FloatSpatialUpSamplingNearest_init(L); nn_FloatLookupTable_init(L); nn_DoubleSqrt_init(L); nn_DoubleSquare_init(L); nn_DoubleLogSoftMax_init(L); nn_DoubleMSECriterion_init(L); nn_DoubleSmoothL1Criterion_init(L); nn_DoubleMarginCriterion_init(L); nn_DoubleLogSigmoid_init(L); nn_DoubleSigmoid_init(L); nn_DoubleSoftMax_init(L); nn_DoubleSoftPlus_init(L); nn_DoubleTanh_init(L); nn_DoubleSoftShrink_init(L); nn_DoubleThreshold_init(L); nn_DoublePReLU_init(L); nn_DoubleRReLU_init(L); nn_DoubleELU_init(L); nn_DoubleLeakyReLU_init(L); nn_DoubleSparseLinear_init(L); nn_DoubleTemporalConvolution_init(L); nn_DoubleTemporalSubSampling_init(L); nn_DoubleTemporalMaxPooling_init(L); nn_DoubleSpatialMaxUnpooling_init(L); nn_DoubleSpatialConvolution_init(L); nn_DoubleSpatialFullConvolution_init(L); nn_DoubleSpatialFullConvolutionMap_init(L); nn_DoubleSpatialConvolutionMM_init(L); nn_DoubleSpatialFullConvolution_init(L); nn_DoubleSpatialConvolutionMap_init(L); nn_DoubleSpatialSubSampling_init(L); nn_DoubleSpatialMaxPooling_init(L); nn_DoubleSpatialFractionalMaxPooling_init(L); nn_DoubleSpatialAveragePooling_init(L); nn_DoubleSpatialAdaptiveMaxPooling_init(L); nn_DoubleVolumetricConvolution_init(L); nn_DoubleVolumetricConvolutionMM_init(L); nn_DoubleVolumetricFullConvolution_init(L); nn_DoubleVolumetricMaxPooling_init(L); nn_DoubleVolumetricAveragePooling_init(L); nn_DoubleMultiMarginCriterion_init(L); nn_DoubleMultiLabelMarginCriterion_init(L); nn_DoubleSpatialUpSamplingNearest_init(L); nn_DoubleLookupTable_init(L); return 1; }
void lua_tinker::push(lua_State *L, lua_tinker::table ret) { lua_pushvalue(L, ret.m_obj->m_index); }
static void auxsort (lua_State *L, int l, int u) { while (l < u) { /* for tail recursion */ int i, j; /* sort elements a[l], a[(l+u)/2] and a[u] */ lua_rawgeti(L, 1, l); lua_rawgeti(L, 1, u); if (sort_comp(L, -1, -2)) /* a[u] < a[l]? */ set2(L, l, u); /* swap a[l] - a[u] */ else lua_pop(L, 2); if (u-l == 1) break; /* only 2 elements */ i = (l+u)/2; lua_rawgeti(L, 1, i); lua_rawgeti(L, 1, l); if (sort_comp(L, -2, -1)) /* a[i]<a[l]? */ set2(L, i, l); else { lua_pop(L, 1); /* remove a[l] */ lua_rawgeti(L, 1, u); if (sort_comp(L, -1, -2)) /* a[u]<a[i]? */ set2(L, i, u); else lua_pop(L, 2); } if (u-l == 2) break; /* only 3 elements */ lua_rawgeti(L, 1, i); /* Pivot */ lua_pushvalue(L, -1); lua_rawgeti(L, 1, u-1); set2(L, i, u-1); /* a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */ i = l; j = u-1; for (;;) { /* invariant: a[l..i] <= P <= a[j..u] */ /* repeat ++i until a[i] >= P */ while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) { if (i>u) luaL_error(L, "invalid order function for sorting"); lua_pop(L, 1); /* remove a[i] */ } /* repeat --j until a[j] <= P */ while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) { if (j<l) luaL_error(L, "invalid order function for sorting"); lua_pop(L, 1); /* remove a[j] */ } if (j<i) { lua_pop(L, 3); /* pop pivot, a[i], a[j] */ break; } set2(L, i, j); } lua_rawgeti(L, 1, u-1); lua_rawgeti(L, 1, i); set2(L, u-1, i); /* swap pivot (a[u-1]) with a[i] */ /* a[l..i-1] <= a[i] == P <= a[i+1..u] */ /* adjust so that smaller half is in [j..i] and larger one in [l..u] */ if (i-l < u-i) { j=l; i=i-1; l=i+2; } else { j=i+1; i=u; u=j-2; } auxsort(L, j, i); /* call recursively the smaller one */ } /* repeat the routine for the larger one */ }
void LuaConsole::ExecOrContinue(const std::string &stmt) { int result; lua_State *L = Lua::manager->GetLuaState(); // If the statement is an expression, print its final value. result = luaL_loadbuffer(L, ("return " + stmt).c_str(), stmt.size()+7, CONSOLE_CHUNK_NAME); if (result == LUA_ERRSYNTAX) result = luaL_loadbuffer(L, stmt.c_str(), stmt.size(), CONSOLE_CHUNK_NAME); // check for an incomplete statement // (follows logic from the official Lua interpreter lua.c:incomplete()) if (result == LUA_ERRSYNTAX) { const char eofstring[] = "<eof>"; size_t msglen; const char *msg = lua_tolstring(L, -1, &msglen); if (msglen >= (sizeof(eofstring) - 1)) { const char *tail = msg + msglen - (sizeof(eofstring) - 1); if (strcmp(tail, eofstring) == 0) { // statement is incomplete -- allow the user to continue on the next line m_entry->SetText(stmt + "\n"); lua_pop(L, 1); return; } } } if (result == LUA_ERRSYNTAX) { size_t msglen; const char *msg = lua_tolstring(L, -1, &msglen); AddOutput(std::string(msg, msglen)); lua_pop(L, 1); return; } if (result == LUA_ERRMEM) { // this will probably fail too, since we've apparently // just had a memory allocation failure... AddOutput("memory allocation failure"); return; } // set the global table lua_getfield(L, LUA_REGISTRYINDEX, "ConsoleGlobal"); lua_setupvalue(L, -2, 1); std::istringstream stmt_stream(stmt); std::string string_buffer; std::getline(stmt_stream, string_buffer); AddOutput("> " + string_buffer); while(!stmt_stream.eof()) { std::getline(stmt_stream, string_buffer); AddOutput(" " + string_buffer); } // perform a protected call int top = lua_gettop(L) - 1; // -1 for the chunk itself result = lua_pcall(L, 0, LUA_MULTRET, 0); if (result == LUA_ERRRUN) { size_t len; const char *s = lua_tolstring(L, -1, &len); AddOutput(std::string(s, len)); } else if (result == LUA_ERRERR) { size_t len; const char *s = lua_tolstring(L, -1, &len); AddOutput("error in error handler: " + std::string(s, len)); } else if (result == LUA_ERRMEM) { AddOutput("memory allocation failure"); } else { int nresults = lua_gettop(L) - top; if (nresults) { std::ostringstream ss; // call tostring() on each value and display it lua_getglobal(L, "tostring"); // i starts at 1 because Lua stack uses 1-based indexing for (int i = 1; i <= nresults; ++i) { ss.str(std::string()); if (nresults > 1) ss << "[" << i << "] "; // duplicate the tostring function for the call lua_pushvalue(L, -1); lua_pushvalue(L, top+i); result = lua_pcall(L, 1, 1, 0); size_t len = 0; const char *s = 0; if (result == 0) s = lua_tolstring(L, -1, &len); ss << s ? std::string(s, len) : "<internal error when converting result to string>"; // pop the result lua_pop(L, 1); AddOutput(ss.str()); } } } // pop all return values lua_settop(L, top); // update the history list if (! result) { // command succeeded... add it to the history unless it's just // an exact repeat of the immediate last command if (m_statementHistory.empty() || (stmt != m_statementHistory.back())) m_statementHistory.push_back(stmt); // clear the entry box m_entry->SetText(""); } // always forget the history position and clear the stashed command m_historyPosition = -1; m_stashedStatement.clear(); }
int main (int argc, char* argv[]) { #ifdef LUA_VERSION_NUM /* lua 5.1 */ lua_State* L = luaL_newstate(); luaL_openlibs(L); #else lua_State* L = lua_open(); luaopen_base(L); luaopen_io(L); luaopen_string(L); luaopen_table(L); luaopen_math(L); luaopen_debug(L); #endif lua_pushstring(L,TOLUA_VERSION); lua_setglobal(L,"TOLUA_VERSION"); lua_pushstring(L,LUA_VERSION); lua_setglobal(L,"TOLUA_LUA_VERSION"); if (argc==1) { help(); return 0; } else { int i, t; lua_newtable(L); lua_setglobal(L, "_extra_parameters"); lua_newtable(L); lua_pushvalue(L,-1); lua_setglobal(L,"flags"); t = lua_gettop(L); for (i=1; i<argc; ++i) { if (*argv[i] == '-') { switch (argv[i][1]) { case 'v': version(); return 0; case 'h': help(); return 0; case 'p': setfield(L,t,"p",""); break; case 'P': setfield(L,t,"P",""); break; case 'o': setfield(L,t,"o",argv[++i]); break; case 'n': setfield(L,t,"n",argv[++i]); break; case 'H': setfield(L,t,"H",argv[++i]); break; case 'S': setfield(L,t,"S",""); break; case '1': setfield(L,t,"1",""); break; case 'L': setfield(L,t,"L",argv[++i]); break; case 'D': setfield(L,t,"D",""); break; case 'W': setfield(L,t,"W",""); break; case 'C': setfield(L,t,"C",""); break; case 'E': add_extra(L,argv[++i]); break; case 't': setfield(L,t,"t",""); break; case 'q': setfield(L,t,"q",""); break; default: error(argv[i]); break; } } else { setfield(L,t,"f",argv[i]); break; } } lua_pop(L,1); } /*#define TOLUA_SCRIPT_RUN*/ #ifndef TOLUA_SCRIPT_RUN { int tolua_tolua_open (lua_State* L); tolua_tolua_open(L); } #else { char* p; char path[BUFSIZ]; strcpy(path,argv[0]); p = strrchr(path,'/'); if (p==NULL) p = strrchr(path,'\\'); p = (p==NULL) ? path : p+1; sprintf(p,"%s","../src/bin/lua/"); lua_pushstring(L,path); lua_setglobal(L,"path"); strcat(path,"all.lua"); if( luaL_dofile(L,path) ) { printf(stderr,"dofile %s error : %s", path, lua_tostring(L, -1)); } } #endif return 0; }
void ExeciteAspPage(lua_State *L, const char *asp_page, const struct AspPageContext *context) { void *compiled_page = NULL; int result; char *error_message = NULL; struct AspliteCallbackUserdata *udata; int stack = lua_gettop(L); luaL_openlibs(L); luaopen_asplite(L); // create and populate 'context' table lua_pushstring(L, "context"); lua_newtable(L); lua_pushstring(L, "write_func"); udata = lua_newuserdata(L, sizeof(struct AspliteCallbackUserdata)); udata->context = context; udata->write_func = context->write_func; lua_pushcclosure(L, WriteCallbackWrapper, 1); lua_settable(L, -3); lua_pushstring(L, "error_func"); udata = lua_newuserdata(L, sizeof(struct AspliteCallbackUserdata)); udata->context = context; udata->write_func = context->error_func; lua_pushcclosure(L, WriteCallbackWrapper, 1); lua_settable(L, -3); lua_pushstring(L, "log_func"); udata = lua_newuserdata(L, sizeof(struct AspliteCallbackUserdata)); udata->context = context; udata->write_func = context->log_func; lua_pushcclosure(L, WriteCallbackWrapper, 1); lua_settable(L, -3); // create request table lua_pushstring(L, "request"); lua_newtable(L); lua_pushstring(L, "QUERY_STRING"); lua_pushstring(L, context->request.query_string); lua_settable(L, -3); lua_pushstring(L, "HTTP_METHOD"); lua_pushstring(L, context->request.request_method); lua_settable(L, -3); lua_pushstring(L, "REQUEST_METHOD"); lua_pushstring(L, context->request.request_method); lua_settable(L, -3); // set context.request field lua_settable(L, -3); // set asplite.context field lua_settable(L, -3); lua_pop(L, 1); // pop asplite table result = CompileAspPage(L, asp_page, &context->engine_config, &error_message); if (result) { udata = lua_newuserdata(L, sizeof(struct AspliteCallbackUserdata)); udata->context = context; udata->write_func = context->error_func; lua_pushcclosure(L, WriteCallbackWrapper, 1); lua_pushstring(L, error_message); lua_call(L, 1, 0); free(error_message); assert(stack == lua_gettop(L)); return; } #ifdef USE_EMBEDDED_DRIVER result = luaL_loadbufferx(L, asplite_Driver, sizeof(asplite_Driver), "asplite_Driver", NULL); #else result = luaL_loadfile(L, "asplite.lua"); #endif // USE_EMBEDDED_DRIVER if (result == LUA_OK) { result = lua_pcall(L, 0, 0, 0); } if (result != LUA_OK) { udata = lua_newuserdata(L, sizeof(struct AspliteCallbackUserdata)); udata->context = context; udata->write_func = context->error_func; lua_pushcclosure(L, WriteCallbackWrapper, 1); lua_pushvalue(L, -2); lua_call(L, 1, 0); } assert(stack == lua_gettop(L)); return; }
static int ngx_http_lua_ngx_timer_at(lua_State *L) { int nargs, co_ref; u_char *p; lua_State *vm; /* the main thread */ lua_State *co; ngx_msec_t delay; ngx_event_t *ev = NULL; ngx_http_request_t *r; ngx_connection_t *saved_c = NULL; ngx_http_lua_ctx_t *ctx; #if 0 ngx_http_connection_t *hc; #endif ngx_http_lua_timer_ctx_t *tctx = NULL; ngx_http_lua_main_conf_t *lmcf; #if 0 ngx_http_core_main_conf_t *cmcf; #endif nargs = lua_gettop(L); if (nargs < 2) { return luaL_error(L, "expecting at least 2 arguments but got %d", nargs); } delay = (ngx_msec_t) (luaL_checknumber(L, 1) * 1000); luaL_argcheck(L, lua_isfunction(L, 2) && !lua_iscfunction(L, 2), 2, "Lua function expected"); r = ngx_http_lua_get_req(L); if (r == NULL) { return luaL_error(L, "no request"); } ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module); if (ngx_exiting && delay > 0) { lua_pushnil(L); lua_pushliteral(L, "process exiting"); return 2; } lmcf = ngx_http_get_module_main_conf(r, ngx_http_lua_module); if (lmcf->pending_timers >= lmcf->max_pending_timers) { lua_pushnil(L); lua_pushliteral(L, "too many pending timers"); return 2; } if (lmcf->watcher == NULL) { /* create the watcher fake connection */ ngx_log_debug0(NGX_LOG_DEBUG_HTTP, ngx_cycle->log, 0, "lua creating fake watcher connection"); if (ngx_cycle->files) { saved_c = ngx_cycle->files[0]; } lmcf->watcher = ngx_get_connection(0, ngx_cycle->log); if (ngx_cycle->files) { ngx_cycle->files[0] = saved_c; } if (lmcf->watcher == NULL) { return luaL_error(L, "no memory"); } /* to work around the -1 check in ngx_worker_process_cycle: */ lmcf->watcher->fd = (ngx_socket_t) -2; lmcf->watcher->idle = 1; lmcf->watcher->read->handler = ngx_http_lua_abort_pending_timers; lmcf->watcher->data = lmcf; } vm = ngx_http_lua_get_lua_vm(r, ctx); co = lua_newthread(vm); /* L stack: time func [args] thread */ ngx_http_lua_probe_user_coroutine_create(r, L, co); lua_createtable(co, 0, 0); /* the new globals table */ /* co stack: global_tb */ lua_createtable(co, 0, 1); /* the metatable */ ngx_http_lua_get_globals_table(co); lua_setfield(co, -2, "__index"); lua_setmetatable(co, -2); /* co stack: global_tb */ ngx_http_lua_set_globals_table(co); /* co stack: <empty> */ dd("stack top: %d", lua_gettop(L)); lua_xmove(vm, L, 1); /* move coroutine from main thread to L */ /* L stack: time func [args] thread */ /* vm stack: empty */ lua_pushvalue(L, 2); /* copy entry function to top of L*/ /* L stack: time func [args] thread func */ lua_xmove(L, co, 1); /* move entry function from L to co */ /* L stack: time func [args] thread */ /* co stack: func */ ngx_http_lua_get_globals_table(co); lua_setfenv(co, -2); /* co stack: func */ lua_pushlightuserdata(L, &ngx_http_lua_coroutines_key); lua_rawget(L, LUA_REGISTRYINDEX); /* L stack: time func [args] thread corountines */ lua_pushvalue(L, -2); /* L stack: time func [args] thread coroutines thread */ co_ref = luaL_ref(L, -2); lua_pop(L, 1); /* L stack: time func [args] thread */ if (nargs > 2) { lua_pop(L, 1); /* L stack: time func [args] */ lua_xmove(L, co, nargs - 2); /* L stack: time func */ /* co stack: func [args] */ } p = ngx_alloc(sizeof(ngx_event_t) + sizeof(ngx_http_lua_timer_ctx_t), r->connection->log); if (p == NULL) { goto nomem; } ev = (ngx_event_t *) p; ngx_memzero(ev, sizeof(ngx_event_t)); p += sizeof(ngx_event_t); tctx = (ngx_http_lua_timer_ctx_t *) p; tctx->premature = 0; tctx->co_ref = co_ref; tctx->co = co; tctx->main_conf = r->main_conf; tctx->srv_conf = r->srv_conf; tctx->loc_conf = r->loc_conf; tctx->lmcf = lmcf; tctx->pool = ngx_create_pool(128, ngx_cycle->log); if (tctx->pool == NULL) { goto nomem; } if (r->connection) { tctx->listening = r->connection->listening; } else { tctx->listening = NULL; } if (r->connection->addr_text.len) { tctx->client_addr_text.data = ngx_palloc(tctx->pool, r->connection->addr_text.len); if (tctx->client_addr_text.data == NULL) { goto nomem; } ngx_memcpy(tctx->client_addr_text.data, r->connection->addr_text.data, r->connection->addr_text.len); tctx->client_addr_text.len = r->connection->addr_text.len; } else { tctx->client_addr_text.len = 0; tctx->client_addr_text.data = NULL; } if (ctx && ctx->vm_state) { tctx->vm_state = ctx->vm_state; tctx->vm_state->count++; } else { tctx->vm_state = NULL; } ev->handler = ngx_http_lua_timer_handler; ev->data = tctx; ev->log = ngx_cycle->log; lmcf->pending_timers++; ngx_add_timer(ev, delay); lua_pushinteger(L, 1); return 1; nomem: if (tctx && tctx->pool) { ngx_destroy_pool(tctx->pool); } if (ev) { ngx_free(ev); } lua_pushlightuserdata(L, &ngx_http_lua_coroutines_key); lua_rawget(L, LUA_REGISTRYINDEX); luaL_unref(L, -1, co_ref); return luaL_error(L, "no memory"); }
void callback(int type, void *event) { if (type == GGEOLOCATION_LOCATION_UPDATE_EVENT && !isUpdatingLocation_) return; if (type == GGEOLOCATION_HEADING_UPDATE_EVENT && !isUpdatingHeading_) return; if (type == GGEOLOCATION_ERROR_EVENT && !isUpdatingLocation_) return; if (type == GGEOLOCATION_LOCATION_UPDATE_EVENT && !hasEventListener(LOCATION_UPDATE)) return; if (type == GGEOLOCATION_HEADING_UPDATE_EVENT && !hasEventListener(HEADING_UPDATE)) return; if (type == GGEOLOCATION_ERROR_EVENT && !hasEventListener(ERROR)) return; luaL_rawgetptr(L, LUA_REGISTRYINDEX, &key); luaL_rawgetptr(L, -1, this); if (lua_isnil(L, -1)) { lua_pop(L, 2); return; } lua_getfield(L, -1, "dispatchEvent"); lua_pushvalue(L, -2); // create copy of geolocation if (type == GGEOLOCATION_LOCATION_UPDATE_EVENT) { lua_getfield(L, -1, "__updateLocationEvent"); ggeolocation_LocationUpdateEvent *event2 = (ggeolocation_LocationUpdateEvent*)event; lua_pushnumber(L, event2->latitude); lua_setfield(L, -2, "latitude"); lua_pushnumber(L, event2->longitude); lua_setfield(L, -2, "longitude"); lua_pushnumber(L, event2->altitude); lua_setfield(L, -2, "altitude"); } else if (type == GGEOLOCATION_HEADING_UPDATE_EVENT) { lua_getfield(L, -1, "__updateHeadingEvent"); ggeolocation_HeadingUpdateEvent *event2 = (ggeolocation_HeadingUpdateEvent*)event; lua_pushnumber(L, event2->magneticHeading); lua_setfield(L, -2, "magneticHeading"); lua_pushnumber(L, event2->trueHeading); lua_setfield(L, -2, "trueHeading"); } else if (type == GGEOLOCATION_ERROR_EVENT) { lua_getfield(L, -1, "__errorEvent"); } lua_call(L, 2, 0); // call geolocation:dispatchEvent(event) lua_pop(L, 2); }
static int tek_lib_exec_runchild(lua_State *L) { int i; struct LuaExecChild *ctx = lua_touserdata(L, 1); struct TExecBase *TExecBase = ctx->exec; lua_gc(L, LUA_GCSTOP, 0); luaL_openlibs(L); lua_gc(L, LUA_GCRESTART, 0); lua_createtable(L, ctx->numargs + 1, 0); lua_pushvalue(L, -1); lua_setglobal(L, "arg"); for (i = 0; i < ctx->numargs; ++i) { if (ctx->args[i].arg == TNULL) continue; lua_pushlstring(L, ctx->args[i].arg, ctx->args[i].len); lua_rawseti(L, -2, i); } tek_lib_exec_freectxargs(ctx); if (ctx->fname) { lua_pushstring(L, ctx->fname); lua_rawseti(L, -2, 0); ctx->status = luaL_loadfile(ctx->L, ctx->fname); } else if (ctx->chunklen) ctx->status = luaL_loadbuffer(L, (const char *) (ctx + 1), ctx->chunklen, "..."); if (ctx->status == 0) { int narg = 0; int base = lua_gettop(L) - narg; #if LUA_VERSION_NUM < 502 lua_pushcfunction(L, traceback); #else lua_pushcfunction(L, msghandler); #endif lua_insert(L, base); tek_lib_exec_register_task_hook(ctx->L, TExecBase); ctx->status = ctx->luastatus = lua_pcall(L, narg, LUA_MULTRET, base); lua_remove(L, base); if (ctx->status) { TDBPRINTF(TDB_TRACE,("pcall ctx->status=%d, signal to parent\n", ctx->status)); struct LuaExecTask *parent = ctx->parent; TSignal(parent->task, TTASK_SIG_ABORT); } else { int nres = ctx->numres = lua_gettop(L) - 2; ctx->results = tek_lib_exec_getargs(L, TExecBase, 3, nres, 0); } } TDBPRINTF(TDB_TRACE,("collecting1...\n")); lua_gc(L, LUA_GCCOLLECT, 0); return report(L, ctx->status); }
// increase lua function reference counter, return functionId int LuaJavaBridge::retainLuaFunction(lua_State *L, int functionIndex, int *retainCountReturn) { /* L: f ... */ lua_pushstring(L, LUAJ_REGISTRY_FUNCTION); /* L: f ... key */ lua_rawget(L, LUA_REGISTRYINDEX); /* L: f ... f_id */ if (!lua_istable(L, -1)) { lua_pop(L, 1); lua_newtable(L); lua_pushstring(L, LUAJ_REGISTRY_FUNCTION); lua_pushvalue(L, -2); lua_rawset(L, LUA_REGISTRYINDEX); } lua_pushstring(L, LUAJ_REGISTRY_RETAIN); /* L: f ... f_id key */ lua_rawget(L, LUA_REGISTRYINDEX); /* L: f ... f_id id_r */ if (!lua_istable(L, -1)) { lua_pop(L, 1); lua_newtable(L); lua_pushstring(L, LUAJ_REGISTRY_RETAIN); lua_pushvalue(L, -2); lua_rawset(L, LUA_REGISTRYINDEX); } // get function id lua_pushvalue(L, functionIndex - 2); /* L: f ... f_id id_r f */ lua_rawget(L, -3); /* L: f ... f_id id_r id */ int functionId; if (lua_type(L, -1) != LUA_TNUMBER) { // first retain, create new id lua_pop(L, 1); /* L: f ... f_id id_r */ s_newFunctionId++; functionId = s_newFunctionId; lua_pushvalue(L, functionIndex - 2); /* L: f ... f_id id_r f */ lua_pushinteger(L, functionId); /* L: f ... f_id id_r f id */ lua_rawset(L, -4); /* f_id[f] = id, L: f ... f_id id_r */ lua_pushinteger(L, functionId); /* L: f ... f_id id_r id */ } else { functionId = lua_tonumber(L, -1); } // get function retain lua_pushvalue(L, -1); /* L: f ... f_id id_r id id */ lua_rawget(L, -3); /* L: f ... f_id id_r id r */ int retainCount = 1; if (lua_type(L, -1) != LUA_TNUMBER) { // first retain, set retain count = 1 lua_pop(L, 1); lua_pushinteger(L, retainCount); } else { // add retain count retainCount = lua_tonumber(L, -1); retainCount++; lua_pop(L, 1); lua_pushinteger(L, retainCount); } lua_rawset(L, -3); /* id_r[id] = r, L: f ... f_id id_r */ lua_pop(L, 2); /* L: f ... */ if (retainCountReturn) *retainCountReturn = retainCount; return functionId; }
void luadebug_interactive_enter(struct lua_State *L, const char *single, const char *multi, const char *msg) { char *line, *full_line = NULL; bool multiline = false; bool stop = false; struct luadebug_interactive session; { mutex_lock(¤t_user_mutex); session.user = current_user; if (!session.user) { message(HAKA_LOG_ERROR, L"interactive", L"no input/output handler"); mutex_unlock(¤t_user_mutex); return; } luadebug_user_addref(session.user); mutex_unlock(¤t_user_mutex); } mutex_lock(&active_session_mutex); if (!single) single = "> "; if (!multi) multi = ">> "; session.user->completion = completion; if (!session.user->start(session.user, "haka")) { on_user_error(); luadebug_user_release(&session.user); mutex_unlock(&active_session_mutex); return; } current_session = &session; LUA_STACK_MARK(L); session.user->print(session.user, GREEN "entering interactive session" CLEAR ": %s\n", msg); session.L = L; session.env_index = capture_env(L, 1); assert(session.env_index != -1); session.complete.stack_env = session.env_index; while (!stop && (line = session.user->readline(session.user, multiline ? multi : single))) { int status = -1; bool is_return = false; char *current_line; if (multiline) { const size_t full_line_size = strlen(full_line); assert(full_line); full_line = realloc(full_line, full_line_size + 1 + strlen(line) + 1); full_line[full_line_size] = ' '; strcpy(full_line + full_line_size + 1, line); current_line = full_line; } else { session.user->addhistory(session.user, line); current_line = line; } while (*current_line == ' ' || *current_line == '\t') { ++current_line; } is_return = (strncmp(current_line, "return ", 7) == 0) || (strcmp(current_line, "return") == 0); if (!multiline && !is_return) { char *return_line = malloc(7 + strlen(current_line) + 1); strcpy(return_line, "return "); strcpy(return_line+7, current_line); status = luaL_loadbuffer(L, return_line, strlen(return_line), "stdin"); if (status) { lua_pop(L, 1); status = -1; } free(return_line); } if (status == -1) { status = luaL_loadbuffer(L, current_line, strlen(current_line), "stdin"); } multiline = false; /* Change the chunk environment */ lua_pushvalue(L, session.env_index); lua_setfenv(L, -2); if (status == LUA_ERRSYNTAX) { const char *message; const int k = sizeof(EOF_MARKER) / sizeof(char) - 1; size_t n; message = lua_tolstring(L, -1, &n); if (n > k && !strncmp(message + n - k, EOF_MARKER, k) && strlen(line) > 0) { multiline = true; } else { session.user->print(session.user, RED "%s" CLEAR "\n", lua_tostring(L, -1)); } lua_pop(L, 1); } else if (status == LUA_ERRMEM) { session.user->print(session.user, RED "%s" CLEAR "\n", lua_tostring(L, -1)); lua_pop(L, 1); } else { execute_print(L, session.user); lua_pop(L, 1); if (is_return) { stop = true; } } if (!multiline) { free(full_line); full_line = NULL; } else if (!full_line) { full_line = strdup(line); } free(line); } free(full_line); session.user->print(session.user, "\n"); session.user->print(session.user, GREEN "continue" CLEAR "\n"); lua_pop(L, 1); LUA_STACK_CHECK(L, 0); if (!session.user->stop(session.user)) { on_user_error(); } luadebug_user_release(&session.user); current_session = NULL; mutex_unlock(&active_session_mutex); }
MethodBase *LSProfiler::getTopMethod(lua_State *L) { int top = lua_gettop(L); lua_Debug stack; // if we get a null result here, we are out of stack if (!lua_getstack(L, 0, &stack)) { lua_settop(L, top); return NULL; } if (!lua_getinfo(L, "f", &stack)) { lua_settop(L, top); return NULL; } bool iscfunc = false; if (lua_iscfunction(L, -1)) { iscfunc = true; } #ifdef LOOM_ENABLE_JIT // We do not receive line return hooks for native calls under JIT :( // So, if we want to profile native methods, we need to be under interpreted VM if (iscfunc) { lua_settop(L, top); return NULL; } #endif lua_rawgeti(L, LUA_GLOBALSINDEX, LSINDEXMETHODLOOKUP); lua_pushvalue(L, -2); lua_rawget(L, -2); if (lua_isnil(L, -1)) { lua_settop(L, top); return NULL; } MethodBase *methodBase = (MethodBase *)lua_topointer(L, -1); lua_settop(L, top); if (iscfunc && !methodBase->isNative()) { return NULL; } if (shouldFilterFunction(methodBase->getFullMemberName())) { return NULL; } return methodBase; }
static int f_write (lua_State *L) { FILE *f = tofile(L); lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */ return g_write(L, f, 2); }
void LSProfiler::getCurrentStack(lua_State *L, utStack<MethodBase *>& stack) { int top = lua_gettop(L); lua_Debug lstack; int stackFrame = 0; MethodBase *lastMethod = NULL; while (true) { // if we get a null result here, we are out of stack if (!lua_getstack(L, stackFrame++, &lstack)) { lua_settop(L, top); return; } // something bad in denmark if (!lua_getinfo(L, "f", &lstack)) { lua_settop(L, top); return; } bool cfunc = false; if (lua_iscfunction(L, -1)) { cfunc = true; } lua_rawgeti(L, LUA_GLOBALSINDEX, LSINDEXMETHODLOOKUP); lua_pushvalue(L, -2); lua_rawget(L, -2); if (lua_isnil(L, -1)) { lua_settop(L, top); continue; } MethodBase *methodBase = (MethodBase *)lua_topointer(L, -1); lua_settop(L, top); #ifdef LOOM_ENABLE_JIT // We do not receive line return hooks for native calls under JIT :( // So, don't add to initial stack if (cfunc) { continue; } #endif if (shouldFilterFunction(methodBase->getFullMemberName())) { continue; } // we only want the root call, not the pcall wrapper if (cfunc && (lastMethod == methodBase)) { continue; } lastMethod = methodBase; stack.push(methodBase); } }
int32 interpreter::get_function_handle(lua_State* L, int32 index) { lua_pushvalue(L, index); int32 ref = luaL_ref(L, LUA_REGISTRYINDEX); return ref; }
// Lua: net.dns.resolve( domain, function(ip) ) static int net_dns_static( lua_State* L ) { const char *mt = "net.socket"; if (!lua_isstring( L, 1 )) return luaL_error( L, "wrong parameter type (domain)" ); int rfunc = LUA_NOREF; //save reference to func if (lua_type(L, 2) == LUA_TFUNCTION || lua_type(L, 2) == LUA_TLIGHTFUNCTION){ rfunc = luaL_ref(L, LUA_REGISTRYINDEX); } int rdom = luaL_ref(L, LUA_REGISTRYINDEX); //save reference to domain lua_settop(L,0); //empty stack lua_getfield(L, LUA_GLOBALSINDEX, "net"); lua_getfield(L, -1, "createConnection"); lua_remove(L, -2); //remove "net" from stack lua_pushinteger(L, UDP); // we are going to create a new dummy UDP socket lua_call(L,1,1);// after this the stack should have a socket lua_rawgeti(gL, LUA_REGISTRYINDEX, rdom); // load domain back to the stack lua_rawgeti(gL, LUA_REGISTRYINDEX, rfunc); // load the callback function back to the stack luaL_unref(L, LUA_REGISTRYINDEX, rdom); //free reference luaL_unref(L, LUA_REGISTRYINDEX, rfunc); //free reference bool isserver = false; struct espconn *pesp_conn = NULL; lnet_userdata *nud; size_t l; nud = (lnet_userdata *)luaL_checkudata(L, 1, mt); luaL_argcheck(L, nud, 1, "Server/Socket expected"); if(nud==NULL){ NODE_DBG("userdata is nil.\n"); return 0; } if(nud->pesp_conn == NULL){ NODE_DBG("nud->pesp_conn is NULL.\n"); return 0; } pesp_conn = nud->pesp_conn; lua_pushvalue(L, 1); // copy to the top of stack if(nud->self_ref != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, nud->self_ref); nud->self_ref = luaL_ref(L, LUA_REGISTRYINDEX); const char *domain = luaL_checklstring( L, 2, &l ); if (l>128 || domain == NULL) return luaL_error( L, "need <128 domain" ); if (lua_type(L, 3) == LUA_TFUNCTION || lua_type(L, 3) == LUA_TLIGHTFUNCTION){ lua_pushvalue(L, 3); // copy argument (func) to the top of stack if(nud->cb_dns_found_ref != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, nud->cb_dns_found_ref); nud->cb_dns_found_ref = luaL_ref(L, LUA_REGISTRYINDEX); } host_ip.addr = 0; if(ESPCONN_OK == espconn_gethostbyname(pesp_conn, domain, &host_ip, net_dns_found)) net_dns_found(domain, &host_ip, pesp_conn); // ip is returned in host_ip. return 0; }