r/programminghumor • • 19d ago

Lua

Post image
3.1k Upvotes

168 comments sorted by

251

u/y0shii3 19d ago

1-indexing makes sense in a vacuum, at least for high-level languages where you aren't thinking of indices as pointer offsets, but in a world where 0-indexing is the default, deciding to go against that norm does nothing but cause confusion

77

u/Conscious_Switch3580 19d ago

It’s even worse when dealing with data structures. This inoffensive little quirk can change the math in non-trivial ways.

23

u/bloody-albatross 19d ago

The Unix terminal uses a 1-,based coordinate system! It made as o much of a mess for nested drawing areas, I just do it all 0-based and add 1 when generating the ANSI escape code.

7

u/Ver_Nick 19d ago

You can probably just make a wrapper for the operations with indices

26

u/Conscious_Switch3580 19d ago

I could do many things. That’s besides the point.

1

u/Old_County5271 16d ago

You shouldn't even use a wrapper, numerical for loops are faster than an iterator.

3

u/Valuable_Leopard_799 18d ago

Yes it changes the math, it makes some easier and some harder, so it's a trade-off, depends on what you think your users will do more often.

1

u/Conscious_Switch3580 18d ago edited 18d ago

sure, but then we could use that same logic to justify every decision for every software ever made; it's not falsifiable.

but ultimately, that's not the point.

1

u/ProbablyPuck 16d ago

but then we could use that same logic to justify every decision

Yeah, sounds rightm That's pretty much been my experience over a dozen years in the field. 🤣🤣🤣

1

u/Few-Employment4580 14d ago

i like that it can make proofs/algos/math easier since it translates to the 1-indexing used in a lot of discrete maths and textbooks

1

u/TrueBirch 18d ago

I write a lot of R, and having to switch back to zero base takes conscious effort. 

1

u/qwertyjgly 14d ago

mathematica is the least bad version of a 1-indexed language i can think of. the 0 position is the head of whatever expression you're looking at

so:

{1,2,3}[[0]] returns 'List'
(a+b)[[0]] returns 'Plus'
etc

and

expr = {1,2,3};
expr[[0]] = Plus;
expr

returns 6

1

u/DVMyZone 13d ago

Fortran was the first widely used language and is 1-indexed, as is the older language "autocode". So 0-indexing came later and had to buck the existing system

57

u/schewb 19d ago

What's worse is that you can fully legally assign and access index 0; the typical iterators just won't ever hit it.

11

u/caj_account 19d ago

ipairs() won't hit it?

11

u/schewb 19d ago

Nope. Try this in something like weblua:

tlist = { 'b', 'c', 'd' }
tlist[0] = 'a'

print('ipairs(tlist):')
for i,v in ipairs(tlist) do
  print(i..': '..v)
end

print('tlist[0]')
print(tlist[0])

7

u/Blue_Moon_Lake 19d ago

Funnily enough, you can do 0-index table by "hacking" it

local t = { "B", "C", "D" }
t[0] = "A"

local inext = ipairs({})

for i,v in inext, t, -1 do
    print(i, v)
end

Which you can wrap in your own ipairs version

local inext = ipairs({})

function ipairs0(table)
    return inext, table, -1
end

local t = { "B", "C", "D" }
t[0] = "A"

for i,v in ipairs0(t) do
    print(i, v)
end

1

u/Blue_Moon_Lake 19d ago

ipairs doesn't do much though

function ipairs(table)
    return inext, table, 0
end

And inext is something like this

function inext(table, previous_index)

    local next_index = previous_index + 1
    local next_value = table[next_index]

    if next_value == nil then
        return nil
    end

    return next_index, next_value
end

21

u/Simpicity 19d ago

LuaU: It's like Lua but with OO and typechecking!

Me: Oh, I should typecheck my objects. 

LuaU: I wouldn't if I were you...

16

u/carltr0n 19d ago

