user3124306
user3124306

Reputation: 705

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?

Upvotes: 3

Views: 3067

Answers (3)

user6245072
user6245072

Reputation: 2161

I think you're confused because object.attribute is usually the way in other languages to access, obviously, an object's attributes.

Anyway as Lua doesn't have classes the dot can be used to access tables' fields and table.field works exactly the same as writing table["field"].

Upvotes: 1

user1783292
user1783292

Reputation: 528

Lua has no classes, but only tables, with metatable. Lua use prototype to implement OOP

Upvotes: 2

Nicol Bolas
Nicol Bolas

Reputation: 473272

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.

Upvotes: 12

Related Questions