Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Lua tables and classes?

I'm a beginner to programming in general and I have been trying a few different languages. In Lua, there are tables which seem to be like super lists (arrays, dictionaries, lists all in one) but in Lua it is possible to do this:

player = { health = 100, attack = 50, mana = 54 }
print(player.health)

and it would return 100. But in other programming languages, you would need to make a class to get the same output. But from my understanding, Lua has classes as well as tables? But tables seem to act very similar so are they the same? If not, what makes them different and what are the pros and cons of using either?

like image 777
user3124306 Avatar asked Apr 13 '26 00:04

user3124306


1 Answers

But from my understanding, Lua has classes as well as tables?

No, it does not.

Lua (ignoring C API stuff) has exactly one complex data structure: tables.

You can create a class using a table. You can create all kinds of things using a table. Lua tables are very flexible, precisely because they are the only data structure Lua has.

In Lua, every complex thing at its base level is a table. Or if it's from a C API, userdata.

A class is basically a prototype for creating objects. You declare that a class has X, Y, and Z members in it, then you create an object of that class type which will have X, Y and Z members in it.

You can create Lua tables that mimic the behavior of classes. But there's no language construct in Lua that is formally like a class.

like image 200
Nicol Bolas Avatar answered Apr 15 '26 10:04

Nicol Bolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!