Can someone fork Lua and make it exactly the same but with zero indexing? Call it zlua?

6

u/ICON_4 19d ago

or just make a wrapper that offsets by -1

10

u/bloody-albatross 19d ago • Bravo

Make it so that the first index of the array is the line number on which the array is created.

2

u/ScallionSmooth5925 18d ago

That's too simple. Because we use tables anyway intex it like this 10n * (-1)n -1. So the first will be 0 and the security will be -11 then 99 and so on

3

u/ScallionSmooth5925 18d ago

You only have to folk the std lib. Otherwise you can index from 0 because it's a table 

2

u/ardicilliq 18d ago

The for loop lib methods stop working for ipairs tho

1

u/Ed_Blue 18d ago

You can wrap ipairs in your own iterator function that starts at 0.

1

u/ardicilliq 18d ago

You could do that yeah, but again, lua starts treating the array as a dictionary, and eventually you end up with code that keeps trying to offset the index start. Until you miss a spot and the code breaks 😅

I hate that lua starts array indices with one, but I leave it alone, just an opinion though ¯_(ツ)_/¯

1

u/Old_County5271 17d ago edited 16d ago

You don't need to wrap ipairs, just use a counting for loop instead of an iterator

This is also what PIL recommends btw.

2

u/Ed_Blue 16d ago

True. In any case there are many ways to work around it if you really need or want to.

2

u/EatingSolidBricks 18d ago

Pretty sure tsoding did that on stream

1

u/taptrappapalapa 19d ago

Arrays starting at one are a good thing for some data structures, such as with binary heaps. Otherwise you have to do some flooring math and it’s annoying.

1

u/Professional_Top8485 19d ago

How about array_offset()

1

u/Old_County5271 17d ago

Go use squirrel then

12

u/0xt0bi03 19d ago

really??

12

u/teetaps 19d ago

R also starts at 1 and it was my first programming language, so imagine my surprise when I learned it’s an outlier

14

u/kuwisdelu 19d ago

It’s not an outlier among data languages. Julia, Matlab, Fortran, etc all typically index from 1.

7

u/teetaps 19d ago

You and I know that, but the computer science hive mind certainly doesn’t

7

u/DefenitlyNotADolphin 19d ago

Any undeclarated variable is undefined, I think that's a larger comcern

1

u/Old_County5271 17d ago

You can make it so it errors

12

u/Techrocket9 19d ago

1-indexing arrays is far from Lua's greatest sin.

18

u/No_Effort6224 19d ago

Yep. Some more:

  • Lack of class syntax to automate the prototype-based OOP it has.
  • "Everything is a table!" means the length operator has undefined behavior
  • It has floats and ints, but really doesn't want you to know, which can result in odd results from math since the ints are wrapping

I think it just went a bit too far into the idea of simplicity. And if you correct it, you are very close to JS with stackful coroutines as a library (good thing) rather than async/await.

That being said, it was the first language I had a lot of fun programming in, mostly in ConputerCraft. I loved it enough to be the guy who wrote half of the StackOverflow wiki on it back in the mid 10s.

6

u/aaronjamt 19d ago

Thank you so much, from my 12 year old self. I spent so much time on ComputerCraft, learning everything between StackOverflow and YouTube videos. I never would have built half the insane stuff I did without people like you!

2

u/theScottyJam 17d ago
  • Their "function doThing()" syntax automatically creates functions in the global scope. That one bit me.

1

u/Blue_Moon_Lake 19d ago

TBH, it's great for writing one time use code to get the result of a computation.

But it's unsuited for bigger projects, like game mods.

2

u/Old_County5271 17d ago

This is true of all dynamic PLs

1

u/Bluecoregamming 18d ago

dropped an insane fun fact so casually 

1

