/* * Arguments: dpool_udata, [timeout (milliseconds)] * Returns: data_items (any) ... */ static int dpool_get (lua_State *L) { struct sys_thread *td = sys_thread_get(); struct data_pool *dp = checkudata(L, 1, DPOOL_TYPENAME); const msec_t timeout = lua_isnoneornil(L, 2) ? TIMEOUT_INFINITE : (msec_t) lua_tointeger(L, 2); int nput; if (!td) luaL_argerror(L, 0, "Threading not initialized"); lua_settop(L, 1); lua_getfenv(L, 1); /* storage */ lua_insert(L, 1); if ((dp->flags & DPOOL_GETONEMPTY) && !dp->n) { lua_rawgetp(L, 1, (void *) DPOOL_GETONEMPTY); lua_insert(L, 2); lua_call(L, 1, LUA_MULTRET); nput = lua_gettop(L) - 1; if (nput) return nput; } for (; ; ) { /* get from storage */ if (dp->n) { const int idx = dp->idx + 1; int i; lua_rawgeti(L, 1, idx); nput = lua_tointeger(L, -1); lua_pushnil(L); lua_rawseti(L, 1, idx); dp->idx = idx + nput; for (i = dp->idx; i > idx; --i) { lua_rawgeti(L, 1, i); lua_pushnil(L); lua_rawseti(L, 1, i); } if (dp->idx == dp->top) dp->idx = dp->top = 0; if (dp->n-- == dp->max) { thread_event_signal(&dp->tev); } return nput; } /* wait signal */ { int res; dp->nwaits++; res = thread_event_wait(&dp->tev, td, timeout); dp->nwaits--; sys_thread_check(td); if (res) { if (res == 1) { lua_pushboolean(L, 0); return 1; /* timed out */ } return sys_seterror(L, 0); } } /* get directly from another thread */ nput = dp->nput; if (nput) { dp->nput = 0; luaL_checkstack(L, nput, NULL); lua_xmove(dp->td->L, L, nput); return nput; } } }
/******************************向栈中压入元素*************************************/ void LuaWrapper::pushNil() { lua_pushnil(m_luaState); }
int lua_Model_setMaterial(lua_State* state) { // Get the number of parameters. int paramCount = lua_gettop(state); // Attempt to match the parameters to a valid binding. switch (paramCount) { case 2: { do { if ((lua_type(state, 1) == LUA_TUSERDATA) && (lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TTABLE || lua_type(state, 2) == LUA_TNIL)) { // Get parameter 1 off the stack. bool param1Valid; gameplay::ScriptUtil::LuaArray<Material> param1 = gameplay::ScriptUtil::getObjectPointer<Material>(2, "Material", false, ¶m1Valid); if (!param1Valid) break; Model* instance = getInstance(state); instance->setMaterial(param1); return 0; } } while (0); do { if ((lua_type(state, 1) == LUA_TUSERDATA) && (lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL)) { // Get parameter 1 off the stack. const char* param1 = gameplay::ScriptUtil::getString(2, false); Model* instance = getInstance(state); void* returnPtr = ((void*)instance->setMaterial(param1)); if (returnPtr) { gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject)); object->instance = returnPtr; object->owns = false; luaL_getmetatable(state, "Material"); lua_setmetatable(state, -2); } else { lua_pushnil(state); } return 1; } } while (0); lua_pushstring(state, "lua_Model_setMaterial - Failed to match the given parameters to a valid function signature."); lua_error(state); break; } case 3: { do { if ((lua_type(state, 1) == LUA_TUSERDATA) && (lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TTABLE || lua_type(state, 2) == LUA_TNIL) && lua_type(state, 3) == LUA_TNUMBER) { // Get parameter 1 off the stack. bool param1Valid; gameplay::ScriptUtil::LuaArray<Material> param1 = gameplay::ScriptUtil::getObjectPointer<Material>(2, "Material", false, ¶m1Valid); if (!param1Valid) break; // Get parameter 2 off the stack. int param2 = (int)luaL_checkint(state, 3); Model* instance = getInstance(state); instance->setMaterial(param1, param2); return 0; } } while (0); do { if ((lua_type(state, 1) == LUA_TUSERDATA) && (lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) && (lua_type(state, 3) == LUA_TSTRING || lua_type(state, 3) == LUA_TNIL)) { // Get parameter 1 off the stack. const char* param1 = gameplay::ScriptUtil::getString(2, false); // Get parameter 2 off the stack. const char* param2 = gameplay::ScriptUtil::getString(3, false); Model* instance = getInstance(state); void* returnPtr = ((void*)instance->setMaterial(param1, param2)); if (returnPtr) { gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject)); object->instance = returnPtr; object->owns = false; luaL_getmetatable(state, "Material"); lua_setmetatable(state, -2); } else { lua_pushnil(state); } return 1; } } while (0); do { if ((lua_type(state, 1) == LUA_TUSERDATA) && (lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) && lua_type(state, 3) == LUA_TNUMBER) { // Get parameter 1 off the stack. const char* param1 = gameplay::ScriptUtil::getString(2, false); // Get parameter 2 off the stack. int param2 = (int)luaL_checkint(state, 3); Model* instance = getInstance(state); void* returnPtr = ((void*)instance->setMaterial(param1, param2)); if (returnPtr) { gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject)); object->instance = returnPtr; object->owns = false; luaL_getmetatable(state, "Material"); lua_setmetatable(state, -2); } else { lua_pushnil(state); } return 1; } } while (0); lua_pushstring(state, "lua_Model_setMaterial - Failed to match the given parameters to a valid function signature."); lua_error(state); break; } case 4: { do { if ((lua_type(state, 1) == LUA_TUSERDATA) && (lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) && (lua_type(state, 3) == LUA_TSTRING || lua_type(state, 3) == LUA_TNIL) && (lua_type(state, 4) == LUA_TSTRING || lua_type(state, 4) == LUA_TNIL)) { // Get parameter 1 off the stack. const char* param1 = gameplay::ScriptUtil::getString(2, false); // Get parameter 2 off the stack. const char* param2 = gameplay::ScriptUtil::getString(3, false); // Get parameter 3 off the stack. const char* param3 = gameplay::ScriptUtil::getString(4, false); Model* instance = getInstance(state); void* returnPtr = ((void*)instance->setMaterial(param1, param2, param3)); if (returnPtr) { gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject)); object->instance = returnPtr; object->owns = false; luaL_getmetatable(state, "Material"); lua_setmetatable(state, -2); } else { lua_pushnil(state); } return 1; } } while (0); lua_pushstring(state, "lua_Model_setMaterial - Failed to match the given parameters to a valid function signature."); lua_error(state); break; } case 5: { do { if ((lua_type(state, 1) == LUA_TUSERDATA) && (lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) && (lua_type(state, 3) == LUA_TSTRING || lua_type(state, 3) == LUA_TNIL) && (lua_type(state, 4) == LUA_TSTRING || lua_type(state, 4) == LUA_TNIL) && lua_type(state, 5) == LUA_TNUMBER) { // Get parameter 1 off the stack. const char* param1 = gameplay::ScriptUtil::getString(2, false); // Get parameter 2 off the stack. const char* param2 = gameplay::ScriptUtil::getString(3, false); // Get parameter 3 off the stack. const char* param3 = gameplay::ScriptUtil::getString(4, false); // Get parameter 4 off the stack. int param4 = (int)luaL_checkint(state, 5); Model* instance = getInstance(state); void* returnPtr = ((void*)instance->setMaterial(param1, param2, param3, param4)); if (returnPtr) { gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject)); object->instance = returnPtr; object->owns = false; luaL_getmetatable(state, "Material"); lua_setmetatable(state, -2); } else { lua_pushnil(state); } return 1; } } while (0); lua_pushstring(state, "lua_Model_setMaterial - Failed to match the given parameters to a valid function signature."); lua_error(state); break; } default: { lua_pushstring(state, "Invalid number of parameters (expected 2, 3, 4 or 5)."); lua_error(state); break; } } return 0; }
/* ** Unregisters a given C object from the registry */ static void lua_unregisterobj(lua_State *L, void *obj) { lua_pushlightuserdata(L, obj); lua_pushnil(L); lua_settable(L, LUA_REGISTRYINDEX); }
/*****************************************************************************\ file:GetAttribute(attrib) \*****************************************************************************/ static int imluaFileGetAttribute (lua_State *L) { int data_type; int i, count; const void *data; int as_string = 0; imFile *ifile = imlua_checkfile(L, 1); const char *attrib = luaL_checkstring(L, 2); data = imFileGetAttribute(ifile, attrib, &data_type, &count); if (!data) { lua_pushnil(L); return 1; } if (data_type == IM_BYTE && lua_isboolean(L, 3)) as_string = lua_toboolean(L, 3); if (!as_string) lua_newtable(L); switch (data_type) { case IM_BYTE: { if (as_string) { lua_pushstring(L, (const char*)data); } else { imbyte *data_byte = (imbyte*) data; for (i = 0; i < count; i++, data_byte++) { lua_pushnumber(L, *data_byte); lua_rawseti(L, -2, i+1); } } } break; case IM_SHORT: { short *data_short = (short*) data; for (i = 0; i < count; i++, data_short += 2) { lua_pushnumber(L, *data_short); lua_rawseti(L, -2, i+1); } } break; case IM_USHORT: { imushort *data_ushort = (imushort*) data; for (i = 0; i < count; i++, data_ushort += 2) { lua_pushnumber(L, *data_ushort); lua_rawseti(L, -2, i+1); } } break; case IM_INT: { int *data_int = (int*) data; for (i = 0; i < count; i++, data_int++) { lua_pushnumber(L, *data_int); lua_rawseti(L, -2, i+1); } } break; case IM_FLOAT: { float *data_float = (float*) data; for (i = 0; i < count; i++, data_float++) { lua_pushnumber(L, *data_float); lua_rawseti(L, -2, i+1); } } break; case IM_CFLOAT: { float *data_float = (float*) data; for (i = 0; i < count; i++, data_float += 2) { imlua_newarrayfloat(L, data_float, 2, 1); lua_rawseti(L, -2, i+1); } } break; case IM_DOUBLE: { double *data_double = (double*) data; for (i = 0; i < count; i++, data_double++) { lua_pushnumber(L, *data_double); lua_rawseti(L, -2, i+1); } } break; case IM_CDOUBLE: { double *data_double = (double*) data; for (i = 0; i < count; i++, data_double += 2) { imlua_newarraydouble(L, data_double, 2, 1); lua_rawseti(L, -2, i+1); } } break; } lua_pushinteger(L, data_type); return 2; }
static int lua_iso8583_pack(lua_State *L) { iso8583_userdata *iso8583u; char error[BUFSIZ]; int n = lua_gettop(L); unsigned int iso8583_maxsize = ISO8583_MAXSIZE; unsigned char iso8583_data[ISO8583_MAXSIZE]; if (n < 2) { lua_pushnil(L); lua_pushstring(L, "arguments error! too small!"); return 2; } iso8583u = (iso8583_userdata *)luaL_checkudata(L, 1, "iso8583"); if (!lua_istable(L, 2)) { lua_pushnil(L); lua_pushstring(L, "argument error! data must be table!"); return 2; } lua_pushnil(L); while(lua_next(L, 2) != 0) { if (lua_isnumber(L, -2)) { int i = lua_tointeger(L, -2); if (i >= 0 && i <= 128) { size_t size; const unsigned char *data; if (!lua_isstring(L, -1)) { lua_pushnil(L); snprintf(error, BUFSIZ, "data %d error! is not a string!", i); lua_pushstring(L, error); return 2; } data = (const unsigned char *)lua_tolstring(L, -1, &size); if (iso8583_set(iso8583u->handle, i, data, (unsigned int)size) != ISO8583_OK) { lua_pushnil(L); snprintf(error, BUFSIZ, "data %d error!", i); lua_pushstring(L, error); return 2; } } } lua_pop(L, 1); } lua_pop(L, 1); if (iso8583_pack(iso8583u->handle, iso8583_data, &iso8583_maxsize) != ISO8583_OK) { lua_pushnil(L); snprintf(error, BUFSIZ, "pack iso8583 error! %s", iso8583u->handle->error); lua_pushstring(L, error); return 2; } lua_pushlstring(L, (const char *)iso8583_data, iso8583_maxsize); return 1; }
static int lua_dir(lua_State *L) { int k = 0; const char *s = luaL_checkstring(L, 1); #ifdef _WIN32 SB sb; struct _finddata_t info; long hfind; /* special cases */ lua_createtable(L, 0, 0); if ((s[0]=='/' || s[0]=='\\') && (s[1]=='/' || s[1]=='\\') && !s[2]) { int drive; hfind = GetLogicalDrives(); for (drive='A'; drive<='Z'; drive++) if (hfind & (1<<(drive-'A'))) { lua_pushfstring(L, "%c:/", drive); lua_rawseti(L, -2, ++k); } } else if (dirp(L, 1)) { lua_pushliteral(L, ".."); lua_rawseti(L, -2, ++k); } else { lua_pushnil(L); return 1; } /* files */ sbinit(&sb); sbaddn(&sb, s, strlen(s)); if (sb.len>0 && sb.buffer[sb.len-1]!='/' && sb.buffer[sb.len-1]!='\\') sbadd1(&sb, '/'); sbaddn(&sb, "*.*", 3); sbadd1(&sb, 0); hfind = _findfirst(sb.buffer, &info); if (hfind != -1) { do { if (strcmp(".",info.name) && strcmp("..",info.name)) { lua_pushstring(L, info.name); lua_rawseti(L, -2, ++k); } } while ( _findnext(hfind, &info) != -1 ); _findclose(hfind); } sbfree(&sb); #else DIR *dirp; struct dirent *d; dirp = opendir(s); if (dirp) { lua_createtable(L, 0, 0); while ((d = readdir(dirp))) { int n = NAMLEN(d); lua_pushlstring(L, d->d_name, n); lua_rawseti(L, -2, ++k); } closedir(dirp); } else lua_pushnil(L); #endif return 1; }
void read_object_properties(lua_State *L, int index, ObjectProperties *prop) { if(index < 0) index = lua_gettop(L) + 1 + index; if(!lua_istable(L, index)) return; prop->hp_max = getintfield_default(L, -1, "hp_max", 10); getboolfield(L, -1, "physical", prop->physical); getboolfield(L, -1, "collide_with_objects", prop->collideWithObjects); getfloatfield(L, -1, "weight", prop->weight); lua_getfield(L, -1, "collisionbox"); if(lua_istable(L, -1)) prop->collisionbox = read_aabb3f(L, -1, 1.0); lua_pop(L, 1); getstringfield(L, -1, "visual", prop->visual); getstringfield(L, -1, "mesh", prop->mesh); lua_getfield(L, -1, "visual_size"); if(lua_istable(L, -1)) prop->visual_size = read_v2f(L, -1); lua_pop(L, 1); lua_getfield(L, -1, "textures"); if(lua_istable(L, -1)){ prop->textures.clear(); int table = lua_gettop(L); lua_pushnil(L); while(lua_next(L, table) != 0){ // key at index -2 and value at index -1 if(lua_isstring(L, -1)) prop->textures.push_back(lua_tostring(L, -1)); else prop->textures.push_back(""); // removes value, keeps key for next iteration lua_pop(L, 1); } } lua_pop(L, 1); lua_getfield(L, -1, "colors"); if(lua_istable(L, -1)){ prop->colors.clear(); int table = lua_gettop(L); lua_pushnil(L); while(lua_next(L, table) != 0){ // key at index -2 and value at index -1 if(lua_isstring(L, -1)) prop->colors.push_back(readARGB8(L, -1)); else prop->colors.push_back(video::SColor(255, 255, 255, 255)); // removes value, keeps key for next iteration lua_pop(L, 1); } } lua_pop(L, 1); lua_getfield(L, -1, "spritediv"); if(lua_istable(L, -1)) prop->spritediv = read_v2s16(L, -1); lua_pop(L, 1); lua_getfield(L, -1, "initial_sprite_basepos"); if(lua_istable(L, -1)) prop->initial_sprite_basepos = read_v2s16(L, -1); lua_pop(L, 1); getboolfield(L, -1, "is_visible", prop->is_visible); getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound); getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate); getfloatfield(L, -1, "stepheight", prop->stepheight); prop->stepheight*=BS; getboolfield(L, -1, "automatic_face_movement_dir", prop->automatic_face_movement_dir); }
ContentFeatures read_content_features(lua_State *L, int index) { if(index < 0) index = lua_gettop(L) + 1 + index; ContentFeatures f; /* Cache existence of some callbacks */ lua_getfield(L, index, "on_construct"); if(!lua_isnil(L, -1)) f.has_on_construct = true; lua_pop(L, 1); lua_getfield(L, index, "on_destruct"); if(!lua_isnil(L, -1)) f.has_on_destruct = true; lua_pop(L, 1); lua_getfield(L, index, "after_destruct"); if(!lua_isnil(L, -1)) f.has_after_destruct = true; lua_pop(L, 1); lua_getfield(L, index, "on_rightclick"); f.rightclickable = lua_isfunction(L, -1); lua_pop(L, 1); /* Name */ getstringfield(L, index, "name", f.name); /* Groups */ lua_getfield(L, index, "groups"); read_groups(L, -1, f.groups); lua_pop(L, 1); /* Visual definition */ f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", ScriptApiNode::es_DrawType,NDT_NORMAL); getfloatfield(L, index, "visual_scale", f.visual_scale); // tiles = {} lua_getfield(L, index, "tiles"); // If nil, try the deprecated name "tile_images" instead if(lua_isnil(L, -1)){ lua_pop(L, 1); warn_if_field_exists(L, index, "tile_images", "Deprecated; new name is \"tiles\"."); lua_getfield(L, index, "tile_images"); } if(lua_istable(L, -1)){ int table = lua_gettop(L); lua_pushnil(L); int i = 0; while(lua_next(L, table) != 0){ // Read tiledef from value f.tiledef[i] = read_tiledef(L, -1); // removes value, keeps key for next iteration lua_pop(L, 1); i++; if(i==6){ lua_pop(L, 1); break; } } // Copy last value to all remaining textures if(i >= 1){ TileDef lasttile = f.tiledef[i-1]; while(i < 6){ f.tiledef[i] = lasttile; i++; } } } lua_pop(L, 1); // special_tiles = {} lua_getfield(L, index, "special_tiles"); // If nil, try the deprecated name "special_materials" instead if(lua_isnil(L, -1)){ lua_pop(L, 1); warn_if_field_exists(L, index, "special_materials", "Deprecated; new name is \"special_tiles\"."); lua_getfield(L, index, "special_materials"); } if(lua_istable(L, -1)){ int table = lua_gettop(L); lua_pushnil(L); int i = 0; while(lua_next(L, table) != 0){ // Read tiledef from value f.tiledef_special[i] = read_tiledef(L, -1); // removes value, keeps key for next iteration lua_pop(L, 1); i++; if(i==6){ lua_pop(L, 1); break; } } } lua_pop(L, 1); f.alpha = getintfield_default(L, index, "alpha", 255); bool usealpha = getboolfield_default(L, index, "use_texture_alpha", false); if (usealpha) f.alpha = 0; /* Other stuff */ lua_getfield(L, index, "post_effect_color"); if(!lua_isnil(L, -1)) f.post_effect_color = readARGB8(L, -1); lua_pop(L, 1); f.param_type = (ContentParamType)getenumfield(L, index, "paramtype", ScriptApiNode::es_ContentParamType, CPT_NONE); f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2", ScriptApiNode::es_ContentParamType2, CPT2_NONE); // Warn about some deprecated fields warn_if_field_exists(L, index, "wall_mounted", "deprecated: use paramtype2 = 'wallmounted'"); warn_if_field_exists(L, index, "light_propagates", "deprecated: determined from paramtype"); warn_if_field_exists(L, index, "dug_item", "deprecated: use 'drop' field"); warn_if_field_exists(L, index, "extra_dug_item", "deprecated: use 'drop' field"); warn_if_field_exists(L, index, "extra_dug_item_rarity", "deprecated: use 'drop' field"); warn_if_field_exists(L, index, "metadata_name", "deprecated: use on_add and metadata callbacks"); // True for all ground-like things like stone and mud, false for eg. trees getboolfield(L, index, "is_ground_content", f.is_ground_content); f.light_propagates = (f.param_type == CPT_LIGHT); getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates); // This is used for collision detection. // Also for general solidness queries. getboolfield(L, index, "walkable", f.walkable); // Player can point to these getboolfield(L, index, "pointable", f.pointable); // Player can dig these getboolfield(L, index, "diggable", f.diggable); // Player can climb these getboolfield(L, index, "climbable", f.climbable); // Player can build on these getboolfield(L, index, "buildable_to", f.buildable_to); // Whether the node is non-liquid, source liquid or flowing liquid f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype", ScriptApiNode::es_LiquidType, LIQUID_NONE); // If the content is liquid, this is the flowing version of the liquid. getstringfield(L, index, "liquid_alternative_flowing", f.liquid_alternative_flowing); // If the content is liquid, this is the source version of the liquid. getstringfield(L, index, "liquid_alternative_source", f.liquid_alternative_source); // Viscosity for fluid flow, ranging from 1 to 7, with // 1 giving almost instantaneous propagation and 7 being // the slowest possible f.liquid_viscosity = getintfield_default(L, index, "liquid_viscosity", f.liquid_viscosity); f.liquid_range = getintfield_default(L, index, "liquid_range", f.liquid_range); f.leveled = getintfield_default(L, index, "leveled", f.leveled); getboolfield(L, index, "liquid_renewable", f.liquid_renewable); getstringfield(L, index, "freezemelt", f.freezemelt); f.drowning = getintfield_default(L, index, "drowning", f.drowning); // Amount of light the node emits f.light_source = getintfield_default(L, index, "light_source", f.light_source); f.damage_per_second = getintfield_default(L, index, "damage_per_second", f.damage_per_second); lua_getfield(L, index, "node_box"); if(lua_istable(L, -1)) f.node_box = read_nodebox(L, -1); lua_pop(L, 1); lua_getfield(L, index, "selection_box"); if(lua_istable(L, -1)) f.selection_box = read_nodebox(L, -1); lua_pop(L, 1); // Set to true if paramtype used to be 'facedir_simple' getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple); // Set to true if wall_mounted used to be set to true getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted); // Sound table lua_getfield(L, index, "sounds"); if(lua_istable(L, -1)){ lua_getfield(L, -1, "footstep"); read_soundspec(L, -1, f.sound_footstep); lua_pop(L, 1); lua_getfield(L, -1, "dig"); read_soundspec(L, -1, f.sound_dig); lua_pop(L, 1); lua_getfield(L, -1, "dug"); read_soundspec(L, -1, f.sound_dug); lua_pop(L, 1); } lua_pop(L, 1); return f; }
int PhysicObject::methodsBridge(lua_State* luaVM) { if (isCurrentMethod("applyImpulse")) { applyImpulse(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3)), CVector(lua_tonumber(luaVM, 4), lua_tonumber(luaVM, 5), lua_tonumber(luaVM, 6))); return 0; } if (isCurrentMethod("applyForce")) { applyForce(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3)), CVector(lua_tonumber(luaVM, 4), lua_tonumber(luaVM, 5), lua_tonumber(luaVM, 6))); return 0; } if (isCurrentMethod("setLinearVelocity")) { setLinearVelocity(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3))); return 0; } if (isCurrentMethod("getLinearVelocity")) { luaPushVector(luaVM, getLinearVelocity().x, getLinearVelocity().y, getLinearVelocity().z); return 1; } if (isCurrentMethod("setMass")) { setMass(lua_tonumber(luaVM, 1)); return 0; } if (isCurrentMethod("getMass")) { lua_pushnumber(luaVM, getMass()); return 1; } if (isCurrentMethod("setCollisionShapeType")) { setCollisionShapeType((CollisionShapeType)lua_tointeger(luaVM, 1)); return 0; } if (isCurrentMethod("getCollisionShapeType")) { lua_pushinteger(luaVM, getCollisionShapeType()); return 1; } if (isCurrentMethod("enablePhysics")) { enablePhysics(lua_toboolean(luaVM, 1)); return 0; } if (isCurrentMethod("isEnabledPhysics")) { lua_pushboolean(luaVM, isEnabledPhysics()); return 1; } if (isCurrentMethod("setAngularFactor")) { setAngularFactor(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3))); return 0; } if (isCurrentMethod("getAngularFactor")) { luaPushVector(luaVM, getAngularFactor().x, getAngularFactor().y, getAngularFactor().z); return 1; } if (isCurrentMethod("setLinearFactor")) { setLinearFactor(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3))); return 0; } if (isCurrentMethod("getLinearFactor")) { luaPushVector(luaVM, getLinearFactor().x, getLinearFactor().y, getLinearFactor().z); return 1; } if (isCurrentMethod("setTrigger")) { setTrigger(lua_toboolean(luaVM, 1)); return 0; } if (isCurrentMethod("isTrigger")) { lua_pushboolean(luaVM, isTrigger()); return 1; } if (isCurrentMethod("getCollisionShape")) { if (getCollisionShape() == NULL) { lua_pushnil(luaVM); } else { lua_getglobal(luaVM, getCollisionShape()->getGOID().c_str()); } return 1; } if (isCurrentMethod("setCollisionShape")) { if (lua_isnil(luaVM, 1)) { setCollisionShape(NULL); return 0; } lua_pushstring(luaVM, "cpointer"); lua_gettable(luaVM, -2); GOCollisionShape* o = (GOCollisionShape*)lua_tointeger(luaVM, -1); setCollisionShape(o); lua_pop(luaVM, -1); return 0; } if (isCurrentMethod("setEnableDeactivation")) { setEnableDeactivation(lua_toboolean(luaVM, 1)); return 0; } if (isCurrentMethod("isEnableDeactivation")) { lua_pushboolean(luaVM, isEnableDeactivation()); return 1; } if (isCurrentMethod("setFriction")) { setFriction(lua_tonumber(luaVM, 1)); return 0; } if (isCurrentMethod("getFriction")) { lua_pushnumber(luaVM, getFriction()); return 1; } if (isCurrentMethod("setRestitution")) { setRestitution(lua_tonumber(luaVM, 1)); return 0; } if (isCurrentMethod("getRestitution")) { lua_pushnumber(luaVM, getRestitution()); return 1; } if (isCurrentMethod("setLinearDumping")) { setLinearDumping(lua_tonumber(luaVM, 1)); return 0; } if (isCurrentMethod("getLinearDumping")) { lua_pushnumber(luaVM, getLinearDumping()); return 1; } if (isCurrentMethod("setAngularDumping")) { setAngularDumping(lua_tonumber(luaVM, 1)); return 0; } if (isCurrentMethod("getAngularDumping")) { lua_pushnumber(luaVM, getAngularDumping()); return 1; } if (isCurrentMethod("setAngularVelocity")) { setAngularVelocity(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3))); return 0; } if (isCurrentMethod("getAngularVelocity")) { CVector av = getAngularVelocity(); luaPushVector(luaVM, av.x, av.y, av.z); return 1; } if (isCurrentMethod("addConstraint")) { if (lua_isnil(luaVM, 1)) { return 0; } lua_pushstring(luaVM, "cpointer"); lua_gettable(luaVM, -2); GOConstraint* o = (GOConstraint*)lua_tointeger(luaVM, -1); addConstraint(o); lua_pop(luaVM, -1); return 0; } if (isCurrentMethod("getConstraints")) { lua_newtable(luaVM); int tableIndex = lua_gettop(luaVM); vector<GOConstraint*> objs; for (unsigned int i = 0; i < constraints.size(); ++i) { if (constraints.at(i)->id == "undefined" || constraints.at(i)->id == "") continue; objs.push_back(constraints.at(i)); } for (unsigned int i = 0; i < objs.size(); ++i) { lua_pushinteger(luaVM, i+1); lua_getglobal(luaVM, objs.at(i)->id.c_str()); lua_settable (luaVM, tableIndex); } return 1; } if (isCurrentMethod("removeConstraint")) { if (lua_isnil(luaVM, 1)) { return 0; } lua_pushstring(luaVM, "cpointer"); lua_gettable(luaVM, -2); GOConstraint* o = (GOConstraint*)lua_tointeger(luaVM, -1); removeConstraint(o); lua_pop(luaVM, -1); return 0; } if (isCurrentMethod("removeAllConstrains")) { removeAllConstraints(); return 0; } if (isCurrentMethod("secondObjectForConstraint")) { if (lua_isnil(luaVM, 1)) { return 0; } lua_pushstring(luaVM, "cpointer"); lua_gettable(luaVM, -2); GOConstraint* o = (GOConstraint*)lua_tointeger(luaVM, -1); secondObjectForConstraint(o); lua_pop(luaVM, -1); return 0; } if (isCurrentMethod("isSecondObjectForConstraints")) { lua_newtable(luaVM); int tableIndex = lua_gettop(luaVM); vector<GOConstraint*> objs; for (unsigned int i = 0; i < secondObjectForConstraints.size(); ++i) { if (secondObjectForConstraints.at(i)->id == "undefined" || secondObjectForConstraints.at(i)->id == "") continue; objs.push_back(secondObjectForConstraints.at(i)); } for (unsigned int i = 0; i < objs.size(); ++i) { lua_pushinteger(luaVM, i+1); lua_getglobal(luaVM, objs.at(i)->id.c_str()); lua_settable (luaVM, tableIndex); } return 1; } if (isCurrentMethod("notUseAsSecondObjectForConstraint")) { if (lua_isnil(luaVM, 1)) { return 0; } lua_pushstring(luaVM, "cpointer"); lua_gettable(luaVM, -2); GOConstraint* o = (GOConstraint*)lua_tointeger(luaVM, -1); notUseAsSecondObjectForConstraint(o); lua_pop(luaVM, -1); return 0; } return LuaBridge::methodsBridge(luaVM); }
static int b_pack (lua_State *L) { luaL_Buffer b; int native; const char *fmt = luaL_checkstring(L, 1); int endian = getendianess(&fmt, &native); int align = getalign(&fmt); int arg = 2; int totalsize = 0; void *p; lua_pushnil(L); /* mark to separate arguments from string buffer */ luaL_buffinit(L, &b); for (; *fmt; arg++) { int opt = *fmt++; int size = optsize(opt, &fmt); int toalign = gettoalign(L, align, opt, size); while ((totalsize&(toalign-1)) != 0) { luaL_putchar(&b, '\0'); totalsize++; } switch (opt) { case ' ': break; /* ignore white spaces */ case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'i': case 'I': { /* integer types */ putinteger(L, &b, arg, endian, size); break; } case 'x': { arg--; /* undo increment */ luaL_putchar(&b, '\0'); break; } case 'f': { float f = (float)luaL_checknumber(L, arg); if (endian != native) invertbytes((char *)&f, size); luaL_addlstring(&b, (char *)&f, size); break; } case 'd': { double d = luaL_checknumber(L, arg); if (endian != native) invertbytes((char *)&d, size); luaL_addlstring(&b, (char *)&d, size); break; } case 'c': case 's': { size_t l; const char *s = luaL_checklstring(L, arg, &l); if (size == 0) size = l; luaL_argcheck(L, l >= (size_t)size, arg, "string too short"); luaL_addlstring(&b, s, size); if (opt == 's') { luaL_putchar(&b, '\0'); /* add zero at the end */ size++; } break; } case 'p': { luaL_argcheck(L, lua_isuserdata(L, arg) || lua_isnil(L, arg), arg, "userdata, light userdata, or nil required"); p = lua_touserdata(L, arg); luaL_addlstring(&b, (char*)&p, size); break; } default: invalidformat(L, opt); } totalsize += size; } luaL_pushresult(&b); return 1; }
void LuaSerializer::pickle(lua_State *l, int idx, std::string &out, const char *key = NULL) { static char buf[256]; LUA_DEBUG_START(l); 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%lu\n", strlen(str)); out += buf; out += str; lua_pop(l, 1); break; } case LUA_TTABLE: { out += "t"; 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%d\n%d\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%d\n", Serializer::LookupBody(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); }
/* static void stackDump (lua_State *L) { int i; int top = lua_gettop(L); for (i = 1; i <= top; i++) { // repeat for each level int t = lua_type(L, i); printf("%i: ", (top-i+1)); switch (t) { case LUA_TSTRING: // strings printf("[string]"); break; case LUA_TBOOLEAN: // booleans printf(lua_toboolean(L, i) ? "true" : "false"); break; case LUA_TNUMBER: // numbers printf("%g", lua_tonumber(L, i)); break; default: // other values printf("%s", lua_typename(L, t)); break; } printf("\n"); // put a separator } printf("\n----------\n"); // end the listing } */ SYMID lua_syck_parser_handler(SyckParser *p, SyckNode *n) { struct parser_xtra *bonus = (struct parser_xtra *)p->bonus; int o, o2, o3 = -1; SYMID oid; int i; if(!lua_checkstack(bonus->L, 1)) luaL_error(bonus->orig,"syck parser wanted too much stack space."); switch (n->kind) { case syck_str_kind: if (n->type_id == NULL || strcmp(n->type_id, "str") == 0) { lua_pushlstring(bonus->L, n->data.str->ptr, n->data.str->len); o = lua_gettop(bonus->L); } else if (strcmp(n->type_id, "null") == 0) { lua_pushnil(bonus->L); o = lua_gettop(bonus->L); } else if (strcmp(n->type_id, "bool#yes") == 0) { lua_pushboolean(bonus->L, 1); o = lua_gettop(bonus->L); } else if (strcmp(n->type_id, "bool#no") == 0) { lua_pushboolean(bonus->L, 0); o = lua_gettop(bonus->L); } else if (strcmp(n->type_id, "float") == 0 || strcmp(n->type_id, "float#fix") == 0 || strcmp(n->type_id, "float#exp") == 0) { double f; syck_str_blow_away_commas(n); f = strtod(n->data.str->ptr, NULL); lua_pushnumber(bonus->L, f); o = lua_gettop(bonus->L); } else if (strcmp(n->type_id, "int#hex") == 0) { long intVal = strtol(n->data.str->ptr, NULL, 16); lua_pushnumber(bonus->L, intVal); o = lua_gettop(bonus->L); } else if (strcmp(n->type_id, "int") == 0) { long intVal = strtol(n->data.str->ptr, NULL, 10); lua_pushnumber(bonus->L, intVal); o = lua_gettop(bonus->L); } else { lua_pushlstring(bonus->L, n->data.str->ptr, n->data.str->len); o = lua_gettop(bonus->L); } break; case syck_seq_kind: lua_newtable(bonus->L); o = lua_gettop(bonus->L); for ( i=0; i < n->data.list->idx; i++ ) { oid = syck_seq_read(n, i); syck_lookup_sym(p, oid, (char **)&o2); lua_pushvalue(bonus->L, o2); lua_rawseti(bonus->L, o, i+1); } break; case syck_map_kind: lua_newtable(bonus->L); o = lua_gettop(bonus->L); for ( i=0; i < n->data.pairs->idx; i++ ) { oid = syck_map_read(n, map_key, i); syck_lookup_sym(p, oid, (char **)&o2); oid = syck_map_read(n, map_value, i); syck_lookup_sym(p, oid, (char **)&o3); lua_pushvalue(bonus->L, o2); lua_pushvalue(bonus->L, o3); lua_settable(bonus->L, o); } break; } oid = syck_add_sym(p, (char *)o); return oid; }
void lua_syck_emitter_handler(SyckEmitter *e, st_data_t data) { struct emitter_xtra *bonus = (struct emitter_xtra *)e->bonus; int type = lua_type(bonus->L, -1); char buf[32]; /* find a better way, if possible */ switch (type) { case LUA_TBOOLEAN: if (lua_toboolean(bonus->L, -1)) strcpy(buf, "true"); else strcpy(buf, "false"); syck_emit_scalar(e, "boolean", scalar_none, 0, 0, 0, (char *)buf, strlen(buf)); break; case LUA_TSTRING: syck_emit_scalar(e, "string", scalar_none, 0, 0, 0, (char *)lua_tostring(bonus->L, -1), lua_strlen(bonus->L, -1)); break; case LUA_TNUMBER: ; lua_Number lnum; //is it an int or a float? lnum = lua_tonumber(bonus->L, -1); int asInt = lnum; if(asInt == lnum) snprintf(buf, sizeof(buf), "%i", asInt); else { snprintf(buf, sizeof(buf), "%f", lnum); /* Remove trailing zeroes after the decimal point */ int k; for (k = strlen(buf) - 1; buf[k] == '0' && buf[k - 1] != '.'; k--) buf[k] = '\0'; } syck_emit_scalar(e, "number", scalar_none, 0, 0, 0, buf, strlen(buf)); break; case LUA_TTABLE: if (luaL_getn(bonus->L, -1) > 0) { /* treat it as an array */ syck_emit_seq(e, "table", seq_none); lua_pushnil(bonus->L); /* first key */ while (lua_next(bonus->L, -2) != 0) { /* `key' is at index -2 and `value' at index -1 */ syck_emit_item(e, bonus->id++); lua_pop(bonus->L, 1); /* removes `value'; keeps `key' for next iteration */ } syck_emit_end(e); } else { /* treat it as a map */ syck_emit_map(e, "table", map_none); lua_pushnil(bonus->L); while (lua_next(bonus->L, -2) != 0) { lua_pushvalue(bonus->L, -2); syck_emit_item(e, bonus->id++); lua_pop(bonus->L, 1); syck_emit_item(e, bonus->id++); lua_pop(bonus->L, 1); } syck_emit_end(e); } break; } bonus->id++; }
/* Get fields in an existing slurmctld job record. * * This is an incomplete list of job record fields. Add more as needed and * send patches to [email protected]. */ static int _job_rec_field(const struct job_record *job_ptr, const char *name) { int i; if (job_ptr == NULL) { error("_job_rec_field: job_ptr is NULL"); lua_pushnil (L); } else if (!strcmp(name, "account")) { lua_pushstring (L, job_ptr->account); } else if (!strcmp(name, "burst_buffer")) { lua_pushstring (L, job_ptr->burst_buffer); } else if (!strcmp(name, "comment")) { lua_pushstring (L, job_ptr->comment); } else if (!strcmp(name, "direct_set_prio")) { lua_pushnumber (L, job_ptr->direct_set_prio); } else if (!strcmp(name, "gres")) { lua_pushstring (L, job_ptr->gres); } else if (!strcmp(name, "job_id")) { lua_pushnumber (L, job_ptr->job_id); } else if (!strcmp(name, "job_state")) { lua_pushnumber (L, job_ptr->job_state); } else if (!strcmp(name, "licenses")) { lua_pushstring (L, job_ptr->licenses); } else if (!strcmp(name, "max_cpus")) { if (job_ptr->details) lua_pushnumber (L, job_ptr->details->max_cpus); else lua_pushnumber (L, 0); } else if (!strcmp(name, "max_nodes")) { if (job_ptr->details) lua_pushnumber (L, job_ptr->details->max_nodes); else lua_pushnumber (L, 0); } else if (!strcmp(name, "min_cpus")) { if (job_ptr->details) lua_pushnumber (L, job_ptr->details->min_cpus); else lua_pushnumber (L, 0); } else if (!strcmp(name, "min_nodes")) { if (job_ptr->details) lua_pushnumber (L, job_ptr->details->min_nodes); else lua_pushnumber (L, 0); } else if (!strcmp(name, "nice")) { if (job_ptr->details) lua_pushnumber (L, job_ptr->details->nice); else lua_pushnumber (L, (uint16_t)NO_VAL); } else if (!strcmp(name, "partition")) { lua_pushstring (L, job_ptr->partition); } else if (!strcmp(name, "priority")) { lua_pushnumber (L, job_ptr->priority); } else if (!strcmp(name, "qos")) { if (job_ptr->qos_ptr) { slurmdb_qos_rec_t *qos_ptr = (slurmdb_qos_rec_t *)job_ptr->qos_ptr; lua_pushstring (L, qos_ptr->name); } else { lua_pushnil (L); } } else if (!strcmp(name, "req_switch")) { lua_pushnumber (L, job_ptr->req_switch); } else if (!strcmp(name, "spank_job_env")) { if ((job_ptr->spank_job_env_size == 0) || (job_ptr->spank_job_env == NULL)) { lua_pushnil (L); } else { lua_newtable(L); for (i = 0; i < job_ptr->spank_job_env_size; i++) { if (job_ptr->spank_job_env[i] != NULL) { lua_pushnumber (L, i); lua_pushstring (L, job_ptr->spank_job_env[i]); lua_settable (L, -3); } } } } else if (!strcmp(name, "spank_job_env_size")) { lua_pushnumber (L, job_ptr->spank_job_env_size); } else if (!strcmp(name, "time_limit")) { lua_pushnumber (L, job_ptr->time_limit); } else if (!strcmp(name, "time_min")) { lua_pushnumber (L, job_ptr->time_min); } else if (!strcmp(name, "wait4switch")) { lua_pushnumber (L, job_ptr->wait4switch); } else if (!strcmp(name, "wckey")) { lua_pushstring (L, job_ptr->wckey); } else if (!strcmp(name, "spank_job_env")) { if (job_ptr->spank_job_env_size == 0 || job_ptr->spank_job_env == NULL) { lua_pushnil (L); } else { int idx = 0; int lidx = 1; lua_newtable(L); for (idx = 0; idx < job_ptr->spank_job_env_size; idx++) { if (job_ptr->spank_job_env[idx] != NULL) { lua_pushnumber (L, lidx++); lua_pushstring (L, job_ptr->spank_job_env[idx]); lua_settable (L, -3); } } } } else if (!strcmp(name, "spank_job_env_size")) { lua_pushnumber (L, job_ptr->spank_job_env_size); } else { lua_pushnil (L); } return 1; }
ToolCapabilities read_tool_capabilities( lua_State *L, int table) { ToolCapabilities toolcap; getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval); getintfield(L, table, "max_drop_level", toolcap.max_drop_level); lua_getfield(L, table, "groupcaps"); if(lua_istable(L, -1)){ int table_groupcaps = lua_gettop(L); lua_pushnil(L); while(lua_next(L, table_groupcaps) != 0){ // key at index -2 and value at index -1 std::string groupname = luaL_checkstring(L, -2); if(lua_istable(L, -1)){ int table_groupcap = lua_gettop(L); // This will be created ToolGroupCap groupcap; // Read simple parameters getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel); getintfield(L, table_groupcap, "uses", groupcap.uses); // DEPRECATED: maxwear float maxwear = 0; if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){ if(maxwear != 0) groupcap.uses = 1.0/maxwear; else groupcap.uses = 0; infostream<<script_get_backtrace(L)<<std::endl; infostream<<"WARNING: field \"maxwear\" is deprecated; " <<"should replace with uses=1/maxwear"<<std::endl; } // Read "times" table lua_getfield(L, table_groupcap, "times"); if(lua_istable(L, -1)){ int table_times = lua_gettop(L); lua_pushnil(L); while(lua_next(L, table_times) != 0){ // key at index -2 and value at index -1 int rating = luaL_checkinteger(L, -2); float time = luaL_checknumber(L, -1); groupcap.times[rating] = time; // removes value, keeps key for next iteration lua_pop(L, 1); } } lua_pop(L, 1); // Insert groupcap into toolcap toolcap.groupcaps[groupname] = groupcap; } // removes value, keeps key for next iteration lua_pop(L, 1); } } lua_pop(L, 1); lua_getfield(L, table, "damage_groups"); if(lua_istable(L, -1)){ int table_damage_groups = lua_gettop(L); lua_pushnil(L); while(lua_next(L, table_damage_groups) != 0){ // key at index -2 and value at index -1 std::string groupname = luaL_checkstring(L, -2); u16 value = luaL_checkinteger(L, -1); toolcap.damageGroups[groupname] = value; // removes value, keeps key for next iteration lua_pop(L, 1); } } lua_pop(L, 1); return toolcap; }
static int _get_job_req_field(const struct job_descriptor *job_desc, const char *name) { int i; if (job_desc == NULL) { error("%s: job_desc is NULL", __func__); lua_pushnil (L); } else if (!strcmp(name, "account")) { lua_pushstring (L, job_desc->account); } else if (!strcmp(name, "acctg_freq")) { lua_pushstring (L, job_desc->acctg_freq); } else if (!strcmp(name, "alloc_node")) { lua_pushstring (L, job_desc->alloc_node); } else if (!strcmp(name, "begin_time")) { lua_pushnumber (L, job_desc->begin_time); } else if (!strcmp(name, "boards_per_node")) { lua_pushnumber (L, job_desc->boards_per_node); } else if (!strcmp(name, "burst_buffer")) { lua_pushstring (L, job_desc->burst_buffer); } else if (!strcmp(name, "clusters")) { lua_pushstring (L, job_desc->clusters); } else if (!strcmp(name, "comment")) { lua_pushstring (L, job_desc->comment); } else if (!strcmp(name, "contiguous")) { lua_pushnumber (L, job_desc->contiguous); } else if (!strcmp(name, "cores_per_socket")) { lua_pushnumber (L, job_desc->cores_per_socket); } else if (!strcmp(name, "cpu_freq_min")) { lua_pushnumber (L, job_desc->cpu_freq_min); } else if (!strcmp(name, "cpu_freq_max")) { lua_pushnumber (L, job_desc->cpu_freq_max); } else if (!strcmp(name, "cpu_freq_gov")) { lua_pushnumber (L, job_desc->cpu_freq_gov); } else if (!strcmp(name, "cpus_per_task")) { lua_pushnumber (L, job_desc->cpus_per_task); } else if (!strcmp(name, "default_account")) { lua_pushstring (L, _get_default_account(job_desc->user_id)); } else if (!strcmp(name, "default_qos")) { lua_pushstring (L, _get_default_qos(job_desc->user_id, job_desc->account, job_desc->partition)); } else if (!strcmp(name, "dependency")) { lua_pushstring (L, job_desc->dependency); } else if (!strcmp(name, "end_time")) { lua_pushnumber (L, job_desc->end_time); } else if (!strcmp(name, "environment")) { _push_job_env ((struct job_descriptor *)job_desc); // No const } else if (!strcmp(name, "exc_nodes")) { lua_pushstring (L, job_desc->exc_nodes); } else if (!strcmp(name, "features")) { lua_pushstring (L, job_desc->features); } else if (!strcmp(name, "gres")) { lua_pushstring (L, job_desc->gres); } else if (!strcmp(name, "group_id")) { lua_pushnumber (L, job_desc->group_id); } else if (!strcmp(name, "licenses")) { lua_pushstring (L, job_desc->licenses); } else if (!strcmp(name, "mail_type")) { lua_pushnumber (L, job_desc->mail_type); } else if (!strcmp(name, "mail_user")) { lua_pushstring (L, job_desc->mail_user); } else if (!strcmp(name, "max_cpus")) { lua_pushnumber (L, job_desc->max_cpus); } else if (!strcmp(name, "max_nodes")) { lua_pushnumber (L, job_desc->max_nodes); } else if (!strcmp(name, "min_cpus")) { lua_pushnumber (L, job_desc->min_cpus); } else if (!strcmp(name, "min_nodes")) { lua_pushnumber (L, job_desc->min_nodes); } else if (!strcmp(name, "name")) { lua_pushstring (L, job_desc->name); } else if (!strcmp(name, "nice")) { lua_pushnumber (L, job_desc->nice); } else if (!strcmp(name, "ntasks_per_board")) { lua_pushnumber (L, job_desc->ntasks_per_board); } else if (!strcmp(name, "ntasks_per_core")) { lua_pushnumber (L, job_desc->ntasks_per_core); } else if (!strcmp(name, "ntasks_per_node")) { lua_pushnumber (L, job_desc->ntasks_per_node); } else if (!strcmp(name, "ntasks_per_socket")) { lua_pushnumber (L, job_desc->ntasks_per_socket); } else if (!strcmp(name, "num_tasks")) { lua_pushnumber (L, job_desc->num_tasks); } else if (!strcmp(name, "partition")) { lua_pushstring (L, job_desc->partition); } else if (!strcmp(name, "power_flags")) { lua_pushnumber (L, job_desc->power_flags); } else if (!strcmp(name, "pn_min_cpus")) { lua_pushnumber (L, job_desc->pn_min_cpus); } else if (!strcmp(name, "pn_min_memory")) { lua_pushnumber (L, job_desc->pn_min_memory); } else if (!strcmp(name, "pn_min_tmp_disk")) { lua_pushnumber (L, job_desc->pn_min_tmp_disk); } else if (!strcmp(name, "priority")) { lua_pushnumber (L, job_desc->priority); } else if (!strcmp(name, "qos")) { lua_pushstring (L, job_desc->qos); } else if (!strcmp(name, "req_nodes")) { lua_pushstring (L, job_desc->req_nodes); } else if (!strcmp(name, "req_switch")) { lua_pushnumber (L, job_desc->req_switch); } else if (!strcmp(name, "requeue")) { lua_pushnumber (L, job_desc->requeue); } else if (!strcmp(name, "reservation")) { lua_pushstring (L, job_desc->reservation); } else if (!strcmp(name, "script")) { lua_pushstring (L, job_desc->script); } else if (!strcmp(name, "shared")) { lua_pushnumber (L, job_desc->shared); } else if (!strcmp(name, "sicp_mode")) { lua_pushnumber (L, job_desc->sicp_mode); } else if (!strcmp(name, "sockets_per_board")) { lua_pushnumber (L, job_desc->sockets_per_board); } else if (!strcmp(name, "sockets_per_node")) { lua_pushnumber (L, job_desc->sockets_per_node); } else if (!strcmp(name, "spank_job_env")) { if ((job_desc->spank_job_env_size == 0) || (job_desc->spank_job_env == NULL)) { lua_pushnil (L); } else { lua_newtable(L); for (i = 0; i < job_desc->spank_job_env_size; i++) { if (job_desc->spank_job_env[i] != NULL) { lua_pushnumber (L, i); lua_pushstring (L, job_desc->spank_job_env[i]); lua_settable (L, -3); } } } } else if (!strcmp(name, "spank_job_env_size")) { lua_pushnumber (L, job_desc->spank_job_env_size); } else if (!strcmp(name, "std_err")) { lua_pushstring (L, job_desc->std_err); } else if (!strcmp(name, "std_in")) { lua_pushstring (L, job_desc->std_in); } else if (!strcmp(name, "std_out")) { lua_pushstring (L, job_desc->std_out); } else if (!strcmp(name, "threads_per_core")) { lua_pushnumber (L, job_desc->threads_per_core); } else if (!strcmp(name, "time_limit")) { lua_pushnumber (L, job_desc->time_limit); } else if (!strcmp(name, "time_min")) { lua_pushnumber (L, job_desc->time_min); } else if (!strcmp(name, "user_id")) { lua_pushnumber (L, job_desc->user_id); } else if (!strcmp(name, "wait4switch")) { lua_pushnumber (L, job_desc->wait4switch); } else if (!strcmp(name, "work_dir")) { lua_pushstring (L, job_desc->work_dir); } else if (!strcmp(name, "wckey")) { lua_pushstring (L, job_desc->wckey); } else if (!strcmp(name, "spank_job_env")) { if (job_desc->spank_job_env_size == 0 || job_desc->spank_job_env == NULL) { lua_pushnil (L); } else { int idx = 0; int lidx = 1; lua_newtable(L); for (idx = 0; idx < job_desc->spank_job_env_size; idx++) { if (job_desc->spank_job_env[idx] != NULL) { lua_pushnumber (L, lidx++); lua_pushstring (L, job_desc->spank_job_env[idx]); lua_settable (L, -3); } } } } else if (!strcmp(name, "spank_job_env_size")) { lua_pushnumber (L, job_desc->spank_job_env_size); } else { lua_pushnil (L); } return 1; }
bool read_schematic(lua_State *L, int index, DecoSchematic *dschem, Server *server) { if (index < 0) index = lua_gettop(L) + 1 + index; INodeDefManager *ndef = server->getNodeDefManager(); if (lua_istable(L, index)) { lua_getfield(L, index, "size"); v3s16 size = read_v3s16(L, -1); lua_pop(L, 1); int numnodes = size.X * size.Y * size.Z; MapNode *schemdata = new MapNode[numnodes]; int i = 0; lua_getfield(L, index, "data"); luaL_checktype(L, -1, LUA_TTABLE); lua_pushnil(L); while (lua_next(L, -2)) { if (i < numnodes) { // same as readnode, except param1 default is MTSCHEM_PROB_CONST lua_getfield(L, -1, "name"); const char *name = luaL_checkstring(L, -1); lua_pop(L, 1); u8 param1; lua_getfield(L, -1, "param1"); param1 = !lua_isnil(L, -1) ? lua_tonumber(L, -1) : MTSCHEM_PROB_ALWAYS; lua_pop(L, 1); u8 param2; lua_getfield(L, -1, "param2"); param2 = !lua_isnil(L, -1) ? lua_tonumber(L, -1) : 0; lua_pop(L, 1); schemdata[i] = MapNode(ndef, name, param1, param2); } i++; lua_pop(L, 1); } dschem->size = size; dschem->schematic = schemdata; if (i != numnodes) { errorstream << "read_schematic: incorrect number of " "nodes provided in raw schematic data (got " << i << ", expected " << numnodes << ")." << std::endl; return false; } } else if (lua_isstring(L, index)) { dschem->filename = std::string(lua_tostring(L, index)); } else { errorstream << "read_schematic: missing schematic " "filename or raw schematic data" << std::endl; return false; } return true; }
static int lua_iso8583_new(lua_State *L) { struct iso8583 *iso8583h; iso8583_userdata *iso8583u = (iso8583_userdata *)lua_newuserdata(L, sizeof(iso8583_userdata)); char error[BUFSIZ]; iso8583u->handle = NULL; luaL_getmetatable(L, "iso8583"); lua_setmetatable(L, -2); iso8583h = iso8583u->handle = iso8583_create(); if (!iso8583h) { lua_pushnil(L); lua_pushstring(L, "alloc memory failed!"); return 2; } if (lua_istable(L, 1)) { lua_pushnil(L); while (lua_next(L, 1) != 0) { if (lua_isnumber(L, -2)) { int i = lua_tointeger(L, -2); if (i >= 0 && i <= 128) { if (lua_istable(L, -1)) { int size; int type; int align; int compress; char pad; // get size lua_getfield(L, -1, "size"); if (!lua_isnumber(L, -1)) { lua_pushnil(L); snprintf(error, BUFSIZ, "field %d error! the size is not a number!", i); lua_pushstring(L, error); return 2; } size = lua_tointeger(L, -1); if (size < 0) { lua_pushnil(L); snprintf(error, BUFSIZ, "field %d error! the size is little then 0! size = %d", i, size); lua_pushstring(L, error); return 2; } lua_pop(L, 1); // get type lua_getfield(L, -1, "type"); if (!lua_isnumber(L, -1)) { lua_pushnil(L); snprintf(error, BUFSIZ, "field %d error! the type is invalid!", i); lua_pushstring(L, error); return 2; } type = lua_tointeger(L, -1); lua_pop(L, 1); // get align; lua_getfield(L, -1, "align"); if (!lua_isnumber(L, -1)) { lua_pushnil(L); snprintf(error, BUFSIZ, "field %d error! the align is invalid!", i); lua_pushstring(L, error); return 2; } align = lua_tointeger(L, -1); lua_pop(L, 1); // get compress; lua_getfield(L, -1, "compress"); if (!lua_isnumber(L, -1)) { lua_pushnil(L); snprintf(error, BUFSIZ, "field %d error! the compress is invalid!", i); lua_pushstring(L, error); return 2; } compress = lua_tointeger(L, -1); lua_pop(L, 1); // get pad; lua_getfield(L, -1, "pad"); if (!lua_isstring(L, -1) || !lua_objlen(L, -1)) { lua_pushnil(L); snprintf(error, BUFSIZ, "field %d error! the pad is invalid!", i); lua_pushstring(L, error); return 2; } pad = *lua_tostring(L, -1); lua_pop(L, 1); // define field if (iso8583_define(iso8583h, i, (unsigned int)size, pad, (unsigned int)type, (unsigned int)align, (unsigned int)compress) != ISO8583_OK) { lua_pushnil(L); snprintf(error, BUFSIZ, "field %u error! the field is invalid! size = %u, " "pad = %c, type = %u, align = %u, compress = %u!", i, size, pad, type, align, compress); lua_pushstring(L, error); return 2; } } } } lua_pop(L, 1); } } return 1; }
void Lua_V2::GammaEnabled() { warning("Lua_V2::GammaEnabled: implement opcode, pushing nil"); lua_pushnil(); }
static int lua_getregistryvalue(lua_State *L) { #ifdef _WIN32 static char *keynames[] = { "HKEY_CLASSES_ROOT", "HKEY_CURRENT_CONFIG", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE", "HKEY_USERS", NULL }; static HKEY keys[] = { HKEY_CLASSES_ROOT, HKEY_CURRENT_CONFIG, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, HKEY_USERS }; HKEY rkey = keys[ luaL_checkoption(L, 1, NULL, keynames) ]; const char *subkey = luaL_checkstring(L, 2); const char *value = luaL_checkstring(L, 3); HKEY skey; DWORD type; DWORD len = 0; char *data = NULL; LONG res; res = RegOpenKeyExA(rkey, subkey, 0, KEY_READ, &skey); if (res != ERROR_SUCCESS) { lua_pushnil(L); lua_pushinteger(L, res); if (res == ERROR_FILE_NOT_FOUND) lua_pushstring(L, "subkey not found"); if (res == ERROR_ACCESS_DENIED) lua_pushstring(L, "subkey access denied"); else return 2; return 3; } res = RegQueryValueExA(skey, value, NULL, &type, (LPBYTE)data, &len); if (len > 0) { len += 8; data = (char*)malloc(len); if (! data) luaL_error(L, "out of memory"); res = RegQueryValueExA(skey, value, NULL, &type, (LPBYTE)data, &len); } RegCloseKey(skey); if (res != ERROR_SUCCESS) { if (data) free(data); lua_pushnil(L); lua_pushinteger(L, res); if (res == ERROR_FILE_NOT_FOUND) lua_pushstring(L, "value not found"); if (res == ERROR_ACCESS_DENIED) lua_pushstring(L, "value access denied"); else return 2; return 3; } switch(type) { case REG_DWORD: lua_pushinteger(L, (lua_Integer)*(const DWORD*)data); if (data) free(data); return 1; case REG_EXPAND_SZ: if (data && len > 0) { if ((len = ExpandEnvironmentStrings(data, NULL, 0)) > 0) { char *buf = (char*)malloc(len + 8); if (!buf) luaL_error(L, "out of memory"); len = ExpandEnvironmentStrings(data, buf, len+8); free(data); data = buf; } } /* fall thru */ case REG_SZ: if (data && len > 0) if (((const char*)data)[len-1] == 0) len -= 1; /* fall thru */ case REG_BINARY: if (data && len > 0) lua_pushlstring(L, (const char*)data, (int)len); else lua_pushliteral(L, ""); if (data) free(data); return 1; /* unimplemented */ case REG_QWORD: case REG_MULTI_SZ: default: lua_pushnil(L); lua_pushinteger(L, res); lua_pushfstring(L, "getting registry type %d not implemented", type); return 3; } #else luaL_error(L, "This function exists only on windows"); return 0; #endif }
bool luaW_toconfig(lua_State *L, int index, config &cfg) { if (!lua_checkstack(L, LUA_MINSTACK)) return false; // Get the absolute index of the table. index = lua_absindex(L, index); int initial_top = lua_gettop(L); switch (lua_type(L, index)) { case LUA_TTABLE: break; case LUA_TUSERDATA: { if (vconfig * ptr = static_cast<vconfig *> (luaL_testudata(L, index, vconfigKey))) { cfg = ptr->get_parsed_config(); return true; } else { return false; } } case LUA_TNONE: case LUA_TNIL: return true; default: return false; } // First convert the children (integer indices). for (int i = 1, i_end = lua_rawlen(L, index); i <= i_end; ++i) { lua_rawgeti(L, index, i); if (!lua_istable(L, -1)) return_misformed(); lua_rawgeti(L, -1, 1); char const *m = lua_tostring(L, -1); if (!m) return_misformed(); lua_rawgeti(L, -2, 2); if (!luaW_toconfig(L, -1, cfg.add_child(m))) return_misformed(); lua_pop(L, 3); } // Then convert the attributes (string indices). for (lua_pushnil(L); lua_next(L, index); lua_pop(L, 1)) { if (lua_isnumber(L, -2)) continue; if (!lua_isstring(L, -2)) return_misformed(); config::attribute_value &v = cfg[lua_tostring(L, -2)]; if (lua_istable(L, -1)) { int subindex = lua_absindex(L, -1); std::ostringstream str; for (int i = 1, i_end = lua_rawlen(L, subindex); i <= i_end; ++i, lua_pop(L, 1)) { lua_rawgeti(L, -1, i); config::attribute_value item; if (!luaW_toscalar(L, -1, item)) return_misformed(); if (i > 1) str << ','; str << item; } // If there are any string keys, it's misformed for (lua_pushnil(L); lua_next(L, subindex); lua_pop(L, 1)) { if (!lua_isnumber(L, -2)) return_misformed(); } v = str.str(); } else if (!luaW_toscalar(L, -1, v)) return_misformed(); } lua_settop(L, initial_top); return true; }
/* ** Pushes the indexed value onto the lua stack */ static void push_column(lua_State *L, int i, cur_data *cur) { int varcharlen; struct tm timevar; char timestr[256]; ISC_STATUS blob_stat; isc_blob_handle blob_handle = 0; ISC_QUAD blob_id; luaL_Buffer b; char *buffer; unsigned short actual_seg_len; if( (cur->out_sqlda->sqlvar[i].sqlind != NULL) && (*(cur->out_sqlda->sqlvar[i].sqlind) != 0) ) { /* a null field? */ lua_pushnil(L); } else { switch(cur->out_sqlda->sqlvar[i].sqltype & ~1) { case SQL_VARYING: varcharlen = (int)isc_vax_integer(cur->out_sqlda->sqlvar[i].sqldata, 2); lua_pushlstring(L, cur->out_sqlda->sqlvar[i].sqldata+2, varcharlen); break; case SQL_TEXT: lua_pushlstring(L, cur->out_sqlda->sqlvar[i].sqldata, cur->out_sqlda->sqlvar[i].sqllen); break; case SQL_SHORT: luasql_pushinteger(L, *(short*)(cur->out_sqlda->sqlvar[i].sqldata)); break; case SQL_LONG: luasql_pushinteger(L, *(long*)(cur->out_sqlda->sqlvar[i].sqldata)); break; case SQL_INT64: luasql_pushinteger(L, *(ISC_INT64*)(cur->out_sqlda->sqlvar[i].sqldata)); break; case SQL_FLOAT: lua_pushnumber(L, *(float*)(cur->out_sqlda->sqlvar[i].sqldata)); break; case SQL_DOUBLE: lua_pushnumber(L, *(double*)(cur->out_sqlda->sqlvar[i].sqldata)); break; case SQL_TYPE_TIME: isc_decode_sql_time((ISC_TIME*)(cur->out_sqlda->sqlvar[i].sqldata), &timevar); strftime(timestr, 255, "%X", &timevar); lua_pushstring(L, timestr); break; case SQL_TYPE_DATE: isc_decode_sql_date((ISC_DATE*)(cur->out_sqlda->sqlvar[i].sqldata), &timevar); strftime(timestr, 255, "%x", &timevar); lua_pushstring(L, timestr); break; case SQL_TIMESTAMP: isc_decode_timestamp((ISC_TIMESTAMP*)(cur->out_sqlda->sqlvar[i].sqldata), &timevar); strftime(timestr, 255, "%x %X", &timevar); lua_pushstring(L, timestr); break; case SQL_BLOB: /* get the BLOB ID and open it */ memcpy(&blob_id, cur->out_sqlda->sqlvar[i].sqldata, sizeof(ISC_QUAD)); isc_open_blob2( cur->env->status_vector, &cur->conn->db, &cur->conn->transaction, &blob_handle, &blob_id, 0, NULL ); /* fetch the blob data */ luaL_buffinit(L, &b); buffer = luaL_prepbuffer(&b); blob_stat = isc_get_segment( cur->env->status_vector, &blob_handle, &actual_seg_len, LUAL_BUFFERSIZE, buffer ); while(blob_stat == 0 || cur->env->status_vector[1] == isc_segment) { luaL_addsize(&b, actual_seg_len); buffer = luaL_prepbuffer(&b); blob_stat = isc_get_segment( cur->env->status_vector, &blob_handle, &actual_seg_len, LUAL_BUFFERSIZE, buffer ); } /* finnished, close the BLOB */ isc_close_blob(cur->env->status_vector, &blob_handle); blob_handle = 0; luaL_pushresult(&b); break; default: lua_pushstring(L, "<unsupported data type>"); break; } } }
void LuaParser::ReloadQuests() { loaded_.clear(); errors_.clear(); lua_encounter_events_registered.clear(); lua_encounters_loaded.clear(); for (auto encounter : lua_encounters) { encounter.second->Depop(); } lua_encounters.clear(); if(L) { lua_close(L); } L = luaL_newstate(); luaL_openlibs(L); if(luaopen_bit(L) != 1) { std::string error = lua_tostring(L, -1); AddError(error); } if(luaL_dostring(L, "math.randomseed(os.time())")) { std::string error = lua_tostring(L, -1); AddError(error); } #ifdef SANITIZE_LUA_LIBS //io lua_pushnil(L); lua_setglobal(L, "io"); //some os/debug are okay some are not lua_getglobal(L, "os"); lua_pushnil(L); lua_setfield(L, -2, "exit"); lua_pushnil(L); lua_setfield(L, -2, "execute"); lua_pushnil(L); lua_setfield(L, -2, "getenv"); lua_pushnil(L); lua_setfield(L, -2, "remove"); lua_pushnil(L); lua_setfield(L, -2, "rename"); lua_pushnil(L); lua_setfield(L, -2, "setlocale"); lua_pushnil(L); lua_setfield(L, -2, "tmpname"); lua_pop(L, 1); lua_pushnil(L); lua_setglobal(L, "collectgarbage"); lua_pushnil(L); lua_setglobal(L, "loadfile"); #endif // lua 5.2+ defines these #if defined(LUA_VERSION_MAJOR) && defined(LUA_VERSION_MINOR) const char lua_version[] = LUA_VERSION_MAJOR "." LUA_VERSION_MINOR; #elif LUA_VERSION_NUM == 501 const char lua_version[] = "5.1"; #else #error Incompatible lua version #endif #ifdef WINDOWS const char libext[] = ".dll"; #else // lua doesn't care OSX doesn't use sonames const char libext[] = ".so"; #endif lua_getglobal(L, "package"); lua_getfield(L, -1, "path"); std::string module_path = lua_tostring(L,-1); module_path += ";./" + Config->LuaModuleDir + "?.lua;./" + Config->LuaModuleDir + "?/init.lua"; // luarock paths using lua_modules as tree // to path it adds foo/share/lua/5.1/?.lua and foo/share/lua/5.1/?/init.lua module_path += ";./" + Config->LuaModuleDir + "share/lua/" + lua_version + "/?.lua"; module_path += ";./" + Config->LuaModuleDir + "share/lua/" + lua_version + "/?/init.lua"; lua_pop(L, 1); lua_pushstring(L, module_path.c_str()); lua_setfield(L, -2, "path"); lua_pop(L, 1); lua_getglobal(L, "package"); lua_getfield(L, -1, "cpath"); module_path = lua_tostring(L, -1); module_path += ";./" + Config->LuaModuleDir + "?" + libext; // luarock paths using lua_modules as tree // luarocks adds foo/lib/lua/5.1/?.so for cpath module_path += ";./" + Config->LuaModuleDir + "lib/lua/" + lua_version + "/?" + libext; lua_pop(L, 1); lua_pushstring(L, module_path.c_str()); lua_setfield(L, -2, "cpath"); lua_pop(L, 1); MapFunctions(L); //load init std::string path = Config->QuestDir; path += "/"; path += QUEST_GLOBAL_DIRECTORY; path += "/script_init.lua"; FILE *f = fopen(path.c_str(), "r"); if(f) { fclose(f); if(luaL_dofile(L, path.c_str())) { std::string error = lua_tostring(L, -1); AddError(error); } } //zone init - always loads after global if(zone) { std::string zone_script = Config->QuestDir; zone_script += "/"; zone_script += zone->GetShortName(); zone_script += "/script_init_v"; zone_script += std::to_string(zone->GetInstanceVersion()); zone_script += ".lua"; f = fopen(zone_script.c_str(), "r"); if(f) { fclose(f); if(luaL_dofile(L, zone_script.c_str())) { std::string error = lua_tostring(L, -1); AddError(error); } return; } zone_script = Config->QuestDir; zone_script += "/"; zone_script += zone->GetShortName(); zone_script += "/script_init.lua"; f = fopen(zone_script.c_str(), "r"); if(f) { fclose(f); if(luaL_dofile(L, zone_script.c_str())) { std::string error = lua_tostring(L, -1); AddError(error); } } } }
/** * @brief Gets a planet. * * Possible values of param: * - nil : -OBSOLETE- Gets the current landed planet or nil if there is none. Use planet.cur() instead. * - bool : Gets a random planet. * - faction : Gets random planet belonging to faction matching the number. * - string : Gets the planet by name. * - table : Gets random planet belonging to any of the factions in the * table. * * @usage p,s = planet.get( "Anecu" ) -- Gets planet by name * @usage p,s = planet.get( faction.get( "Empire" ) ) -- Gets random Empire planet * @usage p,s = planet.get(true) -- Gets completely random planet * @usage p,s = planet.get( { faction.get("Empire"), faction.get("Dvaered") } ) -- Random planet belonging to Empire or Dvaered * @luaparam param See description. * @luareturn Returns the planet and the system it belongs to. * @luafunc get( param ) */ static int planetL_get( lua_State *L ) { int i; int *factions; int nfactions; char **planets; int nplanets; const char *rndplanet; LuaPlanet planet; LuaSystem luasys; LuaFaction *f; Planet *pnt; StarSystem *sys; char *sysname; rndplanet = NULL; planets = NULL; nplanets = 0; /* Get the landed planet */ if (lua_gettop(L) == 0) { if (land_planet != NULL) { planet.id = planet_index( land_planet ); lua_pushplanet(L,planet); luasys.id = system_index( system_get( planet_getSystem(land_planet->name) ) ); lua_pushsystem(L,luasys); return 2; } NLUA_ERROR(L,"Attempting to get landed planet when player not landed."); return 0; /* Not landed. */ } /* If boolean return random. */ else if (lua_isboolean(L,1)) { pnt = planet_get( space_getRndPlanet() ); planet.id = planet_index( pnt ); lua_pushplanet(L,planet); luasys.id = system_index( system_get( planet_getSystem(pnt->name) ) ); lua_pushsystem(L,luasys); return 2; } /* Get a planet by faction */ else if (lua_isfaction(L,1)) { f = lua_tofaction(L,1); planets = space_getFactionPlanet( &nplanets, &f->f, 1 ); } /* Get a planet by name */ else if (lua_isstring(L,1)) { rndplanet = lua_tostring(L,1); } /* Get a planet from faction list */ else if (lua_istable(L,1)) { /* Get table length and preallocate. */ nfactions = (int) lua_objlen(L,1); factions = malloc( sizeof(int) * nfactions ); /* Load up the table. */ lua_pushnil(L); i = 0; while (lua_next(L, -2) != 0) { f = lua_tofaction(L, -1); factions[i++] = f->f; lua_pop(L,1); } /* get the planets */ planets = space_getFactionPlanet( &nplanets, factions, nfactions ); free(factions); } else NLUA_INVALID_PARAMETER(L); /* Bad Parameter */ /* No suitable planet found */ if ((rndplanet == NULL) && ((planets == NULL) || nplanets == 0)) return 0; /* Pick random planet */ else if (rndplanet == NULL) { rndplanet = planets[RNG(0,nplanets-1)]; free(planets); } /* Push the planet */ pnt = planet_get(rndplanet); /* The real planet */ if (pnt == NULL) { NLUA_ERROR(L, "Planet '%s' not found in stack", rndplanet); return 0; } sysname = planet_getSystem(rndplanet); if (sysname == NULL) { NLUA_ERROR(L, "Planet '%s' is not placed in a system", rndplanet); return 0; } sys = system_get( sysname ); if (sys == NULL) { NLUA_ERROR(L, "Planet '%s' can't find system '%s'", rndplanet, sysname); return 0; } planet.id = planet_index( pnt ); lua_pushplanet(L,planet); luasys.id = system_index( sys ); lua_pushsystem(L,luasys); return 2; }
void LuaContext::PushJson(const Json::Value& value) { if (value.isString()) { const std::string s = value.asString(); lua_pushlstring(lua_, s.c_str(), s.size()); } else if (value.isDouble()) { lua_pushnumber(lua_, value.asDouble()); } else if (value.isInt()) { lua_pushinteger(lua_, value.asInt()); } else if (value.isUInt()) { lua_pushinteger(lua_, value.asUInt()); } else if (value.isBool()) { lua_pushboolean(lua_, value.asBool()); } else if (value.isNull()) { lua_pushnil(lua_); } else if (value.isArray()) { lua_newtable(lua_); // http://lua-users.org/wiki/SimpleLuaApiExample for (Json::Value::ArrayIndex i = 0; i < value.size(); i++) { // Push the table index (note the "+1" because of Lua conventions) lua_pushnumber(lua_, i + 1); // Push the value of the cell PushJson(value[i]); // Stores the pair in the table lua_rawset(lua_, -3); } } else if (value.isObject()) { lua_newtable(lua_); Json::Value::Members members = value.getMemberNames(); for (Json::Value::Members::const_iterator it = members.begin(); it != members.end(); ++it) { // Push the index of the cell lua_pushlstring(lua_, it->c_str(), it->size()); // Push the value of the cell PushJson(value[*it]); // Stores the pair in the table lua_rawset(lua_, -3); } } else { throw LuaException("Unsupported JSON conversion"); } }
int lua_Model_getMaterial(lua_State* state) { // Get the number of parameters. int paramCount = lua_gettop(state); // Attempt to match the parameters to a valid binding. switch (paramCount) { case 1: { if ((lua_type(state, 1) == LUA_TUSERDATA)) { Model* instance = getInstance(state); void* returnPtr = ((void*)instance->getMaterial()); if (returnPtr) { gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject)); object->instance = returnPtr; object->owns = false; luaL_getmetatable(state, "Material"); lua_setmetatable(state, -2); } else { lua_pushnil(state); } return 1; } lua_pushstring(state, "lua_Model_getMaterial - Failed to match the given parameters to a valid function signature."); lua_error(state); break; } case 2: { if ((lua_type(state, 1) == LUA_TUSERDATA) && lua_type(state, 2) == LUA_TNUMBER) { // Get parameter 1 off the stack. int param1 = (int)luaL_checkint(state, 2); Model* instance = getInstance(state); void* returnPtr = ((void*)instance->getMaterial(param1)); if (returnPtr) { gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject)); object->instance = returnPtr; object->owns = false; luaL_getmetatable(state, "Material"); lua_setmetatable(state, -2); } else { lua_pushnil(state); } return 1; } lua_pushstring(state, "lua_Model_getMaterial - Failed to match the given parameters to a valid function signature."); lua_error(state); break; } default: { lua_pushstring(state, "Invalid number of parameters (expected 1 or 2)."); lua_error(state); break; } } return 0; }
void LuaContext::GetJson(Json::Value& result, int top) { if (lua_istable(lua_, top)) { Json::Value tmp = Json::objectValue; bool isArray = true; size_t size = 0; // Code adapted from: http://stackoverflow.com/a/6142700/881731 // Push another reference to the table on top of the stack (so we know // where it is, and this function can work for negative, positive and // pseudo indices lua_pushvalue(lua_, top); // stack now contains: -1 => table lua_pushnil(lua_); // stack now contains: -1 => nil; -2 => table while (lua_next(lua_, -2)) { // stack now contains: -1 => value; -2 => key; -3 => table // copy the key so that lua_tostring does not modify the original lua_pushvalue(lua_, -2); // stack now contains: -1 => key; -2 => value; -3 => key; -4 => table std::string key(lua_tostring(lua_, -1)); Json::Value v; GetJson(v, -2); tmp[key] = v; size += 1; try { if (boost::lexical_cast<size_t>(key) != size) { isArray = false; } } catch (boost::bad_lexical_cast&) { isArray = false; } // pop value + copy of key, leaving original key lua_pop(lua_, 2); // stack now contains: -1 => key; -2 => table } // stack now contains: -1 => table (when lua_next returns 0 it pops the key // but does not push anything.) // Pop table lua_pop(lua_, 1); // Stack is now the same as it was on entry to this function if (isArray) { result = Json::arrayValue; for (size_t i = 0; i < size; i++) { result.append(tmp[boost::lexical_cast<std::string>(i + 1)]); } } else { result = tmp; } } else if (lua_isnil(lua_, top)) { result = Json::nullValue; } else if (lua_isboolean(lua_, top)) { result = lua_toboolean(lua_, top) ? true : false; } else if (lua_isnumber(lua_, top)) { // Convert to "int" if truncation does not loose precision double value = static_cast<double>(lua_tonumber(lua_, top)); int truncated = static_cast<int>(value); if (std::abs(value - static_cast<double>(truncated)) <= std::numeric_limits<double>::epsilon()) { result = truncated; } else { result = value; } } else if (lua_isstring(lua_, top)) { // Caution: The "lua_isstring()" case must be the last, since // Lua can convert most types to strings by default. result = std::string(lua_tostring(lua_, top)); } else { LOG(WARNING) << "Unsupported Lua type when returning Json"; result = Json::nullValue; } }
void deleteUserdata(lua_State *L, void *ptr) { lua_pushnil(L); lua_rawsetp(L, LUA_REGISTRYINDEX, ptr); }
static int qltimer_add(lua_State *state) { int timeout, cycle; const char *mod, *func; qactor_t *actor; qdict_t *args; qengine_t *engine; qid_t id; qltimer_t *timer; timeout = (int)lua_tonumber(state, 1); cycle = (int)lua_tonumber(state, 2); mod = lua_tostring(state, 3); func = lua_tostring(state, 4); if (timeout < 0 || cycle < 0 || mod == NULL || func == NULL) { lua_pushnil(state); lua_pushliteral(state, "wrong param"); return 2; } /* if there exist mod.fun? */ lua_getglobal(state, mod); if (!lua_istable(state, -1)) { lua_pushnil(state); lua_pushfstring(state, "mod %s not exist", mod); return 2; } lua_getfield(state, -1, func); if (!lua_isfunction(state, -1)) { lua_pushnil(state); lua_pushfstring(state, "%s.%s is not lua function", mod, func); return 2; } /* pop the result */ lua_pop(state, -1); args = qdict_new(5); if (args == NULL) { lua_pushnil(state); lua_pushliteral(state, "create args table error"); return 2; } if (qlua_copy_table(state, 4, args) != QOK) { qdict_free(args); lua_pushnil(state); lua_pushliteral(state, "copy args table error"); return 2; } timer = new_timer(args, mod, func); if (timer == NULL) { qdict_free(args); lua_pushnil(state); lua_pushliteral(state, "create timer error"); return 2; } actor = qlua_get_actor(state); engine = qactor_get_engine(actor->aid); id = qtimer_add(engine, timeout, timer_handler, free_timer, cycle, timer); timer->state = state; timer->id = id; timer->engine = engine; qdict_set_numdata(actor->timers, id, timer, engine_free_timer); lua_pushnumber(state, id); return 1; }