Are Tables the equivilent to a structure in coding?

Two questions, is a table basically a struct in other languages such as C? I would assume so since from reading it can hold multiple data types.

Second question, the code below. I got the table to print out the string, but it outputs nil when I try to call PlayerData[x]?

local PlayerData = {
	x = 5,
	name = "matt"
}
print(PlayerData[x])
print(PlayerData["name"])

Edit: if I make the value a string it works, and it also doesn’t require a Integer to string conversion either to be used in math, is this a new change in recent years? I don’t recall this being possible without a data type conversion.

Not exactly, structs are user-defined data types, e.g.

int main() {
	struct test {
		int a;
		char b;
	};

	test thing;
	thing.a = 5;
	thing.b = 'x';
	thing.c = "aaa"; // causes error since not defined in the struct
}

So it’s like a way of defining the structure each instance of it is going to have. Luau actually has this, in the TS-style:

type test = {
    a: number,
    b: string -- no char type in luau obviously
}

local thing: test = { a = 5, b = "x" }
thing.c = "aaa" -- will lint that `c` isn't valid or whatever

PlayerData[x] will index PlayerData with the value of the variable x, PlayerData["x"] or more conveniently PlayerData.x will index PlayerData with the string "x". This has always been the behavior – nothing has changed.

3 Likes

Under the hood, Lua’s tables are a dynamic combination of an array and a hash table.

As @sjr04 said, you can use them as structs by defining them with Luau types.

1 Like