u/Old_County5271 17d ago edited 17d ago
  1. The class syntax is not a big deal, plenty of libraries doing that.
  2. It should be said that yes, the length operator has undefined behavior but it's only for sparse arrays, this is why table.pack returns an .n, for length, if you're going to have sparse arrays, add a __length that does what you want, sadly, once you have sparse arrays, it's hard to know the length unless you use next() and check all the keys, returning the largest element, you have to be careful with sparse arrays.

Tables can and should be used to create the data structure you want, sometimes I want to use sets and you can easily treat lua like an array language with operator overloading

3. I don't know what you mean... math.type() returns the number subtype, it has functions to convert to an int or float

2

u/Wertbon1789 19d ago

That there's no proper array, but only array-like tables is by far the worst sin of Lua. You can write as many fancy helpers, but you can never outclass the wackyness that deep in a language.

6

u/ilmaestrofficial 18d ago

What's an array?

12

u/Base-After 18d ago

Who is json

4

u/Hipnotize_nl 18d ago

Can you pass me that j, son?

1

u/ilmaestrofficial 18d ago

Idk what y'all are talking about

5

u/ScallionSmooth5925 18d ago

A table. Like everything in lua.

1

u/ilmaestrofficial 18d ago

What?

3

u/ScallionSmooth5925 18d ago
foo = {}
foo[1]=1
foo["appletree"]=2
for k, v in pairs(foo) do 
print("foo[" .. k .. "]=" .. v )
end

0

u/ilmaestrofficial 18d ago

I just wanted to know what an array is 😭

5

u/Hipnotize_nl 18d ago

A table. Like everything in lua

2

u/Logogram_alt 18d ago

A array is a ordered list of eliments. For example in pseudocode

A = [1, 2, 3, 4]

#this is a array

#in a 0-indexed array

A[0] == 1

#in a 1-indexed areay

A[1] == 1

1

u/soggycheesestickjoos 18d ago

it’s a list of things. “one” is just a string/text, [“one”, “two”, “three”] is an array of strings/text.

3

u/MrHellYe 18d ago

Are you a programmer or did this subreddit get randomly recommended to you?

Anyway, an array is a list of elements in a sequence, usually represented by brackets, so:

[10, 5, 7, 2, 1] is an array with 5 integers.

In programming, more often than not, array counting starts at 0, so the 0th number here would 10, 1st would be 5, 2nd is 7, etc.

Lua is a programming language that this counting starts at 1 instead of 0, which although is more intuitive for most people, it isn't for experienced programmers

2

u/Toad128128 18d ago

Also note that array sizes are fixed on declarations.

1

u/OgLikeSmash 18d ago • Bravo

Yuck

1

u/AliceCode 17d ago

That's how arrays usually behave. If you want something dynamic, that requires constant reallocation to resize, which isn't always desireable. At a low level, arrays don't even exist. It's just raw memory. And in order for arrays to keep growing, you have to keep moving them to new places in memory that have enough space to hold all of the elements. Normally, the array grows by a factor of 2 upon resizing so that the next resize is further away each time.

1

u/Informal_954 13d ago

Because it isn't the 0th number to a programmer, it is the number with offset 0, then the number with offset 1, etc

0

u/[deleted] 18d ago

[deleted] — view deleted comment

1

u/MrHellYe 18d ago

The guy said below that he's not joking, he legitimely does not know what an array is

3

u/05-nery 18d ago

No way il maestro

È una lista di variabili (praticamente numeri o stringhe che decidi tu). Di solito, negli altri linguaggi di programmazione, il primo elemento di un array ha l'indice (il numero che usi per riferirti all'elemento) "0". In lua il primo elemento ha indice "1" che seppur possa sembrare più intuitivo finisce per essere il contrario.

2

u/ilmaestrofficial 18d ago

hello fellow italian

1

u/05-nery 18d ago

Sempre bello beccare uno di noi in giro così

2

u/Wonderful-Habit-139 18d ago

List of elements

2

u/PENTIUM1111 18d ago

So fire, ice, lightning, earth and green?

2

u/RealRockyMoney 18d ago

