Structures in Lua?

Structures in GLSL are like

struct NameOfStruct {
  classType dataName,
  classType dataName
};

It’s very important that it is type safe. I’d use a dictionary then. The class type should also be able to harbor other structures* they are a data type in a sense

2 Likes

Um, what is the question you are asking exactly? Like the way you written this feels more like an Luau suggestion than asking for help in typed Luau.
If you’re asking how to replicate structures in Luau, the closest thing you will find is typed tables:

type Struct = {value1: classType, value2: classType2}
local Structure: Struct = {value1 = ValueSomething, value2 = ValueSomething2}
1 Like

Ahh C has these as well.

Lua is a Dynamically Typed language, meaning that the types of vars are figured out in run time.
Statically vs Dynamically Typed Languages

So this is valid:

local myString = "yolo"
print(type(myString)) --output: string

myString = 2
print(type(myString)) --output: number

Take a look here to get type checking in Luau:
https://roblox.github.io/luau/typecheck
https://roblox.github.io/luau/syntax

1 Like

Better if you said Luau than Lua.

1 Like

If you want them on Roblox, use types.

type NameOfStruct = {
    value1:number,
    value2:number,
}

local obj:NameOfStruct = {
    value1 = 1,
    value2 = 2,
}

If you want them in pure Lua 5.1, you can check types using metatables.

local struct_meta = {
__newindex = function(self,i,v)
    if i=="value1" and type(v)~="number" then
        error("Type mismatch")
    elseif i=="value2" and type(v)~="number" then
        error("Type mismatch")
    end
    rawset(self,i,v)
end
}

local obj = setmetatable({},struct_meta)
obj.value1 = 1
obj.value2 = 2
1 Like