/** * \brief Implementation of game:get_value(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::game_api_get_value(lua_State* l) { Savegame& savegame = check_game(l, 1); const std::string& key = luaL_checkstring(l, 2); if (!is_valid_lua_identifier(key)) { arg_error(l, 3, StringConcat() << "Invalid savegame variable '" << key << "': the name should only contain alphanumeric characters or '_'" << " and cannot start with a digit"); } if (savegame.is_boolean(key)) { lua_pushboolean(l, savegame.get_boolean(key)); } else if (savegame.is_integer(key)) { lua_pushinteger(l, savegame.get_integer(key)); } else if (savegame.is_string(key)) { lua_pushstring(l, savegame.get_string(key).c_str()); } else { lua_pushnil(l); } return 1; }
/** * \brief Implementation of item:set_amount_savegame_variable(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::item_api_set_amount_savegame_variable(lua_State* l) { EquipmentItem& item = check_item(l, 1); std::string amount_savegame_variable; if (lua_gettop(l) >= 2) { amount_savegame_variable = luaL_checkstring(l, 2); } if (!amount_savegame_variable.empty() && !is_valid_lua_identifier(amount_savegame_variable)) { arg_error(l, 2, StringConcat() << "savegame variable identifier expected, got '" << amount_savegame_variable << "'"); } item.set_amount_savegame_variable(amount_savegame_variable); return 0; }
/** * \brief Implementation of game:set_value(). * \param l The Lua context that is calling this function. * \return Number of values to return to Lua. */ int LuaContext::game_api_set_value(lua_State* l) { Savegame& savegame = check_game(l, 1); const std::string& key = luaL_checkstring(l, 2); if (key[0] == '_') { arg_error(l, 3, StringConcat() << "Invalid savegame variable '" << key << "': names prefixed by '_' are reserved for built-in variables"); } if (!is_valid_lua_identifier(key)) { arg_error(l, 3, StringConcat() << "Invalid savegame variable '" << key << "': the name should only contain alphanumeric characters or '_'" << " and cannot start with a digit"); } switch (lua_type(l, 3)) { case LUA_TBOOLEAN: savegame.set_boolean(key, lua_toboolean(l, 3)); break; case LUA_TNUMBER: savegame.set_integer(key, int(lua_tointeger(l, 3))); break; case LUA_TSTRING: savegame.set_string(key, lua_tostring(l, 3)); break; case LUA_TNIL: savegame.unset(key); break; default: arg_error(l, 3, StringConcat() << "Expected string, number or boolean, got " << luaL_typename(l, 3)); } return 0; }