// decrease lua function reference counter, return counter int LuaJavaBridge::releaseLuaFunctionById(int functionId) { lua_State *L = s_luaState; /* L: */ lua_pushstring(L, LUAJ_REGISTRY_FUNCTION); /* L: key */ lua_rawget(L, LUA_REGISTRYINDEX); /* L: f_id */ if (!lua_istable(L, -1)) { lua_pop(L, 1); LOGD("%s", "luajreleaseLuaFunctionById() - LUAJ_REGISTRY_FUNCTION not exists"); return 0; } lua_pushstring(L, LUAJ_REGISTRY_RETAIN); /* L: f_id key */ lua_rawget(L, LUA_REGISTRYINDEX); /* L: f_id id_r */ if (!lua_istable(L, -1)) { lua_pop(L, 2); LOGD("%s", "luajreleaseLuaFunctionById() - LUAJ_REGISTRY_RETAIN not exists"); return 0; } lua_pushinteger(L, functionId); /* L: f_id id_r id */ lua_rawget(L, -2); /* L: f_id id_r r */ if (lua_type(L, -1) != LUA_TNUMBER) { lua_pop(L, 3); LOGD("luajreleaseLuaFunctionById() - function id %d not found", functionId); return 0; } int retainCount = lua_tonumber(L, -1); retainCount--; if (retainCount > 0) { // update counter lua_pop(L, 1); /* L: f_id id_r */ lua_pushinteger(L, functionId); /* L: f_id id_r id */ lua_pushinteger(L, retainCount); /* L: f_id id_r id r */ lua_rawset(L, -3); /* id_r[id] = r, L: f_id id_r */ lua_pop(L, 2); LOGD("luajreleaseLuaFunctionById() - function id %d retain count = %d", functionId, retainCount); return retainCount; } // remove lua function reference lua_pop(L, 1); /* L: f_id id_r */ lua_pushinteger(L, functionId); /* L: f_id id_r id */ lua_pushnil(L); /* L: f_id id_r id nil */ lua_rawset(L, -3); /* id_r[id] = nil, L: f_id id_r */ lua_pop(L, 1); /* L: f_id */ lua_pushnil(L); /* L: f_id nil */ while (lua_next(L, -2) != 0) /* L: f_id f id */ { int value = lua_tonumber(L, -1); lua_pop(L, 1); /* L: f_id f */ if (value == functionId) { lua_pushnil(L); /* L: f_id f nil */ lua_rawset(L, -3); /* f_id[f] = nil, L: f_id */ break; } } /* L: f_id */ lua_pop(L, 1); LOGD("luajreleaseLuaFunctionById() - function id %d released", functionId); return 0; }
void LuaSerializer::pickle(lua_State *l, int idx, std::string &out, const char *key = NULL) { static char buf[256]; LUA_DEBUG_START(l); idx = lua_absindex(l, idx); if (lua_getmetatable(l, idx)) { lua_getfield(l, -1, "class"); if (lua_isnil(l, -1)) lua_pop(l, 2); else { const char *cl = lua_tostring(l, -1); snprintf(buf, sizeof(buf), "o%s\n", cl); lua_getglobal(l, cl); if (lua_isnil(l, -1)) luaL_error(l, "No Serialize method found for class '%s'\n", cl); lua_getfield(l, -1, "Serialize"); if (lua_isnil(l, -1)) luaL_error(l, "No Serialize method found for class '%s'\n", cl); lua_pushvalue(l, idx); pi_lua_protected_call(l, 1, 1); lua_remove(l, idx); lua_insert(l, idx); lua_pop(l, 3); if (lua_isnil(l, idx)) { LUA_DEBUG_END(l, 0); return; } out += buf; } } switch (lua_type(l, idx)) { case LUA_TNIL: break; case LUA_TNUMBER: { snprintf(buf, sizeof(buf), "f%f\n", lua_tonumber(l, idx)); out += buf; break; } case LUA_TBOOLEAN: { snprintf(buf, sizeof(buf), "b%d", lua_toboolean(l, idx) ? 1 : 0); out += buf; break; } case LUA_TSTRING: { lua_pushvalue(l, idx); const char *str = lua_tostring(l, -1); snprintf(buf, sizeof(buf), "s" SIZET_FMT "\n", strlen(str)); out += buf; out += str; lua_pop(l, 1); break; } case LUA_TTABLE: { lua_pushinteger(l, lua_Integer(lua_topointer(l, idx))); // ptr lua_getfield(l, LUA_REGISTRYINDEX, "PiSerializerTableRefs"); // ptr reftable lua_pushvalue(l, -2); // ptr reftable ptr lua_rawget(l, -2); // ptr reftable ??? if (!lua_isnil(l, -1)) { out += "r"; pickle(l, -3, out, key); lua_pop(l, 3); // [empty] } else { out += "t"; lua_pushvalue(l, -3); // ptr reftable nil ptr lua_pushvalue(l, idx); // ptr reftable nil ptr table lua_rawset(l, -4); // ptr reftable nil pickle(l, -3, out, key); lua_pop(l, 3); // [empty] lua_pushvalue(l, idx); lua_pushnil(l); while (lua_next(l, -2)) { if (key) { pickle(l, -2, out, key); pickle(l, -1, out, key); } else { lua_pushvalue(l, -2); const char *k = lua_tostring(l, -1); pickle(l, -3, out, k); pickle(l, -2, out, k); lua_pop(l, 1); } lua_pop(l, 1); } lua_pop(l, 1); out += "n"; } break; } case LUA_TUSERDATA: { out += "u"; lid *idp = static_cast<lid*>(lua_touserdata(l, idx)); LuaObjectBase *lo = LuaObjectBase::Lookup(*idp); if (!lo) Error("Lua serializer '%s' tried to serialize object with id 0x%08x, but it no longer exists", key, *idp); // XXX object wrappers should really have Serialize/Unserialize // methods to deal with this if (lo->Isa("SystemPath")) { SystemPath *sbp = dynamic_cast<SystemPath*>(lo->m_object); snprintf(buf, sizeof(buf), "SystemPath\n%d\n%d\n%d\n%u\n%u\n", sbp->sectorX, sbp->sectorY, sbp->sectorZ, sbp->systemIndex, sbp->bodyIndex); out += buf; break; } if (lo->Isa("Body")) { Body *b = dynamic_cast<Body*>(lo->m_object); snprintf(buf, sizeof(buf), "Body\n%u\n", Pi::game->GetSpace()->GetIndexForBody(b)); out += buf; break; } Error("Lua serializer '%s' tried to serialize unsupported userdata value", key); break; } default: Error("Lua serializer '%s' tried to serialize %s value", key, lua_typename(l, lua_type(l, idx))); break; } LUA_DEBUG_END(l, 0); }
LUA_EXPORT(int openldap_uv_lua_search(lua_State *L)) { openldap_uv_lua_handle_t *ldap = luaL_checkudata(L, 1, META_TABLE); if(!ldap->ldap) { luaL_error(L, "Handle is not connected"); } const char *dn = openldap_uv_lua__string_or_null(L, 2); const char *scope = luaL_checkstring(L, 3); int _scope; if(strcmp(scope, "LDAP_SCOPE_BASE") == 0 || strcmp(scope, "LDAP_SCOPE_BASEOBJECT") == 0) _scope = LDAP_SCOPE_BASEOBJECT; else if(strcmp(scope, "LDAP_SCOPE_ONE") == 0 || strcasecmp(scope, "LDAP_SCOPE_ONELEVEL") == 0) _scope = LDAP_SCOPE_ONELEVEL; else if(strcmp(scope, "LDAP_SCOPE_SUB") == 0 || strcasecmp(scope, "LDAP_SCOPE_SUBTREE") == 0) _scope = LDAP_SCOPE_SUBTREE; else if(strcmp(scope, "LDAP_SCOPE_CHILDREN") == 0 || strcasecmp(scope, "LDAP_SCOPE_SUBORDINATE") == 0) _scope = LDAP_SCOPE_CHILDREN; else luaL_error(L, "Unsupported scope %s", scope); const char *filter = openldap_uv_lua__string_or_null(L, 4); char **fieldSelector = NULL; if(!lua_isnil(L, 5)) { luaL_checktype(L, 5, LUA_TTABLE); int size = lua_objlen(L, 5); fieldSelector = malloc(sizeof(*fieldSelector) * (size + 1)); lua_pushnil(L); for(int i = 0; lua_next(L, 5); i++) { fieldSelector[i] = (char *)lua_tostring(L, -1); fieldSelector[i+1] = 0; lua_pop(L, 1); } lua_pop(L, 1); } int onlyFieldNames = lua_toboolean(L, 6) ? 1 : 0; LDAPMessage *message = 0; int err = ldap_search_ext_s(ldap->ldap, dn, _scope, filter, fieldSelector, onlyFieldNames, 0, 0, 0, LDAP_NO_LIMIT, &message); if(err != 0) { ldap_msgfree(message); openldap_uv_lua__check_error(L, ldap, err); } LDAPMessage *entry = ldap_first_entry(ldap->ldap, message); lua_newtable(L); while(entry) { char *dn = ldap_get_dn(ldap->ldap, entry); lua_pushstring(L, dn); free(dn); lua_newtable(L); BerElement *ber; char *attr = ldap_first_attribute(ldap->ldap, entry, &ber); int j = 0; while(attr) { struct berval **vals = ldap_get_values_len(ldap->ldap, entry, attr ); if(vals) { for(int i = 0; vals[i]; i++) { lua_pushnumber(L, ++j); lua_newtable(L); lua_pushnumber(L, 1); lua_pushstring(L, attr); lua_rawset(L, -3); lua_pushnumber(L, 2); lua_pushlstring(L, vals[i]->bv_val, vals[i]->bv_len); lua_rawset(L, -3); lua_rawset(L, -3); } ldap_value_free_len( vals ); } ldap_memfree( attr ); attr = ldap_next_attribute( ldap->ldap, entry, ber); } lua_rawset(L, -3); entry = ldap_next_entry(ldap->ldap, entry); } ldap_msgfree(message); return 1; }
static int lua_util_geturlinfo(lua_State* L) { const char* www_root=lua_tostring(L,1); const char* www_url=lua_tostring(L,2); if(!www_root) www_root="./"; if(!www_url || *www_url!='/') return 0; char url[1024]; int n=snprintf(url,sizeof(url),"%s",www_url); if(n<0 || n>=sizeof(url)) return 0; for(char* p=url;*p;p++) if(*p=='\\') *p='/'; if(strstr(url,"/../")) return 0; char* args=strchr(url,'?'); if(args) { *args=0; args++; }else args=(char*)""; char path[512]; char* p=url; while(*p=='/') p++; int l=strlen(www_root); if(l>0 && www_root[l-1]!='/') n=snprintf(path,sizeof(path),"%s/%s",www_root,p); else n=snprintf(path,sizeof(path),"%s%s",www_root,p); if(n<0 || n>=sizeof(path)) return 0; lua_newtable(L); lua_pushstring(L,url); lua_setfield(L,-2,"url"); lua_pushstring(L,"args"); lua_newtable(L); for(char* p1=args,*p2;p1;p1=p2) { p2=strchr(p1,'&'); if(p2) { *p2=0; p2++; } p=strchr(p1,'='); if(p) { *p=0; p++; if(*p1 && *p) { lua_pushstring(L,p1); lua_pushstring(L,util::url_decode(p)); lua_rawset(L,-3); } } } lua_rawset(L,-3); lua_pushstring(L,path); lua_setfield(L,-2,"path"); const char* type="none"; DIR* d=opendir(path); if(d) { type="dir"; closedir(d); }else { int fd=open(path,O_RDONLY|O_LARGEFILE); if(fd!=-1) { off64_t len=lseek64(fd,0,SEEK_END); if(len!=(off64_t)-1) { lua_pushstring(L,"length"); lua_pushnumber(L,len); lua_rawset(L,-3); } type="file"; close(fd); } } lua_pushstring(L,"type"); lua_pushstring(L,type); lua_rawset(L,-3); char ext[32]; if(util::get_file_ext(url,ext,sizeof(ext))>0) { lua_pushstring(L,"ext"); lua_pushstring(L,ext); lua_rawset(L,-3); } return 1; }
void LuaNbtReader::read_tag(int8_t type) { if(type == 0) { lua_pushnil(this->l); } else if(type == 1) { lua_pushinteger(this->l, this->read_i8()); } else if(type == 2) { lua_pushinteger(this->l, this->read_i16()); } else if(type == 3) { lua_pushinteger(this->l, this->read_i32()); } else if(type == 4) { lua_pushinteger(this->l, this->read_i64()); } else if(type == 5) { lua_pushnumber(this->l, this->read_float()); } else if(type == 6) { lua_pushnumber(this->l, this->read_double()); } else if(type == 7 || type == 8) { int32_t length = type == 7 ? this->read_i32() : this->read_i16(); if(length < 0) { luaL_error(this->l, "Array length must be non-negative"); } std::string data(this->read_string(length)); lua_pushlstring(this->l, data.data(), data.size()); } else if(type == 9) { int8_t list_type = this->read_i8(); int32_t list_length = this->read_i32(); if(list_length < 0) { luaL_error(this->l, "List length must be non-negative"); } lua_createtable(this->l, list_length, 0); lua_checkstack(this->l, 10); for(int32_t i = 0; i < list_length; ++i) { this->read_tag(list_type); lua_rawseti(this->l, -2, i + 1); } } else if(type == 10) { lua_createtable(this->l, 0, 0); lua_checkstack(this->l, 10); for(;;) { this->read_named(); if(lua_isnil(this->l, -1)) { lua_pop(this->l, 1); break; } lua_rawset(this->l, -3); } } else if(type == 11) { int32_t array_length = this->read_i32(); if(array_length < 0) { luaL_error(this->l, "Array length must be non-negative"); } lua_createtable(this->l, array_length, 0); for(int32_t i = 0; i < array_length; ++i) { lua_pushinteger(this->l, this->read_i32()); lua_rawseti(this->l, -2, i + 1); } } else { luaL_error(this->l, "Unknown NBT type: %d", type); } }
TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) { void* ptr = NULL; const char* type = NULL; void** ud = NULL; if (refid == 0) return -1; // get ptr from tolua_refid_ptr_mapping lua_pushstring(L, TOLUA_REFID_PTR_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: refid_ptr */ lua_pushinteger(L, refid); /* stack: refid_ptr refid */ lua_rawget(L, -2); /* stack: refid_ptr ptr */ ptr = lua_touserdata(L, -1); lua_pop(L, 1); /* stack: refid_ptr */ if (ptr == NULL) { lua_pop(L, 1); // Lua stack has closed, C++ object not in Lua. // printf("[LUA ERROR] remove CCObject with NULL ptr, refid: %d\n", refid); return -2; } // remove ptr from tolua_refid_ptr_mapping lua_pushinteger(L, refid); /* stack: refid_ptr refid */ lua_pushnil(L); /* stack: refid_ptr refid nil */ lua_rawset(L, -3); /* delete refid_ptr[refid], stack: refid_ptr */ lua_pop(L, 1); /* stack: - */ // get type from tolua_refid_type_mapping lua_pushstring(L, TOLUA_REFID_TYPE_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: refid_type */ lua_pushinteger(L, refid); /* stack: refid_type refid */ lua_rawget(L, -2); /* stack: refid_type type */ if (lua_isnil(L, -1)) { lua_pop(L, 2); printf("[LUA ERROR] remove CCObject with NULL type, refid: %d, ptr: %p\n", refid, ptr); return -1; } type = lua_tostring(L, -1); lua_pop(L, 1); /* stack: refid_type */ // remove type from tolua_refid_type_mapping lua_pushinteger(L, refid); /* stack: refid_type refid */ lua_pushnil(L); /* stack: refid_type refid nil */ lua_rawset(L, -3); /* delete refid_type[refid], stack: refid_type */ lua_pop(L, 1); /* stack: - */ // get ubox luaL_getmetatable(L, type); /* stack: mt */ lua_pushstring(L, "tolua_ubox"); /* stack: mt key */ lua_rawget(L, -2); /* stack: mt ubox */ if (lua_isnil(L, -1)) { // use global ubox lua_pop(L, 1); /* stack: mt */ lua_pushstring(L, "tolua_ubox"); /* stack: mt key */ lua_rawget(L, LUA_REGISTRYINDEX); /* stack: mt ubox */ }; // cleanup root tolua_remove_value_from_root(L, ptr); // check peer lua_pushlightuserdata(L, ptr); /* stack: mt ubox ptr */ lua_rawget(L,-2); /* stack: mt ubox ud */ if (lua_isnil(L, -1)) { // Lua object has released (GC), C++ object not in ubox. //printf("[LUA ERROR] remove CCObject with NULL ubox, refid: %d, ptr: %x, type: %s\n", refid, (int)ptr, type); lua_pop(L, 3); return -3; } // cleanup peer lua_pushvalue(L, LUA_REGISTRYINDEX); lua_setfenv(L, -2); ud = (void**)lua_touserdata(L, -1); lua_pop(L, 1); /* stack: mt ubox */ if (ud == NULL) { printf("[LUA ERROR] remove CCObject with NULL userdata, refid: %d, ptr: %p, type: %s\n", refid, ptr, type); lua_pop(L, 2); return -1; } // clean userdata *ud = NULL; lua_pushlightuserdata(L, ptr); /* stack: mt ubox ptr */ lua_pushnil(L); /* stack: mt ubox ptr nil */ lua_rawset(L, -3); /* ubox[ptr] = nil, stack: mt ubox */ lua_pop(L, 2); //printf("[LUA] remove CCObject, refid: %d, ptr: %x, type: %s\n", refid, (int)ptr, type); return 0; }
/* t.name - name of playlist t.size - number of elements t.elements - array of elements ------------- t.elements[i].name - element name t.elements[i].url - element url */ static int lua_m3u_parse(lua_State* L) { //printf("* %i\n",lua_gettop(L)); const char* name=lua_tostring(L,1); if(!name) name=""; const char* ext=strrchr(name,'.'); if(!ext || strcasecmp(ext+1,"m3u")) return 0; FILE* fp=fopen(name,"r"); if(!fp) return 0; else { lua_newtable(L); /* lua_pushstring(L,"path"); lua_pushstring(L,name); lua_rawset(L,-3); */ char playlist_name[256]=""; { const char* fname=strrchr(name,'/'); if(!fname) fname=name; else fname++; int n=ext-fname; if(n>=sizeof(playlist_name)) n=sizeof(playlist_name)-1; memcpy(playlist_name,fname,n); playlist_name[n]=0; } lua_pushstring(L,"name"); lua_pushstring(L,playlist_name); lua_rawset(L,-3); lua_pushstring(L,"elements"); lua_newtable(L); int idx=1; char track_name[256]=""; char track_ext[512]=""; char track_url[256]=""; char buf[256]; while(fgets(buf,sizeof(buf),fp)) { char* beg=buf; while(*beg && (*beg==' ' || *beg=='\t')) beg++; char* p=strpbrk(beg,"\r\n"); if(p) *p=0; else p=beg+strlen(beg); while(p>beg && (p[-1]==' ' || p[-1]=='\t')) p--; *p=0; p=beg; if(!strncmp(p,"\xEF\xBB\xBF",3)) // skip BOM p+=3; if(!*p) continue; if(*p=='#') { p++; static const char tag[]="EXTINF:"; static const char tag_m3u[]="EXTM3U "; if(!strncmp(p,tag,sizeof(tag)-1)) { p+=sizeof(tag)-1; while(*p && *p==' ') p++; char* p2=strchr(p,','); if(p2) { *p2=0; p2++; char* p3=strchr(p,' '); if(p3) { p3++; while(*p3 && *p3==' ') p3++; int n=snprintf(track_ext,sizeof(track_ext),"%s",p3); if(n==-1 || n>=sizeof(track_ext)) track_ext[sizeof(track_ext)-1]=0; } int n=snprintf(track_name,sizeof(track_name),"%s",p2); if(n==-1 || n>=sizeof(track_name)) track_name[sizeof(track_name)-1]=0; } }else if(!strncmp(p,tag_m3u,sizeof(tag_m3u)-1)) { p+=sizeof(tag_m3u)-1; while(*p && *p==' ') p++; lua_m3u_parse_track_ext(L,p,-5); } }else { int n=snprintf(track_url,sizeof(track_url),"%s",p); if(n==-1 || n>=sizeof(track_url)) track_url[sizeof(track_url)-1]=0; lua_pushinteger(L,idx++); lua_newtable(L); lua_pushstring(L,"name"); lua_pushstring(L,track_name); lua_rawset(L,-3); static const char file_tag[]="file://"; if(strncmp(track_url,file_tag,sizeof(file_tag)-1)) { lua_pushstring(L,"url"); lua_pushstring(L,track_url); lua_rawset(L,-3); }else { char* _track_url=track_url+sizeof(file_tag)-1; lua_pushstring(L,"path"); lua_pushstring(L,_track_url); lua_rawset(L,-3); char* pp=strrchr(track_url,'/'); if(pp) pp++; else pp=track_url; lua_pushstring(L,"url"); lua_pushstring(L,pp); lua_rawset(L,-3); int fd=open(_track_url,O_RDONLY|O_LARGEFILE); if(fd!=-1) { off64_t len=lseek64(fd,0,SEEK_END); if(len!=(off64_t)-1) { lua_pushstring(L,"length"); lua_pushnumber(L,len); lua_rawset(L,-3); } close(fd); } } lua_m3u_parse_track_ext(L,track_ext,-3); lua_rawset(L,-3); *track_name=0; *track_ext=0; *track_url=0; } } lua_rawset(L,-3); lua_pushstring(L,"size"); lua_pushinteger(L,idx-1); lua_rawset(L,-3); fclose(fp); } //printf("* %i\n",lua_gettop(L)); return 1; }
static int shared_dict_get2mqtt(lua_State * L) { ngx_http_lua_shdict_ctx_t *ctx; ngx_shm_zone_t *zone; ngx_queue_t *q, *prev; ngx_http_lua_shdict_node_t *sd; ngx_time_t *tp; int n; int total = 0; int attempts = 1024; uint64_t now; ngx_str_t zone_name,topic; double *num; bool is_expression; uint32_t hash; u_char c; n = lua_gettop(L); if (n != 2) { return luaL_error(L, "expecting 2 arguments, " "but only seen %d", n); } //zone = lua_touserdata(L, 1); //if (zone == NULL) { //return luaL_error(L, "bad \"zone\" argument"); //} zone_name.data = (u_char *) luaL_checklstring(L, 1, &zone_name.len); if (zone_name.len == 0) { lua_pushnil(L); lua_pushliteral(L, "empty zone_name"); return 2; } topic.data = (u_char *) luaL_checklstring(L, 2, &topic.len); if (topic.len == 0) { lua_pushnil(L); lua_pushliteral(L, "empty topic"); return 2; } zone = ngx_http_lua_find_zone(zone_name.data,zone_name.len); if (zone == NULL) { return luaL_error(L, "not found \"zone\" by argument: %s",zone_name.data); } ctx = zone->data; if (ctx == NULL) { return luaL_error(L, "bad \"ctx\" argument"); } tp = ngx_timeofday(); now = (uint64_t) tp->sec * 1000 + tp->msec; for(n=topic.len-1;n>=0;n--){ switch(topic.data[n]){ case '+': case '#': n=-1; is_expression=true; break; } } if(!is_expression) hash = ngx_crc32_short(topic.data, topic.len); //ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "is_expression %d,topic: %s",is_expression,topic.data); ngx_shmtx_lock(&ctx->shpool->mutex); if(!is_expression){ n = ngx_http_lua_shdict_lookup(zone, hash, topic.data, topic.len, &sd); ngx_shmtx_unlock(&ctx->shpool->mutex); if (n == NGX_OK) { lua_createtable(L, 1, 0); lua_pushlstring(L, sd->data, sd->key_len); num = (double *) (sd->data+sd->key_len); lua_pushnumber(L, *num); lua_rawset(L, -3); }else{ lua_createtable(L, 0, 0); } return 1; } if (ngx_queue_empty(&ctx->sh->queue)) { ngx_shmtx_unlock(&ctx->shpool->mutex); lua_createtable(L, 0, 0); return 1; } lua_createtable(L, 10000, 0); total = 0; q = ngx_queue_last(&ctx->sh->queue); while (q != ngx_queue_sentinel(&ctx->sh->queue)) { prev = ngx_queue_prev(q); sd = ngx_queue_data(q, ngx_http_lua_shdict_node_t, queue); if(ngx_mqtt_str_is_match(sd->data, sd->key_len,topic.data,topic.len)){ if (sd->expires == 0 || sd->expires > now) { lua_pushlstring(L, sd->data, sd->key_len); num = (double *) (sd->data+sd->key_len); lua_pushnumber(L, *num); //lua_rawseti(L, -3);//, ++total); lua_rawset(L, -3); } } q = prev; } ngx_shmtx_unlock(&ctx->shpool->mutex); return 1; }
int main(int argc,char** argv) { #if 0 const char* p=strrchr(argv[0],'/'); int rc; if(p) { char location[512]; int n=p-argv[0]; if(n>=sizeof(location)) n=sizeof(location)-1; strncpy(location,argv[0],n); location[n]=0; rc=chdir(location); argv[0]=(char*)p+1; } #else int rc = chdir("/etc/xupnpd"); #endif const char* root=getenv("XUPNPDROOTDIR"); if(root && *root) rc=chdir(root); { FILE* fp=fopen("xupnpd.lua","r"); if(fp) fclose(fp); else rc=chdir("/usr/share/xupnpd/"); } lua_State* L=lua_open(); if(L) { luaL_openlibs(L); luaopen_luaxlib(L); luaopen_luaxcore(L); luaopen_luajson(L); lua_newtable(L); for(int i=0;i<argc;i++) { lua_pushinteger(L,i+1); lua_pushstring(L,argv[i]); lua_rawset(L,-3); } lua_setglobal(L,"arg"); // char initfile[128]; // snprintf(initfile,sizeof(initfile),"%s.lua",argv[0]); const char initfile[]="xupnpd.lua"; if(luaL_loadfile(L,initfile) || lua_pcall(L,0,0,0)) { const char* s=lua_tostring(L,-1); if(core::detached) syslog(LOG_INFO,"%s",s); else fprintf(stderr,"%s\n",s); lua_pop(L,1); } lua_close(L); } return 0; }
void ngx_http_lua_inject_shdict_api(ngx_http_lua_main_conf_t *lmcf, lua_State *L) { ngx_http_lua_shdict_ctx_t *ctx; ngx_uint_t i; ngx_shm_zone_t **zone; if (lmcf->shm_zones != NULL) { lua_createtable(L, 0, lmcf->shm_zones->nelts /* nrec */); /* ngx.shared */ lua_createtable(L, 0 /* narr */, 12 /* nrec */); /* shared mt */ lua_pushcfunction(L, ngx_http_lua_shdict_get); lua_setfield(L, -2, "get"); lua_pushcfunction(L, ngx_http_lua_shdict_set); lua_setfield(L, -2, "set"); lua_pushcfunction(L, ngx_http_lua_shdict_safe_set); lua_setfield(L, -2, "safe_set"); lua_pushcfunction(L, ngx_http_lua_shdict_add); lua_setfield(L, -2, "add"); lua_pushcfunction(L, ngx_http_lua_shdict_safe_add); lua_setfield(L, -2, "safe_add"); lua_pushcfunction(L, ngx_http_lua_shdict_replace); lua_setfield(L, -2, "replace"); lua_pushcfunction(L, ngx_http_lua_shdict_incr); lua_setfield(L, -2, "incr"); lua_pushcfunction(L, ngx_http_lua_shdict_delete); lua_setfield(L, -2, "delete"); lua_pushcfunction(L, ngx_http_lua_shdict_flush_all); lua_setfield(L, -2, "flush_all"); lua_pushcfunction(L, ngx_http_lua_shdict_flush_expired); lua_setfield(L, -2, "flush_expired"); lua_pushcfunction(L, ngx_http_lua_shdict_get_keys); lua_setfield(L, -2, "get_keys"); lua_pushvalue(L, -1); /* shared mt mt */ lua_setfield(L, -2, "__index"); /* shared mt */ zone = lmcf->shm_zones->elts; for (i = 0; i < lmcf->shm_zones->nelts; i++) { ctx = zone[i]->data; lua_pushlstring(L, (char *) ctx->name.data, ctx->name.len); /* shared mt key */ lua_pushlightuserdata(L, zone[i]); /* shared mt key ud */ lua_pushvalue(L, -3); /* shared mt key ud mt */ lua_setmetatable(L, -2); /* shared mt key ud */ lua_rawset(L, -4); /* shared mt */ } lua_pop(L, 1); /* shared */ } else { lua_newtable(L); /* ngx.shared */ } lua_setfield(L, -2, "shared"); }
static int ml_gamecenter_report_score(lua_State* l) { checkargs(3, "gamecenter.report_score"); const char* category = luaL_checkstring(l, 1); int context = luaL_checkinteger(l, 2); int value = luaL_checkinteger(l, 3); GameCenterScore score = { .category = category, .context = (int64)context, .value = (int64)value, .player = NULL }; gamecenter_report_score(&score); return 0; } static PlayerScope _str_to_player_scope(const char* ps) { if(strcmp(ps, "everyone") == 0) return PS_GLOBAL; if(strcmp(ps, "friends") == 0) return PS_FRIENDS; assert(0 && "Bad player scope string"); return PS_GLOBAL; } static TimeScope _str_to_time_scope(const char* ts) { if(strcmp(ts, "day") == 0) return TS_DAY; if(strcmp(ts, "week") == 0) return TS_WEEK; if(strcmp(ts, "all") == 0) return TS_ALL; assert(0 && "Bad time scope string"); return TS_ALL; } static lua_State* cb_l = NULL; static int cb_score_ref = -1; static bool live_scores_req = false; static void _score_to_tbl(lua_State* l, GameCenterScore* s) { lua_createtable(l, 0, 4); int tbl = lua_gettop(l); lua_pushstring(l, "category"); lua_pushstring(l, s->category); lua_rawset(l, tbl); lua_pushstring(l, "context"); lua_pushinteger(l, (int)s->context); lua_rawset(l, tbl); lua_pushstring(l, "value"); lua_pushinteger(l, (int)s->value); lua_rawset(l, tbl); lua_pushstring(l, "player"); lua_pushstring(l, s->player); lua_rawset(l, tbl); }
/** * @brief Creates the Trace sub-module. * * This function simulates opening the Trace sub-module. * * @return A table defining the Trace sub-module. */ void l2dbus_openTrace ( struct lua_State* L ) { lua_newtable(L); lua_pushcfunction(L, l2dbus_traceSetFlags); lua_setfield(L, -2, "setFlags"); lua_pushcfunction(L, l2dbus_traceGetFlags); lua_setfield(L, -2, "getFlags"); /** @constant OFF This flag disables all tracing. */ lua_pushstring(L, "OFF"); lua_pushinteger(L, L2DBUS_TRC_OFF); lua_rawset(L, -3); /** @constant FATAL This flag controls the output of *FATAL* category trace messages. */ lua_pushstring(L, "FATAL"); lua_pushinteger(L, L2DBUS_TRC_FATAL); lua_rawset(L, -3); /** @constant ERROR This flag controls the output of *ERROR* category trace messages. */ lua_pushstring(L, "ERROR"); lua_pushinteger(L, L2DBUS_TRC_ERROR); lua_rawset(L, -3); /** @constant WARN This flag controls the output of *WARN* category trace messages. */ lua_pushstring(L, "WARN"); lua_pushinteger(L, L2DBUS_TRC_WARN); lua_rawset(L, -3); /** @constant INFO This flag controls the output of *INFO* category trace messages. */ lua_pushstring(L, "INFO"); lua_pushinteger(L, L2DBUS_TRC_INFO); lua_rawset(L, -3); /** @constant DEBUG This flag controls the output of *DEBUG* category trace messages. */ lua_pushstring(L, "DEBUG"); lua_pushinteger(L, L2DBUS_TRC_DEBUG); lua_rawset(L, -3); /** @constant TRACE This flag controls the output of *TRACE* category trace messages. */ lua_pushstring(L, "TRACE"); lua_pushinteger(L, L2DBUS_TRC_TRACE); lua_rawset(L, -3); /** @constant ALL This flag turns *on* (enables) all the trace flags. */ lua_pushstring(L, "ALL"); lua_pushinteger(L, L2DBUS_TRC_ALL); lua_rawset(L, -3); }
int lua_cocos2dx_dhspine_DHSkeleton_getIntersectionBySlot(lua_State* tolua_S) { int argc = 0; cocos2d::DHSkeleton* cobj = nullptr; bool ok = true; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; #endif #if COCOS2D_DEBUG >= 1 if (!tolua_isusertype(tolua_S,1,"cc.DHSkeleton",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::DHSkeleton*)tolua_tousertype(tolua_S,1,0); #if COCOS2D_DEBUG >= 1 if (!cobj) { tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_dhspine_DHSkeleton_getIntersectionBySlot'", nullptr); return 0; } #endif argc = lua_gettop(tolua_S)-1; if (argc == 3) { const char* arg0; cocos2d::Point arg1; cocos2d::Point arg2; std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "cc.DHSkeleton:getIntersectionBySlot"); arg0 = arg0_tmp.c_str(); ok &= luaval_to_point(tolua_S, 3, &arg1, "cc.DHSkeleton:getIntersectionBySlot"); ok &= luaval_to_point(tolua_S, 4, &arg2, "cc.DHSkeleton:getIntersectionBySlot"); if(!ok) { tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_dhspine_DHSkeleton_getIntersectionBySlot'", nullptr); return 0; } std::pair<bool, cocos2d::Vec2> ret = cobj->getIntersectionBySlot(arg0, arg1, arg2); lua_newtable(tolua_S); lua_pushstring(tolua_S, "intersect"); tolua_pushboolean(tolua_S, ret.first); lua_rawset(tolua_S, -3); lua_pushstring(tolua_S, "pointX"); lua_pushnumber(tolua_S, (lua_Number) ret.second.x); lua_rawset(tolua_S, -3); lua_pushstring(tolua_S, "pointY"); lua_pushnumber(tolua_S, (lua_Number) ret.second.y); lua_rawset(tolua_S, -3); return 1; } luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.DHSkeleton:getIntersectionBySlot",argc, 3); return 0; #if COCOS2D_DEBUG >= 1 tolua_lerror: tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_dhspine_DHSkeleton_getIntersectionBySlot'.",&tolua_err); #endif return 0; }
// 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; }
/** * Initialize the library, returns a table. This function is called by Lua * when this library is dynamically loaded. Note that the table is also stored * as the global "gnome" (by the "require" command), and that is accessed * from this library sometimes. * * @luaparam name This library's name, i.e. "gnome". */ int luaopen_gnome(lua_State *L) { // get this module's name, then discard the argument. lib_name = strdup(lua_tostring(L, 1)); lg_dl_init(L, &gnome_dynlink); lua_settop(L, 0); lg_debug_flags_global(L); g_type_init(); /* make the table to return, and make it global as "gnome" */ luaL_register(L, lib_name, gnome_methods); _init_module_info(L); lg_init_object(L); lg_init_debug(L); lg_init_boxed(L); lg_init_closure(L); // an object that can be used as NIL lua_pushliteral(L, "NIL"); lua_pushlightuserdata(L, NULL); lua_rawset(L, -3); // a metatable to make another table have weak values lua_newtable(L); // gnome mt lua_pushliteral(L, "v"); // gnome mt "v" lua_setfield(L, -2, "__mode"); // gnome mt // Table with all object metatables; [name] = table. When no objects // of the given type exist anymore, they may be removed if weak values // are used; this doesn't make much sense, as a program will most likely // use a certain object type again if it is used once. lua_newtable(L); // gnome mt t lua_setfield(L, 1, LUAGNOME_METATABLES); // gnome mt // objects: not a weak table. It only contains references to entries // in the aliases table; they are removed manually when the last alias // is garbage collected. lua_newtable(L); // gnome mt t lua_setfield(L, 1, LUAGNOME_WIDGETS); // gnome mt // gnome.aliases. It has automatic garbage collection (weak values). lua_newtable(L); lua_pushvalue(L, -2); lua_setmetatable(L, -2); lua_setfield(L, 1, LUAGNOME_ALIASES); // gnome mt // gnome.typemap is a table that maps hash values of native types to // their typespec_t. It is required in lg_type_normalize. lua_newtable(L); lua_setfield(L, 1, "typemap"); // gnome.fundamental_map is a table that maps hash values of fundamental // types to their index in ffi_type_map. lg_create_fundamental_map(L); lua_pop(L, 1); // gnome /* default attribute table of an object */ lua_newtable(L); // gnome t lua_setfield(L, 1, LUAGNOME_EMPTYATTR); /* execute the glue library (compiled in) */ // XXX this should be moved to the modules // luaL_loadbuffer(L, override_data, override_size, "override.lua"); // lua_pcall(L, 0, 0, 0); // make gnome its own metatable - it contains __index and maybe other // special methods. lua_pushvalue(L, -1); lua_setmetatable(L, -2); // Add the API lua_pushlightuserdata(L, &module_api); lua_setfield(L, 1, "api"); // Can't initialize Gtk right away: if memory tracing is used, it must // be activated first; otherwise, initial allocations are not noted and // lead to errors later on, e.g. when a block is reallocated. // gtk_init(NULL, NULL); // set up error logging to be more useful: display which function is // currently running before showing the error message. g_log_set_default_handler(lg_log_func, NULL); /* one retval on the stack: gnome. This is usually not used anywhere, * but you have to use the global variable "gnome". */ return 1; }
unsigned tagtransform::lua_filter_rel_member_tags(const taglist_t &rel_tags, const multitaglist_t &member_tags, const rolelist_t &member_roles, int *member_superseeded, int *make_boundary, int *make_polygon, int *roads, taglist_t &out_tags) { lua_getglobal(L, m_rel_mem_func.c_str()); lua_newtable(L); /* relations key value table */ for (taglist_t::const_iterator it = rel_tags.begin(); it != rel_tags.end(); ++it) { lua_pushstring(L, it->key.c_str()); lua_pushstring(L, it->value.c_str()); lua_rawset(L, -3); } lua_newtable(L); /* member tags table */ int idx = 1; for (multitaglist_t::const_iterator list = member_tags.begin(); list != member_tags.end(); ++list) { lua_pushnumber(L, idx++); lua_newtable(L); /* member key value table */ for (taglist_t::const_iterator it = list->begin(); it != list->end(); ++it) { lua_pushstring(L, it->key.c_str()); lua_pushstring(L, it->value.c_str()); lua_rawset(L, -3); } lua_rawset(L, -3); } lua_newtable(L); /* member roles table */ for (size_t i = 0; i < member_roles.size(); i++) { lua_pushnumber(L, i + 1); lua_pushstring(L, member_roles[i]->c_str()); lua_rawset(L, -3); } lua_pushnumber(L, member_roles.size()); if (lua_pcall(L,4,6,0)) { fprintf(stderr, "Failed to execute lua function for relation tag processing: %s\n", lua_tostring(L, -1)); /* lua function failed */ return 1; } *roads = lua_tointeger(L, -1); lua_pop(L,1); *make_polygon = lua_tointeger(L, -1); lua_pop(L,1); *make_boundary = lua_tointeger(L,-1); lua_pop(L,1); lua_pushnil(L); for (size_t i = 0; i < member_tags.size(); i++) { if (lua_next(L,-2)) { member_superseeded[i] = lua_tointeger(L,-1); lua_pop(L,1); } else { fprintf(stderr, "Failed to read member_superseeded from lua function\n"); } } lua_pop(L,2); lua_pushnil(L); while (lua_next(L,-2) != 0) { const char *key = lua_tostring(L,-2); const char *value = lua_tostring(L,-1); out_tags.push_back(tag(key, value)); lua_pop(L,1); } lua_pop(L,1); int filter = lua_tointeger(L, -1); lua_pop(L,1); return filter; }
void serverVar() { LuaFCGI_ServerInfo serverInfo = getServerInfo(); // Create table to hold these values for Lua to read from lua_createtable(Lua, 0, 0); lua_pushstring(Lua, "query_string"); lua_pushstring(Lua, serverInfo.query_string); lua_rawset(Lua, -3); lua_pushstring(Lua, "request_method"); lua_pushstring(Lua, serverInfo.request_method); lua_rawset(Lua, -3); lua_pushstring(Lua, "content_type"); lua_pushstring(Lua, serverInfo.content_type); lua_rawset(Lua, -3); lua_pushstring(Lua, "content_length"); lua_pushstring(Lua, serverInfo.content_length); lua_rawset(Lua, -3); lua_pushstring(Lua, "script_filename"); lua_pushstring(Lua, serverInfo.script_filename); lua_rawset(Lua, -3); lua_pushstring(Lua, "script_name"); lua_pushstring(Lua, serverInfo.script_name); lua_rawset(Lua, -3); lua_pushstring(Lua, "request_uri"); lua_pushstring(Lua, serverInfo.request_uri); lua_rawset(Lua, -3); lua_pushstring(Lua, "document_uri"); lua_pushstring(Lua, serverInfo.document_uri); lua_rawset(Lua, -3); lua_pushstring(Lua, "document_root"); lua_pushstring(Lua, serverInfo.document_root); lua_rawset(Lua, -3); lua_pushstring(Lua, "server_protocol"); lua_pushstring(Lua, serverInfo.server_protocol); lua_rawset(Lua, -3); lua_pushstring(Lua, "gateway_interface"); lua_pushstring(Lua, serverInfo.gateway_interface); lua_rawset(Lua, -3); lua_pushstring(Lua, "server_software"); lua_pushstring(Lua, serverInfo.server_software); lua_rawset(Lua, -3); lua_pushstring(Lua, "remote_address"); lua_pushstring(Lua, serverInfo.remote_address); lua_rawset(Lua, -3); lua_pushstring(Lua, "remote_port"); lua_pushstring(Lua, serverInfo.remote_port); lua_rawset(Lua, -3); lua_pushstring(Lua, "server_address"); lua_pushstring(Lua, serverInfo.server_address); lua_rawset(Lua, -3); lua_pushstring(Lua, "server_port"); lua_pushstring(Lua, serverInfo.server_port); lua_rawset(Lua, -3); lua_pushstring(Lua, "server_name"); lua_pushstring(Lua, serverInfo.server_name); lua_rawset(Lua, -3); lua_pushstring(Lua, "https"); lua_pushstring(Lua, serverInfo.https); lua_rawset(Lua, -3); // Set table as SERVER variable in lua lua_setglobal(Lua, "SERVER"); }
unsigned tagtransform::lua_filter_basic_tags(OsmType type, const taglist_t &tags, int *polygon, int *roads, taglist_t &out_tags) { #ifdef HAVE_LUA switch (type) { case OSMTYPE_NODE: { lua_getglobal(L, m_node_func.c_str()); break; } case OSMTYPE_WAY: { lua_getglobal(L, m_way_func.c_str()); break; } case OSMTYPE_RELATION: { lua_getglobal(L, m_rel_func.c_str()); break; } } lua_newtable(L); /* key value table */ for (taglist_t::const_iterator it = tags.begin(); it != tags.end(); ++it) { lua_pushstring(L, it->key.c_str()); lua_pushstring(L, it->value.c_str()); lua_rawset(L, -3); } lua_pushinteger(L, tags.size()); if (lua_pcall(L,2,type == OSMTYPE_WAY ? 4 : 2,0)) { fprintf(stderr, "Failed to execute lua function for basic tag processing: %s\n", lua_tostring(L, -1)); /* lua function failed */ return 1; } if (type == OSMTYPE_WAY) { assert(roads); *roads = lua_tointeger(L, -1); lua_pop(L,1); assert(polygon); *polygon = lua_tointeger(L, -1); lua_pop(L,1); } lua_pushnil(L); while (lua_next(L,-2) != 0) { const char *key = lua_tostring(L,-2); const char *value = lua_tostring(L,-1); out_tags.push_back(tag(key, value)); lua_pop(L,1); } int filter = lua_tointeger(L, -2); lua_pop(L,2); return filter; #else return 1; #endif }
static void lua_m3u_parse_track_ext(lua_State* L,const char* track_ext,int tidx) { const char* name=0; int nname=0; const char* value=0; int nvalue=0; int st=0; for(const char* p=track_ext;;p++) { switch(st) { case 0: if(*p!=' ') { name=p; st=1; } break; case 1: if(*p=='=') { nname=p-name; st=2; } else if(*p==' ') st=0; break; case 2: if(*p=='\"') st=10; else { value=p; st=3; } break; case 3: if(*p==' ' || *p==0) { nvalue=p-value; if(nname>0 && nvalue>0) { lua_pushlstring(L,name,nname); lua_pushlstring(L,value,nvalue); lua_rawset(L,tidx); } nname=0; nvalue=0; st=0; } break; case 10: if(*p=='\"') { nname=0; st=0; } else { value=p; st=11; } break; case 11: if(*p=='\"') { nvalue=p-value; if(nname>0 && nvalue>0) { lua_pushlstring(L,name,nname); lua_pushlstring(L,value,nvalue); lua_rawset(L,tidx); } nname=0; nvalue=0; st=0; } break; } if(!*p) break; } }
/* * Push a proxy userdata on the stack. * returns NULL if ok, else some error string related to bad idfunc behavior or module require problem * (error cannot happen with mode_ == eLM_ToKeeper) * * Initializes necessary structures if it's the first time 'idfunc' is being * used in this Lua state (metatable, registring it). Otherwise, increments the * reference count. */ char const* push_deep_proxy( struct s_Universe* U, lua_State* L, DEEP_PRELUDE* prelude, enum eLookupMode mode_) { DEEP_PRELUDE** proxy; // Check if a proxy already exists push_registry_subtable_mode( L, DEEP_PROXY_CACHE_KEY, "v"); // DPC lua_pushlightuserdata( L, prelude->deep); // DPC deep lua_rawget( L, -2); // DPC proxy if ( !lua_isnil( L, -1)) { lua_remove( L, -2); // proxy return NULL; } else { lua_pop( L, 1); // DPC } MUTEX_LOCK( &U->deep_lock); ++ (prelude->refcount); // one more proxy pointing to this deep data MUTEX_UNLOCK( &U->deep_lock); STACK_GROW( L, 7); STACK_CHECK( L); proxy = lua_newuserdata( L, sizeof( DEEP_PRELUDE*)); // DPC proxy ASSERT_L( proxy); *proxy = prelude; // Get/create metatable for 'idfunc' (in this state) lua_pushlightuserdata( L, prelude->idfunc); // DPC proxy idfunc get_deep_lookup( L); // DPC proxy metatable? if( lua_isnil( L, -1)) // // No metatable yet. { char const* modname; int oldtop = lua_gettop( L); // DPC proxy nil lua_pop( L, 1); // DPC proxy // 1 - make one and register it if( mode_ != eLM_ToKeeper) { prelude->idfunc( L, eDO_metatable); // DPC proxy metatable deepversion if( lua_gettop( L) - oldtop != 1 || !lua_istable( L, -2) || !lua_isstring( L, -1)) { lua_settop( L, oldtop); // DPC proxy X lua_pop( L, 3); // return "Bad idfunc(eOP_metatable): unexpected pushed value"; } luaG_pushdeepversion( L); // DPC proxy metatable deepversion deepversion if( !lua501_equal( L, -1, -2)) { lua_pop( L, 5); // return "Bad idfunc(eOP_metatable): mismatched deep version"; } lua_pop( L, 2); // DPC proxy metatable // make sure the idfunc didn't export __gc, as we will store our own lua_getfield( L, -1, "__gc"); // DPC proxy metatable __gc if( !lua_isnil( L, -1)) { lua_pop( L, 4); // return "idfunc-created metatable shouldn't contain __gc"; } lua_pop( L, 1); // DPC proxy metatable } else { // keepers need a minimal metatable that only contains __gc lua_newtable( L); // DPC proxy metatable } // Add our own '__gc' method lua_pushcfunction( L, deep_userdata_gc); // DPC proxy metatable __gc lua_setfield( L, -2, "__gc"); // DPC proxy metatable // Memorize for later rounds lua_pushvalue( L, -1); // DPC proxy metatable metatable lua_pushlightuserdata( L, prelude->idfunc); // DPC proxy metatable metatable idfunc set_deep_lookup( L); // DPC proxy metatable // 2 - cause the target state to require the module that exported the idfunc // this is needed because we must make sure the shared library is still loaded as long as we hold a pointer on the idfunc { int oldtop = lua_gettop( L); modname = (char const*) prelude->idfunc( L, eDO_module); // DPC proxy metatable // make sure the function pushed nothing on the stack! if( lua_gettop( L) - oldtop != 0) { lua_pop( L, 3); // return "Bad idfunc(eOP_module): should not push anything"; } } if( modname) // we actually got a module name { // somehow, L.registry._LOADED can exist without having registered the 'package' library. lua_getglobal( L, "require"); // DPC proxy metatable require() // check that the module is already loaded (or being loaded, we are happy either way) if( lua_isfunction( L, -1)) { lua_pushstring( L, modname); // DPC proxy metatable require() "module" lua_getfield( L, LUA_REGISTRYINDEX, "_LOADED"); // DPC proxy metatable require() "module" _R._LOADED if( lua_istable( L, -1)) { bool_t alreadyloaded; lua_pushvalue( L, -2); // DPC proxy metatable require() "module" _R._LOADED "module" lua_rawget( L, -2); // DPC proxy metatable require() "module" _R._LOADED module alreadyloaded = lua_toboolean( L, -1); if( !alreadyloaded) // not loaded { int require_result; lua_pop( L, 2); // DPC proxy metatable require() "module" // require "modname" require_result = lua_pcall( L, 1, 0, 0); // DPC proxy metatable error? if( require_result != LUA_OK) { // failed, return the error message lua_pushfstring( L, "error while requiring '%s' identified by idfunc(eOP_module): ", modname); lua_insert( L, -2); // DPC proxy metatable prefix error lua_concat( L, 2); // DPC proxy metatable error return lua_tostring( L, -1); } } else // already loaded, we are happy { lua_pop( L, 4); // DPC proxy metatable } } else // no L.registry._LOADED; can this ever happen? { lua_pop( L, 6); // return "unexpected error while requiring a module identified by idfunc(eOP_module)"; } } else // a module name, but no require() function :-( { lua_pop( L, 4); // return "lanes receiving deep userdata should register the 'package' library"; } } } STACK_MID( L, 2); // DPC proxy metatable ASSERT_L( lua_isuserdata( L, -2)); ASSERT_L( lua_istable( L, -1)); lua_setmetatable( L, -2); // DPC proxy // If we're here, we obviously had to create a new proxy, so cache it. lua_pushlightuserdata( L, (*proxy)->deep); // DPC proxy deep lua_pushvalue( L, -2); // DPC proxy deep proxy lua_rawset( L, -4); // DPC proxy lua_remove( L, -2); // proxy ASSERT_L( lua_isuserdata( L, -1)); STACK_END( L, 0); return NULL; }
static int lua_m3u_scan(lua_State* L) { const char* path=lua_tostring(L,1); if(!path) path=""; DIR* d=opendir(path); if(!d) return 0; else { lua_newtable(L); lua_pushstring(L,"filesystem"); lua_pushboolean(L,1); lua_rawset(L,-3); { const char* fname=strrchr(path,'/'); if(!fname) fname=path; else fname++; lua_pushstring(L,"name"); lua_pushstring(L,fname); lua_rawset(L,-3); } const char* delimiter="/"; if(path[strlen(path)-1]=='/') delimiter=""; lua_pushstring(L,"elements"); lua_newtable(L); int idx=1; dirent* de; while((de=readdir(d))) { if(de->d_name[0]!='.') { char track_url[256]=""; int n=snprintf(track_url,sizeof(track_url),"%s%s%s",path,delimiter,de->d_name); if(n==-1 | n>=sizeof(track_url)) track_url[sizeof(track_url)-1]=0; DIR* dd=opendir(track_url); if(dd) { closedir(dd); if(strcmp(de->d_name,"lost+found")) { lua_pushinteger(L,idx++); lua_getglobal(L,"m3u"); lua_getfield(L,-1,"scan"); lua_remove(L,-2); lua_pushstring(L,track_url); lua_call(L,1,1); lua_rawset(L,-3); // element } }else { char* p=strrchr(track_url,'/'); if(p) p++; else p=track_url; char* p2=strrchr(p,'.'); if(p2 && strcasecmp(p2+1,"srt")) { int fd=open(track_url,O_RDONLY|O_LARGEFILE); if(fd!=-1) { lua_pushinteger(L,idx++); lua_newtable(L); lua_pushstring(L,"name"); lua_pushlstring(L,p,p2-p); lua_rawset(L,-3); lua_pushstring(L,"path"); lua_pushstring(L,track_url); lua_rawset(L,-3); lua_pushstring(L,"url"); lua_pushstring(L,p); lua_rawset(L,-3); off64_t len=lseek64(fd,0,SEEK_END); if(len!=(off64_t)-1) { lua_pushstring(L,"length"); lua_pushnumber(L,len); lua_rawset(L,-3); } lua_rawset(L,-3); // element close(fd); } } } } } lua_rawset(L,-3); // elements lua_pushstring(L,"size"); lua_pushinteger(L,idx-1); lua_rawset(L,-3); closedir(d); } return 1; }
TOLUA_API void tolua_open (lua_State* L) { int top = lua_gettop(L); lua_pushstring(L,"tolua_opened"); lua_rawget(L,LUA_REGISTRYINDEX); if (!lua_isboolean(L,-1)) { lua_pushstring(L,"tolua_opened"); lua_pushboolean(L,1); lua_rawset(L,LUA_REGISTRYINDEX); /** create value root table */ lua_pushstring(L, TOLUA_VALUE_ROOT); lua_newtable(L); lua_rawset(L, LUA_REGISTRYINDEX); #ifndef LUA_VERSION_NUM /* only prior to lua 5.1 */ /* create peer object table */ lua_pushstring(L, "tolua_peers"); lua_newtable(L); /* make weak key metatable for peers indexed by userdata object */ lua_newtable(L); lua_pushliteral(L, "__mode"); lua_pushliteral(L, "k"); lua_rawset(L, -3); /* stack: string peers mt */ lua_setmetatable(L, -2); /* stack: string peers */ lua_rawset(L,LUA_REGISTRYINDEX); #endif /* create object ptr -> udata mapping table */ lua_pushstring(L,"tolua_ubox"); lua_newtable(L); /* make weak value metatable for ubox table to allow userdata to be garbage-collected */ lua_newtable(L); lua_pushliteral(L, "__mode"); lua_pushliteral(L, "v"); lua_rawset(L, -3); /* stack: string ubox mt */ lua_setmetatable(L, -2); /* stack: string ubox */ lua_rawset(L,LUA_REGISTRYINDEX); // /* create object ptr -> class type mapping table */ // lua_pushstring(L, "tolua_ptr2type"); // lua_newtable(L); // lua_rawset(L, LUA_REGISTRYINDEX); lua_pushstring(L,"tolua_super"); lua_newtable(L); lua_rawset(L,LUA_REGISTRYINDEX); lua_pushstring(L,"tolua_gc"); lua_newtable(L); lua_rawset(L,LUA_REGISTRYINDEX); /* create gc_event closure */ lua_pushstring(L, "tolua_gc_event"); lua_pushstring(L, "tolua_gc"); lua_rawget(L, LUA_REGISTRYINDEX); lua_pushstring(L, "tolua_super"); lua_rawget(L, LUA_REGISTRYINDEX); lua_pushcclosure(L, class_gc_event, 2); lua_rawset(L, LUA_REGISTRYINDEX); tolua_newmetatable(L,"tolua_commonclass"); tolua_module(L,NULL,0); tolua_beginmodule(L,NULL); tolua_module(L,"tolua",0); tolua_beginmodule(L,"tolua"); tolua_function(L,"type",tolua_bnd_type); tolua_function(L,"takeownership",tolua_bnd_takeownership); tolua_function(L,"releaseownership",tolua_bnd_releaseownership); tolua_function(L,"cast",tolua_bnd_cast); tolua_function(L,"isnull",tolua_bnd_isnulluserdata); tolua_function(L,"inherit", tolua_bnd_inherit); #ifdef LUA_VERSION_NUM /* lua 5.1 */ tolua_function(L, "setpeer", tolua_bnd_setpeer); tolua_function(L, "getpeer", tolua_bnd_getpeer); #endif tolua_endmodule(L); tolua_endmodule(L); } lua_settop(L,top); }
static void push_attack_analysis(lua_State *L, attack_analysis& aa) { lua_newtable(L); // Pushing a pointer to the current object lua_pushstring(L, "att_ptr"); lua_pushlightuserdata(L, &aa); lua_rawset(L, -3); // Registering callback function for the rating method lua_pushstring(L, "rating"); lua_pushlightuserdata(L, &get_engine(L)); lua_pushcclosure(L, &cfun_attack_rating, 1); lua_rawset(L, -3); lua_pushstring(L, "movements"); push_movements(L, aa.movements); lua_rawset(L, -3); lua_pushstring(L, "target"); push_map_location(L, aa.target); lua_rawset(L, -3); lua_pushstring(L, "target_value"); lua_pushnumber(L, aa.target_value); lua_rawset(L, -3); lua_pushstring(L, "avg_losses"); lua_pushnumber(L, aa.avg_losses); lua_rawset(L, -3); lua_pushstring(L, "chance_to_kill"); lua_pushnumber(L, aa.chance_to_kill); lua_rawset(L, -3); lua_pushstring(L, "avg_damage_inflicted"); lua_pushnumber(L, aa.avg_damage_inflicted); lua_rawset(L, -3); lua_pushstring(L, "target_starting_damage"); lua_pushinteger(L, aa.target_starting_damage); lua_rawset(L, -3); lua_pushstring(L, "avg_damage_taken"); lua_pushnumber(L, aa.avg_damage_taken); lua_rawset(L, -3); lua_pushstring(L, "resources_used"); lua_pushnumber(L, aa.resources_used); lua_rawset(L, -3); lua_pushstring(L, "terrain_quality"); lua_pushnumber(L, aa.alternative_terrain_quality); lua_rawset(L, -3); lua_pushstring(L, "alternative_terrain_quality"); lua_pushnumber(L, aa.alternative_terrain_quality); lua_rawset(L, -3); lua_pushstring(L, "vulnerability"); lua_pushnumber(L, aa.vulnerability); lua_rawset(L, -3); lua_pushstring(L, "support"); lua_pushnumber(L, aa.support); lua_rawset(L, -3); lua_pushstring(L, "leader_threat"); lua_pushboolean(L, aa.leader_threat); lua_rawset(L, -3); lua_pushstring(L, "uses_leader"); lua_pushboolean(L, aa.uses_leader); lua_rawset(L, -3); lua_pushstring(L, "is_surrounded"); lua_pushboolean(L, aa.is_surrounded); lua_rawset(L, -3); }
/* Map function * It assigns a function into the current module (or class) */ TOLUA_API void tolua_function (lua_State* L, const char* name, lua_CFunction func) { lua_pushstring(L,name); lua_pushcfunction(L,func); lua_rawset(L,-3); }
const char *LuaSerializer::unpickle(lua_State *l, const char *pos) { LUA_DEBUG_START(l); char type = *pos++; switch (type) { case 'f': { char *end; double f = strtod(pos, &end); if (pos == end) throw SavedGameCorruptException(); lua_pushnumber(l, f); pos = end+1; // skip newline break; } case 'b': { if (*pos != '0' && *pos != '1') throw SavedGameCorruptException(); bool b = (*pos == '0') ? false : true; lua_pushboolean(l, b); pos++; break; } case 's': { char *end; int len = strtol(pos, const_cast<char**>(&end), 0); if (pos == end) throw SavedGameCorruptException(); end++; // skip newline lua_pushlstring(l, end, len); pos = end + len; break; } case 't': { lua_newtable(l); lua_getfield(l, LUA_REGISTRYINDEX, "PiSerializerTableRefs"); pos = unpickle(l, pos); lua_pushvalue(l, -3); lua_rawset(l, -3); lua_pop(l, 1); while (*pos != 'n') { pos = unpickle(l, pos); pos = unpickle(l, pos); lua_rawset(l, -3); } pos++; break; } case 'r': { pos = unpickle(l, pos); lua_getfield(l, LUA_REGISTRYINDEX, "PiSerializerTableRefs"); lua_pushvalue(l, -2); lua_rawget(l, -2); if (lua_isnil(l, -1)) throw SavedGameCorruptException(); lua_insert(l, -3); lua_pop(l, 2); break; } case 'u': { const char *end = strchr(pos, '\n'); if (!end) throw SavedGameCorruptException(); int len = end - pos; end++; // skip newline if (len == 10 && strncmp(pos, "SystemPath", 10) == 0) { pos = end; Sint32 sectorX = strtol(pos, const_cast<char**>(&end), 0); if (pos == end) throw SavedGameCorruptException(); pos = end+1; // skip newline Sint32 sectorY = strtol(pos, const_cast<char**>(&end), 0); if (pos == end) throw SavedGameCorruptException(); pos = end+1; // skip newline Sint32 sectorZ = strtol(pos, const_cast<char**>(&end), 0); if (pos == end) throw SavedGameCorruptException(); pos = end+1; // skip newline Uint32 systemNum = strtoul(pos, const_cast<char**>(&end), 0); if (pos == end) throw SavedGameCorruptException(); pos = end+1; // skip newline Uint32 sbodyId = strtoul(pos, const_cast<char**>(&end), 0); if (pos == end) throw SavedGameCorruptException(); pos = end+1; // skip newline SystemPath *sbp = new SystemPath(sectorX, sectorY, sectorZ, systemNum, sbodyId); LuaSystemPath::PushToLuaGC(sbp); break; } if (len == 4 && strncmp(pos, "Body", 4) == 0) { pos = end; Uint32 n = strtoul(pos, const_cast<char**>(&end), 0); if (pos == end) throw SavedGameCorruptException(); pos = end+1; // skip newline Body *body = Pi::game->GetSpace()->GetBodyByIndex(n); if (pos == end) throw SavedGameCorruptException(); switch (body->GetType()) { case Object::BODY: LuaBody::PushToLua(body); break; case Object::SHIP: LuaShip::PushToLua(dynamic_cast<Ship*>(body)); break; case Object::SPACESTATION: LuaSpaceStation::PushToLua(dynamic_cast<SpaceStation*>(body)); break; case Object::PLANET: LuaPlanet::PushToLua(dynamic_cast<Planet*>(body)); break; case Object::STAR: LuaStar::PushToLua(dynamic_cast<Star*>(body)); break; case Object::PLAYER: LuaPlayer::PushToLua(dynamic_cast<Player*>(body)); break; default: throw SavedGameCorruptException(); } break; } throw SavedGameCorruptException(); } case 'o': { const char *end = strchr(pos, '\n'); if (!end) throw SavedGameCorruptException(); int len = end - pos; end++; // skip newline const char *cl = pos; // unpickle the object, and insert it beneath the method table value pos = unpickle(l, end); // get _G[typename] lua_rawgeti(l, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS); lua_pushlstring(l, cl, len); lua_gettable(l, -2); lua_remove(l, -2); if (lua_isnil(l, -1)) { lua_pop(l, 2); break; } lua_getfield(l, -1, "Unserialize"); if (lua_isnil(l, -1)) { lua_pushlstring(l, cl, len); luaL_error(l, "No Unserialize method found for class '%s'\n", lua_tostring(l, -1)); } lua_insert(l, -3); lua_pop(l, 1); pi_lua_protected_call(l, 1, 1); break; } default: throw SavedGameCorruptException(); } LUA_DEBUG_END(l, 1); return pos; }
/* Map constant number * It assigns a constant number into the current module (or class) */ TOLUA_API void tolua_constant (lua_State* L, const char* name, lua_Number value) { lua_pushstring(L,name); tolua_pushnumber(L,value); lua_rawset(L,-3); }
/* Top-level delegating persist function */ static void persist(PersistInfo *pi) { /* perms reftbl ... obj */ lua_checkstack(pi->L, 2); /* If the object has already been written, write a reference to it */ lua_pushvalue(pi->L, -1); /* perms reftbl ... obj obj */ lua_rawget(pi->L, 2); /* perms reftbl ... obj ref? */ if(!lua_isnil(pi->L, -1)) { /* perms reftbl ... obj ref */ int zero = 0; int ref = (int)lua_touserdata(pi->L, -1); pi->writer(pi->L, &zero, sizeof(int), pi->ud); pi->writer(pi->L, &ref, sizeof(int), pi->ud); lua_pop(pi->L, 1); /* perms reftbl ... obj ref */ #ifdef PLUTO_DEBUG printindent(pi->level); printf("0 %d\n", ref); #endif return; } /* perms reftbl ... obj nil */ lua_pop(pi->L, 1); /* perms reftbl ... obj */ /* If the object is nil, write the pseudoreference 0 */ if(lua_isnil(pi->L, -1)) { int zero = 0; /* firsttime */ pi->writer(pi->L, &zero, sizeof(int), pi->ud); /* ref */ pi->writer(pi->L, &zero, sizeof(int), pi->ud); #ifdef PLUTO_DEBUG printindent(pi->level); printf("0 0\n"); #endif return; } { /* indicate that it's the first time */ int one = 1; pi->writer(pi->L, &one, sizeof(int), pi->ud); } lua_pushvalue(pi->L, -1); /* perms reftbl ... obj obj */ lua_pushlightuserdata(pi->L, (void*)(++(pi->counter))); /* perms reftbl ... obj obj ref */ lua_rawset(pi->L, 2); /* perms reftbl ... obj */ pi->writer(pi->L, &pi->counter, sizeof(int), pi->ud); /* At this point, we'll give the permanents table a chance to play. */ { lua_pushvalue(pi->L, -1); /* perms reftbl ... obj obj */ lua_gettable(pi->L, 1); /* perms reftbl ... obj permkey? */ if(!lua_isnil(pi->L, -1)) { /* perms reftbl ... obj permkey */ int type = PLUTO_TPERMANENT; #ifdef PLUTO_DEBUG printindent(pi->level); printf("1 %d PERM\n", pi->counter); pi->level++; #endif pi->writer(pi->L, &type, sizeof(int), pi->ud); persist(pi); lua_pop(pi->L, 1); /* perms reftbl ... obj */ #ifdef PLUTO_DEBUG pi->level--; #endif return; } else { /* perms reftbl ... obj nil */ lua_pop(pi->L, 1); /* perms reftbl ... obj */ } /* perms reftbl ... obj */ } { int type = lua_type(pi->L, -1); pi->writer(pi->L, &type, sizeof(int), pi->ud); #ifdef PLUTO_DEBUG printindent(pi->level); printf("1 %d %d\n", pi->counter, type); pi->level++; #endif } switch(lua_type(pi->L, -1)) { case LUA_TBOOLEAN: persistboolean(pi); break; case LUA_TLIGHTUSERDATA: persistlightuserdata(pi); break; case LUA_TNUMBER: persistnumber(pi); break; case LUA_TSTRING: persiststring(pi); break; case LUA_TTABLE: persisttable(pi); break; case LUA_TFUNCTION: persistfunction(pi); break; case LUA_TTHREAD: persistthread(pi); break; case LUA_TPROTO: persistproto(pi); break; case LUA_TUPVAL: persistupval(pi); break; case LUA_TUSERDATA: persistuserdata(pi); break; default: lua_assert(0); } #ifdef PLUTO_DEBUG pi->level--; #endif }
/** * Look up a name in the given module. This works for functions, like * gtk.window_new(), constants, like gtk.WINDOW_TOPLEVEL, and global variables. * Lua Stack: [1]=gnome [2]=name * * @name __index * @luaparam mod The module to look in (a table) * @luaparam key The name of the item to look up * @luareturn Either a userdata (for ENUMs) or a closure (for * functions) */ static int lg_generic_index(lua_State *L) { size_t name_len, prefix_len = 0; const char *name = luaL_checklstring(L, 2, &name_len); struct func_info fi = { 0 }; char symname[70]; cmi mi; // Get the module. No checks here because this function is called // by Lua and should always have the correct arguments. lua_getfield(L, 1, "_modinfo"); mi = lua_touserdata(L, -1); lua_pop(L, 1); // check arguments if (!name || !*name) return luaL_error(L, "%s attempt to look up a NULL or empty string", msgprefix); prefix_len = strlen(mi->prefix_func); prefix_len = MAX(prefix_len, strlen(mi->prefix_constant)); if (name_len + prefix_len > sizeof(symname) - 10) return luaL_error(L, "%s key is too long, max is %d", msgprefix, sizeof(symname) - 10); /* if it starts with an uppercase letter, it's probably an ENUM. */ if (name[0] >= 'A' && name[0] <= 'Z') { int val; const char *prefix = mi->prefix_constant; typespec_t ts = { 0 }; ts.module_idx = mi->module_idx; for (;;) { sprintf(symname, "%s%s", prefix ? prefix : "", name); // strcpy(symname, prefix); // strcat(symname, name); switch (lg_find_constant(L, &ts, symname, -1, &val)) { case 1: // ENUM/FLAG found return lg_push_constant(L, ts, val); case 2: // integer found lua_pushinteger(L, val); /* fall through */ case 3: // string found - is on Lua stack return 1; } if (!prefix) break; prefix = NULL; } } // If it starts with "__", then remove that and don't look for // overrides. This is something that overrides written in Lua can use, // to avoid recursively calling itself instead of the Gtk function. if (name[0] == '_' && name[1] == '_') { strcpy(symname, name + 2); if (!lg_find_func(L, mi, symname, &fi)) return luaL_error(L, "%s not found: %s.%s", msgprefix, mi->name, name); goto found_func; } // Check for an override (with the function prefix). strcpy(symname, mi->prefix_func); strcat(symname, name); lua_pushstring(L, symname); lua_rawget(L, 1); if (!lua_isnil(L, -1)) { lua_pushstring(L, name); lua_pushvalue(L, -2); lua_rawset(L, 1); return 1; } lua_pop(L, 1); // Otherwise, simply look it up if (lg_find_func(L, mi, symname, &fi)) goto found_func; // maybe it's a function but with the prefix already added. if (*mi->prefix_func && lg_find_func(L, mi, name, &fi)) goto found_func; // Might be a global variable. This is not so common, therefore // it is not checked for earlier. if (lg_find_global(L, mi, symname)) return 1; // "name" might not need the prefix. if (lg_find_global(L, mi, name)) return 1; // Maybe it's Windows and a function with _utf8 suffix? While there // are a few with the gtk_ prefix and _utf8 suffix, most have the // g_ or gdk_ prefix, so don't automatically add this prefix. #ifdef LUAGNOME_win32 strcat(symname, "_utf8"); // sprintf(symname, "%s%s_utf8", prefix_func, name); if (lg_find_func(L, mi, symname, &fi)) goto found_func; #endif // Not found. return luaL_error(L, "%s not found: %s.%s", msgprefix, mi->name, name); found_func:; lg_push_closure(L, &fi, 2); // cache the result of this lookup, using the key given by the user, // and not necessarily the name of the function that was found. lua_pushvalue(L, 2); // key lua_pushvalue(L, -2); // the new closure lua_rawset(L, 1); // [1]=table return 1; }
/** Set value without invoking meta methods. * Similar to set_table(), but does raw access, i.e. without invoking meta-methods. * @param idx index of the table */ void LuaContext::raw_set(int idx) { lua_rawset(__L, idx); }
static void mar_encode_value(lua_State *L, mar_Buffer *buf, int val, size_t *idx) { size_t l; int val_type = lua_type(L, val); lua_pushvalue(L, val); buf_write(L, (void*)&val_type, MAR_CHR, buf); switch (val_type) { case LUA_TBOOLEAN: { int int_val = lua_toboolean(L, -1); buf_write(L, (void*)&int_val, MAR_CHR, buf); break; } case LUA_TSTRING: { const char *str_val = lua_tolstring(L, -1, &l); buf_write(L, (void*)&l, MAR_I32, buf); buf_write(L, str_val, l, buf); break; } case LUA_TNUMBER: { lua_Number num_val = lua_tonumber(L, -1); buf_write(L, (void*)&num_val, MAR_I64, buf); break; } case LUA_TTABLE: { int tag, ref; lua_pushvalue(L, -1); lua_rawget(L, SEEN_IDX); if (!lua_isnil(L, -1)) { ref = lua_tointeger(L, -1); tag = MAR_TREF; buf_write(L, (void*)&tag, MAR_CHR, buf); buf_write(L, (void*)&ref, MAR_I32, buf); lua_pop(L, 1); } else { mar_Buffer rec_buf; lua_pop(L, 1); /* pop nil */ if (luaL_getmetafield(L, -1, "__persist")) { tag = MAR_TUSR; lua_pushvalue(L, -2); /* self */ lua_call(L, 1, 1); if (!lua_isfunction(L, -1)) { luaL_error(L, "__persist must return a function"); } lua_remove(L, -2); /* __persist */ lua_newtable(L); lua_pushvalue(L, -2); /* callback */ lua_rawseti(L, -2, 1); buf_init(L, &rec_buf); mar_encode_table(L, &rec_buf, idx); buf_write(L, (void*)&tag, MAR_CHR, buf); buf_write(L, (void*)&rec_buf.head, MAR_I32, buf); buf_write(L, rec_buf.data, rec_buf.head, buf); buf_done(L, &rec_buf); lua_pop(L, 1); } else { tag = MAR_TVAL; lua_pushvalue(L, -1); lua_pushinteger(L, (*idx)++); lua_rawset(L, SEEN_IDX); lua_pushvalue(L, -1); buf_init(L, &rec_buf); mar_encode_table(L, &rec_buf, idx); lua_pop(L, 1); buf_write(L, (void*)&tag, MAR_CHR, buf); buf_write(L, (void*)&rec_buf.head, MAR_I32, buf); buf_write(L, rec_buf.data,rec_buf.head, buf); buf_done(L, &rec_buf); } } break; } case LUA_TFUNCTION: { int tag, ref; lua_pushvalue(L, -1); lua_rawget(L, SEEN_IDX); if (!lua_isnil(L, -1)) { ref = lua_tointeger(L, -1); tag = MAR_TREF; buf_write(L, (void*)&tag, MAR_CHR, buf); buf_write(L, (void*)&ref, MAR_I32, buf); lua_pop(L, 1); } else { mar_Buffer rec_buf; int i; lua_Debug ar; lua_pop(L, 1); /* pop nil */ lua_pushvalue(L, -1); lua_getinfo(L, ">nuS", &ar); if (ar.what[0] != 'L') { luaL_error(L, "attempt to persist a C function '%s'", ar.name); } tag = MAR_TVAL; lua_pushvalue(L, -1); lua_pushinteger(L, (*idx)++); lua_rawset(L, SEEN_IDX); lua_pushvalue(L, -1); buf_init(L, &rec_buf); lua_dump(L, (lua_Writer)buf_write, &rec_buf); buf_write(L, (void*)&tag, MAR_CHR, buf); buf_write(L, (void*)&rec_buf.head, MAR_I32, buf); buf_write(L, rec_buf.data, rec_buf.head, buf); buf_done(L, &rec_buf); lua_pop(L, 1); lua_newtable(L); for (i=1; i <= ar.nups; i++) { lua_getupvalue(L, -2, i); lua_rawseti(L, -2, i); } buf_init(L, &rec_buf); mar_encode_table(L, &rec_buf, idx); buf_write(L, (void*)&rec_buf.head, MAR_I32, buf); buf_write(L, rec_buf.data, rec_buf.head, buf); buf_done(L, &rec_buf); lua_pop(L, 1); } break; } case LUA_TUSERDATA: { int tag, ref; lua_pushvalue(L, -1); lua_rawget(L, SEEN_IDX); if (!lua_isnil(L, -1)) { ref = lua_tointeger(L, -1); tag = MAR_TREF; buf_write(L, (void*)&tag, MAR_CHR, buf); buf_write(L, (void*)&ref, MAR_I32, buf); lua_pop(L, 1); } else { mar_Buffer rec_buf; lua_pop(L, 1); /* pop nil */ if (luaL_getmetafield(L, -1, "__persist")) { tag = MAR_TUSR; lua_pushvalue(L, -2); lua_pushinteger(L, (*idx)++); lua_rawset(L, SEEN_IDX); lua_pushvalue(L, -2); lua_call(L, 1, 1); if (!lua_isfunction(L, -1)) { luaL_error(L, "__persist must return a function"); } lua_newtable(L); lua_pushvalue(L, -2); lua_rawseti(L, -2, 1); lua_remove(L, -2); buf_init(L, &rec_buf); mar_encode_table(L, &rec_buf, idx); buf_write(L, (void*)&tag, MAR_CHR, buf); buf_write(L, (void*)&rec_buf.head, MAR_I32, buf); buf_write(L, rec_buf.data, rec_buf.head, buf); buf_done(L, &rec_buf); } else { luaL_error(L, "attempt to encode userdata (no __persist hook)"); } lua_pop(L, 1); } break; } case LUA_TNIL: break; default: luaL_error(L, "invalid value type (%s)", lua_typename(L, val_type)); } lua_pop(L, 1); }