Tables - markpwns1/Dormez GitHub Wiki
Dormez tables are like Lua tables but immutable. Refer to the following example:
declare position = table {
with x = 5;
with y = 2;
}
Alternatively, you can declare tables like this:
declare table position {
with x = 5;
with y = 2;
}
A table can also contain functions:
declare position = table {
with x = 5;
with y = 2;
with myFunc = function : a, b, c {
// whatever
}
}
Functions inside tables can also be declared with this alternative syntax:
declare position = table {
with x = 5;
with y = 2;
function myFunc : a, b, c {
// whatever
}
}
Tables also act like classes, which means the this
keyword is available inside table functions. Refer to the following example:
declare position = table {
with x = 5;
with y = 2;
function magnitude {
return math.sqrt(this.x ^ 2 + this.y ^ 2);
}
}
However, unlike Lua's tables, tables in Dormez are immutable, meaning you cannot add members to the table. The following would throw an exception:
declare position = table {
with x = 5;
with y = 2;
}
position.z = -7; // ERROR: Object does not contain member: z
Obviously, trying to read a member that doesn't exist will also throw the same error:
declare position = table {
with x = 5;
with y = 2;
}
console.print(position.z == undefined); // ERROR: Object does not contain member: z
Why doesn't it return true
? Simple. position.z
isn't undefined because it doesn't exist. So then how do you check if a table contains a member? You can't. Since tables in Dormez are static, they reliably have the same set of variables, so you would never need to check in the first place. Think about it, how often do you need to check if an object contains a member in C# or C++?
Tables can also be indexed like an array to obtain their members, like so:
console.print(table["name"]);
table["name"] = "abc123";
It is easy to see how you could utilize tables as instantiatable objects, especially if you're used to Lua. You could do this to create a 'class' of sorts:
declare Vector = function of x, y {
return table {
with x = x,
with y = y,
function magnitude {
return (this.x ^ 2 + this.y ^ 2).sqrt();
}
}
}
declare position = Vector(5, 2);
But Dormez has a proper alternative, which are templates.