Equivalent of struct or class in lua?

The question is straight forward.
I want to make a data structure for storing the game data. As i have experience in many other languages, all of them has classes or structs, what’s it’s equivalent in lua?

Do you mean like getting Object.ClassName (idk if Object.Class exists, but I know what I gave you does.)

Using module scripts you can make your own class that can be required trough script afterwards.

Here is a simple class

--module scripts
local module = {}

module.MyValue = 5
module.MyFunction = function()
   print("My class")

return module
local myClass = require(path.to.class)
print(myClass.MyValue) -- 5
myClass.MyFunction() -- prints "My class"

Lua does Object Oriented Programming with tables. Here’s what a Struct would look like in Lua.

local Struct = {
["Number"] = 1

function Struct.new()
local NewStruct = {}

for i,v in pairs(Struct) do
NewStruct[i] = v

return NewStruct

local struct = Struct.new()


If done correctly the output should be something like this


and for Classes, they’re basically just tables.

local Class = {
["Number"] = 1
1 Like

Structs can be implemented using simple tables, and an additional type if you want strict typing.
An example of this might be:

type gameData = {
    playerCount: number,
    round: number,
    bossHealth: number
} -- This is optional

local gameData: gameData = { -- You can remove the ": gameData" if you want to
    playerCount = 0,
    round = 1,
    bossHealth = 100

Or maybe another example:

type playerData = {
    health: number,
    money: number,
    name: string,
    inventory: {
        {item: string, count: number}

local playerDataList: {playerData} = {}
playerDataList[12345] = {
    health = 100,
    money = 0,
    name = "John Doe",
    inventory = {}

Forgetting one of the values, or misspelling their name, will give a warning in the script editor. It will still be properly interpreted no matter what types you assign though, so you need to make go through all your scripts to make sure that they’re correct.
You might want to look further into typechecking in luau. A proper tutorial also ought to tell you how to assign types to function return values and parameters, and also how to combine types.

1 Like

I’m trying to create a terrain.
This contains the data of a terrain chunk like x, y, z coords and the ground material.
My map is very big. I want to know that because it my game has like more than a million chunks.
If there is a data structure like that which can hold all the data in very small memory, it can be useful when loading the data with less loading time.

String.pack might be something to look into.