/s ? or no /s ?

1

u/ilmaestrofficial 18d ago

No /s I'm serious

1

u/ScallionSmooth5925 18d ago

An ordered collection of elements. Imagine a chest of drawers. Each drawer is numbered and you can put thing in it. The numer is the index

1

u/impressiveRub69 18d ago

A data structure consisting of a collection of elements, where each element is accessible through an index.

1

u/SeligFay 17d ago

Data collection formed in memory. Like you have 25 elemets of float. You need 25×float_size memory. Every elemet have iterator, like integer number, and you get access in memory use iterator*float_size. Array always direct to first element in memory. So, full access formula is first_element+iterator×float_size. And this is why array start with 0 iterator.

1

u/Furry_Eskimo 13d ago

It's like a list, and each spot holds a value, and most start with 0 (code reasons), but in lua it's 1, which makes more sense to a person, but not to coders.

11

u/Gabriel_Science 19d ago

Yeah, it’s like saying the first number on a ruler is 1. It’s 0.

7

u/MCWizardYT 19d ago

C does arrays using 0 plus an offset, whereas Lua just gives you the index itself.

It's actually why you can write 0[arr] instead of arr[0] and it still works just fine.

Other languages just follow the "0 + offset" design as convention. But Lua's way actually make more sense for a super high level language that has you never even thinking about memory

3

u/Conscious_Switch3580 19d ago

Other languages just follow the "0 + offset" design as convention. But Lua's way actually make more sense for a super high level language that has you never even thinking about memory

By convention and no other reason. None whatsoever. Because range computations make so much more sense with 1-based indices. /s

2

u/Valuable_Leopard_799 18d ago

You trade one thing for another. All the .size-1 vanish with 1 based indexing and some other math becomes simpler.

Of course in exchange for the math that 0 based makes simpler, so it depends on what your language wants to do, both are valid, though I prefer allowing both.

2

u/Conscious_Switch3580 18d ago

I prefer allowing both

translation: "the starting index depends on the person who wrote this piece of code". that's a recipe for disaster.

just saying, there's a reason Perl got rid of that feature.

1

u/Valuable_Leopard_799 18d ago

And there's a reason why Ada writes index agnostic code. It also allows for arbitrary enumerable indexed arrays, which is an amazing feature.

1

u/Conscious_Switch3580 18d ago

