Answered by
7 years ago Edited 7 years ago
There are many different possible solutions for combination locks, and mine is only one of those many. While I do believe there are better solutions out there than mine, I'm pretty happy with what I have, and hopefully you are too.
String comparison
My combination lock involves comparing two string values (they could also be numbers, but I guess it doesn't really matter) after the length of the entry string is equal to the length of the combination string. Here's what I've come up with:
02 | local Combination = "2468" |
15 | local comboLen = #Combination |
16 | local concat = table.concat |
19 | local function buttonEvent(num) |
23 | if #entry = = comboLen then |
25 | if concat(entry) = = Combination then |
27 | print ( "Combination cracked" ) |
30 | print ( "Invalid combination" ) |
34 | for i = 1 , comboLen do |
42 | local button = buttons [ i ] |
44 | button.MouseButton 1 Click:Connect( function () |
It may seem a little complicated, but it's actually pretty simple. Each time we click the button, we push a new digit on the end of our entry
table. We then check if both length and value are equal to the Combination
to determine whether or not it's valid. In both cases, when the length of our entry is equal to the length of the combination, we reset the entry table because their combination was wrong.
Concatenation
In case you're wondering why I'm using table.concat
instead of ..
for concatenation, it's just a small optimization feature. Lua stores all created string values in memory which makes for quick retrieval, but somewhat slower construction. This way we're only creating strings 1-9
, and just reusing what's in memory. If any of that doesn't make sense to you, you can just change it to ..
, it really doesn't matter in this situation.
Help & Questions
Just for fun, I made a quick implementation of the code above to prove it works, which you can check out here. If you have any further questions, just leave a comment and I'll get back to you as soon as possible.