It Is Impossible to Serve Hashem L’shma Initially
I would like to propose a wonderful explanation for these issues based on the teaching in the Gemara (Pesachim 50b): תורה ומצוות אף על פי שלא לשמה, שמתוך שלא לשמה"לעולם יעסוק אדם ב בא לשמה"—a person should (must) always engage in the study of Torah and the performance of mitzvos even though it is not l’shma, i.e., his actions are not purely motivated; because from these activities that are not l’shma, he will eventually come to learn Torah and perform mitzvos for its own sake, with the purest of intentions—l’shma. The Toldos Yaakov Yosef (Vayishlach) comments on the language "לעולם יעסוק אדם" based on an interpretation he heard from his Rav, the holy Ba’al Shem Tov, zy”a, of the passuk (Tehillim 119, 59): "חשבתי דרכי ואשיבה רגלי אל עדותיך"—I considered my ways and returned my feet to Your testimonies. When a Jew begins to serve Hashem by studying Torah and performing mitzvos, he cannot do so from the get-go l’shma, because he will be harassed by the yetzer hara and will not be able to serve Hashem at all.
Therefore, it is advisable to do so initially “lo l’shma,” with ulterior motives. Subsequently, one can begin to serve Hashem exclusively l’shma, solely for the sake of Hashem. This then is the message conveyed by David HaMelech. When I began to study Torah and perform mitzvos: "חשבתי דרכי"—I planned to do so together with the yetzer hara, lo l’shma. Afterwards, I abandoned all the ulterior motives: "ואשיבה רגלי אל עדותיך"—and performed them, because they are Your edicts, which You commanded me to perform. Based on this understanding, the Toldos Yaakov Yosef explains that the Gemara uses the term "לעולם" to emphasize the fact that it is impossible to study Torah and perform mitzvos from the get-go l’shma; one must begin “lo l’shma.”
Only by starting off “lo l’shma,” will a person eventually achieve the ideal of l’shma.
We will now introduce another marvelous chiddush from the Toldos Yaakov Yosef (Emor) concerning this matter. When a person succeeds in ascending this ladder directed toward the heavens, studying Torah and performing mitzvos l’shma, everything he studied and did previously “lo l’shma” is rectified retroactively. This is because they enabled him to ascend and achieve the level of serving Hashem l’shma.