Debugging
When you're not sure why your code doesn't work or some statements aren't executing, a good method of making sure where you're getting to is by debugging with print statements.
This method will allow you to see how far your function or code gets before the error or something you're expecting doesn't happen, and lets you pinpoint what you need to fix.
1
function swap(a)
2
return not a
3
end
4
​
5
function doRandomStuff(a)
6
a = swap(a)
7
return swap(a)
8
end
9
​
10
function test(a)
11
a = doRandomStuff(a)
12
if a then
13
print(123)
14
end
15
end
16
​
17
test(true)
Copied!
Here for example, we swap the boolean's value to the opposite, and if a is true we're supposed to print 123. But the problem is, swap happens twice instead of returning the 1st time it's swapped (which is the "example" error in this case. Here, we can add prints to see what's going on to see why we can't print 123:
1
function swap(a)
2
return not a
3
end
4
​
5
function doRandomStuff(a)
6
print('doRandomStuff - "a" value: '.. tostring(a))
7
a = swap(a)
8
print('doRandomStuff - "a" swapped value: '.. tostring(a))
9
return swap(a)
10
end
11
​
12
function test(a)
13
print('test - initial "a" value: '.. tostring(a))
14
a = doRandomStuff(a)
15
if a then
16
print(123)
17
end
18
end
19
​
20
test(false)
Copied!
This current code will print:
1
test - initial "a" value: false
2
doRandomStuff - "a" value: false
3
doRandomStuff - "a" swapped value: true
Copied!
We can see that we're obviously getting an expected value, after reassigning a to swap(a), which is the value we're supposed to use, but instead we swap it a 2nd time giving us back the original value (false->true->false). From here we know that the error is that we've swapped the boolean twice when it's supposed to be swapped once, so all we need to do is return a instead of return swap(a).
1
function swap(a)
2
return not a
3
end
4
​
5
function doRandomStuff(a)
6
a = swap(a)
7
return a
8
end
9
​
10
function test(a)
11
a = doRandomStuff(a)
12
if a then
13
print(123)
14
end
15
end
16
​
17
test(false)
Copied!
Now the code works as intended, and prints 123.
Last modified 2yr ago
Copy link