What is the difference between Lua tables and classes?

时间:2016-04-21 22:10:46

标签: arrays class oop lua lua-table

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?

3 个答案:

答案 0 :(得分:8)

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.

答案 1 :(得分:2)

Lua没有类,但只有表,有metatable。 Lua使用原型来实现OOP

答案 2 :(得分:1)

我认为您感到困惑,因为object.attribute通常是其他语言访问的方式,显然是对象的属性。

无论如何,由于Lua没有课程,因此可以使用点来访问表格。字段和table.field与撰写table["field"]完全相同。