- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
Hello, and thanks in advance for reading this. I'm a CAD drafter teaching himself a little AutoLISP between projects at work. I don't have any real coding experience prior to this, and am learning mostly by searching through documentation and using the blessed AfraLISP guides. I have already done some searching through these forums as well. Specifically, this link back from 2018 didn't do much to help me, and only served to confuse me more.
I'm having some trouble understanding the difference between global and local variables. I thought a variable being global meant that if it was changed in a function call, it would stay changed if used again outside that function. And a local variable would be discarded after that function call was finished.
I've got some code to explain my problem:
(defun testMe ()
(setq l1 (list 1 2)
l2 (list 2 3)
)
(princ l2)
(defun addPoints (l1 l2)
;Adds the values of two points together
;l1 = first point
;l2 = second point
(setq a (+ (car l1) (car l2))
b (+ (cadr l1) (cadr l2))
l2 (list a b)
)
)
(princ (addPoints l1 l2))
(princ l2)
(princ)
)
addPoints just takes two points, and adds them together. To my understanding, l1 and l2 are global here (not defined following a / ). At the end of the addPoints function, l2 is set to the sum of the two points. Line 19 prints this to verify it.
Because l2 is global, I would expect the value it is set inside of the addPoints function to be retained even after the addPoints function has ended. So after running (testMe), I should receive an output of (l2 prior to call)(l2 after call)(l2 after call), or (2 3)(3 5)(3 5).
What I'm actually getting is (2 3)(3 5)(2 3). I can see that while l2 is being successfully called during the addPoints function, the value isn't being saved afterwards, despite the addPoints function passing the value to the (princ) command. This is how I'd expect the code to run if I had defined it as (addPoints ( / l1 l2)) So, I think I'm missing something about how global vs local variables work.
I don't want to be rude or presumptuous, but I'd prefer responses that directly address my misunderstanding here, as opposed to asking why I didn't do this in a different way or offering another method (unless what I'm thinking is just completely wrong, of course). In this exact example, I'm sure there are plenty of workarounds and other ways to do this, but I'd like to be able to use functions to redefine more complicated items (like drawing elements) in the future, and being able to call (modifyElement(element value)) instead of having to step around with repeated (assoc)'s and (subst)'s would make my life a lot easier, and my code more readable.
Thanks again for your time!
Solved! Go to Solution.