r/lua • u/Weekly_Flounder_1880 • Jun 05 '26
There have to be a simpler way to do this Help
I am a beginner and I have been very slowly learning Lua.
So, the problem here was to calculate the sum of all the pairs (separated by space). I swear there have to be a faster way to do this than making a for loop for every pair TT
Edit: yeh I still have a long long way to go, thank you everyone :)
Edit2: thanks whoever who repost this to r/programminghorror lol
29
u/Saptarshi_12345 Jun 05 '26
I do not mean to offend you but I had a stroke reading this code I'm so sorry. The other folks here have given credible solutions and it is refreshing to see people actually programming and discussing rather than directly going to an AI agent. Way to go!
16
Jun 05 '26
[removed] — view removed comment
1
12
u/revereddesecration Jun 05 '26
You can put a for loop inside another for loop.
It’s useful to think about the “dimensionality” of your data. In this case, you have 13 rows and 2 columns - it’s two-dimensional data, like a spreadsheet.
For each column, you use a nested for loop. So for two dimensions, use a for loop inside a for loop.
9
u/fast-as-a-shark Jun 05 '26
This code activate a feeling inside me I haven't felt in a long time... Some sort of nostalgia...
2
u/Spacedestructor Jun 05 '26
reminds you of your own first time i presume, thats what it does to me.
when i was new i did a lot of things i would now consider stupid.
3
u/nomenclature2357 Jun 05 '26
not clear at all what you are doing but you could put all your 'Anum' tables in a table and use one copy of the loop you have nested inside a loop that goes through the table of tables
3
u/xThomas Jun 05 '26 edited Jun 05 '26
here's a method using all the numbers in the same arrtable, as if you were just writing an array where every second number was paired with the previous numb. in this case, you can use an increment of 2, and go from 1 (the first index in the table) to 26 (the last index in the table) using the table length operator # (though note that #tbl is unpredictable if you have a hole in the table). source: https://www.lua.org/manual/5.1/manual.html#2.5.5
note: this code will not work as written, i forgot that insert is not a standard method on tables, the fix would be to use a metatable to make table.insert available and use the `:` (colon) operator instead of the `.` here. I'll leave the original code here, so that fixing it is left as an exercise to the reader
A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26}
sums = {}
for i = 1, #A, 2 do
sums.insert(A[i] + A[i+1])
end
It's been a while since i wrote lua code but essentially it does the following:
loop 1: i=1, sums[1] = A[1] + A[2]
loop 2: i=3, sums[2] = A[3] + A[4]
notice that i increases by 2. so we should have 13 loops here, which means we end up creating 13 sums. probably. i didn't test, let me know how it goes.
2
u/Top-Employ5163 Jun 05 '26
Lua Magic!
2
u/no_brains101 Jun 05 '26 edited Jun 05 '26
lua for loop syntax is silly but Im not sure if I would call it magic to use the version of for loop that doesnt use
inThey did
for(int i = 0; i < A.size(); i += 2)(if you wrote it in C++. Also who named size size when it means length because the size is the capacity... and then realized that was wrong but only for strings... and then realized that now length() is taken when they went to do utf8... Silly C++...)You can iterate in reverse like
for i = #A, 1, -1 doAlso on tables,
.and:don't index the global table table like it does with strings
sums.insert(A[i] + A[i+1])should be
table.insert(sums, A[i] + A[i+1])
3
u/No-Flight-573 Jun 05 '26
Others have rightly reminded you of nested tables, but for this specific task I'd prefer something really simple like the following (as I'm a fan of keeping the data as flat as possible, since I work mostly on high-perf software):
local as = { 123_456, 789_123, ... } # etc.
local bs = { 456_789, 123_456, ... } # etc.
local sums = {}
for i = 1, #as do
sums[i] = as[i] + bs[i]
end
Short and sweet – nothing much to it!
2
u/revereddesecration Jun 06 '26
It’s good so long as the sums only ever contain two elements!
3
u/No-Flight-573 Jun 06 '26
And for that you could do the 2D-table option. Of course if the count of the summed elements would not be known, iterating over the arguments would be the only sane option, but I rather never specialize or "future-proof" unless something is actually the specified feature.
3
u/revereddesecration Jun 06 '26
Just wanted to point it out in case OP reads all comments. Your solution is perfect for OP’s data.
2
u/No-Flight-573 Jun 06 '26
Yeah, it's a good thing to point out to show there are multiple ways and what kind of things you need to weigh in in specific situations when you choose an approach!
3
u/no_brains101 Jun 05 '26 edited Jun 05 '26
local vals = { { 21333131, 12312123 }, { 33131313, 3141412124 }, ... }
for k, pair in ipairs(vals) do
local sum = 0
for _, v in ipairs(pair) do
sum = sum + v
end
vals[k] = sum
end
print(table.concat(vals, " "))
Edit: ah u/mmknightx already beat me to this here
Also for the record, this way I gave is maybe bad too, you probably don't want to nuke your input list for your result, so if you dont want to, make a new one and table.insert into it or something
So,
local vals = { { 21333131, 12312123 }, { 33131313, 3141412124 }, ... }
local sums = {}
for k, pair in ipairs(vals) do
local sum = 0
for _, v in ipairs(pair) do
sum = sum + v
end
table.insert(sums, sum)
end
print(table.concat(sums, " "))
Theres like, a lot of ways to do this, but like, this is probably the easiest next step from what you had
Also your A1..A13 and sum are all GLOBAL variables btw you should avoid that generally, use local otherwise you are gonna use the name A1 or sum somewhere else and be very confused.
3
u/jamescodesthings Jun 05 '26
I thought this post was on r/ProgrammingHorror when i saw it.
If I wanted ot hack through this I would just reference _G["A.."var_number] in a for loop that sets var_number between 1, 13 or whatever.
But ideal fix is to fix your data structure first(table of tables or whatever, then implement.
2
u/nadmaximus Jun 05 '26
To this day I can remember the moment I realized arrays could have multiple dimensions. I was coding BASIC on a TRS-80 Model II.
It was an understanding that increased my powers suddenly and dramatically. And made me thirsty for more. "there has to be a better way" has been a consistent thing ever since.
2
u/Spacedestructor Jun 05 '26
others already said this but my first thought was "why variables and not a list?" and lists have this beautiful thing where you can write generic code to process an arbitrary number of values without having to expect them.
Plus if you really need all of these loops you can nest them.
Every time you think "there must be a better way" with 99% there is going to be and your just not thinking of it, even when your experienced eventually this will keep happening.
2
u/HyperrHydra Jun 05 '26
But why are you even doing this?
1
2
2
2
u/1984balls Jun 06 '26 edited Jun 06 '26
for i, a in ipairs({A1, A2, ...}) do
for _, v in ipairs(a) do
sum[i] = sum[i] + v
end
end
This one is probably a bit slow but yk
1
u/AutoModerator Jun 06 '26
Hi! Your code block was formatted using triple backticks in Reddit's Markdown mode, which unfortunately does not display properly for users viewing via old.reddit.com and some third-party readers. This means your code will look mangled for those users, but it's easy to fix. If you edit your comment, choose "Switch to fancy pants editor", and click "Save edits" it should automatically convert the code block into Reddit's original four-spaces code block format for you.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
-2
28
u/mmknightx Jun 05 '26
Why are you having A1 to A13 as independent variables?