so does Lua. that by itself doesn't mean it's an "amazing" feature (that's your opinion, not an objective fact) especially considering the drawbacks.

1

u/Blue_Moon_Lake 19d ago

The reason for 0-indexed array is that you can access the value at index N with the memory address of the first value + N.

You shouldn't do the read yourself directly, but that's how it works under the hood.

1

u/overclockedslinky 18d ago

"so what's the zeroth item on your todo list today?"

statements made by the clinically deranged

1

u/Gabriel_Science 18d ago

The first item starts at value 0.

-1

u/Blue_Moon_Lake 19d ago

The single benefit of 1-indexed array is that you can use unsigned integers and still represent the index before the first element (0).

Since Lua is not using strong typing, it's entirely pointless though.

5

u/NoodlyGirl2000 19d ago

that’s horrific lmao

6

u/chkno 19d ago • Popcorn

In most languages, the syntax for array indexing is to enclose the index in [ and ].

Lua has a more verbose syntax where you have to enclose the index in [ and +1].

1

u/Old_County5271 17d ago edited 17d ago

I don't get what you mean

Are you talking about the ++ -- operator?

1

u/csabinho 16d ago

It was a joke about the index.

4

u/cc_apt107 19d ago

it’s not a big deal bro

2

u/Haja024 17d ago

Lua is weird because it's like, "what if C but everything is tables" and nothing but games and Wikipedia runs on it. Which is a weird2 overlap.

1

u/Old_County5271 17d ago

One of it's inspirations is awk, which only has associative arrays as it's only structure type, if you want to keep the language small, associative arrays is the way to go.

1

u/thanosbananos 16d ago

So basically “what if we made Common Lisp even more confusing”

5

u/GoogleIsYourFrenemy 19d ago edited 19d ago

I asked someone who made an embedded DSL if they had considered Lua before they wrote it, and they said "What's Lua?" I knew right then that their language was shit.

2

u/teetaps 19d ago

“Wait, not like that”

3

u/-Ambriae- 19d ago

Lua pains me so much I’m currently writing a replacement for it

1

u/kinchkun 15d ago

*prompting

1

u/-Ambriae- 15d ago

Nope no ai

Edit: it’s been a month I still haven’t finished IR send help

2

u/Sad-Zucchini-949 19d ago

Is this a joke language like brainfuck?

6

u/No_Context2723 19d ago

how do you not know lua

4

u/United-Scene2261 19d ago

he lives in the lua (moon)

1

u/Sad-Zucchini-949 19d ago

I am saying that because when sane people create programming languages, they start arrays at 0.

2

u/Old_County5271 17d ago

Lua doesn't have arrays

6

u/Peverything_14 19d ago

nope. its a scripting language, gaining popularity because of its readability and so on. its amount of use cases are almost comparable to python. its used in Factorio and lots of other games

2

u/SceneOutside4377 19d ago

I'm working on a mod for Friday Night Funkin' and I'm really dragging my feet at having to do some Lua scripts for it. I live in a world of Java and C++ smh

1

u/Devatator_ 18d ago

Doesn't FNF and all engines for it use Haxe?

1

u/SceneOutside4377 18d ago

It does, but recent updates have made it a lot easier for modders to inject custom Lua scripts to help integrate their mods more

1

u/PretendingExtrovert 18d ago

Haxe is still around?! I was looking at porting my AS3 game engine to it in like 2012…

2

u/Blue_Moon_Lake 19d ago

The lack of structured object typing is horrendous though.

Can't know what the key/value are, can't have autocompletion and can't checks that you did not mistype a key.

2

u/Old_County5271 17d ago

Luacheck is pretty good at telling you if you mistype something but it's not good at structures. LSP has ok auto completion. But yeah, is not good

2

u/GreatValueBradPitt 16d ago

Gaining popularity?

Edit: Clarification, lua has been used extensively in modding since the late 90’s and early 2000’s. I forget I’m a thousand years old sometimes.

1

u/catbrane 19d ago

Setting the terrible choice on arrays aside it has some other very nice properties:

  • tiny! it's under 512kb for the compiler and complete runtime
  • fast! luajit is within 50% of native performance (very roughly) on most common CPUs (arm, arm64, x64 etc.)
  • embeddable! you can embed a copy of lua within your application in just a few lines of code
  • embed-outable! luajit includes a very nice integrated FFI which lets you call back to C from lua in a simple, safe and high performance way

0

u/Sad-Zucchini-949 19d ago

Starting arrays at 1 is reliable.

2

u/Conscious_Switch3580 19d ago

Yes, a really unfunny one.

1

u/Professional_Top8485 19d ago

Arrays start at 1. Offset is zero

1

u/Inst2f 19d ago

0 element would be the head of the table

1

u/jas2365 19d ago

Just found lua for lazyvim. Any advice

1

u/coldnitrogen 19d ago

Fortran has entered the chat ...

1

u/pseto-ujeda-zovi 19d ago

And people hate JS

1

u/Logical-Pause-3758 19d ago

Guess what `—` means

1

u/Maleficent-Bag-4850 19d ago

This is unacceptable

1

u/bschlueter 19d ago

You can make them start at zero if you want.

1

u/timonix 18d ago

Eh, I prefer arbitrary ranges. Have an array go from -6 to 53

1

u/overclockedslinky 18d ago

oh no, how traggic. anyway...

1

u/qwertty164 18d ago

Not to be confused with licensed user agreements.

1

u/zrice03 17d ago

Meanwhile in VBA:

Baby, I'll start an array wherever you want.

1

u/Old_County5271 17d ago

Lua doesn't have arrays, so it can also do this

1

u/ThePython11010 16d ago

I like Lua as an embedded language (for modding and things like that). It definitely has a few quirks, but I find the only thing that really annoys me anymore is the lack of a continue statement.

1

u/kinchkun 15d ago

- 1972: C doesn't have proper arrays, because dennies ritchie sucks at designing a language.

- 2026: Mediocre programmers still think it is good design that counting starts at 0, because they never question what they are used to

1

u/zeantar 15d ago

Never understood why it's such a big deal for people tbh.

1

u/Zuruumi 15d ago

Let's go with prime sieve indexing. Arrays are indexed by numbers from 1, but all primes get skipped.

1

u/no_brains101 14d ago

that isn't even the worst part to be honest.

Try arrays with absent elements in the middle.

Also depending on lua version some metatable methods have some unexpected behavior too, usually in the form of just deciding not to work at all for a particular data type as the value.

Somehow still better than python.

1

u/_luki 14d ago

Wait.. WHAT THE FUCK?!?!

1

u/reesa447 13d ago

We have lua at work that needs to be updated like once every 3 years. Just long enough to completely forget how it works

1

u/zhaDeth 13d ago

the horror

1

u/Adn0nnymous 19d ago

0-index lowkey sucks i loooovee 1-indexed arrays! if i have three things i want to be able to get the item at index three!

0

u/Professional_Top8485 19d ago

Zero what is that anyways. It doesn't exist even

1

u/Adn0nnymous 19d ago

exactly you get me
like what is this shit
`Numbers[0]`
yeah lemme get the number at NOTHING??
they’ve been making FOOLS out of us!

0

u/Professional_Top8485 19d ago

They just confuse index with offset

1

u/Black_Swords_Man 19d ago

Non joke:

Is it really too late to standardize all languages? Just change it so arrays start at 0

1

u/Old_County5271 17d ago
   for k,v in pairs(tabl) do into[#into+1] = v end

VS

  for k,v in pairs(tabl) do into[( #into - 1 )+ 1] = v end

When you fill an array, you count the length which returns 0, and add one to it, if the index was 0 based, you'd have to reduce the length first, there's many places which an offset is best, but when it comes to indexing, you want it 1 based.

0

u/Valuable_Leopard_799 18d ago

That screws over half the people. We should agree that arrays can be indexed by arbitrary enumerable types like Pascal/Ada, so whichever you need you can use. It makes Array's so much safer and nicer while making everyone happy.

1

u/psyfregle 19d ago

Of cause. Let us waste this bit.

1

u/himai1 19d ago

Who tf cares. Arrays could start at 5 and it wouldn't matter

0

u/BladeMaster7461 19d ago

how many times do we need to post this

5

u/Some_Useless_Person 19d ago

As long as lua exists

-3

u/Supuhstar 19d ago

No, that’s a good thing

– a lead software engineer with 19 years experience

5

u/i-hate-space 19d ago

Did you just use a Emdash Mr 19 years of experience?

-4

u/ManagerOfLove 19d ago

Unpopular opinion: it is the right way of counting. You don't count 0 apples, 1 apples,.. The only reason programmers start from 0 is because they save 1 bit by doing that. The first element in an adress is at Offset 0.

We don't need that today because we swim in memory. We only keep it for historical reasons

1

u/Valuable_Leopard_799 18d ago

It's not at all about saving a bit. It's because if you index by offsetting the initial array pointer by some number, which is the cheapest and simplest way to do arrays, you get this kind of indexing.

1

u/Old_County5271 17d ago

Fortran also starts at 1 and it didn't waste memory, its just C with it's quirks

-2

u/Conscious_Switch3580 19d ago

It’s not about counting. Your opinion is wrong.

0

u/cr34tive1 18d ago

I can bear this